blob: 39b660cce6e9d41eb7ec3257a9e9dc8870965cd0 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Colin Cross6e18ca42015-07-14 18:55:36 -070018 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000019 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070020 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070021 "reflect"
Chris Wailesb2703ad2021-07-30 13:25:42 -070022 "regexp"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070023 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070024 "strings"
25
26 "github.com/google/blueprint"
Colin Cross0e446152021-05-03 13:35:32 -070027 "github.com/google/blueprint/bootstrap"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070028 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080029)
30
Colin Cross988414c2020-01-11 01:11:46 +000031var absSrcDir string
32
Dan Willemsen34cc69e2015-09-23 15:26:20 -070033// PathContext is the subset of a (Module|Singleton)Context required by the
34// Path methods.
35type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080036 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080037 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080038}
39
Colin Cross7f19f372016-11-01 11:10:25 -070040type PathGlobContext interface {
Colin Cross662d6142022-11-03 20:38:01 -070041 PathContext
Colin Cross7f19f372016-11-01 11:10:25 -070042 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
43}
44
Colin Crossaabf6792017-11-29 00:27:14 -080045var _ PathContext = SingletonContext(nil)
46var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070047
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010048// "Null" path context is a minimal path context for a given config.
49type NullPathContext struct {
50 config Config
51}
52
53func (NullPathContext) AddNinjaFileDeps(...string) {}
54func (ctx NullPathContext) Config() Config { return ctx.config }
55
Liz Kammera830f3a2020-11-10 10:50:34 -080056// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
57// Path methods. These path methods can be called before any mutators have run.
58type EarlyModulePathContext interface {
Liz Kammera830f3a2020-11-10 10:50:34 -080059 PathGlobContext
60
61 ModuleDir() string
62 ModuleErrorf(fmt string, args ...interface{})
63}
64
65var _ EarlyModulePathContext = ModuleContext(nil)
66
67// Glob globs files and directories matching globPattern relative to ModuleDir(),
68// paths in the excludes parameter will be omitted.
69func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
70 ret, err := ctx.GlobWithDeps(globPattern, excludes)
71 if err != nil {
72 ctx.ModuleErrorf("glob: %s", err.Error())
73 }
74 return pathsForModuleSrcFromFullPath(ctx, ret, true)
75}
76
77// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
78// Paths in the excludes parameter will be omitted.
79func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
80 ret, err := ctx.GlobWithDeps(globPattern, excludes)
81 if err != nil {
82 ctx.ModuleErrorf("glob: %s", err.Error())
83 }
84 return pathsForModuleSrcFromFullPath(ctx, ret, false)
85}
86
87// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
88// the Path methods that rely on module dependencies having been resolved.
89type ModuleWithDepsPathContext interface {
90 EarlyModulePathContext
Paul Duffin40131a32021-07-09 17:10:35 +010091 VisitDirectDepsBlueprint(visit func(blueprint.Module))
92 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Liz Kammera830f3a2020-11-10 10:50:34 -080093}
94
95// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
96// the Path methods that rely on module dependencies having been resolved and ability to report
97// missing dependency errors.
98type ModuleMissingDepsPathContext interface {
99 ModuleWithDepsPathContext
100 AddMissingDependencies(missingDeps []string)
101}
102
Dan Willemsen00269f22017-07-06 16:59:48 -0700103type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700104 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700105
106 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700107 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700108 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800109 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700110 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900111 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900112 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700113 InstallInRoot() bool
Colin Crossea30d852023-11-29 16:00:16 -0800114 InstallInOdm() bool
115 InstallInProduct() bool
116 InstallInVendor() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900117 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700118}
119
120var _ ModuleInstallPathContext = ModuleContext(nil)
121
Cole Faust11edf552023-10-13 11:32:14 -0700122type baseModuleContextToModuleInstallPathContext struct {
123 BaseModuleContext
124}
125
126func (ctx *baseModuleContextToModuleInstallPathContext) InstallInData() bool {
127 return ctx.Module().InstallInData()
128}
129
130func (ctx *baseModuleContextToModuleInstallPathContext) InstallInTestcases() bool {
131 return ctx.Module().InstallInTestcases()
132}
133
134func (ctx *baseModuleContextToModuleInstallPathContext) InstallInSanitizerDir() bool {
135 return ctx.Module().InstallInSanitizerDir()
136}
137
138func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRamdisk() bool {
139 return ctx.Module().InstallInRamdisk()
140}
141
142func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendorRamdisk() bool {
143 return ctx.Module().InstallInVendorRamdisk()
144}
145
146func (ctx *baseModuleContextToModuleInstallPathContext) InstallInDebugRamdisk() bool {
147 return ctx.Module().InstallInDebugRamdisk()
148}
149
150func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRecovery() bool {
151 return ctx.Module().InstallInRecovery()
152}
153
154func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRoot() bool {
155 return ctx.Module().InstallInRoot()
156}
157
Colin Crossea30d852023-11-29 16:00:16 -0800158func (ctx *baseModuleContextToModuleInstallPathContext) InstallInOdm() bool {
159 return ctx.Module().InstallInOdm()
160}
161
162func (ctx *baseModuleContextToModuleInstallPathContext) InstallInProduct() bool {
163 return ctx.Module().InstallInProduct()
164}
165
166func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendor() bool {
167 return ctx.Module().InstallInVendor()
168}
169
Cole Faust11edf552023-10-13 11:32:14 -0700170func (ctx *baseModuleContextToModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
171 return ctx.Module().InstallForceOS()
172}
173
174var _ ModuleInstallPathContext = (*baseModuleContextToModuleInstallPathContext)(nil)
175
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700176// errorfContext is the interface containing the Errorf method matching the
177// Errorf method in blueprint.SingletonContext.
178type errorfContext interface {
179 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800180}
181
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700182var _ errorfContext = blueprint.SingletonContext(nil)
183
Spandan Das59a4a2b2024-01-09 21:35:56 +0000184// ModuleErrorfContext is the interface containing the ModuleErrorf method matching
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700185// the ModuleErrorf method in blueprint.ModuleContext.
Spandan Das59a4a2b2024-01-09 21:35:56 +0000186type ModuleErrorfContext interface {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700187 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800188}
189
Spandan Das59a4a2b2024-01-09 21:35:56 +0000190var _ ModuleErrorfContext = blueprint.ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700191
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700192// reportPathError will register an error with the attached context. It
193// attempts ctx.ModuleErrorf for a better error message first, then falls
194// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800195func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100196 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800197}
198
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100199// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800200// attempts ctx.ModuleErrorf for a better error message first, then falls
201// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100202func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Spandan Das59a4a2b2024-01-09 21:35:56 +0000203 if mctx, ok := ctx.(ModuleErrorfContext); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700204 mctx.ModuleErrorf(format, args...)
205 } else if ectx, ok := ctx.(errorfContext); ok {
206 ectx.Errorf(format, args...)
207 } else {
208 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700209 }
210}
211
Colin Cross5e708052019-08-06 13:59:50 -0700212func pathContextName(ctx PathContext, module blueprint.Module) string {
213 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
214 return x.ModuleName(module)
215 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
216 return x.OtherModuleName(module)
217 }
218 return "unknown"
219}
220
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700221type Path interface {
222 // Returns the path in string form
223 String() string
224
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700225 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700226 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700227
228 // Base returns the last element of the path
229 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800230
231 // Rel returns the portion of the path relative to the directory it was created from. For
232 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800233 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800234 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000235
236 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
237 //
238 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
239 // InstallPath then the returned value can be converted to an InstallPath.
240 //
241 // A standard build has the following structure:
242 // ../top/
243 // out/ - make install files go here.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200244 // out/soong - this is the soongOutDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000245 // ... - the source files
246 //
247 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200248 // * Make install paths, which have the pattern "soongOutDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000249 // relative path "out/<path>"
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200250 // * Soong install paths and other writable paths, which have the pattern "soongOutDir/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000251 // converted into the top relative path "out/soong/<path>".
252 // * Source paths are already relative to the top.
253 // * Phony paths are not relative to anything.
254 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
255 // order to test.
256 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700257}
258
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000259const (
260 OutDir = "out"
261 OutSoongDir = OutDir + "/soong"
262)
263
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700264// WritablePath is a type of path that can be used as an output for build rules.
265type WritablePath interface {
266 Path
267
Paul Duffin9b478b02019-12-10 13:41:51 +0000268 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200269 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000270
Jeff Gaston734e3802017-04-10 15:47:24 -0700271 // the writablePath method doesn't directly do anything,
272 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700273 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100274
275 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700276}
277
278type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800279 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
yangbill6d032dd2024-04-18 03:05:49 +0000280 genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700281}
282type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800283 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700284}
285type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800286 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700287}
288
289// GenPathWithExt derives a new file path in ctx's generated sources directory
290// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800291func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700292 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700293 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700294 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100295 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700296 return PathForModuleGen(ctx)
297}
298
yangbill6d032dd2024-04-18 03:05:49 +0000299// GenPathWithExtAndTrimExt derives a new file path in ctx's generated sources directory
300// from the current path, but with the new extension and trim the suffix.
301func GenPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir string, p Path, ext string, trimExt string) ModuleGenPath {
302 if path, ok := p.(genPathProvider); ok {
303 return path.genPathWithExtAndTrimExt(ctx, subdir, ext, trimExt)
304 }
305 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
306 return PathForModuleGen(ctx)
307}
308
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700309// ObjPathWithExt derives a new file path in ctx's object directory from the
310// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800311func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700312 if path, ok := p.(objPathProvider); ok {
313 return path.objPathWithExt(ctx, subdir, ext)
314 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100315 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700316 return PathForModuleObj(ctx)
317}
318
319// ResPathWithName derives a new path in ctx's output resource directory, using
320// the current path to create the directory name, and the `name` argument for
321// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800322func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700323 if path, ok := p.(resPathProvider); ok {
324 return path.resPathWithName(ctx, name)
325 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100326 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700327 return PathForModuleRes(ctx)
328}
329
330// OptionalPath is a container that may or may not contain a valid Path.
331type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100332 path Path // nil if invalid.
333 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700334}
335
336// OptionalPathForPath returns an OptionalPath containing the path.
337func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100338 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700339}
340
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100341// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
342func InvalidOptionalPath(reason string) OptionalPath {
343
344 return OptionalPath{invalidReason: reason}
345}
346
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700347// Valid returns whether there is a valid path
348func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100349 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700350}
351
352// Path returns the Path embedded in this OptionalPath. You must be sure that
353// there is a valid path, since this method will panic if there is not.
354func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100355 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100356 msg := "Requesting an invalid path"
357 if p.invalidReason != "" {
358 msg += ": " + p.invalidReason
359 }
360 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700361 }
362 return p.path
363}
364
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100365// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
366func (p OptionalPath) InvalidReason() string {
367 if p.path != nil {
368 return ""
369 }
370 if p.invalidReason == "" {
371 return "unknown"
372 }
373 return p.invalidReason
374}
375
Paul Duffinef081852021-05-13 11:11:15 +0100376// AsPaths converts the OptionalPath into Paths.
377//
378// It returns nil if this is not valid, or a single length slice containing the Path embedded in
379// this OptionalPath.
380func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100381 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100382 return nil
383 }
384 return Paths{p.path}
385}
386
Paul Duffinafdd4062021-03-30 19:44:07 +0100387// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
388// result of calling Path.RelativeToTop on it.
389func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100390 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100391 return p
392 }
393 p.path = p.path.RelativeToTop()
394 return p
395}
396
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700397// String returns the string version of the Path, or "" if it isn't valid.
398func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100399 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700400 return p.path.String()
401 } else {
402 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700403 }
404}
Colin Cross6e18ca42015-07-14 18:55:36 -0700405
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700406// Paths is a slice of Path objects, with helpers to operate on the collection.
407type Paths []Path
408
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000409// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
410// item in this slice.
411func (p Paths) RelativeToTop() Paths {
412 ensureTestOnly()
413 if p == nil {
414 return p
415 }
416 ret := make(Paths, len(p))
417 for i, path := range p {
418 ret[i] = path.RelativeToTop()
419 }
420 return ret
421}
422
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000423func (paths Paths) containsPath(path Path) bool {
424 for _, p := range paths {
425 if p == path {
426 return true
427 }
428 }
429 return false
430}
431
Liz Kammer7aa52882021-02-11 09:16:14 -0500432// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
433// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700434func PathsForSource(ctx PathContext, paths []string) Paths {
435 ret := make(Paths, len(paths))
436 for i, path := range paths {
437 ret[i] = PathForSource(ctx, path)
438 }
439 return ret
440}
441
Liz Kammer7aa52882021-02-11 09:16:14 -0500442// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
443// module's local source directory, that are found in the tree. If any are not found, they are
444// 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 -0700445func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800446 ret := make(Paths, 0, len(paths))
447 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800448 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800449 if p.Valid() {
450 ret = append(ret, p.Path())
451 }
452 }
453 return ret
454}
455
Liz Kammer620dea62021-04-14 17:36:10 -0400456// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700457// - filepath, relative to local module directory, resolves as a filepath relative to the local
458// source directory
459// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
460// source directory.
461// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
462// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
463// filepath.
464//
Liz Kammer620dea62021-04-14 17:36:10 -0400465// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700466// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000467// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400468// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700469// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400470// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700471// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800472func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800473 return PathsForModuleSrcExcludes(ctx, paths, nil)
474}
475
Liz Kammer619be462022-01-28 15:13:39 -0500476type SourceInput struct {
477 Context ModuleMissingDepsPathContext
478 Paths []string
479 ExcludePaths []string
480 IncludeDirs bool
481}
482
Liz Kammer620dea62021-04-14 17:36:10 -0400483// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
484// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700485// - filepath, relative to local module directory, resolves as a filepath relative to the local
486// source directory
487// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
488// source directory. Not valid in excludes.
489// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
490// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
491// filepath.
492//
Liz Kammer620dea62021-04-14 17:36:10 -0400493// excluding the items (similarly resolved
494// Properties passed as the paths argument must have been annotated with struct tag
495// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000496// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400497// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700498// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400499// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700500// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800501func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500502 return PathsRelativeToModuleSourceDir(SourceInput{
503 Context: ctx,
504 Paths: paths,
505 ExcludePaths: excludes,
506 IncludeDirs: true,
507 })
508}
509
510func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
511 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
512 if input.Context.Config().AllowMissingDependencies() {
513 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700514 } else {
515 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500516 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700517 }
518 }
519 return ret
520}
521
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000522// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
523type OutputPaths []OutputPath
524
525// Paths returns the OutputPaths as a Paths
526func (p OutputPaths) Paths() Paths {
527 if p == nil {
528 return nil
529 }
530 ret := make(Paths, len(p))
531 for i, path := range p {
532 ret[i] = path
533 }
534 return ret
535}
536
537// Strings returns the string forms of the writable paths.
538func (p OutputPaths) Strings() []string {
539 if p == nil {
540 return nil
541 }
542 ret := make([]string, len(p))
543 for i, path := range p {
544 ret[i] = path.String()
545 }
546 return ret
547}
548
Colin Crossa44551f2021-10-25 15:36:21 -0700549// PathForGoBinary returns the path to the installed location of a bootstrap_go_binary module.
550func PathForGoBinary(ctx PathContext, goBinary bootstrap.GoBinaryTool) Path {
Cole Faust3b703f32023-10-16 13:30:51 -0700551 goBinaryInstallDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "bin")
Colin Crossa44551f2021-10-25 15:36:21 -0700552 rel := Rel(ctx, goBinaryInstallDir.String(), goBinary.InstallPath())
553 return goBinaryInstallDir.Join(ctx, rel)
554}
555
Liz Kammera830f3a2020-11-10 10:50:34 -0800556// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
557// If the dependency is not found, a missingErrorDependency is returned.
558// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
559func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100560 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800561 if module == nil {
562 return nil, missingDependencyError{[]string{moduleName}}
563 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700564 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
565 return nil, missingDependencyError{[]string{moduleName}}
566 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800567 if outProducer, ok := module.(OutputFileProducer); ok {
568 outputFiles, err := outProducer.OutputFiles(tag)
569 if err != nil {
570 return nil, fmt.Errorf("path dependency %q: %s", path, err)
571 }
572 return outputFiles, nil
573 } else if tag != "" {
574 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
Colin Cross0e446152021-05-03 13:35:32 -0700575 } else if goBinary, ok := module.(bootstrap.GoBinaryTool); ok {
Colin Crossa44551f2021-10-25 15:36:21 -0700576 goBinaryPath := PathForGoBinary(ctx, goBinary)
577 return Paths{goBinaryPath}, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800578 } else if srcProducer, ok := module.(SourceFileProducer); ok {
579 return srcProducer.Srcs(), nil
580 } else {
581 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
582 }
583}
584
Paul Duffind5cf92e2021-07-09 17:38:55 +0100585// GetModuleFromPathDep will return the module that was added as a dependency automatically for
586// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
587// ExtractSourcesDeps.
588//
589// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
590// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
591// the tag must be "".
592//
593// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
594// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100595func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100596 var found blueprint.Module
597 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
598 // module name and the tag. Dependencies added automatically for properties tagged with
599 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
600 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
601 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
602 // moduleName referring to the same dependency module.
603 //
604 // It does not matter whether the moduleName is a fully qualified name or if the module
605 // dependency is a prebuilt module. All that matters is the same information is supplied to
606 // create the tag here as was supplied to create the tag when the dependency was added so that
607 // this finds the matching dependency module.
608 expectedTag := sourceOrOutputDepTag(moduleName, tag)
609 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
610 depTag := ctx.OtherModuleDependencyTag(module)
611 if depTag == expectedTag {
612 found = module
613 }
614 })
615 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100616}
617
Liz Kammer620dea62021-04-14 17:36:10 -0400618// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
619// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700620// - filepath, relative to local module directory, resolves as a filepath relative to the local
621// source directory
622// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
623// source directory. Not valid in excludes.
624// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
625// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
626// filepath.
627//
Liz Kammer620dea62021-04-14 17:36:10 -0400628// and a list of the module names of missing module dependencies are returned as the second return.
629// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700630// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000631// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500632func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
633 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
634 Context: ctx,
635 Paths: paths,
636 ExcludePaths: excludes,
637 IncludeDirs: true,
638 })
639}
640
641func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
642 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800643
644 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500645 if input.ExcludePaths != nil {
646 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700647 }
Colin Cross8a497952019-03-05 22:25:09 -0800648
Colin Crossba71a3f2019-03-18 12:12:48 -0700649 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500650 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700651 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500652 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800653 if m, ok := err.(missingDependencyError); ok {
654 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
655 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500656 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800657 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800658 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800659 }
660 } else {
661 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
662 }
663 }
664
Liz Kammer619be462022-01-28 15:13:39 -0500665 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700666 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800667 }
668
Colin Crossba71a3f2019-03-18 12:12:48 -0700669 var missingDeps []string
670
Liz Kammer619be462022-01-28 15:13:39 -0500671 expandedSrcFiles := make(Paths, 0, len(input.Paths))
672 for _, s := range input.Paths {
673 srcFiles, err := expandOneSrcPath(sourcePathInput{
674 context: input.Context,
675 path: s,
676 expandedExcludes: expandedExcludes,
677 includeDirs: input.IncludeDirs,
678 })
Colin Cross8a497952019-03-05 22:25:09 -0800679 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700680 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800681 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500682 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800683 }
684 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
685 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700686
Jihoon Kang0e3a5352024-04-12 00:45:50 +0000687 // TODO: b/334169722 - Replace with an error instead of implicitly removing duplicates.
688 return FirstUniquePaths(expandedSrcFiles), append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800689}
690
691type missingDependencyError struct {
692 missingDeps []string
693}
694
695func (e missingDependencyError) Error() string {
696 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
697}
698
Liz Kammer619be462022-01-28 15:13:39 -0500699type sourcePathInput struct {
700 context ModuleWithDepsPathContext
701 path string
702 expandedExcludes []string
703 includeDirs bool
704}
705
Liz Kammera830f3a2020-11-10 10:50:34 -0800706// Expands one path string to Paths rooted from the module's local source
707// directory, excluding those listed in the expandedExcludes.
708// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500709func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900710 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500711 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900712 return paths
713 }
714 remainder := make(Paths, 0, len(paths))
715 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500716 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900717 remainder = append(remainder, p)
718 }
719 }
720 return remainder
721 }
Liz Kammer619be462022-01-28 15:13:39 -0500722 if m, t := SrcIsModuleWithTag(input.path); m != "" {
723 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800724 if err != nil {
725 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800726 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800727 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800728 }
Colin Cross8a497952019-03-05 22:25:09 -0800729 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500730 p := pathForModuleSrc(input.context, input.path)
731 if pathtools.IsGlob(input.path) {
732 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
733 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
734 } else {
735 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
736 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
737 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
738 ReportPathErrorf(input.context, "module source path %q does not exist", p)
739 } else if !input.includeDirs {
740 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
741 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
742 } else if isDir {
743 ReportPathErrorf(input.context, "module source path %q is a directory", p)
744 }
745 }
Colin Cross8a497952019-03-05 22:25:09 -0800746
Liz Kammer619be462022-01-28 15:13:39 -0500747 if InList(p.String(), input.expandedExcludes) {
748 return nil, nil
749 }
750 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800751 }
Colin Cross8a497952019-03-05 22:25:09 -0800752 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700753}
754
755// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
756// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800757// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700758// It intended for use in globs that only list files that exist, so it allows '$' in
759// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800760func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200761 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700762 if prefix == "./" {
763 prefix = ""
764 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700765 ret := make(Paths, 0, len(paths))
766 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800767 if !incDirs && strings.HasSuffix(p, "/") {
768 continue
769 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700770 path := filepath.Clean(p)
771 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100772 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700773 continue
774 }
Colin Crosse3924e12018-08-15 20:18:53 -0700775
Colin Crossfe4bc362018-09-12 10:02:13 -0700776 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700777 if err != nil {
778 reportPathError(ctx, err)
779 continue
780 }
781
Colin Cross07e51612019-03-05 12:46:40 -0800782 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700783
Colin Cross07e51612019-03-05 12:46:40 -0800784 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700785 }
786 return ret
787}
788
Liz Kammera830f3a2020-11-10 10:50:34 -0800789// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
790// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
791func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800792 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700793 return PathsForModuleSrc(ctx, input)
794 }
795 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
796 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200797 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800798 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700799}
800
801// Strings returns the Paths in string form
802func (p Paths) Strings() []string {
803 if p == nil {
804 return nil
805 }
806 ret := make([]string, len(p))
807 for i, path := range p {
808 ret[i] = path.String()
809 }
810 return ret
811}
812
Colin Crossc0efd1d2020-07-03 11:56:24 -0700813func CopyOfPaths(paths Paths) Paths {
814 return append(Paths(nil), paths...)
815}
816
Colin Crossb6715442017-10-24 11:13:31 -0700817// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
818// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700819func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800820 // 128 was chosen based on BenchmarkFirstUniquePaths results.
821 if len(list) > 128 {
822 return firstUniquePathsMap(list)
823 }
824 return firstUniquePathsList(list)
825}
826
Colin Crossc0efd1d2020-07-03 11:56:24 -0700827// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
828// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900829func SortedUniquePaths(list Paths) Paths {
830 unique := FirstUniquePaths(list)
831 sort.Slice(unique, func(i, j int) bool {
832 return unique[i].String() < unique[j].String()
833 })
834 return unique
835}
836
Colin Cross27027c72020-02-28 15:34:17 -0800837func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700838 k := 0
839outer:
840 for i := 0; i < len(list); i++ {
841 for j := 0; j < k; j++ {
842 if list[i] == list[j] {
843 continue outer
844 }
845 }
846 list[k] = list[i]
847 k++
848 }
849 return list[:k]
850}
851
Colin Cross27027c72020-02-28 15:34:17 -0800852func firstUniquePathsMap(list Paths) Paths {
853 k := 0
854 seen := make(map[Path]bool, len(list))
855 for i := 0; i < len(list); i++ {
856 if seen[list[i]] {
857 continue
858 }
859 seen[list[i]] = true
860 list[k] = list[i]
861 k++
862 }
863 return list[:k]
864}
865
Colin Cross5d583952020-11-24 16:21:24 -0800866// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
867// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
868func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
869 // 128 was chosen based on BenchmarkFirstUniquePaths results.
870 if len(list) > 128 {
871 return firstUniqueInstallPathsMap(list)
872 }
873 return firstUniqueInstallPathsList(list)
874}
875
876func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
877 k := 0
878outer:
879 for i := 0; i < len(list); i++ {
880 for j := 0; j < k; j++ {
881 if list[i] == list[j] {
882 continue outer
883 }
884 }
885 list[k] = list[i]
886 k++
887 }
888 return list[:k]
889}
890
891func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
892 k := 0
893 seen := make(map[InstallPath]bool, len(list))
894 for i := 0; i < len(list); i++ {
895 if seen[list[i]] {
896 continue
897 }
898 seen[list[i]] = true
899 list[k] = list[i]
900 k++
901 }
902 return list[:k]
903}
904
Colin Crossb6715442017-10-24 11:13:31 -0700905// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
906// modifies the Paths slice contents in place, and returns a subslice of the original slice.
907func LastUniquePaths(list Paths) Paths {
908 totalSkip := 0
909 for i := len(list) - 1; i >= totalSkip; i-- {
910 skip := 0
911 for j := i - 1; j >= totalSkip; j-- {
912 if list[i] == list[j] {
913 skip++
914 } else {
915 list[j+skip] = list[j]
916 }
917 }
918 totalSkip += skip
919 }
920 return list[totalSkip:]
921}
922
Colin Crossa140bb02018-04-17 10:52:26 -0700923// ReversePaths returns a copy of a Paths in reverse order.
924func ReversePaths(list Paths) Paths {
925 if list == nil {
926 return nil
927 }
928 ret := make(Paths, len(list))
929 for i := range list {
930 ret[i] = list[len(list)-1-i]
931 }
932 return ret
933}
934
Jeff Gaston294356f2017-09-27 17:05:30 -0700935func indexPathList(s Path, list []Path) int {
936 for i, l := range list {
937 if l == s {
938 return i
939 }
940 }
941
942 return -1
943}
944
945func inPathList(p Path, list []Path) bool {
946 return indexPathList(p, list) != -1
947}
948
949func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000950 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
951}
952
953func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700954 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000955 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700956 filtered = append(filtered, l)
957 } else {
958 remainder = append(remainder, l)
959 }
960 }
961
962 return
963}
964
Colin Cross93e85952017-08-15 13:34:18 -0700965// HasExt returns true of any of the paths have extension ext, otherwise false
966func (p Paths) HasExt(ext string) bool {
967 for _, path := range p {
968 if path.Ext() == ext {
969 return true
970 }
971 }
972
973 return false
974}
975
976// FilterByExt returns the subset of the paths that have extension ext
977func (p Paths) FilterByExt(ext string) Paths {
978 ret := make(Paths, 0, len(p))
979 for _, path := range p {
980 if path.Ext() == ext {
981 ret = append(ret, path)
982 }
983 }
984 return ret
985}
986
987// FilterOutByExt returns the subset of the paths that do not have extension ext
988func (p Paths) FilterOutByExt(ext string) Paths {
989 ret := make(Paths, 0, len(p))
990 for _, path := range p {
991 if path.Ext() != ext {
992 ret = append(ret, path)
993 }
994 }
995 return ret
996}
997
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700998// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
999// (including subdirectories) are in a contiguous subslice of the list, and can be found in
1000// O(log(N)) time using a binary search on the directory prefix.
1001type DirectorySortedPaths Paths
1002
1003func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
1004 ret := append(DirectorySortedPaths(nil), paths...)
1005 sort.Slice(ret, func(i, j int) bool {
1006 return ret[i].String() < ret[j].String()
1007 })
1008 return ret
1009}
1010
1011// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1012// that are in the specified directory and its subdirectories.
1013func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1014 prefix := filepath.Clean(dir) + "/"
1015 start := sort.Search(len(p), func(i int) bool {
1016 return prefix < p[i].String()
1017 })
1018
1019 ret := p[start:]
1020
1021 end := sort.Search(len(ret), func(i int) bool {
1022 return !strings.HasPrefix(ret[i].String(), prefix)
1023 })
1024
1025 ret = ret[:end]
1026
1027 return Paths(ret)
1028}
1029
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001030// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001031type WritablePaths []WritablePath
1032
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001033// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1034// each item in this slice.
1035func (p WritablePaths) RelativeToTop() WritablePaths {
1036 ensureTestOnly()
1037 if p == nil {
1038 return p
1039 }
1040 ret := make(WritablePaths, len(p))
1041 for i, path := range p {
1042 ret[i] = path.RelativeToTop().(WritablePath)
1043 }
1044 return ret
1045}
1046
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001047// Strings returns the string forms of the writable paths.
1048func (p WritablePaths) Strings() []string {
1049 if p == nil {
1050 return nil
1051 }
1052 ret := make([]string, len(p))
1053 for i, path := range p {
1054 ret[i] = path.String()
1055 }
1056 return ret
1057}
1058
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001059// Paths returns the WritablePaths as a Paths
1060func (p WritablePaths) Paths() Paths {
1061 if p == nil {
1062 return nil
1063 }
1064 ret := make(Paths, len(p))
1065 for i, path := range p {
1066 ret[i] = path
1067 }
1068 return ret
1069}
1070
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001071type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001072 path string
1073 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001074}
1075
1076func (p basePath) Ext() string {
1077 return filepath.Ext(p.path)
1078}
1079
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001080func (p basePath) Base() string {
1081 return filepath.Base(p.path)
1082}
1083
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001084func (p basePath) Rel() string {
1085 if p.rel != "" {
1086 return p.rel
1087 }
1088 return p.path
1089}
1090
Colin Cross0875c522017-11-28 17:34:01 -08001091func (p basePath) String() string {
1092 return p.path
1093}
1094
Colin Cross0db55682017-12-05 15:36:55 -08001095func (p basePath) withRel(rel string) basePath {
1096 p.path = filepath.Join(p.path, rel)
1097 p.rel = rel
1098 return p
1099}
1100
Cole Faustbc65a3f2023-08-01 16:38:55 +00001101func (p basePath) RelativeToTop() Path {
1102 ensureTestOnly()
1103 return p
1104}
1105
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001106// SourcePath is a Path representing a file path rooted from SrcDir
1107type SourcePath struct {
1108 basePath
1109}
1110
1111var _ Path = SourcePath{}
1112
Colin Cross0db55682017-12-05 15:36:55 -08001113func (p SourcePath) withRel(rel string) SourcePath {
1114 p.basePath = p.basePath.withRel(rel)
1115 return p
1116}
1117
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001118// safePathForSource is for paths that we expect are safe -- only for use by go
1119// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001120func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1121 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001122 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001123 if err != nil {
1124 return ret, err
1125 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001126
Colin Cross7b3dcc32019-01-24 13:14:39 -08001127 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001128 // special-case api surface gen files for now
1129 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001130 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001131 }
1132
Colin Crossfe4bc362018-09-12 10:02:13 -07001133 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001134}
1135
Colin Cross192e97a2018-02-22 14:21:02 -08001136// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1137func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001138 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001139 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001140 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001141 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001142 }
1143
Colin Cross7b3dcc32019-01-24 13:14:39 -08001144 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001145 // special-case for now
1146 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001147 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001148 }
1149
Colin Cross192e97a2018-02-22 14:21:02 -08001150 return ret, nil
1151}
1152
1153// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1154// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001155func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001156 var files []string
1157
Colin Cross662d6142022-11-03 20:38:01 -07001158 // Use glob to produce proper dependencies, even though we only want
1159 // a single file.
1160 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001161
1162 if err != nil {
1163 return false, fmt.Errorf("glob: %s", err.Error())
1164 }
1165
1166 return len(files) > 0, nil
1167}
1168
1169// PathForSource joins the provided path components and validates that the result
1170// neither escapes the source dir nor is in the out dir.
1171// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1172func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1173 path, err := pathForSource(ctx, pathComponents...)
1174 if err != nil {
1175 reportPathError(ctx, err)
1176 }
1177
Colin Crosse3924e12018-08-15 20:18:53 -07001178 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001179 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001180 }
1181
Liz Kammera830f3a2020-11-10 10:50:34 -08001182 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001183 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001184 if err != nil {
1185 reportPathError(ctx, err)
1186 }
1187 if !exists {
1188 modCtx.AddMissingDependencies([]string{path.String()})
1189 }
Colin Cross988414c2020-01-11 01:11:46 +00001190 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001191 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001192 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001193 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001194 }
1195 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001196}
1197
Cole Faustbc65a3f2023-08-01 16:38:55 +00001198// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1199// the path is relative to the root of the output folder, not the out/soong folder.
1200func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
1201 p, err := validatePath(pathComponents...)
1202 if err != nil {
1203 reportPathError(ctx, err)
1204 }
1205 return basePath{path: filepath.Join(ctx.Config().OutDir(), p)}
1206}
1207
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001208// MaybeExistentPathForSource joins the provided path components and validates that the result
1209// neither escapes the source dir nor is in the out dir.
1210// It does not validate whether the path exists.
1211func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1212 path, err := pathForSource(ctx, pathComponents...)
1213 if err != nil {
1214 reportPathError(ctx, err)
1215 }
1216
1217 if pathtools.IsGlob(path.String()) {
1218 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1219 }
1220 return path
1221}
1222
Liz Kammer7aa52882021-02-11 09:16:14 -05001223// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1224// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1225// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1226// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001227func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001228 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001229 if err != nil {
1230 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001231 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001232 return OptionalPath{}
1233 }
Colin Crossc48c1432018-02-23 07:09:01 +00001234
Colin Crosse3924e12018-08-15 20:18:53 -07001235 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001236 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001237 return OptionalPath{}
1238 }
1239
Colin Cross192e97a2018-02-22 14:21:02 -08001240 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001241 if err != nil {
1242 reportPathError(ctx, err)
1243 return OptionalPath{}
1244 }
Colin Cross192e97a2018-02-22 14:21:02 -08001245 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001246 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001247 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001248 return OptionalPathForPath(path)
1249}
1250
1251func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001252 if p.path == "" {
1253 return "."
1254 }
1255 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001256}
1257
1258// Join creates a new SourcePath with paths... joined with the current path. The
1259// provided paths... may not use '..' to escape from the current path.
1260func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001261 path, err := validatePath(paths...)
1262 if err != nil {
1263 reportPathError(ctx, err)
1264 }
Colin Cross0db55682017-12-05 15:36:55 -08001265 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001266}
1267
Colin Cross2fafa3e2019-03-05 12:39:51 -08001268// join is like Join but does less path validation.
1269func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1270 path, err := validateSafePath(paths...)
1271 if err != nil {
1272 reportPathError(ctx, err)
1273 }
1274 return p.withRel(path)
1275}
1276
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001277// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1278// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001279func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001280 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001281 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001282 relDir = srcPath.path
1283 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001284 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001285 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001286 return OptionalPath{}
1287 }
Cole Faust483d1f72023-01-09 14:35:27 -08001288 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001289 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001290 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001291 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001292 }
Colin Cross461b4452018-02-23 09:22:42 -08001293 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001294 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001295 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001296 return OptionalPath{}
1297 }
1298 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001299 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001300 }
Cole Faust483d1f72023-01-09 14:35:27 -08001301 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001302}
1303
Colin Cross70dda7e2019-10-01 22:05:35 -07001304// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001305type OutputPath struct {
1306 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001307
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001308 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001309 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001310
Colin Crossd63c9a72020-01-29 16:52:50 -08001311 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001312}
1313
Colin Cross702e0f82017-10-18 17:27:54 -07001314func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001315 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001316 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001317 return p
1318}
1319
Colin Cross3063b782018-08-15 11:19:12 -07001320func (p OutputPath) WithoutRel() OutputPath {
1321 p.basePath.rel = filepath.Base(p.basePath.path)
1322 return p
1323}
1324
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001325func (p OutputPath) getSoongOutDir() string {
1326 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001327}
1328
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001329func (p OutputPath) RelativeToTop() Path {
1330 return p.outputPathRelativeToTop()
1331}
1332
1333func (p OutputPath) outputPathRelativeToTop() OutputPath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001334 p.fullPath = StringPathRelativeToTop(p.soongOutDir, p.fullPath)
1335 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001336 return p
1337}
1338
Paul Duffin0267d492021-02-02 10:05:52 +00001339func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1340 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1341}
1342
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001343var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001344var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001345var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001346
Chris Parsons8f232a22020-06-23 17:37:05 -04001347// toolDepPath is a Path representing a dependency of the build tool.
1348type toolDepPath struct {
1349 basePath
1350}
1351
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001352func (t toolDepPath) RelativeToTop() Path {
1353 ensureTestOnly()
1354 return t
1355}
1356
Chris Parsons8f232a22020-06-23 17:37:05 -04001357var _ Path = toolDepPath{}
1358
1359// pathForBuildToolDep returns a toolDepPath representing the given path string.
1360// There is no validation for the path, as it is "trusted": It may fail
1361// normal validation checks. For example, it may be an absolute path.
1362// Only use this function to construct paths for dependencies of the build
1363// tool invocation.
1364func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001365 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001366}
1367
Jeff Gaston734e3802017-04-10 15:47:24 -07001368// PathForOutput joins the provided paths and returns an OutputPath that is
1369// validated to not escape the build dir.
1370// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1371func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001372 path, err := validatePath(pathComponents...)
1373 if err != nil {
1374 reportPathError(ctx, err)
1375 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001376 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001377 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001378 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001379}
1380
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001381// PathsForOutput returns Paths rooted from soongOutDir
Colin Cross40e33732019-02-15 11:08:35 -08001382func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1383 ret := make(WritablePaths, len(paths))
1384 for i, path := range paths {
1385 ret[i] = PathForOutput(ctx, path)
1386 }
1387 return ret
1388}
1389
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001390func (p OutputPath) writablePath() {}
1391
1392func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001393 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001394}
1395
1396// Join creates a new OutputPath with paths... joined with the current path. The
1397// provided paths... may not use '..' to escape from the current path.
1398func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001399 path, err := validatePath(paths...)
1400 if err != nil {
1401 reportPathError(ctx, err)
1402 }
Colin Cross0db55682017-12-05 15:36:55 -08001403 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001404}
1405
Colin Cross8854a5a2019-02-11 14:14:16 -08001406// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1407func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1408 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001409 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001410 }
1411 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001412 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001413 return ret
1414}
1415
Colin Cross40e33732019-02-15 11:08:35 -08001416// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1417func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1418 path, err := validatePath(paths...)
1419 if err != nil {
1420 reportPathError(ctx, err)
1421 }
1422
1423 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001424 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001425 return ret
1426}
1427
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001428// PathForIntermediates returns an OutputPath representing the top-level
1429// intermediates directory.
1430func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001431 path, err := validatePath(paths...)
1432 if err != nil {
1433 reportPathError(ctx, err)
1434 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001435 return PathForOutput(ctx, ".intermediates", path)
1436}
1437
Colin Cross07e51612019-03-05 12:46:40 -08001438var _ genPathProvider = SourcePath{}
1439var _ objPathProvider = SourcePath{}
1440var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001441
Colin Cross07e51612019-03-05 12:46:40 -08001442// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001443// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001444func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001445 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1446 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1447 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1448 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1449 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001450 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001451 if err != nil {
1452 if depErr, ok := err.(missingDependencyError); ok {
1453 if ctx.Config().AllowMissingDependencies() {
1454 ctx.AddMissingDependencies(depErr.missingDeps)
1455 } else {
1456 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1457 }
1458 } else {
1459 reportPathError(ctx, err)
1460 }
1461 return nil
1462 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001463 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001464 return nil
1465 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001466 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001467 }
1468 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001469}
1470
Liz Kammera830f3a2020-11-10 10:50:34 -08001471func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001472 p, err := validatePath(paths...)
1473 if err != nil {
1474 reportPathError(ctx, err)
1475 }
1476
1477 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1478 if err != nil {
1479 reportPathError(ctx, err)
1480 }
1481
1482 path.basePath.rel = p
1483
1484 return path
1485}
1486
Colin Cross2fafa3e2019-03-05 12:39:51 -08001487// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1488// will return the path relative to subDir in the module's source directory. If any input paths are not located
1489// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001490func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001491 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001492 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001493 for i, path := range paths {
1494 rel := Rel(ctx, subDirFullPath.String(), path.String())
1495 paths[i] = subDirFullPath.join(ctx, rel)
1496 }
1497 return paths
1498}
1499
1500// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1501// 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 -08001502func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001503 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001504 rel := Rel(ctx, subDirFullPath.String(), path.String())
1505 return subDirFullPath.Join(ctx, rel)
1506}
1507
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001508// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1509// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001510func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001511 if p == nil {
1512 return OptionalPath{}
1513 }
1514 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1515}
1516
Liz Kammera830f3a2020-11-10 10:50:34 -08001517func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001518 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001519}
1520
yangbill6d032dd2024-04-18 03:05:49 +00001521func (p SourcePath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1522 // If Trim_extension being set, force append Output_extension without replace original extension.
1523 if trimExt != "" {
1524 if ext != "" {
1525 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1526 }
1527 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1528 }
1529 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1530}
1531
Liz Kammera830f3a2020-11-10 10:50:34 -08001532func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001533 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001534}
1535
Liz Kammera830f3a2020-11-10 10:50:34 -08001536func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001537 // TODO: Use full directory if the new ctx is not the current ctx?
1538 return PathForModuleRes(ctx, p.path, name)
1539}
1540
1541// ModuleOutPath is a Path representing a module's output directory.
1542type ModuleOutPath struct {
1543 OutputPath
1544}
1545
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001546func (p ModuleOutPath) RelativeToTop() Path {
1547 p.OutputPath = p.outputPathRelativeToTop()
1548 return p
1549}
1550
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001551var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001552var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001553
Liz Kammera830f3a2020-11-10 10:50:34 -08001554func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001555 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1556}
1557
Liz Kammera830f3a2020-11-10 10:50:34 -08001558// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1559type ModuleOutPathContext interface {
1560 PathContext
1561
1562 ModuleName() string
1563 ModuleDir() string
1564 ModuleSubDir() string
Inseob Kim8ff69de2023-06-16 14:19:33 +09001565 SoongConfigTraceHash() string
Liz Kammera830f3a2020-11-10 10:50:34 -08001566}
1567
1568func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kim8ff69de2023-06-16 14:19:33 +09001569 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir(), ctx.SoongConfigTraceHash())
Colin Cross702e0f82017-10-18 17:27:54 -07001570}
1571
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001572// PathForModuleOut returns a Path representing the paths... under the module's
1573// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001574func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001575 p, err := validatePath(paths...)
1576 if err != nil {
1577 reportPathError(ctx, err)
1578 }
Colin Cross702e0f82017-10-18 17:27:54 -07001579 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001580 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001581 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001582}
1583
1584// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1585// directory. Mainly used for generated sources.
1586type ModuleGenPath struct {
1587 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001588}
1589
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001590func (p ModuleGenPath) RelativeToTop() Path {
1591 p.OutputPath = p.outputPathRelativeToTop()
1592 return p
1593}
1594
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001595var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001596var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001597var _ genPathProvider = ModuleGenPath{}
1598var _ objPathProvider = ModuleGenPath{}
1599
1600// PathForModuleGen returns a Path representing the paths... under the module's
1601// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001602func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001603 p, err := validatePath(paths...)
1604 if err != nil {
1605 reportPathError(ctx, err)
1606 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001607 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001608 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001609 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001610 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001611 }
1612}
1613
Liz Kammera830f3a2020-11-10 10:50:34 -08001614func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001615 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001616 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001617}
1618
yangbill6d032dd2024-04-18 03:05:49 +00001619func (p ModuleGenPath) genPathWithExtAndTrimExt(ctx ModuleOutPathContext, subdir, ext string, trimExt string) ModuleGenPath {
1620 // If Trim_extension being set, force append Output_extension without replace original extension.
1621 if trimExt != "" {
1622 if ext != "" {
1623 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt)+"."+ext)
1624 }
1625 return PathForModuleGen(ctx, subdir, strings.TrimSuffix(p.path, trimExt))
1626 }
1627 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1628}
1629
Liz Kammera830f3a2020-11-10 10:50:34 -08001630func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001631 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1632}
1633
1634// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1635// directory. Used for compiled objects.
1636type ModuleObjPath struct {
1637 ModuleOutPath
1638}
1639
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001640func (p ModuleObjPath) RelativeToTop() Path {
1641 p.OutputPath = p.outputPathRelativeToTop()
1642 return p
1643}
1644
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001645var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001646var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001647
1648// PathForModuleObj returns a Path representing the paths... under the module's
1649// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001650func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001651 p, err := validatePath(pathComponents...)
1652 if err != nil {
1653 reportPathError(ctx, err)
1654 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001655 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1656}
1657
1658// ModuleResPath is a a Path representing the 'res' directory in a module's
1659// output directory.
1660type ModuleResPath struct {
1661 ModuleOutPath
1662}
1663
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001664func (p ModuleResPath) RelativeToTop() Path {
1665 p.OutputPath = p.outputPathRelativeToTop()
1666 return p
1667}
1668
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001669var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001670var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001671
1672// PathForModuleRes returns a Path representing the paths... under the module's
1673// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001674func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001675 p, err := validatePath(pathComponents...)
1676 if err != nil {
1677 reportPathError(ctx, err)
1678 }
1679
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001680 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1681}
1682
Colin Cross70dda7e2019-10-01 22:05:35 -07001683// InstallPath is a Path representing a installed file path rooted from the build directory
1684type InstallPath struct {
1685 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001686
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001687 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001688 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001689
Jiyong Park957bcd92020-10-20 18:23:33 +09001690 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1691 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1692 partitionDir string
1693
Colin Crossb1692a32021-10-25 15:39:01 -07001694 partition string
1695
Jiyong Park957bcd92020-10-20 18:23:33 +09001696 // makePath indicates whether this path is for Soong (false) or Make (true).
1697 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001698
1699 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001700}
1701
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001702// Will panic if called from outside a test environment.
1703func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001704 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001705 return
1706 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001707 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001708}
1709
1710func (p InstallPath) RelativeToTop() Path {
1711 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001712 if p.makePath {
1713 p.soongOutDir = OutDir
1714 } else {
1715 p.soongOutDir = OutSoongDir
1716 }
1717 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001718 return p
1719}
1720
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001721func (p InstallPath) getSoongOutDir() string {
1722 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001723}
1724
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001725func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1726 panic("Not implemented")
1727}
1728
Paul Duffin9b478b02019-12-10 13:41:51 +00001729var _ Path = InstallPath{}
1730var _ WritablePath = InstallPath{}
1731
Colin Cross70dda7e2019-10-01 22:05:35 -07001732func (p InstallPath) writablePath() {}
1733
1734func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08001735 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09001736}
1737
1738// PartitionDir returns the path to the partition where the install path is rooted at. It is
1739// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1740// The ./soong is dropped if the install path is for Make.
1741func (p InstallPath) PartitionDir() string {
1742 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001743 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001744 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001745 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001746 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001747}
1748
Jihoon Kangf78a8902022-09-01 22:47:07 +00001749func (p InstallPath) Partition() string {
1750 return p.partition
1751}
1752
Colin Cross70dda7e2019-10-01 22:05:35 -07001753// Join creates a new InstallPath with paths... joined with the current path. The
1754// provided paths... may not use '..' to escape from the current path.
1755func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1756 path, err := validatePath(paths...)
1757 if err != nil {
1758 reportPathError(ctx, err)
1759 }
1760 return p.withRel(path)
1761}
1762
1763func (p InstallPath) withRel(rel string) InstallPath {
1764 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08001765 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07001766 return p
1767}
1768
Colin Crossc68db4b2021-11-11 18:59:15 -08001769// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1770// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001771func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001772 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001773 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001774}
1775
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001776// PathForModuleInstall returns a Path representing the install path for the
1777// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001778func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001779 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07001780 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07001781 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001782}
1783
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001784// PathForHostDexInstall returns an InstallPath representing the install path for the
1785// module appended with paths...
1786func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07001787 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001788}
1789
Spandan Das5d1b9292021-06-03 19:36:41 +00001790// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1791func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1792 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07001793 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001794}
1795
1796func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001797 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001798 arch := ctx.Arch().ArchType
1799 forceOS, forceArch := ctx.InstallForceOS()
1800 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001801 os = *forceOS
1802 }
Jiyong Park87788b52020-09-01 12:37:45 +09001803 if forceArch != nil {
1804 arch = *forceArch
1805 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001806 return os, arch
1807}
Colin Cross609c49a2020-02-13 13:20:11 -08001808
Colin Crossc0e42d52024-02-01 16:42:36 -08001809func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
1810 fullPath := ctx.Config().SoongOutDir()
1811 if makePath {
1812 // Make path starts with out/ instead of out/soong.
1813 fullPath = filepath.Join(fullPath, "../", partitionPath)
1814 } else {
1815 fullPath = filepath.Join(fullPath, partitionPath)
1816 }
1817
1818 return InstallPath{
1819 basePath: basePath{partitionPath, ""},
1820 soongOutDir: ctx.Config().soongOutDir,
1821 partitionDir: partitionPath,
1822 partition: partition,
1823 makePath: makePath,
1824 fullPath: fullPath,
1825 }
1826}
1827
Cole Faust3b703f32023-10-16 13:30:51 -07001828func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08001829 pathComponents ...string) InstallPath {
1830
Jiyong Park97859152023-02-14 17:05:48 +09001831 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001832
Colin Cross6e359402020-02-10 15:29:54 -08001833 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09001834 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001835 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001836 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07001837 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09001838 // instead of linux_glibc
1839 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001840 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07001841 if os == LinuxMusl && ctx.Config().UseHostMusl() {
1842 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
1843 // compiling we will still use "linux_musl".
1844 osName = "linux"
1845 }
1846
Jiyong Park87788b52020-09-01 12:37:45 +09001847 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1848 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1849 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1850 // Let's keep using x86 for the existing cases until we have a need to support
1851 // other architectures.
1852 archName := arch.String()
1853 if os.Class == Host && (arch == X86_64 || arch == Common) {
1854 archName = "x86"
1855 }
Jiyong Park97859152023-02-14 17:05:48 +09001856 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001857 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001858
Jiyong Park97859152023-02-14 17:05:48 +09001859 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001860 if err != nil {
1861 reportPathError(ctx, err)
1862 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001863
Colin Crossc0e42d52024-02-01 16:42:36 -08001864 base := pathForPartitionInstallDir(ctx, partition, partitionPath, ctx.Config().KatiEnabled())
Jiyong Park957bcd92020-10-20 18:23:33 +09001865 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001866}
1867
Spandan Dasf280b232024-04-04 21:25:51 +00001868func PathForNdkInstall(ctx PathContext, paths ...string) OutputPath {
1869 return PathForOutput(ctx, append([]string{"ndk"}, paths...)...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001870}
1871
1872func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
Spandan Dasf280b232024-04-04 21:25:51 +00001873 base := pathForPartitionInstallDir(ctx, "", "mainline-sdks", false)
1874 return base.Join(ctx, paths...)
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001875}
1876
Colin Cross70dda7e2019-10-01 22:05:35 -07001877func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07001878 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08001879 return "/" + rel
1880}
1881
Cole Faust11edf552023-10-13 11:32:14 -07001882func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001883 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001884 if ctx.InstallInTestcases() {
1885 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001886 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07001887 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08001888 if ctx.InstallInData() {
1889 partition = "data"
1890 } else if ctx.InstallInRamdisk() {
1891 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1892 partition = "recovery/root/first_stage_ramdisk"
1893 } else {
1894 partition = "ramdisk"
1895 }
1896 if !ctx.InstallInRoot() {
1897 partition += "/system"
1898 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001899 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001900 // The module is only available after switching root into
1901 // /first_stage_ramdisk. To expose the module before switching root
1902 // on a device without a dedicated recovery partition, install the
1903 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001904 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001905 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001906 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001907 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001908 }
1909 if !ctx.InstallInRoot() {
1910 partition += "/system"
1911 }
Inseob Kim08758f02021-04-08 21:13:22 +09001912 } else if ctx.InstallInDebugRamdisk() {
1913 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08001914 } else if ctx.InstallInRecovery() {
1915 if ctx.InstallInRoot() {
1916 partition = "recovery/root"
1917 } else {
1918 // the layout of recovery partion is the same as that of system partition
1919 partition = "recovery/root/system"
1920 }
Colin Crossea30d852023-11-29 16:00:16 -08001921 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08001922 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08001923 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08001924 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08001925 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08001926 partition = ctx.DeviceConfig().ProductPath()
1927 } else if ctx.SystemExtSpecific() {
1928 partition = ctx.DeviceConfig().SystemExtPath()
1929 } else if ctx.InstallInRoot() {
1930 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001931 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001932 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001933 }
Colin Cross6e359402020-02-10 15:29:54 -08001934 if ctx.InstallInSanitizerDir() {
1935 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001936 }
Colin Cross43f08db2018-11-12 10:13:39 -08001937 }
1938 return partition
1939}
1940
Colin Cross609c49a2020-02-13 13:20:11 -08001941type InstallPaths []InstallPath
1942
1943// Paths returns the InstallPaths as a Paths
1944func (p InstallPaths) Paths() Paths {
1945 if p == nil {
1946 return nil
1947 }
1948 ret := make(Paths, len(p))
1949 for i, path := range p {
1950 ret[i] = path
1951 }
1952 return ret
1953}
1954
1955// Strings returns the string forms of the install paths.
1956func (p InstallPaths) Strings() []string {
1957 if p == nil {
1958 return nil
1959 }
1960 ret := make([]string, len(p))
1961 for i, path := range p {
1962 ret[i] = path.String()
1963 }
1964 return ret
1965}
1966
Jingwen Chen24d0c562023-02-07 09:29:36 +00001967// validatePathInternal ensures that a path does not leave its component, and
1968// optionally doesn't contain Ninja variables.
1969func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07001970 initialEmpty := 0
1971 finalEmpty := 0
1972 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00001973 if !allowNinjaVariables && strings.Contains(path, "$") {
1974 return "", fmt.Errorf("Path contains invalid character($): %s", path)
1975 }
1976
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001977 path := filepath.Clean(path)
1978 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001979 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001980 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07001981
1982 if i == initialEmpty && pathComponents[i] == "" {
1983 initialEmpty++
1984 }
1985 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
1986 finalEmpty++
1987 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001988 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07001989 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
1990 // of "foo", while filepath.Join("foo") does not. Strip out any empty
1991 // path components.
1992 if initialEmpty == len(pathComponents) {
1993 return "", nil
1994 }
1995 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001996 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1997 // variables. '..' may remove the entire ninja variable, even if it
1998 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07001999 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002000}
2001
Jingwen Chen24d0c562023-02-07 09:29:36 +00002002// validateSafePath validates a path that we trust (may contain ninja
2003// variables). Ensures that each path component does not attempt to leave its
2004// component. Returns a joined version of each path component.
2005func validateSafePath(pathComponents ...string) (string, error) {
2006 return validatePathInternal(true, pathComponents...)
2007}
2008
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002009// validatePath validates that a path does not include ninja variables, and that
2010// each path component does not attempt to leave its component. Returns a joined
2011// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002012func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002013 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002014}
Colin Cross5b529592017-05-09 13:34:34 -07002015
Colin Cross0875c522017-11-28 17:34:01 -08002016func PathForPhony(ctx PathContext, phony string) WritablePath {
2017 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002018 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002019 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002020 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002021}
2022
Colin Cross74e3fe42017-12-11 15:51:44 -08002023type PhonyPath struct {
2024 basePath
2025}
2026
2027func (p PhonyPath) writablePath() {}
2028
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002029func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002030 // A phone path cannot contain any / so cannot be relative to the build directory.
2031 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002032}
2033
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002034func (p PhonyPath) RelativeToTop() Path {
2035 ensureTestOnly()
2036 // A phony path cannot contain any / so does not have a build directory so switching to a new
2037 // build directory has no effect so just return this path.
2038 return p
2039}
2040
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002041func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2042 panic("Not implemented")
2043}
2044
Colin Cross74e3fe42017-12-11 15:51:44 -08002045var _ Path = PhonyPath{}
2046var _ WritablePath = PhonyPath{}
2047
Colin Cross5b529592017-05-09 13:34:34 -07002048type testPath struct {
2049 basePath
2050}
2051
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002052func (p testPath) RelativeToTop() Path {
2053 ensureTestOnly()
2054 return p
2055}
2056
Colin Cross5b529592017-05-09 13:34:34 -07002057func (p testPath) String() string {
2058 return p.path
2059}
2060
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002061var _ Path = testPath{}
2062
Colin Cross40e33732019-02-15 11:08:35 -08002063// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2064// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002065func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002066 p, err := validateSafePath(paths...)
2067 if err != nil {
2068 panic(err)
2069 }
Colin Cross5b529592017-05-09 13:34:34 -07002070 return testPath{basePath{path: p, rel: p}}
2071}
2072
Sam Delmerico2351eac2022-05-24 17:10:02 +00002073func PathForTestingWithRel(path, rel string) Path {
2074 p, err := validateSafePath(path, rel)
2075 if err != nil {
2076 panic(err)
2077 }
2078 r, err := validatePath(rel)
2079 if err != nil {
2080 panic(err)
2081 }
2082 return testPath{basePath{path: p, rel: r}}
2083}
2084
Colin Cross40e33732019-02-15 11:08:35 -08002085// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2086func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002087 p := make(Paths, len(strs))
2088 for i, s := range strs {
2089 p[i] = PathForTesting(s)
2090 }
2091
2092 return p
2093}
Colin Cross43f08db2018-11-12 10:13:39 -08002094
Colin Cross40e33732019-02-15 11:08:35 -08002095type testPathContext struct {
2096 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002097}
2098
Colin Cross40e33732019-02-15 11:08:35 -08002099func (x *testPathContext) Config() Config { return x.config }
2100func (x *testPathContext) AddNinjaFileDeps(...string) {}
2101
2102// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2103// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002104func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002105 return &testPathContext{
2106 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002107 }
2108}
2109
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002110type testModuleInstallPathContext struct {
2111 baseModuleContext
2112
2113 inData bool
2114 inTestcases bool
2115 inSanitizerDir bool
2116 inRamdisk bool
2117 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002118 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002119 inRecovery bool
2120 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002121 inOdm bool
2122 inProduct bool
2123 inVendor bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002124 forceOS *OsType
2125 forceArch *ArchType
2126}
2127
2128func (m testModuleInstallPathContext) Config() Config {
2129 return m.baseModuleContext.config
2130}
2131
2132func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2133
2134func (m testModuleInstallPathContext) InstallInData() bool {
2135 return m.inData
2136}
2137
2138func (m testModuleInstallPathContext) InstallInTestcases() bool {
2139 return m.inTestcases
2140}
2141
2142func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2143 return m.inSanitizerDir
2144}
2145
2146func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2147 return m.inRamdisk
2148}
2149
2150func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2151 return m.inVendorRamdisk
2152}
2153
Inseob Kim08758f02021-04-08 21:13:22 +09002154func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2155 return m.inDebugRamdisk
2156}
2157
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002158func (m testModuleInstallPathContext) InstallInRecovery() bool {
2159 return m.inRecovery
2160}
2161
2162func (m testModuleInstallPathContext) InstallInRoot() bool {
2163 return m.inRoot
2164}
2165
Colin Crossea30d852023-11-29 16:00:16 -08002166func (m testModuleInstallPathContext) InstallInOdm() bool {
2167 return m.inOdm
2168}
2169
2170func (m testModuleInstallPathContext) InstallInProduct() bool {
2171 return m.inProduct
2172}
2173
2174func (m testModuleInstallPathContext) InstallInVendor() bool {
2175 return m.inVendor
2176}
2177
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002178func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2179 return m.forceOS, m.forceArch
2180}
2181
2182// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2183// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2184// delegated to it will panic.
2185func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2186 ctx := &testModuleInstallPathContext{}
2187 ctx.config = config
2188 ctx.os = Android
2189 return ctx
2190}
2191
Colin Cross43f08db2018-11-12 10:13:39 -08002192// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2193// targetPath is not inside basePath.
2194func Rel(ctx PathContext, basePath string, targetPath string) string {
2195 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2196 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002197 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002198 return ""
2199 }
2200 return rel
2201}
2202
2203// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2204// targetPath is not inside basePath.
2205func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002206 rel, isRel, err := maybeRelErr(basePath, targetPath)
2207 if err != nil {
2208 reportPathError(ctx, err)
2209 }
2210 return rel, isRel
2211}
2212
2213func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002214 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2215 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002216 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002217 }
2218 rel, err := filepath.Rel(basePath, targetPath)
2219 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002220 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002221 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002222 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002223 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002224 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002225}
Colin Cross988414c2020-01-11 01:11:46 +00002226
2227// Writes a file to the output directory. Attempting to write directly to the output directory
2228// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002229// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2230// updating the timestamp if no changes would be made. (This is better for incremental
2231// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002232func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002233 absPath := absolutePath(path.String())
2234 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2235 if err != nil {
2236 return err
2237 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002238 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002239}
2240
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002241func RemoveAllOutputDir(path WritablePath) error {
2242 return os.RemoveAll(absolutePath(path.String()))
2243}
2244
2245func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2246 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002247 return createDirIfNonexistent(dir, perm)
2248}
2249
2250func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002251 if _, err := os.Stat(dir); os.IsNotExist(err) {
2252 return os.MkdirAll(dir, os.ModePerm)
2253 } else {
2254 return err
2255 }
2256}
2257
Jingwen Chen78257e52021-05-21 02:34:24 +00002258// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2259// read arbitrary files without going through the methods in the current package that track
2260// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002261func absolutePath(path string) string {
2262 if filepath.IsAbs(path) {
2263 return path
2264 }
2265 return filepath.Join(absSrcDir, path)
2266}
Chris Parsons216e10a2020-07-09 17:12:52 -04002267
2268// A DataPath represents the path of a file to be used as data, for example
2269// a test library to be installed alongside a test.
2270// The data file should be installed (copied from `<SrcPath>`) to
2271// `<install_root>/<RelativeInstallPath>/<filename>`, or
2272// `<install_root>/<filename>` if RelativeInstallPath is empty.
2273type DataPath struct {
2274 // The path of the data file that should be copied into the data directory
2275 SrcPath Path
2276 // The install path of the data file, relative to the install root.
2277 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002278 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2279 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002280}
Colin Crossdcf71b22021-02-01 13:59:03 -08002281
Colin Crossd442a0e2023-11-16 11:19:26 -08002282func (d *DataPath) ToRelativeInstallPath() string {
2283 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002284 if d.WithoutRel {
2285 relPath = d.SrcPath.Base()
2286 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002287 if d.RelativeInstallPath != "" {
2288 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2289 }
2290 return relPath
2291}
2292
Colin Crossdcf71b22021-02-01 13:59:03 -08002293// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2294func PathsIfNonNil(paths ...Path) Paths {
2295 if len(paths) == 0 {
2296 // Fast path for empty argument list
2297 return nil
2298 } else if len(paths) == 1 {
2299 // Fast path for a single argument
2300 if paths[0] != nil {
2301 return paths
2302 } else {
2303 return nil
2304 }
2305 }
2306 ret := make(Paths, 0, len(paths))
2307 for _, path := range paths {
2308 if path != nil {
2309 ret = append(ret, path)
2310 }
2311 }
2312 if len(ret) == 0 {
2313 return nil
2314 }
2315 return ret
2316}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002317
2318var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2319 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2320 regexp.MustCompile("^hardware/google/"),
2321 regexp.MustCompile("^hardware/interfaces/"),
2322 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2323 regexp.MustCompile("^hardware/ril/"),
2324}
2325
2326func IsThirdPartyPath(path string) bool {
2327 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2328
2329 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2330 for _, prefix := range thirdPartyDirPrefixExceptions {
2331 if prefix.MatchString(path) {
2332 return false
2333 }
2334 }
2335 return true
2336 }
2337 return false
2338}