blob: 5e80a31cbd813f23bbb80eafc959566eae146c94 [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
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700280}
281type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800282 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700283}
284type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800285 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700286}
287
288// GenPathWithExt derives a new file path in ctx's generated sources directory
289// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800290func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700291 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700292 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700293 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100294 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700295 return PathForModuleGen(ctx)
296}
297
298// ObjPathWithExt derives a new file path in ctx's object directory from the
299// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800300func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700301 if path, ok := p.(objPathProvider); ok {
302 return path.objPathWithExt(ctx, subdir, ext)
303 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100304 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700305 return PathForModuleObj(ctx)
306}
307
308// ResPathWithName derives a new path in ctx's output resource directory, using
309// the current path to create the directory name, and the `name` argument for
310// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800311func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700312 if path, ok := p.(resPathProvider); ok {
313 return path.resPathWithName(ctx, name)
314 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100315 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700316 return PathForModuleRes(ctx)
317}
318
319// OptionalPath is a container that may or may not contain a valid Path.
320type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100321 path Path // nil if invalid.
322 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700323}
324
325// OptionalPathForPath returns an OptionalPath containing the path.
326func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100327 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700328}
329
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100330// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
331func InvalidOptionalPath(reason string) OptionalPath {
332
333 return OptionalPath{invalidReason: reason}
334}
335
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700336// Valid returns whether there is a valid path
337func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100338 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700339}
340
341// Path returns the Path embedded in this OptionalPath. You must be sure that
342// there is a valid path, since this method will panic if there is not.
343func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100344 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100345 msg := "Requesting an invalid path"
346 if p.invalidReason != "" {
347 msg += ": " + p.invalidReason
348 }
349 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700350 }
351 return p.path
352}
353
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100354// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
355func (p OptionalPath) InvalidReason() string {
356 if p.path != nil {
357 return ""
358 }
359 if p.invalidReason == "" {
360 return "unknown"
361 }
362 return p.invalidReason
363}
364
Paul Duffinef081852021-05-13 11:11:15 +0100365// AsPaths converts the OptionalPath into Paths.
366//
367// It returns nil if this is not valid, or a single length slice containing the Path embedded in
368// this OptionalPath.
369func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100370 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100371 return nil
372 }
373 return Paths{p.path}
374}
375
Paul Duffinafdd4062021-03-30 19:44:07 +0100376// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
377// result of calling Path.RelativeToTop on it.
378func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100379 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100380 return p
381 }
382 p.path = p.path.RelativeToTop()
383 return p
384}
385
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700386// String returns the string version of the Path, or "" if it isn't valid.
387func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100388 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700389 return p.path.String()
390 } else {
391 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700392 }
393}
Colin Cross6e18ca42015-07-14 18:55:36 -0700394
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700395// Paths is a slice of Path objects, with helpers to operate on the collection.
396type Paths []Path
397
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000398// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
399// item in this slice.
400func (p Paths) RelativeToTop() Paths {
401 ensureTestOnly()
402 if p == nil {
403 return p
404 }
405 ret := make(Paths, len(p))
406 for i, path := range p {
407 ret[i] = path.RelativeToTop()
408 }
409 return ret
410}
411
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000412func (paths Paths) containsPath(path Path) bool {
413 for _, p := range paths {
414 if p == path {
415 return true
416 }
417 }
418 return false
419}
420
Liz Kammer7aa52882021-02-11 09:16:14 -0500421// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
422// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700423func PathsForSource(ctx PathContext, paths []string) Paths {
424 ret := make(Paths, len(paths))
425 for i, path := range paths {
426 ret[i] = PathForSource(ctx, path)
427 }
428 return ret
429}
430
Liz Kammer7aa52882021-02-11 09:16:14 -0500431// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
432// module's local source directory, that are found in the tree. If any are not found, they are
433// 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 -0700434func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800435 ret := make(Paths, 0, len(paths))
436 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800437 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800438 if p.Valid() {
439 ret = append(ret, p.Path())
440 }
441 }
442 return ret
443}
444
Liz Kammer620dea62021-04-14 17:36:10 -0400445// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700446// - filepath, relative to local module directory, resolves as a filepath relative to the local
447// source directory
448// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
449// source directory.
450// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
451// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
452// filepath.
453//
Liz Kammer620dea62021-04-14 17:36:10 -0400454// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700455// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000456// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400457// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700458// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400459// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700460// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800461func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800462 return PathsForModuleSrcExcludes(ctx, paths, nil)
463}
464
Liz Kammer619be462022-01-28 15:13:39 -0500465type SourceInput struct {
466 Context ModuleMissingDepsPathContext
467 Paths []string
468 ExcludePaths []string
469 IncludeDirs bool
470}
471
Liz Kammer620dea62021-04-14 17:36:10 -0400472// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
473// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700474// - filepath, relative to local module directory, resolves as a filepath relative to the local
475// source directory
476// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
477// source directory. Not valid in excludes.
478// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
479// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
480// filepath.
481//
Liz Kammer620dea62021-04-14 17:36:10 -0400482// excluding the items (similarly resolved
483// Properties passed as the paths argument must have been annotated with struct tag
484// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000485// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400486// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700487// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400488// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700489// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800490func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500491 return PathsRelativeToModuleSourceDir(SourceInput{
492 Context: ctx,
493 Paths: paths,
494 ExcludePaths: excludes,
495 IncludeDirs: true,
496 })
497}
498
499func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
500 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
501 if input.Context.Config().AllowMissingDependencies() {
502 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700503 } else {
504 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500505 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700506 }
507 }
508 return ret
509}
510
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000511// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
512type OutputPaths []OutputPath
513
514// Paths returns the OutputPaths as a Paths
515func (p OutputPaths) Paths() Paths {
516 if p == nil {
517 return nil
518 }
519 ret := make(Paths, len(p))
520 for i, path := range p {
521 ret[i] = path
522 }
523 return ret
524}
525
526// Strings returns the string forms of the writable paths.
527func (p OutputPaths) Strings() []string {
528 if p == nil {
529 return nil
530 }
531 ret := make([]string, len(p))
532 for i, path := range p {
533 ret[i] = path.String()
534 }
535 return ret
536}
537
Colin Crossa44551f2021-10-25 15:36:21 -0700538// PathForGoBinary returns the path to the installed location of a bootstrap_go_binary module.
539func PathForGoBinary(ctx PathContext, goBinary bootstrap.GoBinaryTool) Path {
Cole Faust3b703f32023-10-16 13:30:51 -0700540 goBinaryInstallDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "bin")
Colin Crossa44551f2021-10-25 15:36:21 -0700541 rel := Rel(ctx, goBinaryInstallDir.String(), goBinary.InstallPath())
542 return goBinaryInstallDir.Join(ctx, rel)
543}
544
Liz Kammera830f3a2020-11-10 10:50:34 -0800545// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
546// If the dependency is not found, a missingErrorDependency is returned.
547// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
548func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100549 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800550 if module == nil {
551 return nil, missingDependencyError{[]string{moduleName}}
552 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700553 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
554 return nil, missingDependencyError{[]string{moduleName}}
555 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800556 if outProducer, ok := module.(OutputFileProducer); ok {
557 outputFiles, err := outProducer.OutputFiles(tag)
558 if err != nil {
559 return nil, fmt.Errorf("path dependency %q: %s", path, err)
560 }
561 return outputFiles, nil
562 } else if tag != "" {
563 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
Colin Cross0e446152021-05-03 13:35:32 -0700564 } else if goBinary, ok := module.(bootstrap.GoBinaryTool); ok {
Colin Crossa44551f2021-10-25 15:36:21 -0700565 goBinaryPath := PathForGoBinary(ctx, goBinary)
566 return Paths{goBinaryPath}, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800567 } else if srcProducer, ok := module.(SourceFileProducer); ok {
568 return srcProducer.Srcs(), nil
569 } else {
570 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
571 }
572}
573
Paul Duffind5cf92e2021-07-09 17:38:55 +0100574// GetModuleFromPathDep will return the module that was added as a dependency automatically for
575// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
576// ExtractSourcesDeps.
577//
578// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
579// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
580// the tag must be "".
581//
582// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
583// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100584func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100585 var found blueprint.Module
586 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
587 // module name and the tag. Dependencies added automatically for properties tagged with
588 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
589 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
590 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
591 // moduleName referring to the same dependency module.
592 //
593 // It does not matter whether the moduleName is a fully qualified name or if the module
594 // dependency is a prebuilt module. All that matters is the same information is supplied to
595 // create the tag here as was supplied to create the tag when the dependency was added so that
596 // this finds the matching dependency module.
597 expectedTag := sourceOrOutputDepTag(moduleName, tag)
598 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
599 depTag := ctx.OtherModuleDependencyTag(module)
600 if depTag == expectedTag {
601 found = module
602 }
603 })
604 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100605}
606
Liz Kammer620dea62021-04-14 17:36:10 -0400607// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
608// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700609// - filepath, relative to local module directory, resolves as a filepath relative to the local
610// source directory
611// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
612// source directory. Not valid in excludes.
613// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
614// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
615// filepath.
616//
Liz Kammer620dea62021-04-14 17:36:10 -0400617// and a list of the module names of missing module dependencies are returned as the second return.
618// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700619// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000620// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500621func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
622 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
623 Context: ctx,
624 Paths: paths,
625 ExcludePaths: excludes,
626 IncludeDirs: true,
627 })
628}
629
630func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
631 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800632
633 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500634 if input.ExcludePaths != nil {
635 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700636 }
Colin Cross8a497952019-03-05 22:25:09 -0800637
Colin Crossba71a3f2019-03-18 12:12:48 -0700638 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500639 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700640 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500641 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800642 if m, ok := err.(missingDependencyError); ok {
643 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
644 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500645 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800646 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800647 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800648 }
649 } else {
650 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
651 }
652 }
653
Liz Kammer619be462022-01-28 15:13:39 -0500654 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700655 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800656 }
657
Colin Crossba71a3f2019-03-18 12:12:48 -0700658 var missingDeps []string
659
Liz Kammer619be462022-01-28 15:13:39 -0500660 expandedSrcFiles := make(Paths, 0, len(input.Paths))
661 for _, s := range input.Paths {
662 srcFiles, err := expandOneSrcPath(sourcePathInput{
663 context: input.Context,
664 path: s,
665 expandedExcludes: expandedExcludes,
666 includeDirs: input.IncludeDirs,
667 })
Colin Cross8a497952019-03-05 22:25:09 -0800668 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700669 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800670 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500671 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800672 }
673 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
674 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700675
676 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800677}
678
679type missingDependencyError struct {
680 missingDeps []string
681}
682
683func (e missingDependencyError) Error() string {
684 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
685}
686
Liz Kammer619be462022-01-28 15:13:39 -0500687type sourcePathInput struct {
688 context ModuleWithDepsPathContext
689 path string
690 expandedExcludes []string
691 includeDirs bool
692}
693
Liz Kammera830f3a2020-11-10 10:50:34 -0800694// Expands one path string to Paths rooted from the module's local source
695// directory, excluding those listed in the expandedExcludes.
696// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500697func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900698 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500699 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900700 return paths
701 }
702 remainder := make(Paths, 0, len(paths))
703 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500704 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900705 remainder = append(remainder, p)
706 }
707 }
708 return remainder
709 }
Liz Kammer619be462022-01-28 15:13:39 -0500710 if m, t := SrcIsModuleWithTag(input.path); m != "" {
711 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800712 if err != nil {
713 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800714 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800715 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800716 }
Colin Cross8a497952019-03-05 22:25:09 -0800717 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500718 p := pathForModuleSrc(input.context, input.path)
719 if pathtools.IsGlob(input.path) {
720 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
721 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
722 } else {
723 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
724 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
725 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
726 ReportPathErrorf(input.context, "module source path %q does not exist", p)
727 } else if !input.includeDirs {
728 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
729 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
730 } else if isDir {
731 ReportPathErrorf(input.context, "module source path %q is a directory", p)
732 }
733 }
Colin Cross8a497952019-03-05 22:25:09 -0800734
Liz Kammer619be462022-01-28 15:13:39 -0500735 if InList(p.String(), input.expandedExcludes) {
736 return nil, nil
737 }
738 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800739 }
Colin Cross8a497952019-03-05 22:25:09 -0800740 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700741}
742
743// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
744// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800745// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700746// It intended for use in globs that only list files that exist, so it allows '$' in
747// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800748func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200749 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700750 if prefix == "./" {
751 prefix = ""
752 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700753 ret := make(Paths, 0, len(paths))
754 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800755 if !incDirs && strings.HasSuffix(p, "/") {
756 continue
757 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700758 path := filepath.Clean(p)
759 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100760 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700761 continue
762 }
Colin Crosse3924e12018-08-15 20:18:53 -0700763
Colin Crossfe4bc362018-09-12 10:02:13 -0700764 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700765 if err != nil {
766 reportPathError(ctx, err)
767 continue
768 }
769
Colin Cross07e51612019-03-05 12:46:40 -0800770 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700771
Colin Cross07e51612019-03-05 12:46:40 -0800772 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700773 }
774 return ret
775}
776
Liz Kammera830f3a2020-11-10 10:50:34 -0800777// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
778// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
779func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800780 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700781 return PathsForModuleSrc(ctx, input)
782 }
783 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
784 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200785 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800786 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700787}
788
789// Strings returns the Paths in string form
790func (p Paths) Strings() []string {
791 if p == nil {
792 return nil
793 }
794 ret := make([]string, len(p))
795 for i, path := range p {
796 ret[i] = path.String()
797 }
798 return ret
799}
800
Colin Crossc0efd1d2020-07-03 11:56:24 -0700801func CopyOfPaths(paths Paths) Paths {
802 return append(Paths(nil), paths...)
803}
804
Colin Crossb6715442017-10-24 11:13:31 -0700805// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
806// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700807func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800808 // 128 was chosen based on BenchmarkFirstUniquePaths results.
809 if len(list) > 128 {
810 return firstUniquePathsMap(list)
811 }
812 return firstUniquePathsList(list)
813}
814
Colin Crossc0efd1d2020-07-03 11:56:24 -0700815// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
816// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900817func SortedUniquePaths(list Paths) Paths {
818 unique := FirstUniquePaths(list)
819 sort.Slice(unique, func(i, j int) bool {
820 return unique[i].String() < unique[j].String()
821 })
822 return unique
823}
824
Colin Cross27027c72020-02-28 15:34:17 -0800825func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700826 k := 0
827outer:
828 for i := 0; i < len(list); i++ {
829 for j := 0; j < k; j++ {
830 if list[i] == list[j] {
831 continue outer
832 }
833 }
834 list[k] = list[i]
835 k++
836 }
837 return list[:k]
838}
839
Colin Cross27027c72020-02-28 15:34:17 -0800840func firstUniquePathsMap(list Paths) Paths {
841 k := 0
842 seen := make(map[Path]bool, len(list))
843 for i := 0; i < len(list); i++ {
844 if seen[list[i]] {
845 continue
846 }
847 seen[list[i]] = true
848 list[k] = list[i]
849 k++
850 }
851 return list[:k]
852}
853
Colin Cross5d583952020-11-24 16:21:24 -0800854// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
855// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
856func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
857 // 128 was chosen based on BenchmarkFirstUniquePaths results.
858 if len(list) > 128 {
859 return firstUniqueInstallPathsMap(list)
860 }
861 return firstUniqueInstallPathsList(list)
862}
863
864func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
865 k := 0
866outer:
867 for i := 0; i < len(list); i++ {
868 for j := 0; j < k; j++ {
869 if list[i] == list[j] {
870 continue outer
871 }
872 }
873 list[k] = list[i]
874 k++
875 }
876 return list[:k]
877}
878
879func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
880 k := 0
881 seen := make(map[InstallPath]bool, len(list))
882 for i := 0; i < len(list); i++ {
883 if seen[list[i]] {
884 continue
885 }
886 seen[list[i]] = true
887 list[k] = list[i]
888 k++
889 }
890 return list[:k]
891}
892
Colin Crossb6715442017-10-24 11:13:31 -0700893// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
894// modifies the Paths slice contents in place, and returns a subslice of the original slice.
895func LastUniquePaths(list Paths) Paths {
896 totalSkip := 0
897 for i := len(list) - 1; i >= totalSkip; i-- {
898 skip := 0
899 for j := i - 1; j >= totalSkip; j-- {
900 if list[i] == list[j] {
901 skip++
902 } else {
903 list[j+skip] = list[j]
904 }
905 }
906 totalSkip += skip
907 }
908 return list[totalSkip:]
909}
910
Colin Crossa140bb02018-04-17 10:52:26 -0700911// ReversePaths returns a copy of a Paths in reverse order.
912func ReversePaths(list Paths) Paths {
913 if list == nil {
914 return nil
915 }
916 ret := make(Paths, len(list))
917 for i := range list {
918 ret[i] = list[len(list)-1-i]
919 }
920 return ret
921}
922
Jeff Gaston294356f2017-09-27 17:05:30 -0700923func indexPathList(s Path, list []Path) int {
924 for i, l := range list {
925 if l == s {
926 return i
927 }
928 }
929
930 return -1
931}
932
933func inPathList(p Path, list []Path) bool {
934 return indexPathList(p, list) != -1
935}
936
937func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000938 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
939}
940
941func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700942 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000943 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700944 filtered = append(filtered, l)
945 } else {
946 remainder = append(remainder, l)
947 }
948 }
949
950 return
951}
952
Colin Cross93e85952017-08-15 13:34:18 -0700953// HasExt returns true of any of the paths have extension ext, otherwise false
954func (p Paths) HasExt(ext string) bool {
955 for _, path := range p {
956 if path.Ext() == ext {
957 return true
958 }
959 }
960
961 return false
962}
963
964// FilterByExt returns the subset of the paths that have extension ext
965func (p Paths) FilterByExt(ext string) Paths {
966 ret := make(Paths, 0, len(p))
967 for _, path := range p {
968 if path.Ext() == ext {
969 ret = append(ret, path)
970 }
971 }
972 return ret
973}
974
975// FilterOutByExt returns the subset of the paths that do not have extension ext
976func (p Paths) FilterOutByExt(ext string) Paths {
977 ret := make(Paths, 0, len(p))
978 for _, path := range p {
979 if path.Ext() != ext {
980 ret = append(ret, path)
981 }
982 }
983 return ret
984}
985
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700986// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
987// (including subdirectories) are in a contiguous subslice of the list, and can be found in
988// O(log(N)) time using a binary search on the directory prefix.
989type DirectorySortedPaths Paths
990
991func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
992 ret := append(DirectorySortedPaths(nil), paths...)
993 sort.Slice(ret, func(i, j int) bool {
994 return ret[i].String() < ret[j].String()
995 })
996 return ret
997}
998
999// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1000// that are in the specified directory and its subdirectories.
1001func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1002 prefix := filepath.Clean(dir) + "/"
1003 start := sort.Search(len(p), func(i int) bool {
1004 return prefix < p[i].String()
1005 })
1006
1007 ret := p[start:]
1008
1009 end := sort.Search(len(ret), func(i int) bool {
1010 return !strings.HasPrefix(ret[i].String(), prefix)
1011 })
1012
1013 ret = ret[:end]
1014
1015 return Paths(ret)
1016}
1017
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001018// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001019type WritablePaths []WritablePath
1020
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001021// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1022// each item in this slice.
1023func (p WritablePaths) RelativeToTop() WritablePaths {
1024 ensureTestOnly()
1025 if p == nil {
1026 return p
1027 }
1028 ret := make(WritablePaths, len(p))
1029 for i, path := range p {
1030 ret[i] = path.RelativeToTop().(WritablePath)
1031 }
1032 return ret
1033}
1034
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001035// Strings returns the string forms of the writable paths.
1036func (p WritablePaths) Strings() []string {
1037 if p == nil {
1038 return nil
1039 }
1040 ret := make([]string, len(p))
1041 for i, path := range p {
1042 ret[i] = path.String()
1043 }
1044 return ret
1045}
1046
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001047// Paths returns the WritablePaths as a Paths
1048func (p WritablePaths) Paths() Paths {
1049 if p == nil {
1050 return nil
1051 }
1052 ret := make(Paths, len(p))
1053 for i, path := range p {
1054 ret[i] = path
1055 }
1056 return ret
1057}
1058
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001059type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001060 path string
1061 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001062}
1063
1064func (p basePath) Ext() string {
1065 return filepath.Ext(p.path)
1066}
1067
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001068func (p basePath) Base() string {
1069 return filepath.Base(p.path)
1070}
1071
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001072func (p basePath) Rel() string {
1073 if p.rel != "" {
1074 return p.rel
1075 }
1076 return p.path
1077}
1078
Colin Cross0875c522017-11-28 17:34:01 -08001079func (p basePath) String() string {
1080 return p.path
1081}
1082
Colin Cross0db55682017-12-05 15:36:55 -08001083func (p basePath) withRel(rel string) basePath {
1084 p.path = filepath.Join(p.path, rel)
1085 p.rel = rel
1086 return p
1087}
1088
Cole Faustbc65a3f2023-08-01 16:38:55 +00001089func (p basePath) RelativeToTop() Path {
1090 ensureTestOnly()
1091 return p
1092}
1093
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001094// SourcePath is a Path representing a file path rooted from SrcDir
1095type SourcePath struct {
1096 basePath
1097}
1098
1099var _ Path = SourcePath{}
1100
Colin Cross0db55682017-12-05 15:36:55 -08001101func (p SourcePath) withRel(rel string) SourcePath {
1102 p.basePath = p.basePath.withRel(rel)
1103 return p
1104}
1105
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001106// safePathForSource is for paths that we expect are safe -- only for use by go
1107// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001108func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1109 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001110 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001111 if err != nil {
1112 return ret, err
1113 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001114
Colin Cross7b3dcc32019-01-24 13:14:39 -08001115 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001116 // special-case api surface gen files for now
1117 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001118 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001119 }
1120
Colin Crossfe4bc362018-09-12 10:02:13 -07001121 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001122}
1123
Colin Cross192e97a2018-02-22 14:21:02 -08001124// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1125func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001126 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001127 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001128 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001129 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001130 }
1131
Colin Cross7b3dcc32019-01-24 13:14:39 -08001132 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001133 // special-case for now
1134 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001135 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001136 }
1137
Colin Cross192e97a2018-02-22 14:21:02 -08001138 return ret, nil
1139}
1140
Sam Mortimer70472d52019-09-05 15:16:13 -07001141// pathForSourceRelaxed creates a SourcePath from pathComponents, but does not check that it exists.
1142// It differs from pathForSource in that the path is allowed to exist outside of the PathContext.
1143func pathForSourceRelaxed(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1144 p := filepath.Join(pathComponents...)
1145 ret := SourcePath{basePath{p, ""}}
1146
1147 abs, err := filepath.Abs(ret.String())
1148 if err != nil {
1149 return ret, err
1150 }
1151 buildroot, err := filepath.Abs(ctx.Config().soongOutDir)
1152 if err != nil {
1153 return ret, err
1154 }
1155 if strings.HasPrefix(abs, buildroot) {
1156 return ret, fmt.Errorf("source path %s is in output", abs)
1157 }
1158
1159 if pathtools.IsGlob(ret.String()) {
1160 return ret, fmt.Errorf("path may not contain a glob: %s", ret.String())
1161 }
1162
1163 return ret, nil
1164}
1165
Colin Cross192e97a2018-02-22 14:21:02 -08001166// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1167// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001168func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001169 var files []string
1170
Colin Cross662d6142022-11-03 20:38:01 -07001171 // Use glob to produce proper dependencies, even though we only want
1172 // a single file.
1173 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001174
1175 if err != nil {
1176 return false, fmt.Errorf("glob: %s", err.Error())
1177 }
1178
1179 return len(files) > 0, nil
1180}
1181
1182// PathForSource joins the provided path components and validates that the result
1183// neither escapes the source dir nor is in the out dir.
1184// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1185func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1186 path, err := pathForSource(ctx, pathComponents...)
1187 if err != nil {
1188 reportPathError(ctx, err)
1189 }
1190
Colin Crosse3924e12018-08-15 20:18:53 -07001191 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001192 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001193 }
1194
Liz Kammera830f3a2020-11-10 10:50:34 -08001195 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001196 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001197 if err != nil {
1198 reportPathError(ctx, err)
1199 }
1200 if !exists {
1201 modCtx.AddMissingDependencies([]string{path.String()})
1202 }
Colin Cross988414c2020-01-11 01:11:46 +00001203 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001204 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001205 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001206 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001207 }
1208 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001209}
1210
Sam Mortimer70472d52019-09-05 15:16:13 -07001211// PathForSourceRelaxed joins the provided path components. Unlike PathForSource,
1212// the result is allowed to exist outside of the source dir.
1213// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1214func PathForSourceRelaxed(ctx PathContext, pathComponents ...string) SourcePath {
1215 path, err := pathForSourceRelaxed(ctx, pathComponents...)
1216 if err != nil {
1217 reportPathError(ctx, err)
1218 }
1219
1220 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
1221 exists, err := existsWithDependencies(modCtx, path)
1222 if err != nil {
1223 reportPathError(ctx, err)
1224 }
1225 if !exists {
1226 modCtx.AddMissingDependencies([]string{path.String()})
1227 }
1228 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
1229 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
1230 } else if !exists {
1231 ReportPathErrorf(ctx, "source path %s does not exist", path)
1232 }
1233 return path
Jackeagle6cd4aa92024-04-05 01:19:19 -04001234 }
1235
Cole Faustbc65a3f2023-08-01 16:38:55 +00001236// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1237// the path is relative to the root of the output folder, not the out/soong folder.
1238func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
1239 p, err := validatePath(pathComponents...)
1240 if err != nil {
1241 reportPathError(ctx, err)
1242 }
1243 return basePath{path: filepath.Join(ctx.Config().OutDir(), p)}
Sam Mortimer70472d52019-09-05 15:16:13 -07001244}
1245
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001246// MaybeExistentPathForSource joins the provided path components and validates that the result
1247// neither escapes the source dir nor is in the out dir.
1248// It does not validate whether the path exists.
1249func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1250 path, err := pathForSource(ctx, pathComponents...)
1251 if err != nil {
1252 reportPathError(ctx, err)
1253 }
1254
1255 if pathtools.IsGlob(path.String()) {
1256 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1257 }
1258 return path
1259}
1260
Liz Kammer7aa52882021-02-11 09:16:14 -05001261// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1262// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1263// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1264// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001265func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001266 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001267 if err != nil {
1268 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001269 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001270 return OptionalPath{}
1271 }
Colin Crossc48c1432018-02-23 07:09:01 +00001272
Colin Crosse3924e12018-08-15 20:18:53 -07001273 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001274 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001275 return OptionalPath{}
1276 }
1277
Colin Cross192e97a2018-02-22 14:21:02 -08001278 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001279 if err != nil {
1280 reportPathError(ctx, err)
1281 return OptionalPath{}
1282 }
Colin Cross192e97a2018-02-22 14:21:02 -08001283 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001284 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001285 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001286 return OptionalPathForPath(path)
1287}
1288
1289func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001290 if p.path == "" {
1291 return "."
1292 }
1293 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001294}
1295
1296// Join creates a new SourcePath with paths... joined with the current path. The
1297// provided paths... may not use '..' to escape from the current path.
1298func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001299 path, err := validatePath(paths...)
1300 if err != nil {
1301 reportPathError(ctx, err)
1302 }
Colin Cross0db55682017-12-05 15:36:55 -08001303 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001304}
1305
Colin Cross2fafa3e2019-03-05 12:39:51 -08001306// join is like Join but does less path validation.
1307func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1308 path, err := validateSafePath(paths...)
1309 if err != nil {
1310 reportPathError(ctx, err)
1311 }
1312 return p.withRel(path)
1313}
1314
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001315// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1316// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001317func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001318 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001319 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001320 relDir = srcPath.path
1321 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001322 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001323 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001324 return OptionalPath{}
1325 }
Cole Faust483d1f72023-01-09 14:35:27 -08001326 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001327 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001328 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001329 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001330 }
Colin Cross461b4452018-02-23 09:22:42 -08001331 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001332 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001333 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001334 return OptionalPath{}
1335 }
1336 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001337 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001338 }
Cole Faust483d1f72023-01-09 14:35:27 -08001339 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001340}
1341
Colin Cross70dda7e2019-10-01 22:05:35 -07001342// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001343type OutputPath struct {
1344 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001345
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001346 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001347 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001348
Colin Crossd63c9a72020-01-29 16:52:50 -08001349 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001350}
1351
Colin Cross702e0f82017-10-18 17:27:54 -07001352func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001353 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001354 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001355 return p
1356}
1357
Colin Cross3063b782018-08-15 11:19:12 -07001358func (p OutputPath) WithoutRel() OutputPath {
1359 p.basePath.rel = filepath.Base(p.basePath.path)
1360 return p
1361}
1362
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001363func (p OutputPath) getSoongOutDir() string {
1364 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001365}
1366
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001367func (p OutputPath) RelativeToTop() Path {
1368 return p.outputPathRelativeToTop()
1369}
1370
1371func (p OutputPath) outputPathRelativeToTop() OutputPath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001372 p.fullPath = StringPathRelativeToTop(p.soongOutDir, p.fullPath)
1373 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001374 return p
1375}
1376
Paul Duffin0267d492021-02-02 10:05:52 +00001377func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1378 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1379}
1380
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001381var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001382var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001383var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001384
Chris Parsons8f232a22020-06-23 17:37:05 -04001385// toolDepPath is a Path representing a dependency of the build tool.
1386type toolDepPath struct {
1387 basePath
1388}
1389
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001390func (t toolDepPath) RelativeToTop() Path {
1391 ensureTestOnly()
1392 return t
1393}
1394
Chris Parsons8f232a22020-06-23 17:37:05 -04001395var _ Path = toolDepPath{}
1396
1397// pathForBuildToolDep returns a toolDepPath representing the given path string.
1398// There is no validation for the path, as it is "trusted": It may fail
1399// normal validation checks. For example, it may be an absolute path.
1400// Only use this function to construct paths for dependencies of the build
1401// tool invocation.
1402func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001403 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001404}
1405
Jeff Gaston734e3802017-04-10 15:47:24 -07001406// PathForOutput joins the provided paths and returns an OutputPath that is
1407// validated to not escape the build dir.
1408// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1409func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001410 path, err := validatePath(pathComponents...)
1411 if err != nil {
1412 reportPathError(ctx, err)
1413 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001414 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001415 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001416 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001417}
1418
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001419// PathsForOutput returns Paths rooted from soongOutDir
Colin Cross40e33732019-02-15 11:08:35 -08001420func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1421 ret := make(WritablePaths, len(paths))
1422 for i, path := range paths {
1423 ret[i] = PathForOutput(ctx, path)
1424 }
1425 return ret
1426}
1427
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001428func (p OutputPath) writablePath() {}
1429
1430func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001431 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001432}
1433
1434// Join creates a new OutputPath with paths... joined with the current path. The
1435// provided paths... may not use '..' to escape from the current path.
1436func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001437 path, err := validatePath(paths...)
1438 if err != nil {
1439 reportPathError(ctx, err)
1440 }
Colin Cross0db55682017-12-05 15:36:55 -08001441 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001442}
1443
Colin Cross8854a5a2019-02-11 14:14:16 -08001444// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1445func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1446 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001447 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001448 }
1449 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001450 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001451 return ret
1452}
1453
Colin Cross40e33732019-02-15 11:08:35 -08001454// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1455func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1456 path, err := validatePath(paths...)
1457 if err != nil {
1458 reportPathError(ctx, err)
1459 }
1460
1461 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001462 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001463 return ret
1464}
1465
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001466// PathForIntermediates returns an OutputPath representing the top-level
1467// intermediates directory.
1468func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001469 path, err := validatePath(paths...)
1470 if err != nil {
1471 reportPathError(ctx, err)
1472 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001473 return PathForOutput(ctx, ".intermediates", path)
1474}
1475
Colin Cross07e51612019-03-05 12:46:40 -08001476var _ genPathProvider = SourcePath{}
1477var _ objPathProvider = SourcePath{}
1478var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001479
Colin Cross07e51612019-03-05 12:46:40 -08001480// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001481// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001482func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001483 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1484 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1485 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1486 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1487 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001488 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001489 if err != nil {
1490 if depErr, ok := err.(missingDependencyError); ok {
1491 if ctx.Config().AllowMissingDependencies() {
1492 ctx.AddMissingDependencies(depErr.missingDeps)
1493 } else {
1494 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1495 }
1496 } else {
1497 reportPathError(ctx, err)
1498 }
1499 return nil
1500 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001501 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001502 return nil
1503 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001504 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001505 }
1506 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001507}
1508
Liz Kammera830f3a2020-11-10 10:50:34 -08001509func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001510 p, err := validatePath(paths...)
1511 if err != nil {
1512 reportPathError(ctx, err)
1513 }
1514
1515 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1516 if err != nil {
1517 reportPathError(ctx, err)
1518 }
1519
1520 path.basePath.rel = p
1521
1522 return path
1523}
1524
Colin Cross2fafa3e2019-03-05 12:39:51 -08001525// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1526// will return the path relative to subDir in the module's source directory. If any input paths are not located
1527// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001528func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001529 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001530 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001531 for i, path := range paths {
1532 rel := Rel(ctx, subDirFullPath.String(), path.String())
1533 paths[i] = subDirFullPath.join(ctx, rel)
1534 }
1535 return paths
1536}
1537
1538// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1539// 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 -08001540func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001541 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001542 rel := Rel(ctx, subDirFullPath.String(), path.String())
1543 return subDirFullPath.Join(ctx, rel)
1544}
1545
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001546// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1547// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001548func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001549 if p == nil {
1550 return OptionalPath{}
1551 }
1552 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1553}
1554
Liz Kammera830f3a2020-11-10 10:50:34 -08001555func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001556 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001557}
1558
Liz Kammera830f3a2020-11-10 10:50:34 -08001559func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001560 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001561}
1562
Liz Kammera830f3a2020-11-10 10:50:34 -08001563func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001564 // TODO: Use full directory if the new ctx is not the current ctx?
1565 return PathForModuleRes(ctx, p.path, name)
1566}
1567
1568// ModuleOutPath is a Path representing a module's output directory.
1569type ModuleOutPath struct {
1570 OutputPath
1571}
1572
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001573func (p ModuleOutPath) RelativeToTop() Path {
1574 p.OutputPath = p.outputPathRelativeToTop()
1575 return p
1576}
1577
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001578var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001579var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001580
Liz Kammera830f3a2020-11-10 10:50:34 -08001581func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001582 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1583}
1584
Liz Kammera830f3a2020-11-10 10:50:34 -08001585// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1586type ModuleOutPathContext interface {
1587 PathContext
1588
1589 ModuleName() string
1590 ModuleDir() string
1591 ModuleSubDir() string
Inseob Kim8ff69de2023-06-16 14:19:33 +09001592 SoongConfigTraceHash() string
Liz Kammera830f3a2020-11-10 10:50:34 -08001593}
1594
1595func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kim8ff69de2023-06-16 14:19:33 +09001596 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir(), ctx.SoongConfigTraceHash())
Colin Cross702e0f82017-10-18 17:27:54 -07001597}
1598
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001599// PathForModuleOut returns a Path representing the paths... under the module's
1600// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001601func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001602 p, err := validatePath(paths...)
1603 if err != nil {
1604 reportPathError(ctx, err)
1605 }
Colin Cross702e0f82017-10-18 17:27:54 -07001606 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001607 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001608 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001609}
1610
1611// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1612// directory. Mainly used for generated sources.
1613type ModuleGenPath struct {
1614 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001615}
1616
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001617func (p ModuleGenPath) RelativeToTop() Path {
1618 p.OutputPath = p.outputPathRelativeToTop()
1619 return p
1620}
1621
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001622var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001623var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001624var _ genPathProvider = ModuleGenPath{}
1625var _ objPathProvider = ModuleGenPath{}
1626
1627// PathForModuleGen returns a Path representing the paths... under the module's
1628// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001629func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001630 p, err := validatePath(paths...)
1631 if err != nil {
1632 reportPathError(ctx, err)
1633 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001634 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001635 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001636 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001637 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001638 }
1639}
1640
Liz Kammera830f3a2020-11-10 10:50:34 -08001641func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001642 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001643 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001644}
1645
Liz Kammera830f3a2020-11-10 10:50:34 -08001646func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001647 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1648}
1649
1650// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1651// directory. Used for compiled objects.
1652type ModuleObjPath struct {
1653 ModuleOutPath
1654}
1655
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001656func (p ModuleObjPath) RelativeToTop() Path {
1657 p.OutputPath = p.outputPathRelativeToTop()
1658 return p
1659}
1660
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001661var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001662var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001663
1664// PathForModuleObj returns a Path representing the paths... under the module's
1665// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001666func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001667 p, err := validatePath(pathComponents...)
1668 if err != nil {
1669 reportPathError(ctx, err)
1670 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001671 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1672}
1673
1674// ModuleResPath is a a Path representing the 'res' directory in a module's
1675// output directory.
1676type ModuleResPath struct {
1677 ModuleOutPath
1678}
1679
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001680func (p ModuleResPath) RelativeToTop() Path {
1681 p.OutputPath = p.outputPathRelativeToTop()
1682 return p
1683}
1684
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001685var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001686var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001687
1688// PathForModuleRes returns a Path representing the paths... under the module's
1689// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001690func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001691 p, err := validatePath(pathComponents...)
1692 if err != nil {
1693 reportPathError(ctx, err)
1694 }
1695
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001696 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1697}
1698
Colin Cross70dda7e2019-10-01 22:05:35 -07001699// InstallPath is a Path representing a installed file path rooted from the build directory
1700type InstallPath struct {
1701 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001702
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001703 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001704 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001705
Jiyong Park957bcd92020-10-20 18:23:33 +09001706 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1707 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1708 partitionDir string
1709
Colin Crossb1692a32021-10-25 15:39:01 -07001710 partition string
1711
Jiyong Park957bcd92020-10-20 18:23:33 +09001712 // makePath indicates whether this path is for Soong (false) or Make (true).
1713 makePath bool
Colin Crossc0e42d52024-02-01 16:42:36 -08001714
1715 fullPath string
Colin Cross70dda7e2019-10-01 22:05:35 -07001716}
1717
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001718// Will panic if called from outside a test environment.
1719func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001720 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001721 return
1722 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001723 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001724}
1725
1726func (p InstallPath) RelativeToTop() Path {
1727 ensureTestOnly()
Colin Crossc0e42d52024-02-01 16:42:36 -08001728 if p.makePath {
1729 p.soongOutDir = OutDir
1730 } else {
1731 p.soongOutDir = OutSoongDir
1732 }
1733 p.fullPath = filepath.Join(p.soongOutDir, p.path)
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001734 return p
1735}
1736
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001737func (p InstallPath) getSoongOutDir() string {
1738 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001739}
1740
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001741func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1742 panic("Not implemented")
1743}
1744
Paul Duffin9b478b02019-12-10 13:41:51 +00001745var _ Path = InstallPath{}
1746var _ WritablePath = InstallPath{}
1747
Colin Cross70dda7e2019-10-01 22:05:35 -07001748func (p InstallPath) writablePath() {}
1749
1750func (p InstallPath) String() string {
Colin Crossc0e42d52024-02-01 16:42:36 -08001751 return p.fullPath
Jiyong Park957bcd92020-10-20 18:23:33 +09001752}
1753
1754// PartitionDir returns the path to the partition where the install path is rooted at. It is
1755// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1756// The ./soong is dropped if the install path is for Make.
1757func (p InstallPath) PartitionDir() string {
1758 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001759 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001760 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001761 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001762 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001763}
1764
Jihoon Kangf78a8902022-09-01 22:47:07 +00001765func (p InstallPath) Partition() string {
1766 return p.partition
1767}
1768
Colin Cross70dda7e2019-10-01 22:05:35 -07001769// Join creates a new InstallPath with paths... joined with the current path. The
1770// provided paths... may not use '..' to escape from the current path.
1771func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1772 path, err := validatePath(paths...)
1773 if err != nil {
1774 reportPathError(ctx, err)
1775 }
1776 return p.withRel(path)
1777}
1778
1779func (p InstallPath) withRel(rel string) InstallPath {
1780 p.basePath = p.basePath.withRel(rel)
Colin Crossc0e42d52024-02-01 16:42:36 -08001781 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross70dda7e2019-10-01 22:05:35 -07001782 return p
1783}
1784
Colin Crossc68db4b2021-11-11 18:59:15 -08001785// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1786// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001787func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001788 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001789 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001790}
1791
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001792// PathForModuleInstall returns a Path representing the install path for the
1793// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001794func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001795 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07001796 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07001797 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001798}
1799
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001800// PathForHostDexInstall returns an InstallPath representing the install path for the
1801// module appended with paths...
1802func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07001803 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001804}
1805
Spandan Das5d1b9292021-06-03 19:36:41 +00001806// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1807func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1808 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07001809 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001810}
1811
1812func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001813 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001814 arch := ctx.Arch().ArchType
1815 forceOS, forceArch := ctx.InstallForceOS()
1816 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001817 os = *forceOS
1818 }
Jiyong Park87788b52020-09-01 12:37:45 +09001819 if forceArch != nil {
1820 arch = *forceArch
1821 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001822 return os, arch
1823}
Colin Cross609c49a2020-02-13 13:20:11 -08001824
Colin Crossc0e42d52024-02-01 16:42:36 -08001825func pathForPartitionInstallDir(ctx PathContext, partition, partitionPath string, makePath bool) InstallPath {
1826 fullPath := ctx.Config().SoongOutDir()
1827 if makePath {
1828 // Make path starts with out/ instead of out/soong.
1829 fullPath = filepath.Join(fullPath, "../", partitionPath)
1830 } else {
1831 fullPath = filepath.Join(fullPath, partitionPath)
1832 }
1833
1834 return InstallPath{
1835 basePath: basePath{partitionPath, ""},
1836 soongOutDir: ctx.Config().soongOutDir,
1837 partitionDir: partitionPath,
1838 partition: partition,
1839 makePath: makePath,
1840 fullPath: fullPath,
1841 }
1842}
1843
Cole Faust3b703f32023-10-16 13:30:51 -07001844func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08001845 pathComponents ...string) InstallPath {
1846
Jiyong Park97859152023-02-14 17:05:48 +09001847 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001848
Colin Cross6e359402020-02-10 15:29:54 -08001849 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09001850 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001851 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001852 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07001853 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09001854 // instead of linux_glibc
1855 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001856 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07001857 if os == LinuxMusl && ctx.Config().UseHostMusl() {
1858 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
1859 // compiling we will still use "linux_musl".
1860 osName = "linux"
1861 }
1862
Jiyong Park87788b52020-09-01 12:37:45 +09001863 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1864 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1865 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1866 // Let's keep using x86 for the existing cases until we have a need to support
1867 // other architectures.
1868 archName := arch.String()
1869 if os.Class == Host && (arch == X86_64 || arch == Common) {
1870 archName = "x86"
1871 }
Jiyong Park97859152023-02-14 17:05:48 +09001872 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001873 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001874
Jiyong Park97859152023-02-14 17:05:48 +09001875 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001876 if err != nil {
1877 reportPathError(ctx, err)
1878 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001879
Colin Crossc0e42d52024-02-01 16:42:36 -08001880 base := pathForPartitionInstallDir(ctx, partition, partitionPath, ctx.Config().KatiEnabled())
Jiyong Park957bcd92020-10-20 18:23:33 +09001881 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001882}
1883
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001884func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Colin Crossc0e42d52024-02-01 16:42:36 -08001885 base := pathForPartitionInstallDir(ctx, "", prefix, false)
Jiyong Park957bcd92020-10-20 18:23:33 +09001886 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001887}
1888
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001889func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1890 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1891}
1892
1893func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1894 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1895}
1896
Colin Cross70dda7e2019-10-01 22:05:35 -07001897func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07001898 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08001899 return "/" + rel
1900}
1901
Cole Faust11edf552023-10-13 11:32:14 -07001902func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001903 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001904 if ctx.InstallInTestcases() {
1905 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001906 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07001907 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08001908 if ctx.InstallInData() {
1909 partition = "data"
1910 } else if ctx.InstallInRamdisk() {
1911 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1912 partition = "recovery/root/first_stage_ramdisk"
1913 } else {
1914 partition = "ramdisk"
1915 }
1916 if !ctx.InstallInRoot() {
1917 partition += "/system"
1918 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001919 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001920 // The module is only available after switching root into
1921 // /first_stage_ramdisk. To expose the module before switching root
1922 // on a device without a dedicated recovery partition, install the
1923 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001924 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001925 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001926 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001927 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001928 }
1929 if !ctx.InstallInRoot() {
1930 partition += "/system"
1931 }
Inseob Kim08758f02021-04-08 21:13:22 +09001932 } else if ctx.InstallInDebugRamdisk() {
1933 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08001934 } else if ctx.InstallInRecovery() {
1935 if ctx.InstallInRoot() {
1936 partition = "recovery/root"
1937 } else {
1938 // the layout of recovery partion is the same as that of system partition
1939 partition = "recovery/root/system"
1940 }
Colin Crossea30d852023-11-29 16:00:16 -08001941 } else if ctx.SocSpecific() || ctx.InstallInVendor() {
Colin Cross6e359402020-02-10 15:29:54 -08001942 partition = ctx.DeviceConfig().VendorPath()
Colin Crossea30d852023-11-29 16:00:16 -08001943 } else if ctx.DeviceSpecific() || ctx.InstallInOdm() {
Colin Cross6e359402020-02-10 15:29:54 -08001944 partition = ctx.DeviceConfig().OdmPath()
Colin Crossea30d852023-11-29 16:00:16 -08001945 } else if ctx.ProductSpecific() || ctx.InstallInProduct() {
Colin Cross6e359402020-02-10 15:29:54 -08001946 partition = ctx.DeviceConfig().ProductPath()
1947 } else if ctx.SystemExtSpecific() {
1948 partition = ctx.DeviceConfig().SystemExtPath()
1949 } else if ctx.InstallInRoot() {
1950 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001951 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001952 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001953 }
Colin Cross6e359402020-02-10 15:29:54 -08001954 if ctx.InstallInSanitizerDir() {
1955 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001956 }
Colin Cross43f08db2018-11-12 10:13:39 -08001957 }
1958 return partition
1959}
1960
Colin Cross609c49a2020-02-13 13:20:11 -08001961type InstallPaths []InstallPath
1962
1963// Paths returns the InstallPaths as a Paths
1964func (p InstallPaths) Paths() Paths {
1965 if p == nil {
1966 return nil
1967 }
1968 ret := make(Paths, len(p))
1969 for i, path := range p {
1970 ret[i] = path
1971 }
1972 return ret
1973}
1974
1975// Strings returns the string forms of the install paths.
1976func (p InstallPaths) Strings() []string {
1977 if p == nil {
1978 return nil
1979 }
1980 ret := make([]string, len(p))
1981 for i, path := range p {
1982 ret[i] = path.String()
1983 }
1984 return ret
1985}
1986
Jingwen Chen24d0c562023-02-07 09:29:36 +00001987// validatePathInternal ensures that a path does not leave its component, and
1988// optionally doesn't contain Ninja variables.
1989func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07001990 initialEmpty := 0
1991 finalEmpty := 0
1992 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00001993 if !allowNinjaVariables && strings.Contains(path, "$") {
1994 return "", fmt.Errorf("Path contains invalid character($): %s", path)
1995 }
1996
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001997 path := filepath.Clean(path)
1998 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Dmitrii3e980152024-03-09 19:09:51 +00001999 //return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002000 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002001
2002 if i == initialEmpty && pathComponents[i] == "" {
2003 initialEmpty++
2004 }
2005 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
2006 finalEmpty++
2007 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002008 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002009 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
2010 // of "foo", while filepath.Join("foo") does not. Strip out any empty
2011 // path components.
2012 if initialEmpty == len(pathComponents) {
2013 return "", nil
2014 }
2015 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002016 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2017 // variables. '..' may remove the entire ninja variable, even if it
2018 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07002019 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002020}
2021
Jingwen Chen24d0c562023-02-07 09:29:36 +00002022// validateSafePath validates a path that we trust (may contain ninja
2023// variables). Ensures that each path component does not attempt to leave its
2024// component. Returns a joined version of each path component.
2025func validateSafePath(pathComponents ...string) (string, error) {
2026 return validatePathInternal(true, pathComponents...)
2027}
2028
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002029// validatePath validates that a path does not include ninja variables, and that
2030// each path component does not attempt to leave its component. Returns a joined
2031// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002032func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00002033 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002034}
Colin Cross5b529592017-05-09 13:34:34 -07002035
Colin Cross0875c522017-11-28 17:34:01 -08002036func PathForPhony(ctx PathContext, phony string) WritablePath {
2037 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002038 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002039 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002040 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002041}
2042
Colin Cross74e3fe42017-12-11 15:51:44 -08002043type PhonyPath struct {
2044 basePath
2045}
2046
2047func (p PhonyPath) writablePath() {}
2048
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02002049func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00002050 // A phone path cannot contain any / so cannot be relative to the build directory.
2051 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002052}
2053
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002054func (p PhonyPath) RelativeToTop() Path {
2055 ensureTestOnly()
2056 // A phony path cannot contain any / so does not have a build directory so switching to a new
2057 // build directory has no effect so just return this path.
2058 return p
2059}
2060
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002061func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2062 panic("Not implemented")
2063}
2064
Colin Cross74e3fe42017-12-11 15:51:44 -08002065var _ Path = PhonyPath{}
2066var _ WritablePath = PhonyPath{}
2067
Colin Cross5b529592017-05-09 13:34:34 -07002068type testPath struct {
2069 basePath
2070}
2071
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002072func (p testPath) RelativeToTop() Path {
2073 ensureTestOnly()
2074 return p
2075}
2076
Colin Cross5b529592017-05-09 13:34:34 -07002077func (p testPath) String() string {
2078 return p.path
2079}
2080
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002081var _ Path = testPath{}
2082
Colin Cross40e33732019-02-15 11:08:35 -08002083// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2084// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002085func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002086 p, err := validateSafePath(paths...)
2087 if err != nil {
2088 panic(err)
2089 }
Colin Cross5b529592017-05-09 13:34:34 -07002090 return testPath{basePath{path: p, rel: p}}
2091}
2092
Sam Delmerico2351eac2022-05-24 17:10:02 +00002093func PathForTestingWithRel(path, rel string) Path {
2094 p, err := validateSafePath(path, rel)
2095 if err != nil {
2096 panic(err)
2097 }
2098 r, err := validatePath(rel)
2099 if err != nil {
2100 panic(err)
2101 }
2102 return testPath{basePath{path: p, rel: r}}
2103}
2104
Colin Cross40e33732019-02-15 11:08:35 -08002105// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2106func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002107 p := make(Paths, len(strs))
2108 for i, s := range strs {
2109 p[i] = PathForTesting(s)
2110 }
2111
2112 return p
2113}
Colin Cross43f08db2018-11-12 10:13:39 -08002114
Colin Cross40e33732019-02-15 11:08:35 -08002115type testPathContext struct {
2116 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002117}
2118
Colin Cross40e33732019-02-15 11:08:35 -08002119func (x *testPathContext) Config() Config { return x.config }
2120func (x *testPathContext) AddNinjaFileDeps(...string) {}
2121
2122// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2123// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002124func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002125 return &testPathContext{
2126 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002127 }
2128}
2129
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002130type testModuleInstallPathContext struct {
2131 baseModuleContext
2132
2133 inData bool
2134 inTestcases bool
2135 inSanitizerDir bool
2136 inRamdisk bool
2137 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002138 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002139 inRecovery bool
2140 inRoot bool
Colin Crossea30d852023-11-29 16:00:16 -08002141 inOdm bool
2142 inProduct bool
2143 inVendor bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002144 forceOS *OsType
2145 forceArch *ArchType
2146}
2147
2148func (m testModuleInstallPathContext) Config() Config {
2149 return m.baseModuleContext.config
2150}
2151
2152func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2153
2154func (m testModuleInstallPathContext) InstallInData() bool {
2155 return m.inData
2156}
2157
2158func (m testModuleInstallPathContext) InstallInTestcases() bool {
2159 return m.inTestcases
2160}
2161
2162func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2163 return m.inSanitizerDir
2164}
2165
2166func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2167 return m.inRamdisk
2168}
2169
2170func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2171 return m.inVendorRamdisk
2172}
2173
Inseob Kim08758f02021-04-08 21:13:22 +09002174func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2175 return m.inDebugRamdisk
2176}
2177
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002178func (m testModuleInstallPathContext) InstallInRecovery() bool {
2179 return m.inRecovery
2180}
2181
2182func (m testModuleInstallPathContext) InstallInRoot() bool {
2183 return m.inRoot
2184}
2185
Colin Crossea30d852023-11-29 16:00:16 -08002186func (m testModuleInstallPathContext) InstallInOdm() bool {
2187 return m.inOdm
2188}
2189
2190func (m testModuleInstallPathContext) InstallInProduct() bool {
2191 return m.inProduct
2192}
2193
2194func (m testModuleInstallPathContext) InstallInVendor() bool {
2195 return m.inVendor
2196}
2197
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002198func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2199 return m.forceOS, m.forceArch
2200}
2201
2202// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2203// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2204// delegated to it will panic.
2205func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2206 ctx := &testModuleInstallPathContext{}
2207 ctx.config = config
2208 ctx.os = Android
2209 return ctx
2210}
2211
Colin Cross43f08db2018-11-12 10:13:39 -08002212// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2213// targetPath is not inside basePath.
2214func Rel(ctx PathContext, basePath string, targetPath string) string {
2215 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2216 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002217 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002218 return ""
2219 }
2220 return rel
2221}
2222
2223// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2224// targetPath is not inside basePath.
2225func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002226 rel, isRel, err := maybeRelErr(basePath, targetPath)
2227 if err != nil {
2228 reportPathError(ctx, err)
2229 }
2230 return rel, isRel
2231}
2232
2233func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002234 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2235 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002236 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002237 }
2238 rel, err := filepath.Rel(basePath, targetPath)
2239 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002240 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002241 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002242 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002243 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002244 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002245}
Colin Cross988414c2020-01-11 01:11:46 +00002246
2247// Writes a file to the output directory. Attempting to write directly to the output directory
2248// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002249// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2250// updating the timestamp if no changes would be made. (This is better for incremental
2251// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002252func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002253 absPath := absolutePath(path.String())
2254 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2255 if err != nil {
2256 return err
2257 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002258 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002259}
2260
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002261func RemoveAllOutputDir(path WritablePath) error {
2262 return os.RemoveAll(absolutePath(path.String()))
2263}
2264
2265func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2266 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002267 return createDirIfNonexistent(dir, perm)
2268}
2269
2270func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002271 if _, err := os.Stat(dir); os.IsNotExist(err) {
2272 return os.MkdirAll(dir, os.ModePerm)
2273 } else {
2274 return err
2275 }
2276}
2277
Jingwen Chen78257e52021-05-21 02:34:24 +00002278// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2279// read arbitrary files without going through the methods in the current package that track
2280// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002281func absolutePath(path string) string {
2282 if filepath.IsAbs(path) {
2283 return path
2284 }
2285 return filepath.Join(absSrcDir, path)
2286}
Chris Parsons216e10a2020-07-09 17:12:52 -04002287
2288// A DataPath represents the path of a file to be used as data, for example
2289// a test library to be installed alongside a test.
2290// The data file should be installed (copied from `<SrcPath>`) to
2291// `<install_root>/<RelativeInstallPath>/<filename>`, or
2292// `<install_root>/<filename>` if RelativeInstallPath is empty.
2293type DataPath struct {
2294 // The path of the data file that should be copied into the data directory
2295 SrcPath Path
2296 // The install path of the data file, relative to the install root.
2297 RelativeInstallPath string
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002298 // If WithoutRel is true, use SrcPath.Base() instead of SrcPath.Rel() as the filename.
2299 WithoutRel bool
Chris Parsons216e10a2020-07-09 17:12:52 -04002300}
Colin Crossdcf71b22021-02-01 13:59:03 -08002301
Colin Crossd442a0e2023-11-16 11:19:26 -08002302func (d *DataPath) ToRelativeInstallPath() string {
2303 relPath := d.SrcPath.Rel()
Colin Cross5c1d5fb2023-11-15 12:39:40 -08002304 if d.WithoutRel {
2305 relPath = d.SrcPath.Base()
2306 }
Colin Crossd442a0e2023-11-16 11:19:26 -08002307 if d.RelativeInstallPath != "" {
2308 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2309 }
2310 return relPath
Colin Cross3f40fa42015-01-30 17:27:36 -08002311}
Colin Crossdcf71b22021-02-01 13:59:03 -08002312
2313// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2314func PathsIfNonNil(paths ...Path) Paths {
2315 if len(paths) == 0 {
2316 // Fast path for empty argument list
2317 return nil
2318 } else if len(paths) == 1 {
2319 // Fast path for a single argument
2320 if paths[0] != nil {
2321 return paths
2322 } else {
2323 return nil
2324 }
2325 }
2326 ret := make(Paths, 0, len(paths))
2327 for _, path := range paths {
2328 if path != nil {
2329 ret = append(ret, path)
2330 }
2331 }
2332 if len(ret) == 0 {
2333 return nil
2334 }
2335 return ret
2336}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002337
2338var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2339 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2340 regexp.MustCompile("^hardware/google/"),
2341 regexp.MustCompile("^hardware/interfaces/"),
2342 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2343 regexp.MustCompile("^hardware/ril/"),
2344}
2345
2346func IsThirdPartyPath(path string) bool {
2347 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2348
2349 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2350 for _, prefix := range thirdPartyDirPrefixExceptions {
2351 if prefix.MatchString(path) {
2352 return false
2353 }
2354 }
2355 return true
2356 }
2357 return false
2358}