blob: 37b04ddfcec784d4e4394e5b22f6159e8f074935 [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 (
Liz Kammer356f7d42021-01-26 09:18:53 -050018 "android/soong/bazel"
Colin Cross6e18ca42015-07-14 18:55:36 -070019 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000020 "io/ioutil"
21 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070022 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070023 "reflect"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070024 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070025 "strings"
26
27 "github.com/google/blueprint"
28 "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 {
41 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
42}
43
Colin Crossaabf6792017-11-29 00:27:14 -080044var _ PathContext = SingletonContext(nil)
45var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070046
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010047// "Null" path context is a minimal path context for a given config.
48type NullPathContext struct {
49 config Config
50}
51
52func (NullPathContext) AddNinjaFileDeps(...string) {}
53func (ctx NullPathContext) Config() Config { return ctx.config }
54
Liz Kammera830f3a2020-11-10 10:50:34 -080055// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
56// Path methods. These path methods can be called before any mutators have run.
57type EarlyModulePathContext interface {
58 PathContext
59 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
91 GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module
92}
93
94// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
95// the Path methods that rely on module dependencies having been resolved and ability to report
96// missing dependency errors.
97type ModuleMissingDepsPathContext interface {
98 ModuleWithDepsPathContext
99 AddMissingDependencies(missingDeps []string)
100}
101
Dan Willemsen00269f22017-07-06 16:59:48 -0700102type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700103 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700104
105 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700106 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700107 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800108 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700109 InstallInVendorRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900110 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700111 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -0700112 InstallBypassMake() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900113 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700114}
115
116var _ ModuleInstallPathContext = ModuleContext(nil)
117
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700118// errorfContext is the interface containing the Errorf method matching the
119// Errorf method in blueprint.SingletonContext.
120type errorfContext interface {
121 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800122}
123
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700124var _ errorfContext = blueprint.SingletonContext(nil)
125
126// moduleErrorf is the interface containing the ModuleErrorf method matching
127// the ModuleErrorf method in blueprint.ModuleContext.
128type moduleErrorf interface {
129 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800130}
131
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700132var _ moduleErrorf = blueprint.ModuleContext(nil)
133
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700134// reportPathError will register an error with the attached context. It
135// attempts ctx.ModuleErrorf for a better error message first, then falls
136// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800137func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100138 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800139}
140
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100141// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800142// attempts ctx.ModuleErrorf for a better error message first, then falls
143// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100144func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700145 if mctx, ok := ctx.(moduleErrorf); ok {
146 mctx.ModuleErrorf(format, args...)
147 } else if ectx, ok := ctx.(errorfContext); ok {
148 ectx.Errorf(format, args...)
149 } else {
150 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700151 }
152}
153
Colin Cross5e708052019-08-06 13:59:50 -0700154func pathContextName(ctx PathContext, module blueprint.Module) string {
155 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
156 return x.ModuleName(module)
157 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
158 return x.OtherModuleName(module)
159 }
160 return "unknown"
161}
162
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700163type Path interface {
164 // Returns the path in string form
165 String() string
166
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700167 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700168 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700169
170 // Base returns the last element of the path
171 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800172
173 // Rel returns the portion of the path relative to the directory it was created from. For
174 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800175 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800176 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000177
178 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
179 //
180 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
181 // InstallPath then the returned value can be converted to an InstallPath.
182 //
183 // A standard build has the following structure:
184 // ../top/
185 // out/ - make install files go here.
186 // out/soong - this is the buildDir passed to NewTestConfig()
187 // ... - the source files
188 //
189 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
190 // * Make install paths, which have the pattern "buildDir/../<path>" are converted into the top
191 // relative path "out/<path>"
192 // * Soong install paths and other writable paths, which have the pattern "buildDir/<path>" are
193 // converted into the top relative path "out/soong/<path>".
194 // * Source paths are already relative to the top.
195 // * Phony paths are not relative to anything.
196 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
197 // order to test.
198 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700199}
200
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000201const (
202 OutDir = "out"
203 OutSoongDir = OutDir + "/soong"
204)
205
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700206// WritablePath is a type of path that can be used as an output for build rules.
207type WritablePath interface {
208 Path
209
Paul Duffin9b478b02019-12-10 13:41:51 +0000210 // return the path to the build directory.
Paul Duffind65c58b2021-03-24 09:22:07 +0000211 getBuildDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000212
Jeff Gaston734e3802017-04-10 15:47:24 -0700213 // the writablePath method doesn't directly do anything,
214 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700215 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100216
217 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700218}
219
220type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800221 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700222}
223type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800224 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700225}
226type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800227 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700228}
229
230// GenPathWithExt derives a new file path in ctx's generated sources directory
231// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800232func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700233 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700234 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700235 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100236 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700237 return PathForModuleGen(ctx)
238}
239
240// ObjPathWithExt derives a new file path in ctx's object directory from the
241// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800242func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700243 if path, ok := p.(objPathProvider); ok {
244 return path.objPathWithExt(ctx, subdir, ext)
245 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100246 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700247 return PathForModuleObj(ctx)
248}
249
250// ResPathWithName derives a new path in ctx's output resource directory, using
251// the current path to create the directory name, and the `name` argument for
252// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800253func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700254 if path, ok := p.(resPathProvider); ok {
255 return path.resPathWithName(ctx, name)
256 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100257 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700258 return PathForModuleRes(ctx)
259}
260
261// OptionalPath is a container that may or may not contain a valid Path.
262type OptionalPath struct {
263 valid bool
264 path Path
265}
266
267// OptionalPathForPath returns an OptionalPath containing the path.
268func OptionalPathForPath(path Path) OptionalPath {
269 if path == nil {
270 return OptionalPath{}
271 }
272 return OptionalPath{valid: true, path: path}
273}
274
275// Valid returns whether there is a valid path
276func (p OptionalPath) Valid() bool {
277 return p.valid
278}
279
280// Path returns the Path embedded in this OptionalPath. You must be sure that
281// there is a valid path, since this method will panic if there is not.
282func (p OptionalPath) Path() Path {
283 if !p.valid {
284 panic("Requesting an invalid path")
285 }
286 return p.path
287}
288
Paul Duffinafdd4062021-03-30 19:44:07 +0100289// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
290// result of calling Path.RelativeToTop on it.
291func (p OptionalPath) RelativeToTop() OptionalPath {
Paul Duffina5b81352021-03-28 23:57:19 +0100292 if !p.valid {
293 return p
294 }
295 p.path = p.path.RelativeToTop()
296 return p
297}
298
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700299// String returns the string version of the Path, or "" if it isn't valid.
300func (p OptionalPath) String() string {
301 if p.valid {
302 return p.path.String()
303 } else {
304 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700305 }
306}
Colin Cross6e18ca42015-07-14 18:55:36 -0700307
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700308// Paths is a slice of Path objects, with helpers to operate on the collection.
309type Paths []Path
310
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000311// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
312// item in this slice.
313func (p Paths) RelativeToTop() Paths {
314 ensureTestOnly()
315 if p == nil {
316 return p
317 }
318 ret := make(Paths, len(p))
319 for i, path := range p {
320 ret[i] = path.RelativeToTop()
321 }
322 return ret
323}
324
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000325func (paths Paths) containsPath(path Path) bool {
326 for _, p := range paths {
327 if p == path {
328 return true
329 }
330 }
331 return false
332}
333
Liz Kammer7aa52882021-02-11 09:16:14 -0500334// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
335// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700336func PathsForSource(ctx PathContext, paths []string) Paths {
337 ret := make(Paths, len(paths))
338 for i, path := range paths {
339 ret[i] = PathForSource(ctx, path)
340 }
341 return ret
342}
343
Liz Kammer7aa52882021-02-11 09:16:14 -0500344// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
345// module's local source directory, that are found in the tree. If any are not found, they are
346// omitted from the list, and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800347func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800348 ret := make(Paths, 0, len(paths))
349 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800350 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800351 if p.Valid() {
352 ret = append(ret, p.Path())
353 }
354 }
355 return ret
356}
357
Colin Cross41955e82019-05-29 14:40:35 -0700358// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
359// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
360// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
361// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
362// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
363// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800364func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800365 return PathsForModuleSrcExcludes(ctx, paths, nil)
366}
367
Colin Crossba71a3f2019-03-18 12:12:48 -0700368// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700369// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
370// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
371// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
372// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100373// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700374// having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800375func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700376 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
377 if ctx.Config().AllowMissingDependencies() {
378 ctx.AddMissingDependencies(missingDeps)
379 } else {
380 for _, m := range missingDeps {
381 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
382 }
383 }
384 return ret
385}
386
Liz Kammer356f7d42021-01-26 09:18:53 -0500387// A subset of the ModuleContext methods which are sufficient to resolve references to paths/deps in
388// order to form a Bazel-compatible label for conversion.
389type BazelConversionPathContext interface {
390 EarlyModulePathContext
391
392 GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
Liz Kammerbdc60992021-02-24 16:55:11 -0500393 Module() Module
Jingwen Chen12b4c272021-03-10 02:05:59 -0500394 ModuleType() string
Liz Kammer356f7d42021-01-26 09:18:53 -0500395 OtherModuleName(m blueprint.Module) string
396 OtherModuleDir(m blueprint.Module) string
397}
398
399// BazelLabelForModuleDeps returns a Bazel-compatible label for the requested modules which
400// correspond to dependencies on the module within the given ctx.
401func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
402 var labels bazel.LabelList
403 for _, module := range modules {
404 bpText := module
405 if m := SrcIsModule(module); m == "" {
406 module = ":" + module
407 }
408 if m, t := SrcIsModuleWithTag(module); m != "" {
409 l := getOtherModuleLabel(ctx, m, t)
410 l.Bp_text = bpText
411 labels.Includes = append(labels.Includes, l)
412 } else {
413 ctx.ModuleErrorf("%q, is not a module reference", module)
414 }
415 }
416 return labels
417}
418
419// BazelLabelForModuleSrc returns bazel.LabelList with paths rooted from the module's local source
420// directory. It expands globs, and resolves references to modules using the ":name" syntax to
421// bazel-compatible labels. Properties passed as the paths or excludes argument must have been
422// annotated with struct tag `android:"path"` so that dependencies on other modules will have
423// already been handled by the path_properties mutator.
Jingwen Chen63930982021-03-24 10:04:33 -0400424//
425// With expanded globs, we can catch package boundaries problem instead of
426// silently failing to potentially missing files from Bazel's globs.
Liz Kammer356f7d42021-01-26 09:18:53 -0500427func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
428 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
429}
430
431// BazelLabelForModuleSrcExcludes returns bazel.LabelList with paths rooted from the module's local
432// source directory, excluding labels included in the excludes argument. It expands globs, and
433// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
434// passed as the paths or excludes argument must have been annotated with struct tag
435// `android:"path"` so that dependencies on other modules will have already been handled by the
436// path_properties mutator.
Jingwen Chen63930982021-03-24 10:04:33 -0400437//
438// With expanded globs, we can catch package boundaries problem instead of
439// silently failing to potentially missing files from Bazel's globs.
Liz Kammer356f7d42021-01-26 09:18:53 -0500440func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
441 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
442 excluded := make([]string, 0, len(excludeLabels.Includes))
443 for _, e := range excludeLabels.Includes {
444 excluded = append(excluded, e.Label)
445 }
446 labels := expandSrcsForBazel(ctx, paths, excluded)
447 labels.Excludes = excludeLabels.Includes
448 return labels
449}
450
451// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local
452// source directory, excluding labels included in the excludes argument. It expands globs, and
453// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
454// passed as the paths or excludes argument must have been annotated with struct tag
455// `android:"path"` so that dependencies on other modules will have already been handled by the
456// path_properties mutator.
457func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammerebfcf672021-02-16 15:00:05 -0500458 if paths == nil {
459 return bazel.LabelList{}
460 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500461 labels := bazel.LabelList{
462 Includes: []bazel.Label{},
463 }
464 for _, p := range paths {
465 if m, tag := SrcIsModuleWithTag(p); m != "" {
466 l := getOtherModuleLabel(ctx, m, tag)
467 if !InList(l.Label, expandedExcludes) {
468 l.Bp_text = fmt.Sprintf(":%s", m)
469 labels.Includes = append(labels.Includes, l)
470 }
471 } else {
472 var expandedPaths []bazel.Label
473 if pathtools.IsGlob(p) {
474 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
475 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
476 for _, path := range globbedPaths {
477 s := path.Rel()
478 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
479 }
480 } else {
481 if !InList(p, expandedExcludes) {
482 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
483 }
484 }
485 labels.Includes = append(labels.Includes, expandedPaths...)
486 }
487 }
488 return labels
489}
490
491// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
492// module. The label will be relative to the current directory if appropriate. The dependency must
493// already be resolved by either deps mutator or path deps mutator.
494func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
495 m, _ := ctx.GetDirectDep(dep)
Jingwen Chen07027912021-03-15 06:02:43 -0400496 if m == nil {
497 panic(fmt.Errorf("cannot get direct dep %s of %s", dep, ctx.Module().Name()))
498 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500499 otherLabel := bazelModuleLabel(ctx, m, tag)
500 label := bazelModuleLabel(ctx, ctx.Module(), "")
501 if samePackage(label, otherLabel) {
502 otherLabel = bazelShortLabel(otherLabel)
Liz Kammer356f7d42021-01-26 09:18:53 -0500503 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500504
505 return bazel.Label{
506 Label: otherLabel,
507 }
508}
509
510func bazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module, tag string) string {
511 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
512 b, ok := module.(Bazelable)
513 // TODO(b/181155349): perhaps return an error here if the module can't be/isn't being converted
Jingwen Chen12b4c272021-03-10 02:05:59 -0500514 if !ok || !b.ConvertedToBazel(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500515 return bp2buildModuleLabel(ctx, module)
516 }
517 return b.GetBazelLabel(ctx, module)
518}
519
520func bazelShortLabel(label string) string {
521 i := strings.Index(label, ":")
522 return label[i:]
523}
524
525func bazelPackage(label string) string {
526 i := strings.Index(label, ":")
527 return label[0:i]
528}
529
530func samePackage(label1, label2 string) bool {
531 return bazelPackage(label1) == bazelPackage(label2)
532}
533
534func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
535 moduleName := ctx.OtherModuleName(module)
536 moduleDir := ctx.OtherModuleDir(module)
537 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500538}
539
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000540// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
541type OutputPaths []OutputPath
542
543// Paths returns the OutputPaths as a Paths
544func (p OutputPaths) Paths() Paths {
545 if p == nil {
546 return nil
547 }
548 ret := make(Paths, len(p))
549 for i, path := range p {
550 ret[i] = path
551 }
552 return ret
553}
554
555// Strings returns the string forms of the writable paths.
556func (p OutputPaths) Strings() []string {
557 if p == nil {
558 return nil
559 }
560 ret := make([]string, len(p))
561 for i, path := range p {
562 ret[i] = path.String()
563 }
564 return ret
565}
566
Liz Kammera830f3a2020-11-10 10:50:34 -0800567// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
568// If the dependency is not found, a missingErrorDependency is returned.
569// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
570func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
571 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
572 if module == nil {
573 return nil, missingDependencyError{[]string{moduleName}}
574 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700575 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
576 return nil, missingDependencyError{[]string{moduleName}}
577 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800578 if outProducer, ok := module.(OutputFileProducer); ok {
579 outputFiles, err := outProducer.OutputFiles(tag)
580 if err != nil {
581 return nil, fmt.Errorf("path dependency %q: %s", path, err)
582 }
583 return outputFiles, nil
584 } else if tag != "" {
585 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
586 } else if srcProducer, ok := module.(SourceFileProducer); ok {
587 return srcProducer.Srcs(), nil
588 } else {
589 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
590 }
591}
592
Colin Crossba71a3f2019-03-18 12:12:48 -0700593// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700594// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
595// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
596// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
597// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
598// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
599// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
600// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800601func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800602 prefix := pathForModuleSrc(ctx).String()
603
604 var expandedExcludes []string
605 if excludes != nil {
606 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700607 }
Colin Cross8a497952019-03-05 22:25:09 -0800608
Colin Crossba71a3f2019-03-18 12:12:48 -0700609 var missingExcludeDeps []string
610
Colin Cross8a497952019-03-05 22:25:09 -0800611 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700612 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800613 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
614 if m, ok := err.(missingDependencyError); ok {
615 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
616 } else if err != nil {
617 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800618 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800619 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800620 }
621 } else {
622 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
623 }
624 }
625
626 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700627 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800628 }
629
Colin Crossba71a3f2019-03-18 12:12:48 -0700630 var missingDeps []string
631
Colin Cross8a497952019-03-05 22:25:09 -0800632 expandedSrcFiles := make(Paths, 0, len(paths))
633 for _, s := range paths {
634 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
635 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700636 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800637 } else if err != nil {
638 reportPathError(ctx, err)
639 }
640 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
641 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700642
643 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800644}
645
646type missingDependencyError struct {
647 missingDeps []string
648}
649
650func (e missingDependencyError) Error() string {
651 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
652}
653
Liz Kammera830f3a2020-11-10 10:50:34 -0800654// Expands one path string to Paths rooted from the module's local source
655// directory, excluding those listed in the expandedExcludes.
656// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
657func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900658 excludePaths := func(paths Paths) Paths {
659 if len(expandedExcludes) == 0 {
660 return paths
661 }
662 remainder := make(Paths, 0, len(paths))
663 for _, p := range paths {
664 if !InList(p.String(), expandedExcludes) {
665 remainder = append(remainder, p)
666 }
667 }
668 return remainder
669 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800670 if m, t := SrcIsModuleWithTag(sPath); m != "" {
671 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
672 if err != nil {
673 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800674 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800675 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800676 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800677 } else if pathtools.IsGlob(sPath) {
678 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800679 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
680 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800681 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000682 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100683 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000684 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100685 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800686 }
687
Jooyung Han7607dd32020-07-05 10:23:14 +0900688 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800689 return nil, nil
690 }
691 return Paths{p}, nil
692 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700693}
694
695// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
696// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800697// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700698// It intended for use in globs that only list files that exist, so it allows '$' in
699// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800700func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800701 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700702 if prefix == "./" {
703 prefix = ""
704 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700705 ret := make(Paths, 0, len(paths))
706 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800707 if !incDirs && strings.HasSuffix(p, "/") {
708 continue
709 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700710 path := filepath.Clean(p)
711 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100712 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700713 continue
714 }
Colin Crosse3924e12018-08-15 20:18:53 -0700715
Colin Crossfe4bc362018-09-12 10:02:13 -0700716 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700717 if err != nil {
718 reportPathError(ctx, err)
719 continue
720 }
721
Colin Cross07e51612019-03-05 12:46:40 -0800722 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700723
Colin Cross07e51612019-03-05 12:46:40 -0800724 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700725 }
726 return ret
727}
728
Liz Kammera830f3a2020-11-10 10:50:34 -0800729// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
730// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
731func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800732 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700733 return PathsForModuleSrc(ctx, input)
734 }
735 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
736 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800737 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800738 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700739}
740
741// Strings returns the Paths in string form
742func (p Paths) Strings() []string {
743 if p == nil {
744 return nil
745 }
746 ret := make([]string, len(p))
747 for i, path := range p {
748 ret[i] = path.String()
749 }
750 return ret
751}
752
Colin Crossc0efd1d2020-07-03 11:56:24 -0700753func CopyOfPaths(paths Paths) Paths {
754 return append(Paths(nil), paths...)
755}
756
Colin Crossb6715442017-10-24 11:13:31 -0700757// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
758// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700759func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800760 // 128 was chosen based on BenchmarkFirstUniquePaths results.
761 if len(list) > 128 {
762 return firstUniquePathsMap(list)
763 }
764 return firstUniquePathsList(list)
765}
766
Colin Crossc0efd1d2020-07-03 11:56:24 -0700767// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
768// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900769func SortedUniquePaths(list Paths) Paths {
770 unique := FirstUniquePaths(list)
771 sort.Slice(unique, func(i, j int) bool {
772 return unique[i].String() < unique[j].String()
773 })
774 return unique
775}
776
Colin Cross27027c72020-02-28 15:34:17 -0800777func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700778 k := 0
779outer:
780 for i := 0; i < len(list); i++ {
781 for j := 0; j < k; j++ {
782 if list[i] == list[j] {
783 continue outer
784 }
785 }
786 list[k] = list[i]
787 k++
788 }
789 return list[:k]
790}
791
Colin Cross27027c72020-02-28 15:34:17 -0800792func firstUniquePathsMap(list Paths) Paths {
793 k := 0
794 seen := make(map[Path]bool, len(list))
795 for i := 0; i < len(list); i++ {
796 if seen[list[i]] {
797 continue
798 }
799 seen[list[i]] = true
800 list[k] = list[i]
801 k++
802 }
803 return list[:k]
804}
805
Colin Cross5d583952020-11-24 16:21:24 -0800806// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
807// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
808func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
809 // 128 was chosen based on BenchmarkFirstUniquePaths results.
810 if len(list) > 128 {
811 return firstUniqueInstallPathsMap(list)
812 }
813 return firstUniqueInstallPathsList(list)
814}
815
816func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
817 k := 0
818outer:
819 for i := 0; i < len(list); i++ {
820 for j := 0; j < k; j++ {
821 if list[i] == list[j] {
822 continue outer
823 }
824 }
825 list[k] = list[i]
826 k++
827 }
828 return list[:k]
829}
830
831func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
832 k := 0
833 seen := make(map[InstallPath]bool, len(list))
834 for i := 0; i < len(list); i++ {
835 if seen[list[i]] {
836 continue
837 }
838 seen[list[i]] = true
839 list[k] = list[i]
840 k++
841 }
842 return list[:k]
843}
844
Colin Crossb6715442017-10-24 11:13:31 -0700845// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
846// modifies the Paths slice contents in place, and returns a subslice of the original slice.
847func LastUniquePaths(list Paths) Paths {
848 totalSkip := 0
849 for i := len(list) - 1; i >= totalSkip; i-- {
850 skip := 0
851 for j := i - 1; j >= totalSkip; j-- {
852 if list[i] == list[j] {
853 skip++
854 } else {
855 list[j+skip] = list[j]
856 }
857 }
858 totalSkip += skip
859 }
860 return list[totalSkip:]
861}
862
Colin Crossa140bb02018-04-17 10:52:26 -0700863// ReversePaths returns a copy of a Paths in reverse order.
864func ReversePaths(list Paths) Paths {
865 if list == nil {
866 return nil
867 }
868 ret := make(Paths, len(list))
869 for i := range list {
870 ret[i] = list[len(list)-1-i]
871 }
872 return ret
873}
874
Jeff Gaston294356f2017-09-27 17:05:30 -0700875func indexPathList(s Path, list []Path) int {
876 for i, l := range list {
877 if l == s {
878 return i
879 }
880 }
881
882 return -1
883}
884
885func inPathList(p Path, list []Path) bool {
886 return indexPathList(p, list) != -1
887}
888
889func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000890 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
891}
892
893func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700894 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000895 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700896 filtered = append(filtered, l)
897 } else {
898 remainder = append(remainder, l)
899 }
900 }
901
902 return
903}
904
Colin Cross93e85952017-08-15 13:34:18 -0700905// HasExt returns true of any of the paths have extension ext, otherwise false
906func (p Paths) HasExt(ext string) bool {
907 for _, path := range p {
908 if path.Ext() == ext {
909 return true
910 }
911 }
912
913 return false
914}
915
916// FilterByExt returns the subset of the paths that have extension ext
917func (p Paths) FilterByExt(ext string) Paths {
918 ret := make(Paths, 0, len(p))
919 for _, path := range p {
920 if path.Ext() == ext {
921 ret = append(ret, path)
922 }
923 }
924 return ret
925}
926
927// FilterOutByExt returns the subset of the paths that do not have extension ext
928func (p Paths) FilterOutByExt(ext string) Paths {
929 ret := make(Paths, 0, len(p))
930 for _, path := range p {
931 if path.Ext() != ext {
932 ret = append(ret, path)
933 }
934 }
935 return ret
936}
937
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700938// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
939// (including subdirectories) are in a contiguous subslice of the list, and can be found in
940// O(log(N)) time using a binary search on the directory prefix.
941type DirectorySortedPaths Paths
942
943func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
944 ret := append(DirectorySortedPaths(nil), paths...)
945 sort.Slice(ret, func(i, j int) bool {
946 return ret[i].String() < ret[j].String()
947 })
948 return ret
949}
950
951// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
952// that are in the specified directory and its subdirectories.
953func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
954 prefix := filepath.Clean(dir) + "/"
955 start := sort.Search(len(p), func(i int) bool {
956 return prefix < p[i].String()
957 })
958
959 ret := p[start:]
960
961 end := sort.Search(len(ret), func(i int) bool {
962 return !strings.HasPrefix(ret[i].String(), prefix)
963 })
964
965 ret = ret[:end]
966
967 return Paths(ret)
968}
969
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500970// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700971type WritablePaths []WritablePath
972
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000973// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
974// each item in this slice.
975func (p WritablePaths) RelativeToTop() WritablePaths {
976 ensureTestOnly()
977 if p == nil {
978 return p
979 }
980 ret := make(WritablePaths, len(p))
981 for i, path := range p {
982 ret[i] = path.RelativeToTop().(WritablePath)
983 }
984 return ret
985}
986
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700987// Strings returns the string forms of the writable paths.
988func (p WritablePaths) Strings() []string {
989 if p == nil {
990 return nil
991 }
992 ret := make([]string, len(p))
993 for i, path := range p {
994 ret[i] = path.String()
995 }
996 return ret
997}
998
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800999// Paths returns the WritablePaths as a Paths
1000func (p WritablePaths) Paths() Paths {
1001 if p == nil {
1002 return nil
1003 }
1004 ret := make(Paths, len(p))
1005 for i, path := range p {
1006 ret[i] = path
1007 }
1008 return ret
1009}
1010
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001011type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001012 path string
1013 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001014}
1015
1016func (p basePath) Ext() string {
1017 return filepath.Ext(p.path)
1018}
1019
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001020func (p basePath) Base() string {
1021 return filepath.Base(p.path)
1022}
1023
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001024func (p basePath) Rel() string {
1025 if p.rel != "" {
1026 return p.rel
1027 }
1028 return p.path
1029}
1030
Colin Cross0875c522017-11-28 17:34:01 -08001031func (p basePath) String() string {
1032 return p.path
1033}
1034
Colin Cross0db55682017-12-05 15:36:55 -08001035func (p basePath) withRel(rel string) basePath {
1036 p.path = filepath.Join(p.path, rel)
1037 p.rel = rel
1038 return p
1039}
1040
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001041// SourcePath is a Path representing a file path rooted from SrcDir
1042type SourcePath struct {
1043 basePath
Paul Duffin580efc82021-03-24 09:04:03 +00001044
1045 // The sources root, i.e. Config.SrcDir()
1046 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001047}
1048
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001049func (p SourcePath) RelativeToTop() Path {
1050 ensureTestOnly()
1051 return p
1052}
1053
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001054var _ Path = SourcePath{}
1055
Colin Cross0db55682017-12-05 15:36:55 -08001056func (p SourcePath) withRel(rel string) SourcePath {
1057 p.basePath = p.basePath.withRel(rel)
1058 return p
1059}
1060
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001061// safePathForSource is for paths that we expect are safe -- only for use by go
1062// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001063func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1064 p, err := validateSafePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +00001065 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Crossfe4bc362018-09-12 10:02:13 -07001066 if err != nil {
1067 return ret, err
1068 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001069
Colin Cross7b3dcc32019-01-24 13:14:39 -08001070 // absolute path already checked by validateSafePath
1071 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001072 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001073 }
1074
Colin Crossfe4bc362018-09-12 10:02:13 -07001075 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001076}
1077
Colin Cross192e97a2018-02-22 14:21:02 -08001078// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1079func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001080 p, err := validatePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +00001081 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Cross94a32102018-02-22 14:21:02 -08001082 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001083 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001084 }
1085
Colin Cross7b3dcc32019-01-24 13:14:39 -08001086 // absolute path already checked by validatePath
1087 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001088 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001089 }
1090
Colin Cross192e97a2018-02-22 14:21:02 -08001091 return ret, nil
1092}
1093
1094// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1095// path does not exist.
1096func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1097 var files []string
1098
1099 if gctx, ok := ctx.(PathGlobContext); ok {
1100 // Use glob to produce proper dependencies, even though we only want
1101 // a single file.
1102 files, err = gctx.GlobWithDeps(path.String(), nil)
1103 } else {
1104 var deps []string
1105 // We cannot add build statements in this context, so we fall back to
1106 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +00001107 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -08001108 ctx.AddNinjaFileDeps(deps...)
1109 }
1110
1111 if err != nil {
1112 return false, fmt.Errorf("glob: %s", err.Error())
1113 }
1114
1115 return len(files) > 0, nil
1116}
1117
1118// PathForSource joins the provided path components and validates that the result
1119// neither escapes the source dir nor is in the out dir.
1120// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1121func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1122 path, err := pathForSource(ctx, pathComponents...)
1123 if err != nil {
1124 reportPathError(ctx, err)
1125 }
1126
Colin Crosse3924e12018-08-15 20:18:53 -07001127 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001128 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001129 }
1130
Liz Kammera830f3a2020-11-10 10:50:34 -08001131 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001132 exists, err := existsWithDependencies(ctx, path)
1133 if err != nil {
1134 reportPathError(ctx, err)
1135 }
1136 if !exists {
1137 modCtx.AddMissingDependencies([]string{path.String()})
1138 }
Colin Cross988414c2020-01-11 01:11:46 +00001139 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001140 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001141 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001142 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001143 }
1144 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001145}
1146
Liz Kammer7aa52882021-02-11 09:16:14 -05001147// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1148// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1149// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1150// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001151func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001152 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001153 if err != nil {
1154 reportPathError(ctx, err)
1155 return OptionalPath{}
1156 }
Colin Crossc48c1432018-02-23 07:09:01 +00001157
Colin Crosse3924e12018-08-15 20:18:53 -07001158 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001159 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001160 return OptionalPath{}
1161 }
1162
Colin Cross192e97a2018-02-22 14:21:02 -08001163 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001164 if err != nil {
1165 reportPathError(ctx, err)
1166 return OptionalPath{}
1167 }
Colin Cross192e97a2018-02-22 14:21:02 -08001168 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001169 return OptionalPath{}
1170 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001171 return OptionalPathForPath(path)
1172}
1173
1174func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001175 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001176}
1177
1178// Join creates a new SourcePath with paths... joined with the current path. The
1179// provided paths... may not use '..' to escape from the current path.
1180func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001181 path, err := validatePath(paths...)
1182 if err != nil {
1183 reportPathError(ctx, err)
1184 }
Colin Cross0db55682017-12-05 15:36:55 -08001185 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001186}
1187
Colin Cross2fafa3e2019-03-05 12:39:51 -08001188// join is like Join but does less path validation.
1189func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1190 path, err := validateSafePath(paths...)
1191 if err != nil {
1192 reportPathError(ctx, err)
1193 }
1194 return p.withRel(path)
1195}
1196
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001197// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1198// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001199func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001200 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001201 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001202 relDir = srcPath.path
1203 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001204 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001205 return OptionalPath{}
1206 }
Paul Duffin580efc82021-03-24 09:04:03 +00001207 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001208 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001209 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001210 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001211 }
Colin Cross461b4452018-02-23 09:22:42 -08001212 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001213 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001214 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001215 return OptionalPath{}
1216 }
1217 if len(paths) == 0 {
1218 return OptionalPath{}
1219 }
Paul Duffin580efc82021-03-24 09:04:03 +00001220 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001221 return OptionalPathForPath(PathForSource(ctx, relPath))
1222}
1223
Colin Cross70dda7e2019-10-01 22:05:35 -07001224// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001225type OutputPath struct {
1226 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001227
1228 // The soong build directory, i.e. Config.BuildDir()
1229 buildDir string
1230
Colin Crossd63c9a72020-01-29 16:52:50 -08001231 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001232}
1233
Colin Cross702e0f82017-10-18 17:27:54 -07001234func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001235 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001236 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001237 return p
1238}
1239
Colin Cross3063b782018-08-15 11:19:12 -07001240func (p OutputPath) WithoutRel() OutputPath {
1241 p.basePath.rel = filepath.Base(p.basePath.path)
1242 return p
1243}
1244
Paul Duffind65c58b2021-03-24 09:22:07 +00001245func (p OutputPath) getBuildDir() string {
1246 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001247}
1248
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001249func (p OutputPath) RelativeToTop() Path {
1250 return p.outputPathRelativeToTop()
1251}
1252
1253func (p OutputPath) outputPathRelativeToTop() OutputPath {
1254 p.fullPath = StringPathRelativeToTop(p.buildDir, p.fullPath)
1255 p.buildDir = OutSoongDir
1256 return p
1257}
1258
Paul Duffin0267d492021-02-02 10:05:52 +00001259func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1260 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1261}
1262
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001263var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001264var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001265var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001266
Chris Parsons8f232a22020-06-23 17:37:05 -04001267// toolDepPath is a Path representing a dependency of the build tool.
1268type toolDepPath struct {
1269 basePath
1270}
1271
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001272func (t toolDepPath) RelativeToTop() Path {
1273 ensureTestOnly()
1274 return t
1275}
1276
Chris Parsons8f232a22020-06-23 17:37:05 -04001277var _ Path = toolDepPath{}
1278
1279// pathForBuildToolDep returns a toolDepPath representing the given path string.
1280// There is no validation for the path, as it is "trusted": It may fail
1281// normal validation checks. For example, it may be an absolute path.
1282// Only use this function to construct paths for dependencies of the build
1283// tool invocation.
1284func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001285 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001286}
1287
Jeff Gaston734e3802017-04-10 15:47:24 -07001288// PathForOutput joins the provided paths and returns an OutputPath that is
1289// validated to not escape the build dir.
1290// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1291func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001292 path, err := validatePath(pathComponents...)
1293 if err != nil {
1294 reportPathError(ctx, err)
1295 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001296 fullPath := filepath.Join(ctx.Config().buildDir, path)
1297 path = fullPath[len(fullPath)-len(path):]
Paul Duffin74abc5d2021-03-24 09:24:59 +00001298 return OutputPath{basePath{path, ""}, ctx.Config().buildDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001299}
1300
Colin Cross40e33732019-02-15 11:08:35 -08001301// PathsForOutput returns Paths rooted from buildDir
1302func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1303 ret := make(WritablePaths, len(paths))
1304 for i, path := range paths {
1305 ret[i] = PathForOutput(ctx, path)
1306 }
1307 return ret
1308}
1309
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001310func (p OutputPath) writablePath() {}
1311
1312func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001313 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001314}
1315
1316// Join creates a new OutputPath with paths... joined with the current path. The
1317// provided paths... may not use '..' to escape from the current path.
1318func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001319 path, err := validatePath(paths...)
1320 if err != nil {
1321 reportPathError(ctx, err)
1322 }
Colin Cross0db55682017-12-05 15:36:55 -08001323 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001324}
1325
Colin Cross8854a5a2019-02-11 14:14:16 -08001326// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1327func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1328 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001329 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001330 }
1331 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001332 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001333 return ret
1334}
1335
Colin Cross40e33732019-02-15 11:08:35 -08001336// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1337func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1338 path, err := validatePath(paths...)
1339 if err != nil {
1340 reportPathError(ctx, err)
1341 }
1342
1343 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001344 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001345 return ret
1346}
1347
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001348// PathForIntermediates returns an OutputPath representing the top-level
1349// intermediates directory.
1350func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001351 path, err := validatePath(paths...)
1352 if err != nil {
1353 reportPathError(ctx, err)
1354 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001355 return PathForOutput(ctx, ".intermediates", path)
1356}
1357
Colin Cross07e51612019-03-05 12:46:40 -08001358var _ genPathProvider = SourcePath{}
1359var _ objPathProvider = SourcePath{}
1360var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001361
Colin Cross07e51612019-03-05 12:46:40 -08001362// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001363// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001364func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001365 p, err := validatePath(pathComponents...)
1366 if err != nil {
1367 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001368 }
Colin Cross8a497952019-03-05 22:25:09 -08001369 paths, err := expandOneSrcPath(ctx, p, nil)
1370 if err != nil {
1371 if depErr, ok := err.(missingDependencyError); ok {
1372 if ctx.Config().AllowMissingDependencies() {
1373 ctx.AddMissingDependencies(depErr.missingDeps)
1374 } else {
1375 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1376 }
1377 } else {
1378 reportPathError(ctx, err)
1379 }
1380 return nil
1381 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001382 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001383 return nil
1384 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001385 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001386 }
1387 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001388}
1389
Liz Kammera830f3a2020-11-10 10:50:34 -08001390func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001391 p, err := validatePath(paths...)
1392 if err != nil {
1393 reportPathError(ctx, err)
1394 }
1395
1396 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1397 if err != nil {
1398 reportPathError(ctx, err)
1399 }
1400
1401 path.basePath.rel = p
1402
1403 return path
1404}
1405
Colin Cross2fafa3e2019-03-05 12:39:51 -08001406// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1407// will return the path relative to subDir in the module's source directory. If any input paths are not located
1408// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001409func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001410 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001411 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001412 for i, path := range paths {
1413 rel := Rel(ctx, subDirFullPath.String(), path.String())
1414 paths[i] = subDirFullPath.join(ctx, rel)
1415 }
1416 return paths
1417}
1418
1419// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1420// 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 -08001421func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001422 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001423 rel := Rel(ctx, subDirFullPath.String(), path.String())
1424 return subDirFullPath.Join(ctx, rel)
1425}
1426
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001427// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1428// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001429func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001430 if p == nil {
1431 return OptionalPath{}
1432 }
1433 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1434}
1435
Liz Kammera830f3a2020-11-10 10:50:34 -08001436func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001437 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001438}
1439
Liz Kammera830f3a2020-11-10 10:50:34 -08001440func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001441 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001442}
1443
Liz Kammera830f3a2020-11-10 10:50:34 -08001444func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001445 // TODO: Use full directory if the new ctx is not the current ctx?
1446 return PathForModuleRes(ctx, p.path, name)
1447}
1448
1449// ModuleOutPath is a Path representing a module's output directory.
1450type ModuleOutPath struct {
1451 OutputPath
1452}
1453
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001454func (p ModuleOutPath) RelativeToTop() Path {
1455 p.OutputPath = p.outputPathRelativeToTop()
1456 return p
1457}
1458
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001459var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001460var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001461
Liz Kammera830f3a2020-11-10 10:50:34 -08001462func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001463 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1464}
1465
Liz Kammera830f3a2020-11-10 10:50:34 -08001466// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1467type ModuleOutPathContext interface {
1468 PathContext
1469
1470 ModuleName() string
1471 ModuleDir() string
1472 ModuleSubDir() string
1473}
1474
1475func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001476 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1477}
1478
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001479type BazelOutPath struct {
1480 OutputPath
1481}
1482
1483var _ Path = BazelOutPath{}
1484var _ objPathProvider = BazelOutPath{}
1485
Liz Kammera830f3a2020-11-10 10:50:34 -08001486func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001487 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1488}
1489
Logan Chien7eefdc42018-07-11 18:10:41 +08001490// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1491// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001492func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001493 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001494
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001495 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001496 if len(arches) == 0 {
1497 panic("device build with no primary arch")
1498 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001499 currentArch := ctx.Arch()
1500 archNameAndVariant := currentArch.ArchType.String()
1501 if currentArch.ArchVariant != "" {
1502 archNameAndVariant += "_" + currentArch.ArchVariant
1503 }
Logan Chien5237bed2018-07-11 17:15:57 +08001504
1505 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001506 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001507 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001508 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001509 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001510 } else {
1511 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001512 }
Logan Chien5237bed2018-07-11 17:15:57 +08001513
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001514 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001515
1516 var ext string
1517 if isGzip {
1518 ext = ".lsdump.gz"
1519 } else {
1520 ext = ".lsdump"
1521 }
1522
1523 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1524 version, binderBitness, archNameAndVariant, "source-based",
1525 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001526}
1527
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001528// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1529// bazel-owned outputs.
1530func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1531 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1532 execRootPath := filepath.Join(execRootPathComponents...)
1533 validatedExecRootPath, err := validatePath(execRootPath)
1534 if err != nil {
1535 reportPathError(ctx, err)
1536 }
1537
Paul Duffin74abc5d2021-03-24 09:24:59 +00001538 outputPath := OutputPath{basePath{"", ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001539 ctx.Config().buildDir,
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001540 ctx.Config().BazelContext.OutputBase()}
1541
1542 return BazelOutPath{
1543 OutputPath: outputPath.withRel(validatedExecRootPath),
1544 }
1545}
1546
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001547// PathForModuleOut returns a Path representing the paths... under the module's
1548// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001549func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001550 p, err := validatePath(paths...)
1551 if err != nil {
1552 reportPathError(ctx, err)
1553 }
Colin Cross702e0f82017-10-18 17:27:54 -07001554 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001555 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001556 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001557}
1558
1559// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1560// directory. Mainly used for generated sources.
1561type ModuleGenPath struct {
1562 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001563}
1564
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001565func (p ModuleGenPath) RelativeToTop() Path {
1566 p.OutputPath = p.outputPathRelativeToTop()
1567 return p
1568}
1569
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001570var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001571var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001572var _ genPathProvider = ModuleGenPath{}
1573var _ objPathProvider = ModuleGenPath{}
1574
1575// PathForModuleGen returns a Path representing the paths... under the module's
1576// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001577func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001578 p, err := validatePath(paths...)
1579 if err != nil {
1580 reportPathError(ctx, err)
1581 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001582 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001583 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001584 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001585 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001586 }
1587}
1588
Liz Kammera830f3a2020-11-10 10:50:34 -08001589func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001590 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001591 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001592}
1593
Liz Kammera830f3a2020-11-10 10:50:34 -08001594func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001595 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1596}
1597
1598// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1599// directory. Used for compiled objects.
1600type ModuleObjPath struct {
1601 ModuleOutPath
1602}
1603
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001604func (p ModuleObjPath) RelativeToTop() Path {
1605 p.OutputPath = p.outputPathRelativeToTop()
1606 return p
1607}
1608
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001609var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001610var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001611
1612// PathForModuleObj returns a Path representing the paths... under the module's
1613// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001614func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001615 p, err := validatePath(pathComponents...)
1616 if err != nil {
1617 reportPathError(ctx, err)
1618 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001619 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1620}
1621
1622// ModuleResPath is a a Path representing the 'res' directory in a module's
1623// output directory.
1624type ModuleResPath struct {
1625 ModuleOutPath
1626}
1627
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001628func (p ModuleResPath) RelativeToTop() Path {
1629 p.OutputPath = p.outputPathRelativeToTop()
1630 return p
1631}
1632
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001633var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001634var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001635
1636// PathForModuleRes returns a Path representing the paths... under the module's
1637// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001638func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001639 p, err := validatePath(pathComponents...)
1640 if err != nil {
1641 reportPathError(ctx, err)
1642 }
1643
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001644 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1645}
1646
Colin Cross70dda7e2019-10-01 22:05:35 -07001647// InstallPath is a Path representing a installed file path rooted from the build directory
1648type InstallPath struct {
1649 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001650
Paul Duffind65c58b2021-03-24 09:22:07 +00001651 // The soong build directory, i.e. Config.BuildDir()
1652 buildDir string
1653
Jiyong Park957bcd92020-10-20 18:23:33 +09001654 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1655 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1656 partitionDir string
1657
1658 // makePath indicates whether this path is for Soong (false) or Make (true).
1659 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001660}
1661
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001662// Will panic if called from outside a test environment.
1663func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001664 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001665 return
1666 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001667 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001668}
1669
1670func (p InstallPath) RelativeToTop() Path {
1671 ensureTestOnly()
1672 p.buildDir = OutSoongDir
1673 return p
1674}
1675
Paul Duffind65c58b2021-03-24 09:22:07 +00001676func (p InstallPath) getBuildDir() string {
1677 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001678}
1679
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001680func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1681 panic("Not implemented")
1682}
1683
Paul Duffin9b478b02019-12-10 13:41:51 +00001684var _ Path = InstallPath{}
1685var _ WritablePath = InstallPath{}
1686
Colin Cross70dda7e2019-10-01 22:05:35 -07001687func (p InstallPath) writablePath() {}
1688
1689func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001690 if p.makePath {
1691 // Make path starts with out/ instead of out/soong.
Paul Duffind65c58b2021-03-24 09:22:07 +00001692 return filepath.Join(p.buildDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001693 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001694 return filepath.Join(p.buildDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001695 }
1696}
1697
1698// PartitionDir returns the path to the partition where the install path is rooted at. It is
1699// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1700// The ./soong is dropped if the install path is for Make.
1701func (p InstallPath) PartitionDir() string {
1702 if p.makePath {
Paul Duffind65c58b2021-03-24 09:22:07 +00001703 return filepath.Join(p.buildDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001704 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001705 return filepath.Join(p.buildDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001706 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001707}
1708
1709// Join creates a new InstallPath with paths... joined with the current path. The
1710// provided paths... may not use '..' to escape from the current path.
1711func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1712 path, err := validatePath(paths...)
1713 if err != nil {
1714 reportPathError(ctx, err)
1715 }
1716 return p.withRel(path)
1717}
1718
1719func (p InstallPath) withRel(rel string) InstallPath {
1720 p.basePath = p.basePath.withRel(rel)
1721 return p
1722}
1723
Colin Crossff6c33d2019-10-02 16:01:35 -07001724// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1725// i.e. out/ instead of out/soong/.
1726func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001727 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001728 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001729}
1730
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001731// PathForModuleInstall returns a Path representing the install path for the
1732// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001733func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001734 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001735 arch := ctx.Arch().ArchType
1736 forceOS, forceArch := ctx.InstallForceOS()
1737 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001738 os = *forceOS
1739 }
Jiyong Park87788b52020-09-01 12:37:45 +09001740 if forceArch != nil {
1741 arch = *forceArch
1742 }
Colin Cross6e359402020-02-10 15:29:54 -08001743 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001744
Jiyong Park87788b52020-09-01 12:37:45 +09001745 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001746
Jingwen Chencda22c92020-11-23 00:22:30 -05001747 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001748 ret = ret.ToMakePath()
1749 }
1750
1751 return ret
1752}
1753
Jiyong Park87788b52020-09-01 12:37:45 +09001754func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001755 pathComponents ...string) InstallPath {
1756
Jiyong Park957bcd92020-10-20 18:23:33 +09001757 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001758
Colin Cross6e359402020-02-10 15:29:54 -08001759 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001760 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001761 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001762 osName := os.String()
1763 if os == Linux {
1764 // instead of linux_glibc
1765 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001766 }
Jiyong Park87788b52020-09-01 12:37:45 +09001767 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1768 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1769 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1770 // Let's keep using x86 for the existing cases until we have a need to support
1771 // other architectures.
1772 archName := arch.String()
1773 if os.Class == Host && (arch == X86_64 || arch == Common) {
1774 archName = "x86"
1775 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001776 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001777 }
Colin Cross609c49a2020-02-13 13:20:11 -08001778 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001779 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001780 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001781
Jiyong Park957bcd92020-10-20 18:23:33 +09001782 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001783 if err != nil {
1784 reportPathError(ctx, err)
1785 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001786
Jiyong Park957bcd92020-10-20 18:23:33 +09001787 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001788 basePath: basePath{partionPath, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001789 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001790 partitionDir: partionPath,
1791 makePath: false,
1792 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001793
Jiyong Park957bcd92020-10-20 18:23:33 +09001794 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001795}
1796
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001797func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001798 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001799 basePath: basePath{prefix, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001800 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001801 partitionDir: prefix,
1802 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001803 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001804 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001805}
1806
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001807func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1808 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1809}
1810
1811func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1812 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1813}
1814
Colin Cross70dda7e2019-10-01 22:05:35 -07001815func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001816 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1817
1818 return "/" + rel
1819}
1820
Colin Cross6e359402020-02-10 15:29:54 -08001821func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001822 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001823 if ctx.InstallInTestcases() {
1824 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001825 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001826 } else if os.Class == Device {
1827 if ctx.InstallInData() {
1828 partition = "data"
1829 } else if ctx.InstallInRamdisk() {
1830 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1831 partition = "recovery/root/first_stage_ramdisk"
1832 } else {
1833 partition = "ramdisk"
1834 }
1835 if !ctx.InstallInRoot() {
1836 partition += "/system"
1837 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001838 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001839 // The module is only available after switching root into
1840 // /first_stage_ramdisk. To expose the module before switching root
1841 // on a device without a dedicated recovery partition, install the
1842 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001843 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001844 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001845 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001846 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001847 }
1848 if !ctx.InstallInRoot() {
1849 partition += "/system"
1850 }
Colin Cross6e359402020-02-10 15:29:54 -08001851 } else if ctx.InstallInRecovery() {
1852 if ctx.InstallInRoot() {
1853 partition = "recovery/root"
1854 } else {
1855 // the layout of recovery partion is the same as that of system partition
1856 partition = "recovery/root/system"
1857 }
1858 } else if ctx.SocSpecific() {
1859 partition = ctx.DeviceConfig().VendorPath()
1860 } else if ctx.DeviceSpecific() {
1861 partition = ctx.DeviceConfig().OdmPath()
1862 } else if ctx.ProductSpecific() {
1863 partition = ctx.DeviceConfig().ProductPath()
1864 } else if ctx.SystemExtSpecific() {
1865 partition = ctx.DeviceConfig().SystemExtPath()
1866 } else if ctx.InstallInRoot() {
1867 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001868 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001869 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001870 }
Colin Cross6e359402020-02-10 15:29:54 -08001871 if ctx.InstallInSanitizerDir() {
1872 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001873 }
Colin Cross43f08db2018-11-12 10:13:39 -08001874 }
1875 return partition
1876}
1877
Colin Cross609c49a2020-02-13 13:20:11 -08001878type InstallPaths []InstallPath
1879
1880// Paths returns the InstallPaths as a Paths
1881func (p InstallPaths) Paths() Paths {
1882 if p == nil {
1883 return nil
1884 }
1885 ret := make(Paths, len(p))
1886 for i, path := range p {
1887 ret[i] = path
1888 }
1889 return ret
1890}
1891
1892// Strings returns the string forms of the install paths.
1893func (p InstallPaths) Strings() []string {
1894 if p == nil {
1895 return nil
1896 }
1897 ret := make([]string, len(p))
1898 for i, path := range p {
1899 ret[i] = path.String()
1900 }
1901 return ret
1902}
1903
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001904// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001905// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001906func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001907 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001908 path := filepath.Clean(path)
1909 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001910 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001911 }
1912 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001913 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1914 // variables. '..' may remove the entire ninja variable, even if it
1915 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001916 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001917}
1918
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001919// validatePath validates that a path does not include ninja variables, and that
1920// each path component does not attempt to leave its component. Returns a joined
1921// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001922func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001923 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001924 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001925 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001926 }
1927 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001928 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001929}
Colin Cross5b529592017-05-09 13:34:34 -07001930
Colin Cross0875c522017-11-28 17:34:01 -08001931func PathForPhony(ctx PathContext, phony string) WritablePath {
1932 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001933 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001934 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001935 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001936}
1937
Colin Cross74e3fe42017-12-11 15:51:44 -08001938type PhonyPath struct {
1939 basePath
1940}
1941
1942func (p PhonyPath) writablePath() {}
1943
Paul Duffind65c58b2021-03-24 09:22:07 +00001944func (p PhonyPath) getBuildDir() string {
1945 // A phone path cannot contain any / so cannot be relative to the build directory.
1946 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001947}
1948
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001949func (p PhonyPath) RelativeToTop() Path {
1950 ensureTestOnly()
1951 // A phony path cannot contain any / so does not have a build directory so switching to a new
1952 // build directory has no effect so just return this path.
1953 return p
1954}
1955
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001956func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1957 panic("Not implemented")
1958}
1959
Colin Cross74e3fe42017-12-11 15:51:44 -08001960var _ Path = PhonyPath{}
1961var _ WritablePath = PhonyPath{}
1962
Colin Cross5b529592017-05-09 13:34:34 -07001963type testPath struct {
1964 basePath
1965}
1966
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001967func (p testPath) RelativeToTop() Path {
1968 ensureTestOnly()
1969 return p
1970}
1971
Colin Cross5b529592017-05-09 13:34:34 -07001972func (p testPath) String() string {
1973 return p.path
1974}
1975
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001976var _ Path = testPath{}
1977
Colin Cross40e33732019-02-15 11:08:35 -08001978// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1979// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001980func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001981 p, err := validateSafePath(paths...)
1982 if err != nil {
1983 panic(err)
1984 }
Colin Cross5b529592017-05-09 13:34:34 -07001985 return testPath{basePath{path: p, rel: p}}
1986}
1987
Colin Cross40e33732019-02-15 11:08:35 -08001988// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1989func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001990 p := make(Paths, len(strs))
1991 for i, s := range strs {
1992 p[i] = PathForTesting(s)
1993 }
1994
1995 return p
1996}
Colin Cross43f08db2018-11-12 10:13:39 -08001997
Colin Cross40e33732019-02-15 11:08:35 -08001998type testPathContext struct {
1999 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002000}
2001
Colin Cross40e33732019-02-15 11:08:35 -08002002func (x *testPathContext) Config() Config { return x.config }
2003func (x *testPathContext) AddNinjaFileDeps(...string) {}
2004
2005// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2006// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002007func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002008 return &testPathContext{
2009 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002010 }
2011}
2012
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002013type testModuleInstallPathContext struct {
2014 baseModuleContext
2015
2016 inData bool
2017 inTestcases bool
2018 inSanitizerDir bool
2019 inRamdisk bool
2020 inVendorRamdisk bool
2021 inRecovery bool
2022 inRoot bool
2023 forceOS *OsType
2024 forceArch *ArchType
2025}
2026
2027func (m testModuleInstallPathContext) Config() Config {
2028 return m.baseModuleContext.config
2029}
2030
2031func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2032
2033func (m testModuleInstallPathContext) InstallInData() bool {
2034 return m.inData
2035}
2036
2037func (m testModuleInstallPathContext) InstallInTestcases() bool {
2038 return m.inTestcases
2039}
2040
2041func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2042 return m.inSanitizerDir
2043}
2044
2045func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2046 return m.inRamdisk
2047}
2048
2049func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2050 return m.inVendorRamdisk
2051}
2052
2053func (m testModuleInstallPathContext) InstallInRecovery() bool {
2054 return m.inRecovery
2055}
2056
2057func (m testModuleInstallPathContext) InstallInRoot() bool {
2058 return m.inRoot
2059}
2060
2061func (m testModuleInstallPathContext) InstallBypassMake() bool {
2062 return false
2063}
2064
2065func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2066 return m.forceOS, m.forceArch
2067}
2068
2069// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2070// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2071// delegated to it will panic.
2072func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2073 ctx := &testModuleInstallPathContext{}
2074 ctx.config = config
2075 ctx.os = Android
2076 return ctx
2077}
2078
Colin Cross43f08db2018-11-12 10:13:39 -08002079// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2080// targetPath is not inside basePath.
2081func Rel(ctx PathContext, basePath string, targetPath string) string {
2082 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2083 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002084 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002085 return ""
2086 }
2087 return rel
2088}
2089
2090// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2091// targetPath is not inside basePath.
2092func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002093 rel, isRel, err := maybeRelErr(basePath, targetPath)
2094 if err != nil {
2095 reportPathError(ctx, err)
2096 }
2097 return rel, isRel
2098}
2099
2100func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002101 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2102 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002103 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002104 }
2105 rel, err := filepath.Rel(basePath, targetPath)
2106 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002107 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002108 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002109 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002110 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002111 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002112}
Colin Cross988414c2020-01-11 01:11:46 +00002113
2114// Writes a file to the output directory. Attempting to write directly to the output directory
2115// will fail due to the sandbox of the soong_build process.
2116func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
2117 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
2118}
2119
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002120func RemoveAllOutputDir(path WritablePath) error {
2121 return os.RemoveAll(absolutePath(path.String()))
2122}
2123
2124func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2125 dir := absolutePath(path.String())
2126 if _, err := os.Stat(dir); os.IsNotExist(err) {
2127 return os.MkdirAll(dir, os.ModePerm)
2128 } else {
2129 return err
2130 }
2131}
2132
Colin Cross988414c2020-01-11 01:11:46 +00002133func absolutePath(path string) string {
2134 if filepath.IsAbs(path) {
2135 return path
2136 }
2137 return filepath.Join(absSrcDir, path)
2138}
Chris Parsons216e10a2020-07-09 17:12:52 -04002139
2140// A DataPath represents the path of a file to be used as data, for example
2141// a test library to be installed alongside a test.
2142// The data file should be installed (copied from `<SrcPath>`) to
2143// `<install_root>/<RelativeInstallPath>/<filename>`, or
2144// `<install_root>/<filename>` if RelativeInstallPath is empty.
2145type DataPath struct {
2146 // The path of the data file that should be copied into the data directory
2147 SrcPath Path
2148 // The install path of the data file, relative to the install root.
2149 RelativeInstallPath string
2150}
Colin Crossdcf71b22021-02-01 13:59:03 -08002151
2152// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2153func PathsIfNonNil(paths ...Path) Paths {
2154 if len(paths) == 0 {
2155 // Fast path for empty argument list
2156 return nil
2157 } else if len(paths) == 1 {
2158 // Fast path for a single argument
2159 if paths[0] != nil {
2160 return paths
2161 } else {
2162 return nil
2163 }
2164 }
2165 ret := make(Paths, 0, len(paths))
2166 for _, path := range paths {
2167 if path != nil {
2168 ret = append(ret, path)
2169 }
2170 }
2171 if len(ret) == 0 {
2172 return nil
2173 }
2174 return ret
2175}