blob: d20b84a4282f7559ad892c4dd9e83f5acebccf52 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Yu Liufa297642024-06-11 00:13:02 +000018 "bytes"
19 "encoding/gob"
20 "errors"
Colin Cross6e18ca42015-07-14 18:55:36 -070021 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000022 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070023 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070024 "reflect"
Chris Wailesb2703ad2021-07-30 13:25:42 -070025 "regexp"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070026 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070027 "strings"
28
29 "github.com/google/blueprint"
Colin Cross0e446152021-05-03 13:35:32 -070030 "github.com/google/blueprint/bootstrap"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070031 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080032)
33
Colin Cross988414c2020-01-11 01:11:46 +000034var absSrcDir string
35
Dan Willemsen34cc69e2015-09-23 15:26:20 -070036// PathContext is the subset of a (Module|Singleton)Context required by the
37// Path methods.
38type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080039 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080040 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080041}
42
Colin Cross7f19f372016-11-01 11:10:25 -070043type PathGlobContext interface {
Colin Cross662d6142022-11-03 20:38:01 -070044 PathContext
Colin Cross7f19f372016-11-01 11:10:25 -070045 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
46}
47
Colin Crossaabf6792017-11-29 00:27:14 -080048var _ PathContext = SingletonContext(nil)
49var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070050
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010051// "Null" path context is a minimal path context for a given config.
52type NullPathContext struct {
53 config Config
54}
55
56func (NullPathContext) AddNinjaFileDeps(...string) {}
57func (ctx NullPathContext) Config() Config { return ctx.config }
58
Liz Kammera830f3a2020-11-10 10:50:34 -080059// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
60// Path methods. These path methods can be called before any mutators have run.
61type EarlyModulePathContext interface {
Liz Kammera830f3a2020-11-10 10:50:34 -080062 PathGlobContext
63
64 ModuleDir() string
65 ModuleErrorf(fmt string, args ...interface{})
Cole Fausta963b942024-04-11 17:43:00 -070066 OtherModulePropertyErrorf(module Module, property, fmt string, args ...interface{})
Liz Kammera830f3a2020-11-10 10:50:34 -080067}
68
69var _ EarlyModulePathContext = ModuleContext(nil)
70
71// Glob globs files and directories matching globPattern relative to ModuleDir(),
72// paths in the excludes parameter will be omitted.
73func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
74 ret, err := ctx.GlobWithDeps(globPattern, excludes)
75 if err != nil {
76 ctx.ModuleErrorf("glob: %s", err.Error())
77 }
78 return pathsForModuleSrcFromFullPath(ctx, ret, true)
79}
80
81// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
82// Paths in the excludes parameter will be omitted.
83func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
84 ret, err := ctx.GlobWithDeps(globPattern, excludes)
85 if err != nil {
86 ctx.ModuleErrorf("glob: %s", err.Error())
87 }
88 return pathsForModuleSrcFromFullPath(ctx, ret, false)
89}
90
91// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
92// the Path methods that rely on module dependencies having been resolved.
93type ModuleWithDepsPathContext interface {
94 EarlyModulePathContext
Paul Duffin40131a32021-07-09 17:10:35 +010095 VisitDirectDepsBlueprint(visit func(blueprint.Module))
96 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Liz Kammera830f3a2020-11-10 10:50:34 -080097}
98
99// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
100// the Path methods that rely on module dependencies having been resolved and ability to report
101// missing dependency errors.
102type ModuleMissingDepsPathContext interface {
103 ModuleWithDepsPathContext
104 AddMissingDependencies(missingDeps []string)
105}
106
Dan Willemsen00269f22017-07-06 16:59:48 -0700107type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700108 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700109
110 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700111 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700112 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800113 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700114 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900115 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900116 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700117 InstallInRoot() bool
Colin Crossea30d852023-11-29 16:00:16 -0800118 InstallInOdm() bool
119 InstallInProduct() bool
120 InstallInVendor() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900121 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700122}
123
124var _ ModuleInstallPathContext = ModuleContext(nil)
125
Cole Faust11edf552023-10-13 11:32:14 -0700126type baseModuleContextToModuleInstallPathContext struct {
127 BaseModuleContext
128}
129
130func (ctx *baseModuleContextToModuleInstallPathContext) InstallInData() bool {
131 return ctx.Module().InstallInData()
132}
133
134func (ctx *baseModuleContextToModuleInstallPathContext) InstallInTestcases() bool {
135 return ctx.Module().InstallInTestcases()
136}
137
138func (ctx *baseModuleContextToModuleInstallPathContext) InstallInSanitizerDir() bool {
139 return ctx.Module().InstallInSanitizerDir()
140}
141
142func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRamdisk() bool {
143 return ctx.Module().InstallInRamdisk()
144}
145
146func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendorRamdisk() bool {
147 return ctx.Module().InstallInVendorRamdisk()
148}
149
150func (ctx *baseModuleContextToModuleInstallPathContext) InstallInDebugRamdisk() bool {
151 return ctx.Module().InstallInDebugRamdisk()
152}
153
154func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRecovery() bool {
155 return ctx.Module().InstallInRecovery()
156}
157
158func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRoot() bool {
159 return ctx.Module().InstallInRoot()
160}
161
Colin Crossea30d852023-11-29 16:00:16 -0800162func (ctx *baseModuleContextToModuleInstallPathContext) InstallInOdm() bool {
163 return ctx.Module().InstallInOdm()
164}
165
166func (ctx *baseModuleContextToModuleInstallPathContext) InstallInProduct() bool {
167 return ctx.Module().InstallInProduct()
168}
169
170func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendor() bool {
171 return ctx.Module().InstallInVendor()
172}
173
Cole Faust11edf552023-10-13 11:32:14 -0700174func (ctx *baseModuleContextToModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
175 return ctx.Module().InstallForceOS()
176}
177
178var _ ModuleInstallPathContext = (*baseModuleContextToModuleInstallPathContext)(nil)
179
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700180// errorfContext is the interface containing the Errorf method matching the
181// Errorf method in blueprint.SingletonContext.
182type errorfContext interface {
183 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800184}
185
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700186var _ errorfContext = blueprint.SingletonContext(nil)
187
Spandan Das59a4a2b2024-01-09 21:35:56 +0000188// ModuleErrorfContext is the interface containing the ModuleErrorf method matching
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700189// the ModuleErrorf method in blueprint.ModuleContext.
Spandan Das59a4a2b2024-01-09 21:35:56 +0000190type ModuleErrorfContext interface {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700191 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800192}
193
Spandan Das59a4a2b2024-01-09 21:35:56 +0000194var _ ModuleErrorfContext = blueprint.ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700195
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700196// reportPathError will register an error with the attached context. It
197// attempts ctx.ModuleErrorf for a better error message first, then falls
198// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800199func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100200 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800201}
202
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100203// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800204// attempts ctx.ModuleErrorf for a better error message first, then falls
205// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100206func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000207 if mctx, ok := ctx.(ModuleErrorfContext); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700208 mctx.ModuleErrorf(format, args...)
209 } else if ectx, ok := ctx.(errorfContext); ok {
210 ectx.Errorf(format, args...)
211 } else {
212 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700213 }
214}
215
Colin Cross5e708052019-08-06 13:59:50 -0700216func pathContextName(ctx PathContext, module blueprint.Module) string {
217 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
218 return x.ModuleName(module)
219 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
220 return x.OtherModuleName(module)
221 }
222 return "unknown"
223}
224
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700225type Path interface {
226 // Returns the path in string form
227 String() string
228
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700229 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700230 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700231
232 // Base returns the last element of the path
233 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800234
235 // Rel returns the portion of the path relative to the directory it was created from. For
236 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800237 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800238 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000239
Colin Cross7707b242024-07-26 12:02:36 -0700240 // WithoutRel returns a new Path with no relative path, i.e. Rel() will return the same value as Base().
241 WithoutRel() Path
242
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000243 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
244 //
245 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
246 // InstallPath then the returned value can be converted to an InstallPath.
247 //
248 // A standard build has the following structure:
249 // ../top/
250 // out/ - make install files go here.
Colin Cross3b1c6842024-07-26 11:52:57 -0700251 // out/soong - this is the outDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000252 // ... - the source files
253 //
254 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Colin Cross3b1c6842024-07-26 11:52:57 -0700255 // * Make install paths, which have the pattern "outDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000256 // relative path "out/<path>"
Colin Cross3b1c6842024-07-26 11:52:57 -0700257 // * Soong install paths and other writable paths, which have the pattern "outDir/soong/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000258 // converted into the top relative path "out/soong/<path>".
259 // * Source paths are already relative to the top.
260 // * Phony paths are not relative to anything.
261 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
262 // order to test.
263 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700264}
265
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000266const (
Colin Cross3b1c6842024-07-26 11:52:57 -0700267 testOutDir = "out"
268 testOutSoongSubDir = "/soong"
269 TestOutSoongDir = testOutDir + testOutSoongSubDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000270)
271
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700272// WritablePath is a type of path that can be used as an output for build rules.
273type WritablePath interface {
274 Path
275
Paul Duffin9b478b02019-12-10 13:41:51 +0000276 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200277 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000278
Jeff Gaston734e3802017-04-10 15:47:24 -0700279 // the writablePath method doesn't directly do anything,
280 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700281 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100282
283 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700284}
285
286type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800287 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
yangbill6d032dd2024-04-18 03:05:49 +0000288 genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700289}
290type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800291 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700292}
293type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800294 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700295}
296
297// GenPathWithExt derives a new file path in ctx's generated sources directory
298// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800299func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700300 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700301 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700302 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100303 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700304 return PathForModuleGen(ctx)
305}
306
yangbill6d032dd2024-04-18 03:05:49 +0000307// GenPathWithExtAndTrimExt derives a new file path in ctx's generated sources directory
308// from the current path, but with the new extension and trim the suffix.
309func GenPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir string, p Path, ext string, trimExt string) ModuleGenPath {
310 if path, ok := p.(genPathProvider); ok {
311 return path.genPathWithExtAndTrimExt(ctx, subdir, ext, trimExt)
312 }
313 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
314 return PathForModuleGen(ctx)
315}
316
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700317// ObjPathWithExt derives a new file path in ctx's object directory from the
318// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800319func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700320 if path, ok := p.(objPathProvider); ok {
321 return path.objPathWithExt(ctx, subdir, ext)
322 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100323 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700324 return PathForModuleObj(ctx)
325}
326
327// ResPathWithName derives a new path in ctx's output resource directory, using
328// the current path to create the directory name, and the `name` argument for
329// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800330func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700331 if path, ok := p.(resPathProvider); ok {
332 return path.resPathWithName(ctx, name)
333 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100334 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700335 return PathForModuleRes(ctx)
336}
337
338// OptionalPath is a container that may or may not contain a valid Path.
339type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100340 path Path // nil if invalid.
341 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700342}
343
344// OptionalPathForPath returns an OptionalPath containing the path.
345func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100346 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700347}
348
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100349// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
350func InvalidOptionalPath(reason string) OptionalPath {
351
352 return OptionalPath{invalidReason: reason}
353}
354
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700355// Valid returns whether there is a valid path
356func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100357 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700358}
359
360// Path returns the Path embedded in this OptionalPath. You must be sure that
361// there is a valid path, since this method will panic if there is not.
362func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100363 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100364 msg := "Requesting an invalid path"
365 if p.invalidReason != "" {
366 msg += ": " + p.invalidReason
367 }
368 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700369 }
370 return p.path
371}
372
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100373// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
374func (p OptionalPath) InvalidReason() string {
375 if p.path != nil {
376 return ""
377 }
378 if p.invalidReason == "" {
379 return "unknown"
380 }
381 return p.invalidReason
382}
383
Paul Duffinef081852021-05-13 11:11:15 +0100384// AsPaths converts the OptionalPath into Paths.
385//
386// It returns nil if this is not valid, or a single length slice containing the Path embedded in
387// this OptionalPath.
388func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100389 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100390 return nil
391 }
392 return Paths{p.path}
393}
394
Paul Duffinafdd4062021-03-30 19:44:07 +0100395// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
396// result of calling Path.RelativeToTop on it.
397func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100398 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100399 return p
400 }
401 p.path = p.path.RelativeToTop()
402 return p
403}
404
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700405// String returns the string version of the Path, or "" if it isn't valid.
406func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100407 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700408 return p.path.String()
409 } else {
410 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700411 }
412}
Colin Cross6e18ca42015-07-14 18:55:36 -0700413
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700414// Paths is a slice of Path objects, with helpers to operate on the collection.
415type Paths []Path
416
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000417// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
418// item in this slice.
419func (p Paths) RelativeToTop() Paths {
420 ensureTestOnly()
421 if p == nil {
422 return p
423 }
424 ret := make(Paths, len(p))
425 for i, path := range p {
426 ret[i] = path.RelativeToTop()
427 }
428 return ret
429}
430
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000431func (paths Paths) containsPath(path Path) bool {
432 for _, p := range paths {
433 if p == path {
434 return true
435 }
436 }
437 return false
438}
439
Liz Kammer7aa52882021-02-11 09:16:14 -0500440// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
441// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700442func PathsForSource(ctx PathContext, paths []string) Paths {
443 ret := make(Paths, len(paths))
444 for i, path := range paths {
445 ret[i] = PathForSource(ctx, path)
446 }
447 return ret
448}
449
Liz Kammer7aa52882021-02-11 09:16:14 -0500450// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
451// module's local source directory, that are found in the tree. If any are not found, they are
452// 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 -0700453func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800454 ret := make(Paths, 0, len(paths))
455 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800456 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800457 if p.Valid() {
458 ret = append(ret, p.Path())
459 }
460 }
461 return ret
462}
463
Liz Kammer620dea62021-04-14 17:36:10 -0400464// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700465// - filepath, relative to local module directory, resolves as a filepath relative to the local
466// source directory
467// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
468// source directory.
469// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700470// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
471// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700472//
Liz Kammer620dea62021-04-14 17:36:10 -0400473// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700474// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000475// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400476// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700477// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400478// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700479// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800480func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800481 return PathsForModuleSrcExcludes(ctx, paths, nil)
482}
483
Liz Kammer619be462022-01-28 15:13:39 -0500484type SourceInput struct {
485 Context ModuleMissingDepsPathContext
486 Paths []string
487 ExcludePaths []string
488 IncludeDirs bool
489}
490
Liz Kammer620dea62021-04-14 17:36:10 -0400491// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
492// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700493// - filepath, relative to local module directory, resolves as a filepath relative to the local
494// source directory
495// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
496// source directory. Not valid in excludes.
497// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700498// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
499// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700500//
Liz Kammer620dea62021-04-14 17:36:10 -0400501// excluding the items (similarly resolved
502// Properties passed as the paths argument must have been annotated with struct tag
503// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000504// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400505// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700506// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400507// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700508// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800509func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500510 return PathsRelativeToModuleSourceDir(SourceInput{
511 Context: ctx,
512 Paths: paths,
513 ExcludePaths: excludes,
514 IncludeDirs: true,
515 })
516}
517
518func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
519 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
520 if input.Context.Config().AllowMissingDependencies() {
521 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700522 } else {
523 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500524 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700525 }
526 }
527 return ret
528}
529
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000530// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
531type OutputPaths []OutputPath
532
533// Paths returns the OutputPaths as a Paths
534func (p OutputPaths) Paths() Paths {
535 if p == nil {
536 return nil
537 }
538 ret := make(Paths, len(p))
539 for i, path := range p {
540 ret[i] = path
541 }
542 return ret
543}
544
545// Strings returns the string forms of the writable paths.
546func (p OutputPaths) Strings() []string {
547 if p == nil {
548 return nil
549 }
550 ret := make([]string, len(p))
551 for i, path := range p {
552 ret[i] = path.String()
553 }
554 return ret
555}
556
Colin Crossa44551f2021-10-25 15:36:21 -0700557// PathForGoBinary returns the path to the installed location of a bootstrap_go_binary module.
558func PathForGoBinary(ctx PathContext, goBinary bootstrap.GoBinaryTool) Path {
Cole Faust3b703f32023-10-16 13:30:51 -0700559 goBinaryInstallDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "bin")
Colin Crossa44551f2021-10-25 15:36:21 -0700560 rel := Rel(ctx, goBinaryInstallDir.String(), goBinary.InstallPath())
561 return goBinaryInstallDir.Join(ctx, rel)
562}
563
Liz Kammera830f3a2020-11-10 10:50:34 -0800564// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
565// If the dependency is not found, a missingErrorDependency is returned.
566// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
567func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100568 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800569 if module == nil {
570 return nil, missingDependencyError{[]string{moduleName}}
571 }
Cole Fausta963b942024-04-11 17:43:00 -0700572 if aModule, ok := module.(Module); ok && !aModule.Enabled(ctx) {
Colin Crossfa65cee2021-03-22 17:05:59 -0700573 return nil, missingDependencyError{[]string{moduleName}}
574 }
mrziwange6c85812024-05-22 14:36:09 -0700575 if goBinary, ok := module.(bootstrap.GoBinaryTool); ok && tag == "" {
Colin Crossa44551f2021-10-25 15:36:21 -0700576 goBinaryPath := PathForGoBinary(ctx, goBinary)
577 return Paths{goBinaryPath}, nil
mrziwange6c85812024-05-22 14:36:09 -0700578 }
579 outputFiles, err := outputFilesForModule(ctx, module, tag)
580 if outputFiles != nil && err == nil {
581 return outputFiles, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800582 } else {
mrziwange6c85812024-05-22 14:36:09 -0700583 return nil, err
Liz Kammera830f3a2020-11-10 10:50:34 -0800584 }
585}
586
Paul Duffind5cf92e2021-07-09 17:38:55 +0100587// GetModuleFromPathDep will return the module that was added as a dependency automatically for
588// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
589// ExtractSourcesDeps.
590//
591// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
592// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
593// the tag must be "".
594//
595// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
596// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100597func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100598 var found blueprint.Module
599 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
600 // module name and the tag. Dependencies added automatically for properties tagged with
601 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
602 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
603 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
604 // moduleName referring to the same dependency module.
605 //
606 // It does not matter whether the moduleName is a fully qualified name or if the module
607 // dependency is a prebuilt module. All that matters is the same information is supplied to
608 // create the tag here as was supplied to create the tag when the dependency was added so that
609 // this finds the matching dependency module.
610 expectedTag := sourceOrOutputDepTag(moduleName, tag)
611 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
612 depTag := ctx.OtherModuleDependencyTag(module)
613 if depTag == expectedTag {
614 found = module
615 }
616 })
617 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100618}
619
Liz Kammer620dea62021-04-14 17:36:10 -0400620// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
621// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700622// - filepath, relative to local module directory, resolves as a filepath relative to the local
623// source directory
624// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
625// source directory. Not valid in excludes.
626// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
mrziwangd38e63d2024-07-15 13:43:37 -0700627// or set the OutputFilesProvider. These resolve as a filepath to an output filepath or generated
628// source filepath.
Colin Crossd079e0b2022-08-16 10:27:33 -0700629//
Liz Kammer620dea62021-04-14 17:36:10 -0400630// and a list of the module names of missing module dependencies are returned as the second return.
631// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700632// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000633// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500634func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
635 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
636 Context: ctx,
637 Paths: paths,
638 ExcludePaths: excludes,
639 IncludeDirs: true,
640 })
641}
642
643func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
644 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800645
646 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500647 if input.ExcludePaths != nil {
648 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700649 }
Colin Cross8a497952019-03-05 22:25:09 -0800650
Colin Crossba71a3f2019-03-18 12:12:48 -0700651 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500652 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700653 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500654 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800655 if m, ok := err.(missingDependencyError); ok {
656 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
657 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500658 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800659 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800660 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800661 }
662 } else {
663 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
664 }
665 }
666
Liz Kammer619be462022-01-28 15:13:39 -0500667 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700668 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800669 }
670
Colin Crossba71a3f2019-03-18 12:12:48 -0700671 var missingDeps []string
672
Liz Kammer619be462022-01-28 15:13:39 -0500673 expandedSrcFiles := make(Paths, 0, len(input.Paths))
674 for _, s := range input.Paths {
675 srcFiles, err := expandOneSrcPath(sourcePathInput{
676 context: input.Context,
677 path: s,
678 expandedExcludes: expandedExcludes,
679 includeDirs: input.IncludeDirs,
680 })
Colin Cross8a497952019-03-05 22:25:09 -0800681 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700682 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800683 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500684 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800685 }
686 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
687 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700688
Jihoon Kang0e3a5352024-04-12 00:45:50 +0000689 // TODO: b/334169722 - Replace with an error instead of implicitly removing duplicates.
690 return FirstUniquePaths(expandedSrcFiles), append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800691}
692
693type missingDependencyError struct {
694 missingDeps []string
695}
696
697func (e missingDependencyError) Error() string {
698 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
699}
700
Liz Kammer619be462022-01-28 15:13:39 -0500701type sourcePathInput struct {
702 context ModuleWithDepsPathContext
703 path string
704 expandedExcludes []string
705 includeDirs bool
706}
707
Liz Kammera830f3a2020-11-10 10:50:34 -0800708// Expands one path string to Paths rooted from the module's local source
709// directory, excluding those listed in the expandedExcludes.
710// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500711func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900712 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500713 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900714 return paths
715 }
716 remainder := make(Paths, 0, len(paths))
717 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500718 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900719 remainder = append(remainder, p)
720 }
721 }
722 return remainder
723 }
Liz Kammer619be462022-01-28 15:13:39 -0500724 if m, t := SrcIsModuleWithTag(input.path); m != "" {
725 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800726 if err != nil {
727 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800728 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800729 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800730 }
Colin Cross8a497952019-03-05 22:25:09 -0800731 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500732 p := pathForModuleSrc(input.context, input.path)
733 if pathtools.IsGlob(input.path) {
734 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
735 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
736 } else {
737 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
738 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
739 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
740 ReportPathErrorf(input.context, "module source path %q does not exist", p)
741 } else if !input.includeDirs {
742 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
743 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
744 } else if isDir {
745 ReportPathErrorf(input.context, "module source path %q is a directory", p)
746 }
747 }
Colin Cross8a497952019-03-05 22:25:09 -0800748
Liz Kammer619be462022-01-28 15:13:39 -0500749 if InList(p.String(), input.expandedExcludes) {
750 return nil, nil
751 }
752 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800753 }
Colin Cross8a497952019-03-05 22:25:09 -0800754 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700755}
756
757// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
758// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800759// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700760// It intended for use in globs that only list files that exist, so it allows '$' in
761// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800762func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200763 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700764 if prefix == "./" {
765 prefix = ""
766 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700767 ret := make(Paths, 0, len(paths))
768 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800769 if !incDirs && strings.HasSuffix(p, "/") {
770 continue
771 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700772 path := filepath.Clean(p)
773 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100774 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700775 continue
776 }
Colin Crosse3924e12018-08-15 20:18:53 -0700777
Colin Crossfe4bc362018-09-12 10:02:13 -0700778 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700779 if err != nil {
780 reportPathError(ctx, err)
781 continue
782 }
783
Colin Cross07e51612019-03-05 12:46:40 -0800784 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700785
Colin Cross07e51612019-03-05 12:46:40 -0800786 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700787 }
788 return ret
789}
790
Liz Kammera830f3a2020-11-10 10:50:34 -0800791// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
792// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
793func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800794 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700795 return PathsForModuleSrc(ctx, input)
796 }
797 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
798 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200799 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800800 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700801}
802
803// Strings returns the Paths in string form
804func (p Paths) Strings() []string {
805 if p == nil {
806 return nil
807 }
808 ret := make([]string, len(p))
809 for i, path := range p {
810 ret[i] = path.String()
811 }
812 return ret
813}
814
Colin Crossc0efd1d2020-07-03 11:56:24 -0700815func CopyOfPaths(paths Paths) Paths {
816 return append(Paths(nil), paths...)
817}
818
Colin Crossb6715442017-10-24 11:13:31 -0700819// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
820// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700821func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800822 // 128 was chosen based on BenchmarkFirstUniquePaths results.
823 if len(list) > 128 {
824 return firstUniquePathsMap(list)
825 }
826 return firstUniquePathsList(list)
827}
828
Colin Crossc0efd1d2020-07-03 11:56:24 -0700829// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
830// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900831func SortedUniquePaths(list Paths) Paths {
832 unique := FirstUniquePaths(list)
833 sort.Slice(unique, func(i, j int) bool {
834 return unique[i].String() < unique[j].String()
835 })
836 return unique
837}
838
Colin Cross27027c72020-02-28 15:34:17 -0800839func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700840 k := 0
841outer:
842 for i := 0; i < len(list); i++ {
843 for j := 0; j < k; j++ {
844 if list[i] == list[j] {
845 continue outer
846 }
847 }
848 list[k] = list[i]
849 k++
850 }
851 return list[:k]
852}
853
Colin Cross27027c72020-02-28 15:34:17 -0800854func firstUniquePathsMap(list Paths) Paths {
855 k := 0
856 seen := make(map[Path]bool, len(list))
857 for i := 0; i < len(list); i++ {
858 if seen[list[i]] {
859 continue
860 }
861 seen[list[i]] = true
862 list[k] = list[i]
863 k++
864 }
865 return list[:k]
866}
867
Colin Cross5d583952020-11-24 16:21:24 -0800868// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
869// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
870func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
871 // 128 was chosen based on BenchmarkFirstUniquePaths results.
872 if len(list) > 128 {
873 return firstUniqueInstallPathsMap(list)
874 }
875 return firstUniqueInstallPathsList(list)
876}
877
878func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
879 k := 0
880outer:
881 for i := 0; i < len(list); i++ {
882 for j := 0; j < k; j++ {
883 if list[i] == list[j] {
884 continue outer
885 }
886 }
887 list[k] = list[i]
888 k++
889 }
890 return list[:k]
891}
892
893func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
894 k := 0
895 seen := make(map[InstallPath]bool, len(list))
896 for i := 0; i < len(list); i++ {
897 if seen[list[i]] {
898 continue
899 }
900 seen[list[i]] = true
901 list[k] = list[i]
902 k++
903 }
904 return list[:k]
905}
906
Colin Crossb6715442017-10-24 11:13:31 -0700907// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
908// modifies the Paths slice contents in place, and returns a subslice of the original slice.
909func LastUniquePaths(list Paths) Paths {
910 totalSkip := 0
911 for i := len(list) - 1; i >= totalSkip; i-- {
912 skip := 0
913 for j := i - 1; j >= totalSkip; j-- {
914 if list[i] == list[j] {
915 skip++
916 } else {
917 list[j+skip] = list[j]
918 }
919 }
920 totalSkip += skip
921 }
922 return list[totalSkip:]
923}
924
Colin Crossa140bb02018-04-17 10:52:26 -0700925// ReversePaths returns a copy of a Paths in reverse order.
926func ReversePaths(list Paths) Paths {
927 if list == nil {
928 return nil
929 }
930 ret := make(Paths, len(list))
931 for i := range list {
932 ret[i] = list[len(list)-1-i]
933 }
934 return ret
935}
936
Jeff Gaston294356f2017-09-27 17:05:30 -0700937func indexPathList(s Path, list []Path) int {
938 for i, l := range list {
939 if l == s {
940 return i
941 }
942 }
943
944 return -1
945}
946
947func inPathList(p Path, list []Path) bool {
948 return indexPathList(p, list) != -1
949}
950
951func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000952 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
953}
954
955func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700956 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000957 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700958 filtered = append(filtered, l)
959 } else {
960 remainder = append(remainder, l)
961 }
962 }
963
964 return
965}
966
Colin Cross93e85952017-08-15 13:34:18 -0700967// HasExt returns true of any of the paths have extension ext, otherwise false
968func (p Paths) HasExt(ext string) bool {
969 for _, path := range p {
970 if path.Ext() == ext {
971 return true
972 }
973 }
974
975 return false
976}
977
978// FilterByExt returns the subset of the paths that have extension ext
979func (p Paths) FilterByExt(ext string) Paths {
980 ret := make(Paths, 0, len(p))
981 for _, path := range p {
982 if path.Ext() == ext {
983 ret = append(ret, path)
984 }
985 }
986 return ret
987}
988
989// FilterOutByExt returns the subset of the paths that do not have extension ext
990func (p Paths) FilterOutByExt(ext string) Paths {
991 ret := make(Paths, 0, len(p))
992 for _, path := range p {
993 if path.Ext() != ext {
994 ret = append(ret, path)
995 }
996 }
997 return ret
998}
999
Colin Cross5e6cfbe2017-11-03 15:20:35 -07001000// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
1001// (including subdirectories) are in a contiguous subslice of the list, and can be found in
1002// O(log(N)) time using a binary search on the directory prefix.
1003type DirectorySortedPaths Paths
1004
1005func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
1006 ret := append(DirectorySortedPaths(nil), paths...)
1007 sort.Slice(ret, func(i, j int) bool {
1008 return ret[i].String() < ret[j].String()
1009 })
1010 return ret
1011}
1012
1013// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1014// that are in the specified directory and its subdirectories.
1015func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1016 prefix := filepath.Clean(dir) + "/"
1017 start := sort.Search(len(p), func(i int) bool {
1018 return prefix < p[i].String()
1019 })
1020
1021 ret := p[start:]
1022
1023 end := sort.Search(len(ret), func(i int) bool {
1024 return !strings.HasPrefix(ret[i].String(), prefix)
1025 })
1026
1027 ret = ret[:end]
1028
1029 return Paths(ret)
1030}
1031
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001032// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001033type WritablePaths []WritablePath
1034
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001035// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1036// each item in this slice.
1037func (p WritablePaths) RelativeToTop() WritablePaths {
1038 ensureTestOnly()
1039 if p == nil {
1040 return p
1041 }
1042 ret := make(WritablePaths, len(p))
1043 for i, path := range p {
1044 ret[i] = path.RelativeToTop().(WritablePath)
1045 }
1046 return ret
1047}
1048
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001049// Strings returns the string forms of the writable paths.
1050func (p WritablePaths) Strings() []string {
1051 if p == nil {
1052 return nil
1053 }
1054 ret := make([]string, len(p))
1055 for i, path := range p {
1056 ret[i] = path.String()
1057 }
1058 return ret
1059}
1060
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001061// Paths returns the WritablePaths as a Paths
1062func (p WritablePaths) Paths() Paths {
1063 if p == nil {
1064 return nil
1065 }
1066 ret := make(Paths, len(p))
1067 for i, path := range p {
1068 ret[i] = path
1069 }
1070 return ret
1071}
1072
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001073type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001074 path string
1075 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001076}
1077
Yu Liufa297642024-06-11 00:13:02 +00001078func (p basePath) GobEncode() ([]byte, error) {
1079 w := new(bytes.Buffer)
1080 encoder := gob.NewEncoder(w)
1081 err := errors.Join(encoder.Encode(p.path), encoder.Encode(p.rel))
1082 if err != nil {
1083 return nil, err
1084 }
1085
1086 return w.Bytes(), nil
1087}
1088
1089func (p *basePath) GobDecode(data []byte) error {
1090 r := bytes.NewBuffer(data)
1091 decoder := gob.NewDecoder(r)
1092 err := errors.Join(decoder.Decode(&p.path), decoder.Decode(&p.rel))
1093 if err != nil {
1094 return err
1095 }
1096
1097 return nil
1098}
1099
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001100func (p basePath) Ext() string {
1101 return filepath.Ext(p.path)
1102}
1103
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001104func (p basePath) Base() string {
1105 return filepath.Base(p.path)
1106}
1107
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001108func (p basePath) Rel() string {
1109 if p.rel != "" {
1110 return p.rel
1111 }
1112 return p.path
1113}
1114
Colin Cross0875c522017-11-28 17:34:01 -08001115func (p basePath) String() string {
1116 return p.path
1117}
1118
Colin Cross0db55682017-12-05 15:36:55 -08001119func (p basePath) withRel(rel string) basePath {
1120 p.path = filepath.Join(p.path, rel)
1121 p.rel = rel
1122 return p
1123}
1124
Colin Cross7707b242024-07-26 12:02:36 -07001125func (p basePath) withoutRel() basePath {
1126 p.rel = filepath.Base(p.path)
1127 return p
1128}
1129
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001130// SourcePath is a Path representing a file path rooted from SrcDir
1131type SourcePath struct {
1132 basePath
1133}
1134
1135var _ Path = SourcePath{}
1136
Colin Cross0db55682017-12-05 15:36:55 -08001137func (p SourcePath) withRel(rel string) SourcePath {
1138 p.basePath = p.basePath.withRel(rel)
1139 return p
1140}
1141
Colin Crossbd73d0d2024-07-26 12:00:33 -07001142func (p SourcePath) RelativeToTop() Path {
1143 ensureTestOnly()
1144 return p
1145}
1146
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001147// safePathForSource is for paths that we expect are safe -- only for use by go
1148// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001149func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1150 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001151 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001152 if err != nil {
1153 return ret, err
1154 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001155
Colin Cross7b3dcc32019-01-24 13:14:39 -08001156 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001157 // special-case api surface gen files for now
1158 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001159 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001160 }
1161
Colin Crossfe4bc362018-09-12 10:02:13 -07001162 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001163}
1164
Colin Cross192e97a2018-02-22 14:21:02 -08001165// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1166func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001167 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001168 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001169 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001170 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001171 }
1172
Colin Cross7b3dcc32019-01-24 13:14:39 -08001173 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001174 // special-case for now
1175 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001176 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001177 }
1178
Colin Cross192e97a2018-02-22 14:21:02 -08001179 return ret, nil
1180}
1181
1182// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1183// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001184func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001185 var files []string
1186
Colin Cross662d6142022-11-03 20:38:01 -07001187 // Use glob to produce proper dependencies, even though we only want
1188 // a single file.
1189 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001190
1191 if err != nil {
1192 return false, fmt.Errorf("glob: %s", err.Error())
1193 }
1194
1195 return len(files) > 0, nil
1196}
1197
1198// PathForSource joins the provided path components and validates that the result
1199// neither escapes the source dir nor is in the out dir.
1200// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1201func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1202 path, err := pathForSource(ctx, pathComponents...)
1203 if err != nil {
1204 reportPathError(ctx, err)
1205 }
1206
Colin Crosse3924e12018-08-15 20:18:53 -07001207 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001208 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001209 }
1210
Liz Kammera830f3a2020-11-10 10:50:34 -08001211 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001212 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001213 if err != nil {
1214 reportPathError(ctx, err)
1215 }
1216 if !exists {
1217 modCtx.AddMissingDependencies([]string{path.String()})
1218 }
Colin Cross988414c2020-01-11 01:11:46 +00001219 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001220 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001221 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001222 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001223 }
1224 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001225}
1226
Cole Faustbc65a3f2023-08-01 16:38:55 +00001227// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1228// the path is relative to the root of the output folder, not the out/soong folder.
1229func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
Colin Cross3b1c6842024-07-26 11:52:57 -07001230 path, err := validatePath(pathComponents...)
Cole Faustbc65a3f2023-08-01 16:38:55 +00001231 if err != nil {
1232 reportPathError(ctx, err)
1233 }
Colin Cross3b1c6842024-07-26 11:52:57 -07001234 fullPath := filepath.Join(ctx.Config().OutDir(), path)
1235 path = fullPath[len(fullPath)-len(path):]
1236 return OutputPath{basePath{path, ""}, ctx.Config().OutDir(), fullPath}
Cole Faustbc65a3f2023-08-01 16:38:55 +00001237}
1238
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001239// MaybeExistentPathForSource joins the provided path components and validates that the result
1240// neither escapes the source dir nor is in the out dir.
1241// It does not validate whether the path exists.
1242func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1243 path, err := pathForSource(ctx, pathComponents...)
1244 if err != nil {
1245 reportPathError(ctx, err)
1246 }
1247
1248 if pathtools.IsGlob(path.String()) {
1249 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1250 }
1251 return path
1252}
1253
Liz Kammer7aa52882021-02-11 09:16:14 -05001254// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1255// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1256// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1257// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001258func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001259 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001260 if err != nil {
1261 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001262 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001263 return OptionalPath{}
1264 }
Colin Crossc48c1432018-02-23 07:09:01 +00001265
Colin Crosse3924e12018-08-15 20:18:53 -07001266 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001267 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001268 return OptionalPath{}
1269 }
1270
Colin Cross192e97a2018-02-22 14:21:02 -08001271 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001272 if err != nil {
1273 reportPathError(ctx, err)
1274 return OptionalPath{}
1275 }
Colin Cross192e97a2018-02-22 14:21:02 -08001276 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001277 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001278 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001279 return OptionalPathForPath(path)
1280}
1281
1282func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001283 if p.path == "" {
1284 return "."
1285 }
1286 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001287}
1288
Colin Cross7707b242024-07-26 12:02:36 -07001289func (p SourcePath) WithoutRel() Path {
1290 p.basePath = p.basePath.withoutRel()
1291 return p
1292}
1293
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001294// Join creates a new SourcePath with paths... joined with the current path. The
1295// provided paths... may not use '..' to escape from the current path.
1296func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001297 path, err := validatePath(paths...)
1298 if err != nil {
1299 reportPathError(ctx, err)
1300 }
Colin Cross0db55682017-12-05 15:36:55 -08001301 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001302}
1303
Colin Cross2fafa3e2019-03-05 12:39:51 -08001304// join is like Join but does less path validation.
1305func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1306 path, err := validateSafePath(paths...)
1307 if err != nil {
1308 reportPathError(ctx, err)
1309 }
1310 return p.withRel(path)
1311}
1312
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001313// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1314// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001315func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001316 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001317 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001318 relDir = srcPath.path
1319 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001320 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001321 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001322 return OptionalPath{}
1323 }
Cole Faust483d1f72023-01-09 14:35:27 -08001324 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001325 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001326 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001327 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001328 }
Colin Cross461b4452018-02-23 09:22:42 -08001329 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001330 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001331 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001332 return OptionalPath{}
1333 }
1334 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001335 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001336 }
Cole Faust483d1f72023-01-09 14:35:27 -08001337 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001338}
1339
Colin Cross70dda7e2019-10-01 22:05:35 -07001340// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001341type OutputPath struct {
1342 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001343
Colin Cross3b1c6842024-07-26 11:52:57 -07001344 // The base out directory for this path, either Config.SoongOutDir() or Config.OutDir()
1345 outDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001346
Colin Crossd63c9a72020-01-29 16:52:50 -08001347 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001348}
1349
Yu Liufa297642024-06-11 00:13:02 +00001350func (p OutputPath) GobEncode() ([]byte, error) {
1351 w := new(bytes.Buffer)
1352 encoder := gob.NewEncoder(w)
Colin Cross3b1c6842024-07-26 11:52:57 -07001353 err := errors.Join(encoder.Encode(p.basePath), encoder.Encode(p.outDir), encoder.Encode(p.fullPath))
Yu Liufa297642024-06-11 00:13:02 +00001354 if err != nil {
1355 return nil, err
1356 }
1357
1358 return w.Bytes(), nil
1359}
1360
1361func (p *OutputPath) GobDecode(data []byte) error {
1362 r := bytes.NewBuffer(data)
1363 decoder := gob.NewDecoder(r)
Colin Cross3b1c6842024-07-26 11:52:57 -07001364 err := errors.Join(decoder.Decode(&p.basePath), decoder.Decode(&p.outDir), decoder.Decode(&p.fullPath))
Yu Liufa297642024-06-11 00:13:02 +00001365 if err != nil {
1366 return err
1367 }
1368
1369 return nil
1370}
1371
Colin Cross702e0f82017-10-18 17:27:54 -07001372func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001373 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001374 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001375 return p
1376}
1377
Colin Cross7707b242024-07-26 12:02:36 -07001378func (p OutputPath) WithoutRel() Path {
1379 p.basePath = p.basePath.withoutRel()
Colin Cross3063b782018-08-15 11:19:12 -07001380 return p
1381}
1382
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001383func (p OutputPath) getSoongOutDir() string {
Colin Cross3b1c6842024-07-26 11:52:57 -07001384 return p.outDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001385}
1386
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001387func (p OutputPath) RelativeToTop() Path {
1388 return p.outputPathRelativeToTop()
1389}
1390
1391func (p OutputPath) outputPathRelativeToTop() OutputPath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001392 p.fullPath = StringPathRelativeToTop(p.outDir, p.fullPath)
1393 if strings.HasSuffix(p.outDir, testOutSoongSubDir) {
1394 p.outDir = TestOutSoongDir
1395 } else {
1396 // Handle the PathForArbitraryOutput case
1397 p.outDir = testOutDir
1398 }
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001399 return p
1400}
1401
Paul Duffin0267d492021-02-02 10:05:52 +00001402func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1403 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1404}
1405
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001406var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001407var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001408var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001409
Chris Parsons8f232a22020-06-23 17:37:05 -04001410// toolDepPath is a Path representing a dependency of the build tool.
1411type toolDepPath struct {
1412 basePath
1413}
1414
Colin Cross7707b242024-07-26 12:02:36 -07001415func (t toolDepPath) WithoutRel() Path {
1416 t.basePath = t.basePath.withoutRel()
1417 return t
1418}
1419
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001420func (t toolDepPath) RelativeToTop() Path {
1421 ensureTestOnly()
1422 return t
1423}
1424
Chris Parsons8f232a22020-06-23 17:37:05 -04001425var _ Path = toolDepPath{}
1426
1427// pathForBuildToolDep returns a toolDepPath representing the given path string.
1428// There is no validation for the path, as it is "trusted": It may fail
1429// normal validation checks. For example, it may be an absolute path.
1430// Only use this function to construct paths for dependencies of the build
1431// tool invocation.
1432func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001433 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001434}
1435
Jeff Gaston734e3802017-04-10 15:47:24 -07001436// PathForOutput joins the provided paths and returns an OutputPath that is
1437// validated to not escape the build dir.
1438// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1439func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001440 path, err := validatePath(pathComponents...)
1441 if err != nil {
1442 reportPathError(ctx, err)
1443 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001444 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001445 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001446 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001447}
1448
Colin Cross3b1c6842024-07-26 11:52:57 -07001449// PathsForOutput returns Paths rooted from outDir
Colin Cross40e33732019-02-15 11:08:35 -08001450func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1451 ret := make(WritablePaths, len(paths))
1452 for i, path := range paths {
1453 ret[i] = PathForOutput(ctx, path)
1454 }
1455 return ret
1456}
1457
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001458func (p OutputPath) writablePath() {}
1459
1460func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001461 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001462}
1463
1464// Join creates a new OutputPath with paths... joined with the current path. The
1465// provided paths... may not use '..' to escape from the current path.
1466func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001467 path, err := validatePath(paths...)
1468 if err != nil {
1469 reportPathError(ctx, err)
1470 }
Colin Cross0db55682017-12-05 15:36:55 -08001471 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001472}
1473
Colin Cross8854a5a2019-02-11 14:14:16 -08001474// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1475func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1476 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001477 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001478 }
1479 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001480 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001481 return ret
1482}
1483
Colin Cross40e33732019-02-15 11:08:35 -08001484// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1485func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1486 path, err := validatePath(paths...)
1487 if err != nil {
1488 reportPathError(ctx, err)
1489 }
1490
1491 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001492 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001493 return ret
1494}
1495
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001496// PathForIntermediates returns an OutputPath representing the top-level
1497// intermediates directory.
1498func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001499 path, err := validatePath(paths...)
1500 if err != nil {
1501 reportPathError(ctx, err)
1502 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001503 return PathForOutput(ctx, ".intermediates", path)
1504}
1505
Colin Cross07e51612019-03-05 12:46:40 -08001506var _ genPathProvider = SourcePath{}
1507var _ objPathProvider = SourcePath{}
1508var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001509
Colin Cross07e51612019-03-05 12:46:40 -08001510// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001511// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001512func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001513 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1514 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1515 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1516 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1517 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001518 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001519 if err != nil {
1520 if depErr, ok := err.(missingDependencyError); ok {
1521 if ctx.Config().AllowMissingDependencies() {
1522 ctx.AddMissingDependencies(depErr.missingDeps)
1523 } else {
1524 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1525 }
1526 } else {
1527 reportPathError(ctx, err)
1528 }
1529 return nil
1530 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001531 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001532 return nil
1533 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001534 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001535 }
1536 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001537}
1538
Liz Kammera830f3a2020-11-10 10:50:34 -08001539func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001540 p, err := validatePath(paths...)
1541 if err != nil {
1542 reportPathError(ctx, err)
1543 }
1544
1545 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1546 if err != nil {
1547 reportPathError(ctx, err)
1548 }
1549
1550 path.basePath.rel = p
1551
1552 return path
1553}
1554
Colin Cross2fafa3e2019-03-05 12:39:51 -08001555// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1556// will return the path relative to subDir in the module's source directory. If any input paths are not located
1557// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001558func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001559 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001560 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001561 for i, path := range paths {
1562 rel := Rel(ctx, subDirFullPath.String(), path.String())
1563 paths[i] = subDirFullPath.join(ctx, rel)
1564 }
1565 return paths
1566}
1567
1568// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1569// 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 -08001570func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001571 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001572 rel := Rel(ctx, subDirFullPath.String(), path.String())
1573 return subDirFullPath.Join(ctx, rel)
1574}
1575
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001576// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1577// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001578func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001579 if p == nil {
1580 return OptionalPath{}
1581 }
1582 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1583}
1584
Liz Kammera830f3a2020-11-10 10:50:34 -08001585func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001586 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001587}
1588
yangbill6d032dd2024-04-18 03:05:49 +00001589func (p SourcePath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1590 // If Trim_extension being set, force append Output_extension without replace original extension.
1591 if trimExt != "" {
1592 if ext != "" {
1593 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1594 }
1595 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1596 }
1597 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1598}
1599
Liz Kammera830f3a2020-11-10 10:50:34 -08001600func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001601 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001602}
1603
Liz Kammera830f3a2020-11-10 10:50:34 -08001604func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001605 // TODO: Use full directory if the new ctx is not the current ctx?
1606 return PathForModuleRes(ctx, p.path, name)
1607}
1608
1609// ModuleOutPath is a Path representing a module's output directory.
1610type ModuleOutPath struct {
1611 OutputPath
1612}
1613
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001614func (p ModuleOutPath) RelativeToTop() Path {
1615 p.OutputPath = p.outputPathRelativeToTop()
1616 return p
1617}
1618
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001619var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001620var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001621
Liz Kammera830f3a2020-11-10 10:50:34 -08001622func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001623 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1624}
1625
Liz Kammera830f3a2020-11-10 10:50:34 -08001626// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1627type ModuleOutPathContext interface {
1628 PathContext
1629
1630 ModuleName() string
1631 ModuleDir() string
1632 ModuleSubDir() string
1633}
1634
1635func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kimb7e9f5f2024-06-25 17:39:52 +09001636 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
Colin Cross702e0f82017-10-18 17:27:54 -07001637}
1638
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001639// PathForModuleOut returns a Path representing the paths... under the module's
1640// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001641func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001642 p, err := validatePath(paths...)
1643 if err != nil {
1644 reportPathError(ctx, err)
1645 }
Colin Cross702e0f82017-10-18 17:27:54 -07001646 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001647 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001648 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001649}
1650
1651// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1652// directory. Mainly used for generated sources.
1653type ModuleGenPath struct {
1654 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001655}
1656
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001657func (p ModuleGenPath) RelativeToTop() Path {
1658 p.OutputPath = p.outputPathRelativeToTop()
1659 return p
1660}
1661
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001662var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001663var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001664var _ genPathProvider = ModuleGenPath{}
1665var _ objPathProvider = ModuleGenPath{}
1666
1667// PathForModuleGen returns a Path representing the paths... under the module's
1668// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001669func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001670 p, err := validatePath(paths...)
1671 if err != nil {
1672 reportPathError(ctx, err)
1673 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001674 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001675 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001676 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001677 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001678 }
1679}
1680
Liz Kammera830f3a2020-11-10 10:50:34 -08001681func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001682 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001683 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001684}
1685
yangbill6d032dd2024-04-18 03:05:49 +00001686func (p ModuleGenPath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1687 // If Trim_extension being set, force append Output_extension without replace original extension.
1688 if trimExt != "" {
1689 if ext != "" {
1690 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1691 }
1692 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1693 }
1694 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1695}
1696
Liz Kammera830f3a2020-11-10 10:50:34 -08001697func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001698 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1699}
1700
1701// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1702// directory. Used for compiled objects.
1703type ModuleObjPath struct {
1704 ModuleOutPath
1705}
1706
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001707func (p ModuleObjPath) RelativeToTop() Path {
1708 p.OutputPath = p.outputPathRelativeToTop()
1709 return p
1710}
1711
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001712var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001713var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001714
1715// PathForModuleObj returns a Path representing the paths... under the module's
1716// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001717func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001718 p, err := validatePath(pathComponents...)
1719 if err != nil {
1720 reportPathError(ctx, err)
1721 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001722 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1723}
1724
1725// ModuleResPath is a a Path representing the 'res' directory in a module's
1726// output directory.
1727type ModuleResPath struct {
1728 ModuleOutPath
1729}
1730
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001731func (p ModuleResPath) RelativeToTop() Path {
1732 p.OutputPath = p.outputPathRelativeToTop()
1733 return p
1734}
1735
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001736var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001737var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001738
1739// PathForModuleRes returns a Path representing the paths... under the module's
1740// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001741func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001742 p, err := validatePath(pathComponents...)
1743 if err != nil {
1744 reportPathError(ctx, err)
1745 }
1746
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001747 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1748}
1749
Colin Cross70dda7e2019-10-01 22:05:35 -07001750// InstallPath is a Path representing a installed file path rooted from the build directory
1751type InstallPath struct {
1752 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001753
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001754 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001755 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001756
Jiyong Park957bcd92020-10-20 18:23:33 +09001757 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1758 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1759 partitionDir string
1760
Colin Crossb1692a32021-10-25 15:39:01 -07001761 partition string
1762
Jiyong Park957bcd92020-10-20 18:23:33 +09001763 // makePath indicates whether this path is for Soong (false) or Make (true).
1764 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001765
1766 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001767}
1768
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001769// Will panic if called from outside a test environment.
1770func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001771 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001772 return
1773 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001774 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001775}
1776
1777func (p InstallPath) RelativeToTop() Path {
1778 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001779 if p.makePath {
Colin Cross3b1c6842024-07-26 11:52:57 -07001780 p.soongOutDir = testOutDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001781 } else {
Colin Cross3b1c6842024-07-26 11:52:57 -07001782 p.soongOutDir = TestOutSoongDir
Colin Crossc0e42d52024-02-01 16:42:36 -08001783 }
1784 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001785 return p
1786}
1787
Colin Cross7707b242024-07-26 12:02:36 -07001788func (p InstallPath) WithoutRel() Path {
1789 p.basePath = p.basePath.withoutRel()
1790 return p
1791}
1792
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001793func (p InstallPath) getSoongOutDir() string {
1794 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001795}
1796
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001797func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1798 panic("Not implemented")
1799}
1800
Paul Duffin9b478b02019-12-10 13:41:51 +00001801var _ Path = InstallPath{}
1802var _ WritablePath = InstallPath{}
1803
Colin Cross70dda7e2019-10-01 22:05:35 -07001804func (p InstallPath) writablePath() {}
1805
1806func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08001807 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09001808}
1809
1810// PartitionDir returns the path to the partition where the install path is rooted at. It is
1811// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1812// The ./soong is dropped if the install path is for Make.
1813func (p InstallPath) PartitionDir() string {
1814 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001815 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001816 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001817 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001818 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001819}
1820
Jihoon Kangf78a8902022-09-01 22:47:07 +00001821func (p InstallPath) Partition() string {
1822 return p.partition
1823}
1824
Colin Cross70dda7e2019-10-01 22:05:35 -07001825// Join creates a new InstallPath with paths... joined with the current path. The
1826// provided paths... may not use '..' to escape from the current path.
1827func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1828 path, err := validatePath(paths...)
1829 if err != nil {
1830 reportPathError(ctx, err)
1831 }
1832 return p.withRel(path)
1833}
1834
1835func (p InstallPath) withRel(rel string) InstallPath {
1836 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08001837 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07001838 return p
1839}
1840
Colin Crossc68db4b2021-11-11 18:59:15 -08001841// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1842// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001843func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001844 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001845 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001846}
1847
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001848// PathForModuleInstall returns a Path representing the install path for the
1849// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001850func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001851 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07001852 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07001853 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001854}
1855
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001856// PathForHostDexInstall returns an InstallPath representing the install path for the
1857// module appended with paths...
1858func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07001859 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001860}
1861
Spandan Das5d1b9292021-06-03 19:36:41 +00001862// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1863func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1864 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07001865 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001866}
1867
1868func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001869 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001870 arch := ctx.Arch().ArchType
1871 forceOS, forceArch := ctx.InstallForceOS()
1872 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001873 os = *forceOS
1874 }
Jiyong Park87788b52020-09-01 12:37:45 +09001875 if forceArch != nil {
1876 arch = *forceArch
1877 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001878 return os, arch
1879}
Colin Cross609c49a2020-02-13 13:20:11 -08001880
Colin Crossc0e42d52024-02-01 16:42:36 -08001881func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
1882 fullPath := ctx.Config().SoongOutDir()
1883 if makePath {
1884 // Make path starts with out/ instead of out/soong.
1885 fullPath = filepath.Join(fullPath, "../", partitionPath)
1886 } else {
1887 fullPath = filepath.Join(fullPath, partitionPath)
1888 }
1889
1890 return InstallPath{
1891 basePath: basePath{partitionPath, ""},
1892 soongOutDir: ctx.Config().soongOutDir,
1893 partitionDir: partitionPath,
1894 partition: partition,
1895 makePath: makePath,
1896 fullPath: fullPath,
1897 }
1898}
1899
Cole Faust3b703f32023-10-16 13:30:51 -07001900func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08001901 pathComponents ...string) InstallPath {
1902
Jiyong Park97859152023-02-14 17:05:48 +09001903 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001904
Colin Cross6e359402020-02-10 15:29:54 -08001905 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09001906 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001907 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001908 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07001909 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09001910 // instead of linux_glibc
1911 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001912 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07001913 if os == LinuxMusl && ctx.Config().UseHostMusl() {
1914 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
1915 // compiling we will still use "linux_musl".
1916 osName = "linux"
1917 }
1918
Jiyong Park87788b52020-09-01 12:37:45 +09001919 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1920 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1921 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1922 // Let's keep using x86 for the existing cases until we have a need to support
1923 // other architectures.
1924 archName := arch.String()
1925 if os.Class == Host && (arch == X86_64 || arch == Common) {
1926 archName = "x86"
1927 }
Jiyong Park97859152023-02-14 17:05:48 +09001928 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001929 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001930
Jiyong Park97859152023-02-14 17:05:48 +09001931 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001932 if err != nil {
1933 reportPathError(ctx, err)
1934 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001935
Colin Crossc0e42d52024-02-01 16:42:36 -08001936 base := pathForPartitionInstallDir(ctx, partition, partitionPath, ctx.Config().KatiEnabled())
Jiyong Park957bcd92020-10-20 18:23:33 +09001937 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001938}
1939
Spandan Dasf280b232024-04-04 21:25:51 +00001940func PathForNdkInstall(ctx PathContext, paths ...string) OutputPath {
1941 return PathForOutput(ctx, append([]string{"ndk"}, paths...)...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001942}
1943
1944func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
Spandan Dasf280b232024-04-04 21:25:51 +00001945 base := pathForPartitionInstallDir(ctx, "", "mainline-sdks", false)
1946 return base.Join(ctx, paths...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001947}
1948
Colin Cross70dda7e2019-10-01 22:05:35 -07001949func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07001950 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08001951 return "/" + rel
1952}
1953
Cole Faust11edf552023-10-13 11:32:14 -07001954func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001955 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001956 if ctx.InstallInTestcases() {
1957 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001958 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07001959 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08001960 if ctx.InstallInData() {
1961 partition = "data"
1962 } else if ctx.InstallInRamdisk() {
1963 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1964 partition = "recovery/root/first_stage_ramdisk"
1965 } else {
1966 partition = "ramdisk"
1967 }
1968 if !ctx.InstallInRoot() {
1969 partition += "/system"
1970 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001971 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001972 // The module is only available after switching root into
1973 // /first_stage_ramdisk. To expose the module before switching root
1974 // on a device without a dedicated recovery partition, install the
1975 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001976 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001977 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001978 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001979 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001980 }
1981 if !ctx.InstallInRoot() {
1982 partition += "/system"
1983 }
Inseob Kim08758f02021-04-08 21:13:22 +09001984 } else if ctx.InstallInDebugRamdisk() {
1985 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08001986 } else if ctx.InstallInRecovery() {
1987 if ctx.InstallInRoot() {
1988 partition = "recovery/root"
1989 } else {
1990 // the layout of recovery partion is the same as that of system partition
1991 partition = "recovery/root/system"
1992 }
Colin Crossea30d852023-11-29 16:00:16 -08001993 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08001994 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08001995 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08001996 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08001997 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08001998 partition = ctx.DeviceConfig().ProductPath()
1999 } else if ctx.SystemExtSpecific() {
2000 partition = ctx.DeviceConfig().SystemExtPath()
2001 } else if ctx.InstallInRoot() {
2002 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08002003 } else {
Colin Cross6e359402020-02-10 15:29:54 -08002004 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08002005 }
Colin Cross6e359402020-02-10 15:29:54 -08002006 if ctx.InstallInSanitizerDir() {
2007 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08002008 }
Colin Cross43f08db2018-11-12 10:13:39 -08002009 }
2010 return partition
2011}
2012
Colin Cross609c49a2020-02-13 13:20:11 -08002013type InstallPaths []InstallPath
2014
2015// Paths returns the InstallPaths as a Paths
2016func (p InstallPaths) Paths() Paths {
2017 if p == nil {
2018 return nil
2019 }
2020 ret := make(Paths, len(p))
2021 for i, path := range p {
2022 ret[i] = path
2023 }
2024 return ret
2025}
2026
2027// Strings returns the string forms of the install paths.
2028func (p InstallPaths) Strings() []string {
2029 if p == nil {
2030 return nil
2031 }
2032 ret := make([]string, len(p))
2033 for i, path := range p {
2034 ret[i] = path.String()
2035 }
2036 return ret
2037}
2038
Jingwen Chen24d0c562023-02-07 09:29:36 +00002039// validatePathInternal ensures that a path does not leave its component, and
2040// optionally doesn't contain Ninja variables.
2041func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002042 initialEmpty := 0
2043 finalEmpty := 0
2044 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002045 if !allowNinjaVariables && strings.Contains(path, "$") {
2046 return "", fmt.Errorf("Path contains invalid character($): %s", path)
2047 }
2048
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002049 path := filepath.Clean(path)
2050 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002051 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002052 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002053
2054 if i == initialEmpty && pathComponents[i] == "" {
2055 initialEmpty++
2056 }
2057 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
2058 finalEmpty++
2059 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002060 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002061 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
2062 // of "foo", while filepath.Join("foo") does not. Strip out any empty
2063 // path components.
2064 if initialEmpty == len(pathComponents) {
2065 return "", nil
2066 }
2067 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002068 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2069 // variables. '..' may remove the entire ninja variable, even if it
2070 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002071 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002072}
2073
Jingwen Chen24d0c562023-02-07 09:29:36 +00002074// validateSafePath validates a path that we trust (may contain ninja
2075// variables). Ensures that each path component does not attempt to leave its
2076// component. Returns a joined version of each path component.
2077func validateSafePath(pathComponents ...string) (string, error) {
2078 return validatePathInternal(true, pathComponents...)
2079}
2080
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002081// validatePath validates that a path does not include ninja variables, and that
2082// each path component does not attempt to leave its component. Returns a joined
2083// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002084func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002085 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002086}
Colin Cross5b529592017-05-09 13:34:34 -07002087
Colin Cross0875c522017-11-28 17:34:01 -08002088func PathForPhony(ctx PathContext, phony string) WritablePath {
2089 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002090 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002091 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002092 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002093}
2094
Colin Cross74e3fe42017-12-11 15:51:44 -08002095type PhonyPath struct {
2096 basePath
2097}
2098
2099func (p PhonyPath) writablePath() {}
2100
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002101func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002102 // A phone path cannot contain any / so cannot be relative to the build directory.
2103 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002104}
2105
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002106func (p PhonyPath) RelativeToTop() Path {
2107 ensureTestOnly()
2108 // A phony path cannot contain any / so does not have a build directory so switching to a new
2109 // build directory has no effect so just return this path.
2110 return p
2111}
2112
Colin Cross7707b242024-07-26 12:02:36 -07002113func (p PhonyPath) WithoutRel() Path {
2114 p.basePath = p.basePath.withoutRel()
2115 return p
2116}
2117
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002118func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2119 panic("Not implemented")
2120}
2121
Colin Cross74e3fe42017-12-11 15:51:44 -08002122var _ Path = PhonyPath{}
2123var _ WritablePath = PhonyPath{}
2124
Colin Cross5b529592017-05-09 13:34:34 -07002125type testPath struct {
2126 basePath
2127}
2128
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002129func (p testPath) RelativeToTop() Path {
2130 ensureTestOnly()
2131 return p
2132}
2133
Colin Cross7707b242024-07-26 12:02:36 -07002134func (p testPath) WithoutRel() Path {
2135 p.basePath = p.basePath.withoutRel()
2136 return p
2137}
2138
Colin Cross5b529592017-05-09 13:34:34 -07002139func (p testPath) String() string {
2140 return p.path
2141}
2142
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002143var _ Path = testPath{}
2144
Colin Cross40e33732019-02-15 11:08:35 -08002145// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2146// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002147func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002148 p, err := validateSafePath(paths...)
2149 if err != nil {
2150 panic(err)
2151 }
Colin Cross5b529592017-05-09 13:34:34 -07002152 return testPath{basePath{path: p, rel: p}}
2153}
2154
Sam Delmerico2351eac2022-05-24 17:10:02 +00002155func PathForTestingWithRel(path, rel string) Path {
2156 p, err := validateSafePath(path, rel)
2157 if err != nil {
2158 panic(err)
2159 }
2160 r, err := validatePath(rel)
2161 if err != nil {
2162 panic(err)
2163 }
2164 return testPath{basePath{path: p, rel: r}}
2165}
2166
Colin Cross40e33732019-02-15 11:08:35 -08002167// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2168func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002169 p := make(Paths, len(strs))
2170 for i, s := range strs {
2171 p[i] = PathForTesting(s)
2172 }
2173
2174 return p
2175}
Colin Cross43f08db2018-11-12 10:13:39 -08002176
Colin Cross40e33732019-02-15 11:08:35 -08002177type testPathContext struct {
2178 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002179}
2180
Colin Cross40e33732019-02-15 11:08:35 -08002181func (x *testPathContext) Config() Config { return x.config }
2182func (x *testPathContext) AddNinjaFileDeps(...string) {}
2183
2184// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2185// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002186func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002187 return &testPathContext{
2188 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002189 }
2190}
2191
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002192type testModuleInstallPathContext struct {
2193 baseModuleContext
2194
2195 inData bool
2196 inTestcases bool
2197 inSanitizerDir bool
2198 inRamdisk bool
2199 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002200 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002201 inRecovery bool
2202 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002203 inOdm bool
2204 inProduct bool
2205 inVendor bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002206 forceOS *OsType
2207 forceArch *ArchType
2208}
2209
2210func (m testModuleInstallPathContext) Config() Config {
2211 return m.baseModuleContext.config
2212}
2213
2214func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2215
2216func (m testModuleInstallPathContext) InstallInData() bool {
2217 return m.inData
2218}
2219
2220func (m testModuleInstallPathContext) InstallInTestcases() bool {
2221 return m.inTestcases
2222}
2223
2224func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2225 return m.inSanitizerDir
2226}
2227
2228func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2229 return m.inRamdisk
2230}
2231
2232func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2233 return m.inVendorRamdisk
2234}
2235
Inseob Kim08758f02021-04-08 21:13:22 +09002236func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2237 return m.inDebugRamdisk
2238}
2239
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002240func (m testModuleInstallPathContext) InstallInRecovery() bool {
2241 return m.inRecovery
2242}
2243
2244func (m testModuleInstallPathContext) InstallInRoot() bool {
2245 return m.inRoot
2246}
2247
Colin Crossea30d852023-11-29 16:00:16 -08002248func (m testModuleInstallPathContext) InstallInOdm() bool {
2249 return m.inOdm
2250}
2251
2252func (m testModuleInstallPathContext) InstallInProduct() bool {
2253 return m.inProduct
2254}
2255
2256func (m testModuleInstallPathContext) InstallInVendor() bool {
2257 return m.inVendor
2258}
2259
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002260func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2261 return m.forceOS, m.forceArch
2262}
2263
2264// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2265// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2266// delegated to it will panic.
2267func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2268 ctx := &testModuleInstallPathContext{}
2269 ctx.config = config
2270 ctx.os = Android
2271 return ctx
2272}
2273
Colin Cross43f08db2018-11-12 10:13:39 -08002274// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2275// targetPath is not inside basePath.
2276func Rel(ctx PathContext, basePath string, targetPath string) string {
2277 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2278 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002279 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002280 return ""
2281 }
2282 return rel
2283}
2284
2285// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2286// targetPath is not inside basePath.
2287func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002288 rel, isRel, err := maybeRelErr(basePath, targetPath)
2289 if err != nil {
2290 reportPathError(ctx, err)
2291 }
2292 return rel, isRel
2293}
2294
2295func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002296 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2297 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002298 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002299 }
2300 rel, err := filepath.Rel(basePath, targetPath)
2301 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002302 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002303 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002304 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002305 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002306 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002307}
Colin Cross988414c2020-01-11 01:11:46 +00002308
2309// Writes a file to the output directory. Attempting to write directly to the output directory
2310// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002311// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2312// updating the timestamp if no changes would be made. (This is better for incremental
2313// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002314func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002315 absPath := absolutePath(path.String())
2316 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2317 if err != nil {
2318 return err
2319 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002320 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002321}
2322
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002323func RemoveAllOutputDir(path WritablePath) error {
2324 return os.RemoveAll(absolutePath(path.String()))
2325}
2326
2327func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2328 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002329 return createDirIfNonexistent(dir, perm)
2330}
2331
2332func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002333 if _, err := os.Stat(dir); os.IsNotExist(err) {
2334 return os.MkdirAll(dir, os.ModePerm)
2335 } else {
2336 return err
2337 }
2338}
2339
Jingwen Chen78257e52021-05-21 02:34:24 +00002340// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2341// read arbitrary files without going through the methods in the current package that track
2342// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002343func absolutePath(path string) string {
2344 if filepath.IsAbs(path) {
2345 return path
2346 }
2347 return filepath.Join(absSrcDir, path)
2348}
Chris Parsons216e10a2020-07-09 17:12:52 -04002349
2350// A DataPath represents the path of a file to be used as data, for example
2351// a test library to be installed alongside a test.
2352// The data file should be installed (copied from `<SrcPath>`) to
2353// `<install_root>/<RelativeInstallPath>/<filename>`, or
2354// `<install_root>/<filename>` if RelativeInstallPath is empty.
2355type DataPath struct {
2356 // The path of the data file that should be copied into the data directory
2357 SrcPath Path
2358 // The install path of the data file, relative to the install root.
2359 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002360 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2361 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002362}
Colin Crossdcf71b22021-02-01 13:59:03 -08002363
Colin Crossd442a0e2023-11-16 11:19:26 -08002364func (d *DataPath) ToRelativeInstallPath() string {
2365 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002366 if d.WithoutRel {
2367 relPath = d.SrcPath.Base()
2368 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002369 if d.RelativeInstallPath != "" {
2370 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2371 }
2372 return relPath
2373}
2374
Colin Crossdcf71b22021-02-01 13:59:03 -08002375// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2376func PathsIfNonNil(paths ...Path) Paths {
2377 if len(paths) == 0 {
2378 // Fast path for empty argument list
2379 return nil
2380 } else if len(paths) == 1 {
2381 // Fast path for a single argument
2382 if paths[0] != nil {
2383 return paths
2384 } else {
2385 return nil
2386 }
2387 }
2388 ret := make(Paths, 0, len(paths))
2389 for _, path := range paths {
2390 if path != nil {
2391 ret = append(ret, path)
2392 }
2393 }
2394 if len(ret) == 0 {
2395 return nil
2396 }
2397 return ret
2398}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002399
2400var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2401 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2402 regexp.MustCompile("^hardware/google/"),
2403 regexp.MustCompile("^hardware/interfaces/"),
2404 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2405 regexp.MustCompile("^hardware/ril/"),
2406}
2407
2408func IsThirdPartyPath(path string) bool {
2409 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2410
2411 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2412 for _, prefix := range thirdPartyDirPrefixExceptions {
2413 if prefix.MatchString(path) {
2414 return false
2415 }
2416 }
2417 return true
2418 }
2419 return false
2420}