blob: 9d4b6eca3ae591cee76ff09878041fb668ac1582 [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
Inseob Kimf84e9c02021-04-08 21:13:22 +0900110 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900111 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700112 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -0700113 InstallBypassMake() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900114 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700115}
116
117var _ ModuleInstallPathContext = ModuleContext(nil)
118
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700119// errorfContext is the interface containing the Errorf method matching the
120// Errorf method in blueprint.SingletonContext.
121type errorfContext interface {
122 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800123}
124
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700125var _ errorfContext = blueprint.SingletonContext(nil)
126
127// moduleErrorf is the interface containing the ModuleErrorf method matching
128// the ModuleErrorf method in blueprint.ModuleContext.
129type moduleErrorf interface {
130 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800131}
132
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700133var _ moduleErrorf = blueprint.ModuleContext(nil)
134
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700135// reportPathError will register an error with the attached context. It
136// attempts ctx.ModuleErrorf for a better error message first, then falls
137// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800138func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100139 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800140}
141
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100142// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800143// attempts ctx.ModuleErrorf for a better error message first, then falls
144// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100145func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700146 if mctx, ok := ctx.(moduleErrorf); ok {
147 mctx.ModuleErrorf(format, args...)
148 } else if ectx, ok := ctx.(errorfContext); ok {
149 ectx.Errorf(format, args...)
150 } else {
151 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700152 }
153}
154
Colin Cross5e708052019-08-06 13:59:50 -0700155func pathContextName(ctx PathContext, module blueprint.Module) string {
156 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
157 return x.ModuleName(module)
158 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
159 return x.OtherModuleName(module)
160 }
161 return "unknown"
162}
163
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700164type Path interface {
165 // Returns the path in string form
166 String() string
167
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700168 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700169 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700170
171 // Base returns the last element of the path
172 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800173
174 // Rel returns the portion of the path relative to the directory it was created from. For
175 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800176 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800177 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000178
179 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
180 //
181 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
182 // InstallPath then the returned value can be converted to an InstallPath.
183 //
184 // A standard build has the following structure:
185 // ../top/
186 // out/ - make install files go here.
187 // out/soong - this is the buildDir passed to NewTestConfig()
188 // ... - the source files
189 //
190 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
191 // * Make install paths, which have the pattern "buildDir/../<path>" are converted into the top
192 // relative path "out/<path>"
193 // * Soong install paths and other writable paths, which have the pattern "buildDir/<path>" are
194 // converted into the top relative path "out/soong/<path>".
195 // * Source paths are already relative to the top.
196 // * Phony paths are not relative to anything.
197 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
198 // order to test.
199 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700200}
201
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000202const (
203 OutDir = "out"
204 OutSoongDir = OutDir + "/soong"
205)
206
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700207// WritablePath is a type of path that can be used as an output for build rules.
208type WritablePath interface {
209 Path
210
Paul Duffin9b478b02019-12-10 13:41:51 +0000211 // return the path to the build directory.
Paul Duffind65c58b2021-03-24 09:22:07 +0000212 getBuildDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000213
Jeff Gaston734e3802017-04-10 15:47:24 -0700214 // the writablePath method doesn't directly do anything,
215 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700216 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100217
218 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700219}
220
221type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800222 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700223}
224type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800225 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700226}
227type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800228 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700229}
230
231// GenPathWithExt derives a new file path in ctx's generated sources directory
232// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800233func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700234 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700235 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700236 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100237 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700238 return PathForModuleGen(ctx)
239}
240
241// ObjPathWithExt derives a new file path in ctx's object directory from the
242// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800243func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700244 if path, ok := p.(objPathProvider); ok {
245 return path.objPathWithExt(ctx, subdir, ext)
246 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100247 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700248 return PathForModuleObj(ctx)
249}
250
251// ResPathWithName derives a new path in ctx's output resource directory, using
252// the current path to create the directory name, and the `name` argument for
253// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800254func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700255 if path, ok := p.(resPathProvider); ok {
256 return path.resPathWithName(ctx, name)
257 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100258 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700259 return PathForModuleRes(ctx)
260}
261
262// OptionalPath is a container that may or may not contain a valid Path.
263type OptionalPath struct {
264 valid bool
265 path Path
266}
267
268// OptionalPathForPath returns an OptionalPath containing the path.
269func OptionalPathForPath(path Path) OptionalPath {
270 if path == nil {
271 return OptionalPath{}
272 }
273 return OptionalPath{valid: true, path: path}
274}
275
276// Valid returns whether there is a valid path
277func (p OptionalPath) Valid() bool {
278 return p.valid
279}
280
281// Path returns the Path embedded in this OptionalPath. You must be sure that
282// there is a valid path, since this method will panic if there is not.
283func (p OptionalPath) Path() Path {
284 if !p.valid {
285 panic("Requesting an invalid path")
286 }
287 return p.path
288}
289
Paul Duffinafdd4062021-03-30 19:44:07 +0100290// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
291// result of calling Path.RelativeToTop on it.
292func (p OptionalPath) RelativeToTop() OptionalPath {
Paul Duffina5b81352021-03-28 23:57:19 +0100293 if !p.valid {
294 return p
295 }
296 p.path = p.path.RelativeToTop()
297 return p
298}
299
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700300// String returns the string version of the Path, or "" if it isn't valid.
301func (p OptionalPath) String() string {
302 if p.valid {
303 return p.path.String()
304 } else {
305 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700306 }
307}
Colin Cross6e18ca42015-07-14 18:55:36 -0700308
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700309// Paths is a slice of Path objects, with helpers to operate on the collection.
310type Paths []Path
311
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000312// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
313// item in this slice.
314func (p Paths) RelativeToTop() Paths {
315 ensureTestOnly()
316 if p == nil {
317 return p
318 }
319 ret := make(Paths, len(p))
320 for i, path := range p {
321 ret[i] = path.RelativeToTop()
322 }
323 return ret
324}
325
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000326func (paths Paths) containsPath(path Path) bool {
327 for _, p := range paths {
328 if p == path {
329 return true
330 }
331 }
332 return false
333}
334
Liz Kammer7aa52882021-02-11 09:16:14 -0500335// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
336// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700337func PathsForSource(ctx PathContext, paths []string) Paths {
338 ret := make(Paths, len(paths))
339 for i, path := range paths {
340 ret[i] = PathForSource(ctx, path)
341 }
342 return ret
343}
344
Liz Kammer7aa52882021-02-11 09:16:14 -0500345// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
346// module's local source directory, that are found in the tree. If any are not found, they are
347// 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 -0800348func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800349 ret := make(Paths, 0, len(paths))
350 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800351 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800352 if p.Valid() {
353 ret = append(ret, p.Path())
354 }
355 }
356 return ret
357}
358
Colin Cross41955e82019-05-29 14:40:35 -0700359// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
360// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
361// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
362// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
363// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
364// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800365func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800366 return PathsForModuleSrcExcludes(ctx, paths, nil)
367}
368
Colin Crossba71a3f2019-03-18 12:12:48 -0700369// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700370// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
371// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
372// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
373// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100374// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700375// having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800376func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700377 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
378 if ctx.Config().AllowMissingDependencies() {
379 ctx.AddMissingDependencies(missingDeps)
380 } else {
381 for _, m := range missingDeps {
382 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
383 }
384 }
385 return ret
386}
387
Liz Kammer356f7d42021-01-26 09:18:53 -0500388// A subset of the ModuleContext methods which are sufficient to resolve references to paths/deps in
389// order to form a Bazel-compatible label for conversion.
390type BazelConversionPathContext interface {
391 EarlyModulePathContext
392
393 GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
Liz Kammerbdc60992021-02-24 16:55:11 -0500394 Module() Module
Jingwen Chen12b4c272021-03-10 02:05:59 -0500395 ModuleType() string
Liz Kammer356f7d42021-01-26 09:18:53 -0500396 OtherModuleName(m blueprint.Module) string
397 OtherModuleDir(m blueprint.Module) string
398}
399
400// BazelLabelForModuleDeps returns a Bazel-compatible label for the requested modules which
401// correspond to dependencies on the module within the given ctx.
402func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
403 var labels bazel.LabelList
404 for _, module := range modules {
405 bpText := module
406 if m := SrcIsModule(module); m == "" {
407 module = ":" + module
408 }
409 if m, t := SrcIsModuleWithTag(module); m != "" {
410 l := getOtherModuleLabel(ctx, m, t)
411 l.Bp_text = bpText
412 labels.Includes = append(labels.Includes, l)
413 } else {
414 ctx.ModuleErrorf("%q, is not a module reference", module)
415 }
416 }
417 return labels
418}
419
420// BazelLabelForModuleSrc returns bazel.LabelList with paths rooted from the module's local source
421// directory. It expands globs, and resolves references to modules using the ":name" syntax to
422// bazel-compatible labels. Properties passed as the paths or excludes argument must have been
423// annotated with struct tag `android:"path"` so that dependencies on other modules will have
424// already been handled by the path_properties mutator.
Jingwen Chen63930982021-03-24 10:04:33 -0400425//
426// With expanded globs, we can catch package boundaries problem instead of
427// silently failing to potentially missing files from Bazel's globs.
Liz Kammer356f7d42021-01-26 09:18:53 -0500428func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
429 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
430}
431
432// BazelLabelForModuleSrcExcludes returns bazel.LabelList with paths rooted from the module's local
433// source directory, excluding labels included in the excludes argument. It expands globs, and
434// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
435// passed as the paths or excludes argument must have been annotated with struct tag
436// `android:"path"` so that dependencies on other modules will have already been handled by the
437// path_properties mutator.
Jingwen Chen63930982021-03-24 10:04:33 -0400438//
439// With expanded globs, we can catch package boundaries problem instead of
440// silently failing to potentially missing files from Bazel's globs.
Liz Kammer356f7d42021-01-26 09:18:53 -0500441func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
442 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
443 excluded := make([]string, 0, len(excludeLabels.Includes))
444 for _, e := range excludeLabels.Includes {
445 excluded = append(excluded, e.Label)
446 }
447 labels := expandSrcsForBazel(ctx, paths, excluded)
448 labels.Excludes = excludeLabels.Includes
449 return labels
450}
451
452// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local
453// source directory, excluding labels included in the excludes argument. It expands globs, and
454// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
455// passed as the paths or excludes argument must have been annotated with struct tag
456// `android:"path"` so that dependencies on other modules will have already been handled by the
457// path_properties mutator.
458func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammerebfcf672021-02-16 15:00:05 -0500459 if paths == nil {
460 return bazel.LabelList{}
461 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500462 labels := bazel.LabelList{
463 Includes: []bazel.Label{},
464 }
465 for _, p := range paths {
466 if m, tag := SrcIsModuleWithTag(p); m != "" {
467 l := getOtherModuleLabel(ctx, m, tag)
468 if !InList(l.Label, expandedExcludes) {
469 l.Bp_text = fmt.Sprintf(":%s", m)
470 labels.Includes = append(labels.Includes, l)
471 }
472 } else {
473 var expandedPaths []bazel.Label
474 if pathtools.IsGlob(p) {
475 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
476 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
477 for _, path := range globbedPaths {
478 s := path.Rel()
479 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
480 }
481 } else {
482 if !InList(p, expandedExcludes) {
483 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
484 }
485 }
486 labels.Includes = append(labels.Includes, expandedPaths...)
487 }
488 }
489 return labels
490}
491
492// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
493// module. The label will be relative to the current directory if appropriate. The dependency must
494// already be resolved by either deps mutator or path deps mutator.
495func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
496 m, _ := ctx.GetDirectDep(dep)
Jingwen Chen07027912021-03-15 06:02:43 -0400497 if m == nil {
498 panic(fmt.Errorf("cannot get direct dep %s of %s", dep, ctx.Module().Name()))
499 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500500 otherLabel := bazelModuleLabel(ctx, m, tag)
501 label := bazelModuleLabel(ctx, ctx.Module(), "")
502 if samePackage(label, otherLabel) {
503 otherLabel = bazelShortLabel(otherLabel)
Liz Kammer356f7d42021-01-26 09:18:53 -0500504 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500505
506 return bazel.Label{
507 Label: otherLabel,
508 }
509}
510
511func bazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module, tag string) string {
512 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
513 b, ok := module.(Bazelable)
514 // 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 -0500515 if !ok || !b.ConvertedToBazel(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500516 return bp2buildModuleLabel(ctx, module)
517 }
518 return b.GetBazelLabel(ctx, module)
519}
520
521func bazelShortLabel(label string) string {
522 i := strings.Index(label, ":")
523 return label[i:]
524}
525
526func bazelPackage(label string) string {
527 i := strings.Index(label, ":")
528 return label[0:i]
529}
530
531func samePackage(label1, label2 string) bool {
532 return bazelPackage(label1) == bazelPackage(label2)
533}
534
535func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
536 moduleName := ctx.OtherModuleName(module)
537 moduleDir := ctx.OtherModuleDir(module)
538 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500539}
540
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000541// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
542type OutputPaths []OutputPath
543
544// Paths returns the OutputPaths as a Paths
545func (p OutputPaths) Paths() Paths {
546 if p == nil {
547 return nil
548 }
549 ret := make(Paths, len(p))
550 for i, path := range p {
551 ret[i] = path
552 }
553 return ret
554}
555
556// Strings returns the string forms of the writable paths.
557func (p OutputPaths) Strings() []string {
558 if p == nil {
559 return nil
560 }
561 ret := make([]string, len(p))
562 for i, path := range p {
563 ret[i] = path.String()
564 }
565 return ret
566}
567
Liz Kammera830f3a2020-11-10 10:50:34 -0800568// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
569// If the dependency is not found, a missingErrorDependency is returned.
570// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
571func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
572 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
573 if module == nil {
574 return nil, missingDependencyError{[]string{moduleName}}
575 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700576 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
577 return nil, missingDependencyError{[]string{moduleName}}
578 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800579 if outProducer, ok := module.(OutputFileProducer); ok {
580 outputFiles, err := outProducer.OutputFiles(tag)
581 if err != nil {
582 return nil, fmt.Errorf("path dependency %q: %s", path, err)
583 }
584 return outputFiles, nil
585 } else if tag != "" {
586 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
587 } else if srcProducer, ok := module.(SourceFileProducer); ok {
588 return srcProducer.Srcs(), nil
589 } else {
590 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
591 }
592}
593
Colin Crossba71a3f2019-03-18 12:12:48 -0700594// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700595// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
596// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
597// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
598// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
599// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
600// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
601// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800602func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800603 prefix := pathForModuleSrc(ctx).String()
604
605 var expandedExcludes []string
606 if excludes != nil {
607 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700608 }
Colin Cross8a497952019-03-05 22:25:09 -0800609
Colin Crossba71a3f2019-03-18 12:12:48 -0700610 var missingExcludeDeps []string
611
Colin Cross8a497952019-03-05 22:25:09 -0800612 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700613 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800614 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
615 if m, ok := err.(missingDependencyError); ok {
616 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
617 } else if err != nil {
618 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800619 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800620 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800621 }
622 } else {
623 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
624 }
625 }
626
627 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700628 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800629 }
630
Colin Crossba71a3f2019-03-18 12:12:48 -0700631 var missingDeps []string
632
Colin Cross8a497952019-03-05 22:25:09 -0800633 expandedSrcFiles := make(Paths, 0, len(paths))
634 for _, s := range paths {
635 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
636 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700637 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800638 } else if err != nil {
639 reportPathError(ctx, err)
640 }
641 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
642 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700643
644 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800645}
646
647type missingDependencyError struct {
648 missingDeps []string
649}
650
651func (e missingDependencyError) Error() string {
652 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
653}
654
Liz Kammera830f3a2020-11-10 10:50:34 -0800655// Expands one path string to Paths rooted from the module's local source
656// directory, excluding those listed in the expandedExcludes.
657// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
658func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900659 excludePaths := func(paths Paths) Paths {
660 if len(expandedExcludes) == 0 {
661 return paths
662 }
663 remainder := make(Paths, 0, len(paths))
664 for _, p := range paths {
665 if !InList(p.String(), expandedExcludes) {
666 remainder = append(remainder, p)
667 }
668 }
669 return remainder
670 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800671 if m, t := SrcIsModuleWithTag(sPath); m != "" {
672 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
673 if err != nil {
674 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800675 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800676 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800677 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800678 } else if pathtools.IsGlob(sPath) {
679 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800680 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
681 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800682 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000683 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100684 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000685 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100686 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800687 }
688
Jooyung Han7607dd32020-07-05 10:23:14 +0900689 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800690 return nil, nil
691 }
692 return Paths{p}, nil
693 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700694}
695
696// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
697// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800698// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700699// It intended for use in globs that only list files that exist, so it allows '$' in
700// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800701func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800702 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700703 if prefix == "./" {
704 prefix = ""
705 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700706 ret := make(Paths, 0, len(paths))
707 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800708 if !incDirs && strings.HasSuffix(p, "/") {
709 continue
710 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700711 path := filepath.Clean(p)
712 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100713 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700714 continue
715 }
Colin Crosse3924e12018-08-15 20:18:53 -0700716
Colin Crossfe4bc362018-09-12 10:02:13 -0700717 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700718 if err != nil {
719 reportPathError(ctx, err)
720 continue
721 }
722
Colin Cross07e51612019-03-05 12:46:40 -0800723 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700724
Colin Cross07e51612019-03-05 12:46:40 -0800725 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700726 }
727 return ret
728}
729
Liz Kammera830f3a2020-11-10 10:50:34 -0800730// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
731// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
732func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800733 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700734 return PathsForModuleSrc(ctx, input)
735 }
736 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
737 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800738 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800739 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700740}
741
742// Strings returns the Paths in string form
743func (p Paths) Strings() []string {
744 if p == nil {
745 return nil
746 }
747 ret := make([]string, len(p))
748 for i, path := range p {
749 ret[i] = path.String()
750 }
751 return ret
752}
753
Colin Crossc0efd1d2020-07-03 11:56:24 -0700754func CopyOfPaths(paths Paths) Paths {
755 return append(Paths(nil), paths...)
756}
757
Colin Crossb6715442017-10-24 11:13:31 -0700758// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
759// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700760func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800761 // 128 was chosen based on BenchmarkFirstUniquePaths results.
762 if len(list) > 128 {
763 return firstUniquePathsMap(list)
764 }
765 return firstUniquePathsList(list)
766}
767
Colin Crossc0efd1d2020-07-03 11:56:24 -0700768// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
769// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900770func SortedUniquePaths(list Paths) Paths {
771 unique := FirstUniquePaths(list)
772 sort.Slice(unique, func(i, j int) bool {
773 return unique[i].String() < unique[j].String()
774 })
775 return unique
776}
777
Colin Cross27027c72020-02-28 15:34:17 -0800778func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700779 k := 0
780outer:
781 for i := 0; i < len(list); i++ {
782 for j := 0; j < k; j++ {
783 if list[i] == list[j] {
784 continue outer
785 }
786 }
787 list[k] = list[i]
788 k++
789 }
790 return list[:k]
791}
792
Colin Cross27027c72020-02-28 15:34:17 -0800793func firstUniquePathsMap(list Paths) Paths {
794 k := 0
795 seen := make(map[Path]bool, len(list))
796 for i := 0; i < len(list); i++ {
797 if seen[list[i]] {
798 continue
799 }
800 seen[list[i]] = true
801 list[k] = list[i]
802 k++
803 }
804 return list[:k]
805}
806
Colin Cross5d583952020-11-24 16:21:24 -0800807// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
808// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
809func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
810 // 128 was chosen based on BenchmarkFirstUniquePaths results.
811 if len(list) > 128 {
812 return firstUniqueInstallPathsMap(list)
813 }
814 return firstUniqueInstallPathsList(list)
815}
816
817func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
818 k := 0
819outer:
820 for i := 0; i < len(list); i++ {
821 for j := 0; j < k; j++ {
822 if list[i] == list[j] {
823 continue outer
824 }
825 }
826 list[k] = list[i]
827 k++
828 }
829 return list[:k]
830}
831
832func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
833 k := 0
834 seen := make(map[InstallPath]bool, len(list))
835 for i := 0; i < len(list); i++ {
836 if seen[list[i]] {
837 continue
838 }
839 seen[list[i]] = true
840 list[k] = list[i]
841 k++
842 }
843 return list[:k]
844}
845
Colin Crossb6715442017-10-24 11:13:31 -0700846// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
847// modifies the Paths slice contents in place, and returns a subslice of the original slice.
848func LastUniquePaths(list Paths) Paths {
849 totalSkip := 0
850 for i := len(list) - 1; i >= totalSkip; i-- {
851 skip := 0
852 for j := i - 1; j >= totalSkip; j-- {
853 if list[i] == list[j] {
854 skip++
855 } else {
856 list[j+skip] = list[j]
857 }
858 }
859 totalSkip += skip
860 }
861 return list[totalSkip:]
862}
863
Colin Crossa140bb02018-04-17 10:52:26 -0700864// ReversePaths returns a copy of a Paths in reverse order.
865func ReversePaths(list Paths) Paths {
866 if list == nil {
867 return nil
868 }
869 ret := make(Paths, len(list))
870 for i := range list {
871 ret[i] = list[len(list)-1-i]
872 }
873 return ret
874}
875
Jeff Gaston294356f2017-09-27 17:05:30 -0700876func indexPathList(s Path, list []Path) int {
877 for i, l := range list {
878 if l == s {
879 return i
880 }
881 }
882
883 return -1
884}
885
886func inPathList(p Path, list []Path) bool {
887 return indexPathList(p, list) != -1
888}
889
890func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000891 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
892}
893
894func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700895 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000896 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700897 filtered = append(filtered, l)
898 } else {
899 remainder = append(remainder, l)
900 }
901 }
902
903 return
904}
905
Colin Cross93e85952017-08-15 13:34:18 -0700906// HasExt returns true of any of the paths have extension ext, otherwise false
907func (p Paths) HasExt(ext string) bool {
908 for _, path := range p {
909 if path.Ext() == ext {
910 return true
911 }
912 }
913
914 return false
915}
916
917// FilterByExt returns the subset of the paths that have extension ext
918func (p Paths) FilterByExt(ext string) Paths {
919 ret := make(Paths, 0, len(p))
920 for _, path := range p {
921 if path.Ext() == ext {
922 ret = append(ret, path)
923 }
924 }
925 return ret
926}
927
928// FilterOutByExt returns the subset of the paths that do not have extension ext
929func (p Paths) FilterOutByExt(ext string) Paths {
930 ret := make(Paths, 0, len(p))
931 for _, path := range p {
932 if path.Ext() != ext {
933 ret = append(ret, path)
934 }
935 }
936 return ret
937}
938
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700939// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
940// (including subdirectories) are in a contiguous subslice of the list, and can be found in
941// O(log(N)) time using a binary search on the directory prefix.
942type DirectorySortedPaths Paths
943
944func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
945 ret := append(DirectorySortedPaths(nil), paths...)
946 sort.Slice(ret, func(i, j int) bool {
947 return ret[i].String() < ret[j].String()
948 })
949 return ret
950}
951
952// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
953// that are in the specified directory and its subdirectories.
954func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
955 prefix := filepath.Clean(dir) + "/"
956 start := sort.Search(len(p), func(i int) bool {
957 return prefix < p[i].String()
958 })
959
960 ret := p[start:]
961
962 end := sort.Search(len(ret), func(i int) bool {
963 return !strings.HasPrefix(ret[i].String(), prefix)
964 })
965
966 ret = ret[:end]
967
968 return Paths(ret)
969}
970
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500971// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700972type WritablePaths []WritablePath
973
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000974// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
975// each item in this slice.
976func (p WritablePaths) RelativeToTop() WritablePaths {
977 ensureTestOnly()
978 if p == nil {
979 return p
980 }
981 ret := make(WritablePaths, len(p))
982 for i, path := range p {
983 ret[i] = path.RelativeToTop().(WritablePath)
984 }
985 return ret
986}
987
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700988// Strings returns the string forms of the writable paths.
989func (p WritablePaths) Strings() []string {
990 if p == nil {
991 return nil
992 }
993 ret := make([]string, len(p))
994 for i, path := range p {
995 ret[i] = path.String()
996 }
997 return ret
998}
999
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001000// Paths returns the WritablePaths as a Paths
1001func (p WritablePaths) Paths() Paths {
1002 if p == nil {
1003 return nil
1004 }
1005 ret := make(Paths, len(p))
1006 for i, path := range p {
1007 ret[i] = path
1008 }
1009 return ret
1010}
1011
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001012type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001013 path string
1014 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001015}
1016
1017func (p basePath) Ext() string {
1018 return filepath.Ext(p.path)
1019}
1020
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001021func (p basePath) Base() string {
1022 return filepath.Base(p.path)
1023}
1024
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001025func (p basePath) Rel() string {
1026 if p.rel != "" {
1027 return p.rel
1028 }
1029 return p.path
1030}
1031
Colin Cross0875c522017-11-28 17:34:01 -08001032func (p basePath) String() string {
1033 return p.path
1034}
1035
Colin Cross0db55682017-12-05 15:36:55 -08001036func (p basePath) withRel(rel string) basePath {
1037 p.path = filepath.Join(p.path, rel)
1038 p.rel = rel
1039 return p
1040}
1041
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001042// SourcePath is a Path representing a file path rooted from SrcDir
1043type SourcePath struct {
1044 basePath
Paul Duffin580efc82021-03-24 09:04:03 +00001045
1046 // The sources root, i.e. Config.SrcDir()
1047 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001048}
1049
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001050func (p SourcePath) RelativeToTop() Path {
1051 ensureTestOnly()
1052 return p
1053}
1054
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001055var _ Path = SourcePath{}
1056
Colin Cross0db55682017-12-05 15:36:55 -08001057func (p SourcePath) withRel(rel string) SourcePath {
1058 p.basePath = p.basePath.withRel(rel)
1059 return p
1060}
1061
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001062// safePathForSource is for paths that we expect are safe -- only for use by go
1063// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001064func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1065 p, err := validateSafePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +00001066 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Crossfe4bc362018-09-12 10:02:13 -07001067 if err != nil {
1068 return ret, err
1069 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001070
Colin Cross7b3dcc32019-01-24 13:14:39 -08001071 // absolute path already checked by validateSafePath
1072 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001073 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001074 }
1075
Colin Crossfe4bc362018-09-12 10:02:13 -07001076 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001077}
1078
Colin Cross192e97a2018-02-22 14:21:02 -08001079// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1080func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001081 p, err := validatePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +00001082 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Cross94a32102018-02-22 14:21:02 -08001083 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001084 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001085 }
1086
Colin Cross7b3dcc32019-01-24 13:14:39 -08001087 // absolute path already checked by validatePath
1088 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001089 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001090 }
1091
Colin Cross192e97a2018-02-22 14:21:02 -08001092 return ret, nil
1093}
1094
1095// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1096// path does not exist.
1097func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1098 var files []string
1099
1100 if gctx, ok := ctx.(PathGlobContext); ok {
1101 // Use glob to produce proper dependencies, even though we only want
1102 // a single file.
1103 files, err = gctx.GlobWithDeps(path.String(), nil)
1104 } else {
Colin Cross82ea3fb2021-04-05 17:48:26 -07001105 var result pathtools.GlobResult
Colin Cross192e97a2018-02-22 14:21:02 -08001106 // We cannot add build statements in this context, so we fall back to
1107 // AddNinjaFileDeps
Colin Cross82ea3fb2021-04-05 17:48:26 -07001108 result, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
1109 ctx.AddNinjaFileDeps(result.Deps...)
1110 files = result.Matches
Colin Cross192e97a2018-02-22 14:21:02 -08001111 }
1112
1113 if err != nil {
1114 return false, fmt.Errorf("glob: %s", err.Error())
1115 }
1116
1117 return len(files) > 0, nil
1118}
1119
1120// PathForSource joins the provided path components and validates that the result
1121// neither escapes the source dir nor is in the out dir.
1122// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1123func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1124 path, err := pathForSource(ctx, pathComponents...)
1125 if err != nil {
1126 reportPathError(ctx, err)
1127 }
1128
Colin Crosse3924e12018-08-15 20:18:53 -07001129 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001130 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001131 }
1132
Liz Kammera830f3a2020-11-10 10:50:34 -08001133 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001134 exists, err := existsWithDependencies(ctx, path)
1135 if err != nil {
1136 reportPathError(ctx, err)
1137 }
1138 if !exists {
1139 modCtx.AddMissingDependencies([]string{path.String()})
1140 }
Colin Cross988414c2020-01-11 01:11:46 +00001141 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001142 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001143 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001144 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001145 }
1146 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001147}
1148
Liz Kammer7aa52882021-02-11 09:16:14 -05001149// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1150// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1151// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1152// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001153func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001154 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001155 if err != nil {
1156 reportPathError(ctx, err)
1157 return OptionalPath{}
1158 }
Colin Crossc48c1432018-02-23 07:09:01 +00001159
Colin Crosse3924e12018-08-15 20:18:53 -07001160 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001161 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001162 return OptionalPath{}
1163 }
1164
Colin Cross192e97a2018-02-22 14:21:02 -08001165 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001166 if err != nil {
1167 reportPathError(ctx, err)
1168 return OptionalPath{}
1169 }
Colin Cross192e97a2018-02-22 14:21:02 -08001170 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001171 return OptionalPath{}
1172 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001173 return OptionalPathForPath(path)
1174}
1175
1176func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001177 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001178}
1179
1180// Join creates a new SourcePath with paths... joined with the current path. The
1181// provided paths... may not use '..' to escape from the current path.
1182func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001183 path, err := validatePath(paths...)
1184 if err != nil {
1185 reportPathError(ctx, err)
1186 }
Colin Cross0db55682017-12-05 15:36:55 -08001187 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001188}
1189
Colin Cross2fafa3e2019-03-05 12:39:51 -08001190// join is like Join but does less path validation.
1191func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1192 path, err := validateSafePath(paths...)
1193 if err != nil {
1194 reportPathError(ctx, err)
1195 }
1196 return p.withRel(path)
1197}
1198
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001199// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1200// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001201func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001202 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001203 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001204 relDir = srcPath.path
1205 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001206 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001207 return OptionalPath{}
1208 }
Paul Duffin580efc82021-03-24 09:04:03 +00001209 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001210 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001211 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001212 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001213 }
Colin Cross461b4452018-02-23 09:22:42 -08001214 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001215 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001216 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001217 return OptionalPath{}
1218 }
1219 if len(paths) == 0 {
1220 return OptionalPath{}
1221 }
Paul Duffin580efc82021-03-24 09:04:03 +00001222 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001223 return OptionalPathForPath(PathForSource(ctx, relPath))
1224}
1225
Colin Cross70dda7e2019-10-01 22:05:35 -07001226// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001227type OutputPath struct {
1228 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001229
1230 // The soong build directory, i.e. Config.BuildDir()
1231 buildDir string
1232
Colin Crossd63c9a72020-01-29 16:52:50 -08001233 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001234}
1235
Colin Cross702e0f82017-10-18 17:27:54 -07001236func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001237 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001238 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001239 return p
1240}
1241
Colin Cross3063b782018-08-15 11:19:12 -07001242func (p OutputPath) WithoutRel() OutputPath {
1243 p.basePath.rel = filepath.Base(p.basePath.path)
1244 return p
1245}
1246
Paul Duffind65c58b2021-03-24 09:22:07 +00001247func (p OutputPath) getBuildDir() string {
1248 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001249}
1250
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001251func (p OutputPath) RelativeToTop() Path {
1252 return p.outputPathRelativeToTop()
1253}
1254
1255func (p OutputPath) outputPathRelativeToTop() OutputPath {
1256 p.fullPath = StringPathRelativeToTop(p.buildDir, p.fullPath)
1257 p.buildDir = OutSoongDir
1258 return p
1259}
1260
Paul Duffin0267d492021-02-02 10:05:52 +00001261func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1262 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1263}
1264
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001265var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001266var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001267var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001268
Chris Parsons8f232a22020-06-23 17:37:05 -04001269// toolDepPath is a Path representing a dependency of the build tool.
1270type toolDepPath struct {
1271 basePath
1272}
1273
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001274func (t toolDepPath) RelativeToTop() Path {
1275 ensureTestOnly()
1276 return t
1277}
1278
Chris Parsons8f232a22020-06-23 17:37:05 -04001279var _ Path = toolDepPath{}
1280
1281// pathForBuildToolDep returns a toolDepPath representing the given path string.
1282// There is no validation for the path, as it is "trusted": It may fail
1283// normal validation checks. For example, it may be an absolute path.
1284// Only use this function to construct paths for dependencies of the build
1285// tool invocation.
1286func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001287 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001288}
1289
Jeff Gaston734e3802017-04-10 15:47:24 -07001290// PathForOutput joins the provided paths and returns an OutputPath that is
1291// validated to not escape the build dir.
1292// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1293func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001294 path, err := validatePath(pathComponents...)
1295 if err != nil {
1296 reportPathError(ctx, err)
1297 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001298 fullPath := filepath.Join(ctx.Config().buildDir, path)
1299 path = fullPath[len(fullPath)-len(path):]
Paul Duffin74abc5d2021-03-24 09:24:59 +00001300 return OutputPath{basePath{path, ""}, ctx.Config().buildDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001301}
1302
Colin Cross40e33732019-02-15 11:08:35 -08001303// PathsForOutput returns Paths rooted from buildDir
1304func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1305 ret := make(WritablePaths, len(paths))
1306 for i, path := range paths {
1307 ret[i] = PathForOutput(ctx, path)
1308 }
1309 return ret
1310}
1311
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001312func (p OutputPath) writablePath() {}
1313
1314func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001315 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001316}
1317
1318// Join creates a new OutputPath with paths... joined with the current path. The
1319// provided paths... may not use '..' to escape from the current path.
1320func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001321 path, err := validatePath(paths...)
1322 if err != nil {
1323 reportPathError(ctx, err)
1324 }
Colin Cross0db55682017-12-05 15:36:55 -08001325 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001326}
1327
Colin Cross8854a5a2019-02-11 14:14:16 -08001328// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1329func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1330 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001331 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001332 }
1333 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001334 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001335 return ret
1336}
1337
Colin Cross40e33732019-02-15 11:08:35 -08001338// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1339func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1340 path, err := validatePath(paths...)
1341 if err != nil {
1342 reportPathError(ctx, err)
1343 }
1344
1345 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001346 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001347 return ret
1348}
1349
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001350// PathForIntermediates returns an OutputPath representing the top-level
1351// intermediates directory.
1352func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001353 path, err := validatePath(paths...)
1354 if err != nil {
1355 reportPathError(ctx, err)
1356 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001357 return PathForOutput(ctx, ".intermediates", path)
1358}
1359
Colin Cross07e51612019-03-05 12:46:40 -08001360var _ genPathProvider = SourcePath{}
1361var _ objPathProvider = SourcePath{}
1362var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001363
Colin Cross07e51612019-03-05 12:46:40 -08001364// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001365// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001366func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001367 p, err := validatePath(pathComponents...)
1368 if err != nil {
1369 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001370 }
Colin Cross8a497952019-03-05 22:25:09 -08001371 paths, err := expandOneSrcPath(ctx, p, nil)
1372 if err != nil {
1373 if depErr, ok := err.(missingDependencyError); ok {
1374 if ctx.Config().AllowMissingDependencies() {
1375 ctx.AddMissingDependencies(depErr.missingDeps)
1376 } else {
1377 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1378 }
1379 } else {
1380 reportPathError(ctx, err)
1381 }
1382 return nil
1383 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001384 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001385 return nil
1386 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001387 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001388 }
1389 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001390}
1391
Liz Kammera830f3a2020-11-10 10:50:34 -08001392func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001393 p, err := validatePath(paths...)
1394 if err != nil {
1395 reportPathError(ctx, err)
1396 }
1397
1398 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1399 if err != nil {
1400 reportPathError(ctx, err)
1401 }
1402
1403 path.basePath.rel = p
1404
1405 return path
1406}
1407
Colin Cross2fafa3e2019-03-05 12:39:51 -08001408// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1409// will return the path relative to subDir in the module's source directory. If any input paths are not located
1410// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001411func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001412 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001413 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001414 for i, path := range paths {
1415 rel := Rel(ctx, subDirFullPath.String(), path.String())
1416 paths[i] = subDirFullPath.join(ctx, rel)
1417 }
1418 return paths
1419}
1420
1421// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1422// 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 -08001423func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001424 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001425 rel := Rel(ctx, subDirFullPath.String(), path.String())
1426 return subDirFullPath.Join(ctx, rel)
1427}
1428
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001429// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1430// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001431func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001432 if p == nil {
1433 return OptionalPath{}
1434 }
1435 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1436}
1437
Liz Kammera830f3a2020-11-10 10:50:34 -08001438func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001439 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001440}
1441
Liz Kammera830f3a2020-11-10 10:50:34 -08001442func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001443 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001444}
1445
Liz Kammera830f3a2020-11-10 10:50:34 -08001446func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001447 // TODO: Use full directory if the new ctx is not the current ctx?
1448 return PathForModuleRes(ctx, p.path, name)
1449}
1450
1451// ModuleOutPath is a Path representing a module's output directory.
1452type ModuleOutPath struct {
1453 OutputPath
1454}
1455
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001456func (p ModuleOutPath) RelativeToTop() Path {
1457 p.OutputPath = p.outputPathRelativeToTop()
1458 return p
1459}
1460
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001461var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001462var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001463
Liz Kammera830f3a2020-11-10 10:50:34 -08001464func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001465 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1466}
1467
Liz Kammera830f3a2020-11-10 10:50:34 -08001468// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1469type ModuleOutPathContext interface {
1470 PathContext
1471
1472 ModuleName() string
1473 ModuleDir() string
1474 ModuleSubDir() string
1475}
1476
1477func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001478 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1479}
1480
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001481type BazelOutPath struct {
1482 OutputPath
1483}
1484
1485var _ Path = BazelOutPath{}
1486var _ objPathProvider = BazelOutPath{}
1487
Liz Kammera830f3a2020-11-10 10:50:34 -08001488func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001489 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1490}
1491
Logan Chien7eefdc42018-07-11 18:10:41 +08001492// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1493// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001494func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001495 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001496
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001497 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001498 if len(arches) == 0 {
1499 panic("device build with no primary arch")
1500 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001501 currentArch := ctx.Arch()
1502 archNameAndVariant := currentArch.ArchType.String()
1503 if currentArch.ArchVariant != "" {
1504 archNameAndVariant += "_" + currentArch.ArchVariant
1505 }
Logan Chien5237bed2018-07-11 17:15:57 +08001506
1507 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001508 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001509 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001510 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001511 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001512 } else {
1513 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001514 }
Logan Chien5237bed2018-07-11 17:15:57 +08001515
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001516 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001517
1518 var ext string
1519 if isGzip {
1520 ext = ".lsdump.gz"
1521 } else {
1522 ext = ".lsdump"
1523 }
1524
1525 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1526 version, binderBitness, archNameAndVariant, "source-based",
1527 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001528}
1529
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001530// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1531// bazel-owned outputs.
1532func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1533 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1534 execRootPath := filepath.Join(execRootPathComponents...)
1535 validatedExecRootPath, err := validatePath(execRootPath)
1536 if err != nil {
1537 reportPathError(ctx, err)
1538 }
1539
Paul Duffin74abc5d2021-03-24 09:24:59 +00001540 outputPath := OutputPath{basePath{"", ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001541 ctx.Config().buildDir,
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001542 ctx.Config().BazelContext.OutputBase()}
1543
1544 return BazelOutPath{
1545 OutputPath: outputPath.withRel(validatedExecRootPath),
1546 }
1547}
1548
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001549// PathForModuleOut returns a Path representing the paths... under the module's
1550// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001551func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001552 p, err := validatePath(paths...)
1553 if err != nil {
1554 reportPathError(ctx, err)
1555 }
Colin Cross702e0f82017-10-18 17:27:54 -07001556 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001557 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001558 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001559}
1560
1561// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1562// directory. Mainly used for generated sources.
1563type ModuleGenPath struct {
1564 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001565}
1566
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001567func (p ModuleGenPath) RelativeToTop() Path {
1568 p.OutputPath = p.outputPathRelativeToTop()
1569 return p
1570}
1571
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001572var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001573var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001574var _ genPathProvider = ModuleGenPath{}
1575var _ objPathProvider = ModuleGenPath{}
1576
1577// PathForModuleGen returns a Path representing the paths... under the module's
1578// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001579func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001580 p, err := validatePath(paths...)
1581 if err != nil {
1582 reportPathError(ctx, err)
1583 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001584 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001585 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001586 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001587 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001588 }
1589}
1590
Liz Kammera830f3a2020-11-10 10:50:34 -08001591func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001592 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001593 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001594}
1595
Liz Kammera830f3a2020-11-10 10:50:34 -08001596func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001597 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1598}
1599
1600// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1601// directory. Used for compiled objects.
1602type ModuleObjPath struct {
1603 ModuleOutPath
1604}
1605
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001606func (p ModuleObjPath) RelativeToTop() Path {
1607 p.OutputPath = p.outputPathRelativeToTop()
1608 return p
1609}
1610
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001611var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001612var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001613
1614// PathForModuleObj returns a Path representing the paths... under the module's
1615// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001616func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001617 p, err := validatePath(pathComponents...)
1618 if err != nil {
1619 reportPathError(ctx, err)
1620 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001621 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1622}
1623
1624// ModuleResPath is a a Path representing the 'res' directory in a module's
1625// output directory.
1626type ModuleResPath struct {
1627 ModuleOutPath
1628}
1629
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001630func (p ModuleResPath) RelativeToTop() Path {
1631 p.OutputPath = p.outputPathRelativeToTop()
1632 return p
1633}
1634
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001635var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001636var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001637
1638// PathForModuleRes returns a Path representing the paths... under the module's
1639// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001640func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001641 p, err := validatePath(pathComponents...)
1642 if err != nil {
1643 reportPathError(ctx, err)
1644 }
1645
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001646 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1647}
1648
Colin Cross70dda7e2019-10-01 22:05:35 -07001649// InstallPath is a Path representing a installed file path rooted from the build directory
1650type InstallPath struct {
1651 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001652
Paul Duffind65c58b2021-03-24 09:22:07 +00001653 // The soong build directory, i.e. Config.BuildDir()
1654 buildDir string
1655
Jiyong Park957bcd92020-10-20 18:23:33 +09001656 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1657 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1658 partitionDir string
1659
1660 // makePath indicates whether this path is for Soong (false) or Make (true).
1661 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001662}
1663
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001664// Will panic if called from outside a test environment.
1665func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001666 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001667 return
1668 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001669 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001670}
1671
1672func (p InstallPath) RelativeToTop() Path {
1673 ensureTestOnly()
1674 p.buildDir = OutSoongDir
1675 return p
1676}
1677
Paul Duffind65c58b2021-03-24 09:22:07 +00001678func (p InstallPath) getBuildDir() string {
1679 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001680}
1681
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001682func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1683 panic("Not implemented")
1684}
1685
Paul Duffin9b478b02019-12-10 13:41:51 +00001686var _ Path = InstallPath{}
1687var _ WritablePath = InstallPath{}
1688
Colin Cross70dda7e2019-10-01 22:05:35 -07001689func (p InstallPath) writablePath() {}
1690
1691func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001692 if p.makePath {
1693 // Make path starts with out/ instead of out/soong.
Paul Duffind65c58b2021-03-24 09:22:07 +00001694 return filepath.Join(p.buildDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001695 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001696 return filepath.Join(p.buildDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001697 }
1698}
1699
1700// PartitionDir returns the path to the partition where the install path is rooted at. It is
1701// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1702// The ./soong is dropped if the install path is for Make.
1703func (p InstallPath) PartitionDir() string {
1704 if p.makePath {
Paul Duffind65c58b2021-03-24 09:22:07 +00001705 return filepath.Join(p.buildDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001706 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001707 return filepath.Join(p.buildDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001708 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001709}
1710
1711// Join creates a new InstallPath with paths... joined with the current path. The
1712// provided paths... may not use '..' to escape from the current path.
1713func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1714 path, err := validatePath(paths...)
1715 if err != nil {
1716 reportPathError(ctx, err)
1717 }
1718 return p.withRel(path)
1719}
1720
1721func (p InstallPath) withRel(rel string) InstallPath {
1722 p.basePath = p.basePath.withRel(rel)
1723 return p
1724}
1725
Colin Crossff6c33d2019-10-02 16:01:35 -07001726// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1727// i.e. out/ instead of out/soong/.
1728func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001729 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001730 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001731}
1732
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001733// PathForModuleInstall returns a Path representing the install path for the
1734// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001735func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001736 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001737 arch := ctx.Arch().ArchType
1738 forceOS, forceArch := ctx.InstallForceOS()
1739 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001740 os = *forceOS
1741 }
Jiyong Park87788b52020-09-01 12:37:45 +09001742 if forceArch != nil {
1743 arch = *forceArch
1744 }
Colin Cross6e359402020-02-10 15:29:54 -08001745 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001746
Jiyong Park87788b52020-09-01 12:37:45 +09001747 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001748
Jingwen Chencda22c92020-11-23 00:22:30 -05001749 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001750 ret = ret.ToMakePath()
1751 }
1752
1753 return ret
1754}
1755
Jiyong Park87788b52020-09-01 12:37:45 +09001756func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001757 pathComponents ...string) InstallPath {
1758
Jiyong Park957bcd92020-10-20 18:23:33 +09001759 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001760
Colin Cross6e359402020-02-10 15:29:54 -08001761 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001762 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001763 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001764 osName := os.String()
1765 if os == Linux {
1766 // instead of linux_glibc
1767 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001768 }
Jiyong Park87788b52020-09-01 12:37:45 +09001769 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1770 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1771 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1772 // Let's keep using x86 for the existing cases until we have a need to support
1773 // other architectures.
1774 archName := arch.String()
1775 if os.Class == Host && (arch == X86_64 || arch == Common) {
1776 archName = "x86"
1777 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001778 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001779 }
Colin Cross609c49a2020-02-13 13:20:11 -08001780 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001781 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001782 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001783
Jiyong Park957bcd92020-10-20 18:23:33 +09001784 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001785 if err != nil {
1786 reportPathError(ctx, err)
1787 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001788
Jiyong Park957bcd92020-10-20 18:23:33 +09001789 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001790 basePath: basePath{partionPath, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001791 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001792 partitionDir: partionPath,
1793 makePath: false,
1794 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001795
Jiyong Park957bcd92020-10-20 18:23:33 +09001796 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001797}
1798
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001799func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001800 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001801 basePath: basePath{prefix, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001802 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001803 partitionDir: prefix,
1804 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001805 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001806 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001807}
1808
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001809func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1810 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1811}
1812
1813func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1814 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1815}
1816
Colin Cross70dda7e2019-10-01 22:05:35 -07001817func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001818 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1819
1820 return "/" + rel
1821}
1822
Colin Cross6e359402020-02-10 15:29:54 -08001823func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001824 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001825 if ctx.InstallInTestcases() {
1826 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001827 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001828 } else if os.Class == Device {
1829 if ctx.InstallInData() {
1830 partition = "data"
1831 } else if ctx.InstallInRamdisk() {
1832 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1833 partition = "recovery/root/first_stage_ramdisk"
1834 } else {
1835 partition = "ramdisk"
1836 }
1837 if !ctx.InstallInRoot() {
1838 partition += "/system"
1839 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001840 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001841 // The module is only available after switching root into
1842 // /first_stage_ramdisk. To expose the module before switching root
1843 // on a device without a dedicated recovery partition, install the
1844 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001845 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001846 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001847 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001848 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001849 }
1850 if !ctx.InstallInRoot() {
1851 partition += "/system"
1852 }
Inseob Kimf84e9c02021-04-08 21:13:22 +09001853 } else if ctx.InstallInDebugRamdisk() {
1854 // The module is only available after switching root into
1855 // /first_stage_ramdisk. To expose the module before switching root
1856 // on a device without a dedicated recovery partition, install the
1857 // recovery variant.
1858 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1859 partition = "debug_ramdisk/first_stage_ramdisk"
1860 } else {
1861 partition = "debug_ramdisk"
1862 }
Colin Cross6e359402020-02-10 15:29:54 -08001863 } else if ctx.InstallInRecovery() {
1864 if ctx.InstallInRoot() {
1865 partition = "recovery/root"
1866 } else {
1867 // the layout of recovery partion is the same as that of system partition
1868 partition = "recovery/root/system"
1869 }
1870 } else if ctx.SocSpecific() {
1871 partition = ctx.DeviceConfig().VendorPath()
1872 } else if ctx.DeviceSpecific() {
1873 partition = ctx.DeviceConfig().OdmPath()
1874 } else if ctx.ProductSpecific() {
1875 partition = ctx.DeviceConfig().ProductPath()
1876 } else if ctx.SystemExtSpecific() {
1877 partition = ctx.DeviceConfig().SystemExtPath()
1878 } else if ctx.InstallInRoot() {
1879 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001880 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001881 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001882 }
Colin Cross6e359402020-02-10 15:29:54 -08001883 if ctx.InstallInSanitizerDir() {
1884 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001885 }
Colin Cross43f08db2018-11-12 10:13:39 -08001886 }
1887 return partition
1888}
1889
Colin Cross609c49a2020-02-13 13:20:11 -08001890type InstallPaths []InstallPath
1891
1892// Paths returns the InstallPaths as a Paths
1893func (p InstallPaths) Paths() Paths {
1894 if p == nil {
1895 return nil
1896 }
1897 ret := make(Paths, len(p))
1898 for i, path := range p {
1899 ret[i] = path
1900 }
1901 return ret
1902}
1903
1904// Strings returns the string forms of the install paths.
1905func (p InstallPaths) Strings() []string {
1906 if p == nil {
1907 return nil
1908 }
1909 ret := make([]string, len(p))
1910 for i, path := range p {
1911 ret[i] = path.String()
1912 }
1913 return ret
1914}
1915
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001916// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001917// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001918func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001919 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001920 path := filepath.Clean(path)
1921 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001922 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001923 }
1924 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001925 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1926 // variables. '..' may remove the entire ninja variable, even if it
1927 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001928 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001929}
1930
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001931// validatePath validates that a path does not include ninja variables, and that
1932// each path component does not attempt to leave its component. Returns a joined
1933// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001934func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001935 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001936 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001937 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001938 }
1939 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001940 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001941}
Colin Cross5b529592017-05-09 13:34:34 -07001942
Colin Cross0875c522017-11-28 17:34:01 -08001943func PathForPhony(ctx PathContext, phony string) WritablePath {
1944 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001945 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001946 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001947 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001948}
1949
Colin Cross74e3fe42017-12-11 15:51:44 -08001950type PhonyPath struct {
1951 basePath
1952}
1953
1954func (p PhonyPath) writablePath() {}
1955
Paul Duffind65c58b2021-03-24 09:22:07 +00001956func (p PhonyPath) getBuildDir() string {
1957 // A phone path cannot contain any / so cannot be relative to the build directory.
1958 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001959}
1960
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001961func (p PhonyPath) RelativeToTop() Path {
1962 ensureTestOnly()
1963 // A phony path cannot contain any / so does not have a build directory so switching to a new
1964 // build directory has no effect so just return this path.
1965 return p
1966}
1967
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001968func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1969 panic("Not implemented")
1970}
1971
Colin Cross74e3fe42017-12-11 15:51:44 -08001972var _ Path = PhonyPath{}
1973var _ WritablePath = PhonyPath{}
1974
Colin Cross5b529592017-05-09 13:34:34 -07001975type testPath struct {
1976 basePath
1977}
1978
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001979func (p testPath) RelativeToTop() Path {
1980 ensureTestOnly()
1981 return p
1982}
1983
Colin Cross5b529592017-05-09 13:34:34 -07001984func (p testPath) String() string {
1985 return p.path
1986}
1987
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001988var _ Path = testPath{}
1989
Colin Cross40e33732019-02-15 11:08:35 -08001990// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1991// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001992func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001993 p, err := validateSafePath(paths...)
1994 if err != nil {
1995 panic(err)
1996 }
Colin Cross5b529592017-05-09 13:34:34 -07001997 return testPath{basePath{path: p, rel: p}}
1998}
1999
Colin Cross40e33732019-02-15 11:08:35 -08002000// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2001func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002002 p := make(Paths, len(strs))
2003 for i, s := range strs {
2004 p[i] = PathForTesting(s)
2005 }
2006
2007 return p
2008}
Colin Cross43f08db2018-11-12 10:13:39 -08002009
Colin Cross40e33732019-02-15 11:08:35 -08002010type testPathContext struct {
2011 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002012}
2013
Colin Cross40e33732019-02-15 11:08:35 -08002014func (x *testPathContext) Config() Config { return x.config }
2015func (x *testPathContext) AddNinjaFileDeps(...string) {}
2016
2017// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2018// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002019func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002020 return &testPathContext{
2021 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002022 }
2023}
2024
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002025type testModuleInstallPathContext struct {
2026 baseModuleContext
2027
2028 inData bool
2029 inTestcases bool
2030 inSanitizerDir bool
2031 inRamdisk bool
2032 inVendorRamdisk bool
Inseob Kimf84e9c02021-04-08 21:13:22 +09002033 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002034 inRecovery bool
2035 inRoot bool
2036 forceOS *OsType
2037 forceArch *ArchType
2038}
2039
2040func (m testModuleInstallPathContext) Config() Config {
2041 return m.baseModuleContext.config
2042}
2043
2044func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2045
2046func (m testModuleInstallPathContext) InstallInData() bool {
2047 return m.inData
2048}
2049
2050func (m testModuleInstallPathContext) InstallInTestcases() bool {
2051 return m.inTestcases
2052}
2053
2054func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2055 return m.inSanitizerDir
2056}
2057
2058func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2059 return m.inRamdisk
2060}
2061
2062func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2063 return m.inVendorRamdisk
2064}
2065
Inseob Kimf84e9c02021-04-08 21:13:22 +09002066func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2067 return m.inDebugRamdisk
2068}
2069
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002070func (m testModuleInstallPathContext) InstallInRecovery() bool {
2071 return m.inRecovery
2072}
2073
2074func (m testModuleInstallPathContext) InstallInRoot() bool {
2075 return m.inRoot
2076}
2077
2078func (m testModuleInstallPathContext) InstallBypassMake() bool {
2079 return false
2080}
2081
2082func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2083 return m.forceOS, m.forceArch
2084}
2085
2086// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2087// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2088// delegated to it will panic.
2089func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2090 ctx := &testModuleInstallPathContext{}
2091 ctx.config = config
2092 ctx.os = Android
2093 return ctx
2094}
2095
Colin Cross43f08db2018-11-12 10:13:39 -08002096// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2097// targetPath is not inside basePath.
2098func Rel(ctx PathContext, basePath string, targetPath string) string {
2099 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2100 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002101 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002102 return ""
2103 }
2104 return rel
2105}
2106
2107// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2108// targetPath is not inside basePath.
2109func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002110 rel, isRel, err := maybeRelErr(basePath, targetPath)
2111 if err != nil {
2112 reportPathError(ctx, err)
2113 }
2114 return rel, isRel
2115}
2116
2117func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002118 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2119 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002120 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002121 }
2122 rel, err := filepath.Rel(basePath, targetPath)
2123 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002124 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002125 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002126 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002127 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002128 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002129}
Colin Cross988414c2020-01-11 01:11:46 +00002130
2131// Writes a file to the output directory. Attempting to write directly to the output directory
2132// will fail due to the sandbox of the soong_build process.
2133func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
2134 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
2135}
2136
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002137func RemoveAllOutputDir(path WritablePath) error {
2138 return os.RemoveAll(absolutePath(path.String()))
2139}
2140
2141func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2142 dir := absolutePath(path.String())
2143 if _, err := os.Stat(dir); os.IsNotExist(err) {
2144 return os.MkdirAll(dir, os.ModePerm)
2145 } else {
2146 return err
2147 }
2148}
2149
Colin Cross988414c2020-01-11 01:11:46 +00002150func absolutePath(path string) string {
2151 if filepath.IsAbs(path) {
2152 return path
2153 }
2154 return filepath.Join(absSrcDir, path)
2155}
Chris Parsons216e10a2020-07-09 17:12:52 -04002156
2157// A DataPath represents the path of a file to be used as data, for example
2158// a test library to be installed alongside a test.
2159// The data file should be installed (copied from `<SrcPath>`) to
2160// `<install_root>/<RelativeInstallPath>/<filename>`, or
2161// `<install_root>/<filename>` if RelativeInstallPath is empty.
2162type DataPath struct {
2163 // The path of the data file that should be copied into the data directory
2164 SrcPath Path
2165 // The install path of the data file, relative to the install root.
2166 RelativeInstallPath string
2167}
Colin Crossdcf71b22021-02-01 13:59:03 -08002168
2169// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2170func PathsIfNonNil(paths ...Path) Paths {
2171 if len(paths) == 0 {
2172 // Fast path for empty argument list
2173 return nil
2174 } else if len(paths) == 1 {
2175 // Fast path for a single argument
2176 if paths[0] != nil {
2177 return paths
2178 } else {
2179 return nil
2180 }
2181 }
2182 ret := make(Paths, 0, len(paths))
2183 for _, path := range paths {
2184 if path != nil {
2185 ret = append(ret, path)
2186 }
2187 }
2188 if len(ret) == 0 {
2189 return nil
2190 }
2191 return ret
2192}