blob: 5ae242bfbde9ebfbacc347c86cb687efb65acca5 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Colin Cross6e18ca42015-07-14 18:55:36 -070018 "fmt"
Colin Cross6a745c62015-06-16 16:38:10 -070019 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070020 "reflect"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070021 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070022 "strings"
23
24 "github.com/google/blueprint"
25 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080026)
27
Dan Willemsen34cc69e2015-09-23 15:26:20 -070028// PathContext is the subset of a (Module|Singleton)Context required by the
29// Path methods.
30type PathContext interface {
Colin Cross294941b2017-02-01 14:10:36 -080031 Fs() pathtools.FileSystem
Colin Crossaabf6792017-11-29 00:27:14 -080032 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080033 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080034}
35
Colin Cross7f19f372016-11-01 11:10:25 -070036type PathGlobContext interface {
37 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
38}
39
Colin Crossaabf6792017-11-29 00:27:14 -080040var _ PathContext = SingletonContext(nil)
41var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070042
Dan Willemsen00269f22017-07-06 16:59:48 -070043type ModuleInstallPathContext interface {
44 PathContext
45
46 androidBaseContext
47
48 InstallInData() bool
Jaewoong Jung1ffd7932019-09-11 10:25:18 -070049 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -070050 InstallInSanitizerDir() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +090051 InstallInRecovery() bool
Dan Willemsen00269f22017-07-06 16:59:48 -070052}
53
54var _ ModuleInstallPathContext = ModuleContext(nil)
55
Dan Willemsen34cc69e2015-09-23 15:26:20 -070056// errorfContext is the interface containing the Errorf method matching the
57// Errorf method in blueprint.SingletonContext.
58type errorfContext interface {
59 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080060}
61
Dan Willemsen34cc69e2015-09-23 15:26:20 -070062var _ errorfContext = blueprint.SingletonContext(nil)
63
64// moduleErrorf is the interface containing the ModuleErrorf method matching
65// the ModuleErrorf method in blueprint.ModuleContext.
66type moduleErrorf interface {
67 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080068}
69
Dan Willemsen34cc69e2015-09-23 15:26:20 -070070var _ moduleErrorf = blueprint.ModuleContext(nil)
71
Dan Willemsen34cc69e2015-09-23 15:26:20 -070072// reportPathError will register an error with the attached context. It
73// attempts ctx.ModuleErrorf for a better error message first, then falls
74// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -080075func reportPathError(ctx PathContext, err error) {
76 reportPathErrorf(ctx, "%s", err.Error())
77}
78
79// reportPathErrorf will register an error with the attached context. It
80// attempts ctx.ModuleErrorf for a better error message first, then falls
81// back to ctx.Errorf.
82func reportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -070083 if mctx, ok := ctx.(moduleErrorf); ok {
84 mctx.ModuleErrorf(format, args...)
85 } else if ectx, ok := ctx.(errorfContext); ok {
86 ectx.Errorf(format, args...)
87 } else {
88 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -070089 }
90}
91
Dan Willemsen34cc69e2015-09-23 15:26:20 -070092type Path interface {
93 // Returns the path in string form
94 String() string
95
Colin Cross4f6fc9c2016-10-26 10:05:25 -070096 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -070097 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -070098
99 // Base returns the last element of the path
100 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800101
102 // Rel returns the portion of the path relative to the directory it was created from. For
103 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800104 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800105 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700106}
107
108// WritablePath is a type of path that can be used as an output for build rules.
109type WritablePath interface {
110 Path
111
Jeff Gaston734e3802017-04-10 15:47:24 -0700112 // the writablePath method doesn't directly do anything,
113 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700114 writablePath()
115}
116
117type genPathProvider interface {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700118 genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700119}
120type objPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700121 objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700122}
123type resPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700124 resPathWithName(ctx ModuleContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700125}
126
127// GenPathWithExt derives a new file path in ctx's generated sources directory
128// from the current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700129func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700130 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700131 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700132 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800133 reportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700134 return PathForModuleGen(ctx)
135}
136
137// ObjPathWithExt derives a new file path in ctx's object directory from the
138// current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700139func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700140 if path, ok := p.(objPathProvider); ok {
141 return path.objPathWithExt(ctx, subdir, ext)
142 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800143 reportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700144 return PathForModuleObj(ctx)
145}
146
147// ResPathWithName derives a new path in ctx's output resource directory, using
148// the current path to create the directory name, and the `name` argument for
149// the filename.
Colin Cross635c3b02016-05-18 15:37:25 -0700150func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700151 if path, ok := p.(resPathProvider); ok {
152 return path.resPathWithName(ctx, name)
153 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800154 reportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700155 return PathForModuleRes(ctx)
156}
157
158// OptionalPath is a container that may or may not contain a valid Path.
159type OptionalPath struct {
160 valid bool
161 path Path
162}
163
164// OptionalPathForPath returns an OptionalPath containing the path.
165func OptionalPathForPath(path Path) OptionalPath {
166 if path == nil {
167 return OptionalPath{}
168 }
169 return OptionalPath{valid: true, path: path}
170}
171
172// Valid returns whether there is a valid path
173func (p OptionalPath) Valid() bool {
174 return p.valid
175}
176
177// Path returns the Path embedded in this OptionalPath. You must be sure that
178// there is a valid path, since this method will panic if there is not.
179func (p OptionalPath) Path() Path {
180 if !p.valid {
181 panic("Requesting an invalid path")
182 }
183 return p.path
184}
185
186// String returns the string version of the Path, or "" if it isn't valid.
187func (p OptionalPath) String() string {
188 if p.valid {
189 return p.path.String()
190 } else {
191 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700192 }
193}
Colin Cross6e18ca42015-07-14 18:55:36 -0700194
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700195// Paths is a slice of Path objects, with helpers to operate on the collection.
196type Paths []Path
197
198// PathsForSource returns Paths rooted from SrcDir
199func PathsForSource(ctx PathContext, paths []string) Paths {
200 ret := make(Paths, len(paths))
201 for i, path := range paths {
202 ret[i] = PathForSource(ctx, path)
203 }
204 return ret
205}
206
Jeff Gaston734e3802017-04-10 15:47:24 -0700207// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800208// found in the tree. If any are not found, they are omitted from the list,
209// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800210func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800211 ret := make(Paths, 0, len(paths))
212 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800213 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800214 if p.Valid() {
215 ret = append(ret, p.Path())
216 }
217 }
218 return ret
219}
220
Colin Crossc6de83c2019-03-18 12:12:48 -0700221// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs and references
222// to SourceFileProducer modules using the ":name" syntax. Properties passed as the paths argument must have been
223// annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules will have already
224// been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is true, then any missing
225// SourceFileProducer dependencies will cause the module to be marked as having missing dependencies.
Colin Cross635c3b02016-05-18 15:37:25 -0700226func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800227 return PathsForModuleSrcExcludes(ctx, paths, nil)
228}
229
Colin Crossc6de83c2019-03-18 12:12:48 -0700230// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
231// the excludes arguments. It expands globs and references to SourceFileProducer modules in both paths and excludes
232// using the ":name" syntax. Properties passed as the paths or excludes argument must have been annotated with struct
233// tag `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
234// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true, then any missing SourceFileProducer
235// dependencies will cause the module to be marked as having missing dependencies.
Colin Cross8a497952019-03-05 22:25:09 -0800236func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
Colin Crossc6de83c2019-03-18 12:12:48 -0700237 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
238 if ctx.Config().AllowMissingDependencies() {
239 ctx.AddMissingDependencies(missingDeps)
240 } else {
241 for _, m := range missingDeps {
242 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
243 }
244 }
245 return ret
246}
247
248// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
249// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs and references to
250// SourceFileProducer modules in both paths and excludes using the ":name" syntax. Properties passed as the paths or
251// excludes argument must have been annotated with struct tag `android:"path"` so that dependencies on
252// SourceFileProducer modules will have already been handled by the path_properties mutator. If
253// ctx.Config().AllowMissingDependencies() is true, then any missing SourceFileProducer dependencies will be returned,
254// and they will NOT cause the module to be marked as having missing dependencies.
255func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800256 prefix := pathForModuleSrc(ctx).String()
257
258 var expandedExcludes []string
259 if excludes != nil {
260 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700261 }
Colin Cross8a497952019-03-05 22:25:09 -0800262
Colin Crossc6de83c2019-03-18 12:12:48 -0700263 var missingExcludeDeps []string
264
Colin Cross8a497952019-03-05 22:25:09 -0800265 for _, e := range excludes {
266 if m := SrcIsModule(e); m != "" {
267 module := ctx.GetDirectDepWithTag(m, SourceDepTag)
268 if module == nil {
Colin Crossc6de83c2019-03-18 12:12:48 -0700269 missingExcludeDeps = append(missingExcludeDeps, m)
Colin Cross8a497952019-03-05 22:25:09 -0800270 continue
271 }
272 if srcProducer, ok := module.(SourceFileProducer); ok {
273 expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
274 } else {
275 ctx.ModuleErrorf("srcs dependency %q is not a source file producing module", m)
276 }
277 } else {
278 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
279 }
280 }
281
282 if paths == nil {
Colin Crossc6de83c2019-03-18 12:12:48 -0700283 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800284 }
285
Colin Crossc6de83c2019-03-18 12:12:48 -0700286 var missingDeps []string
287
Colin Cross8a497952019-03-05 22:25:09 -0800288 expandedSrcFiles := make(Paths, 0, len(paths))
289 for _, s := range paths {
290 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
291 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossc6de83c2019-03-18 12:12:48 -0700292 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800293 } else if err != nil {
294 reportPathError(ctx, err)
295 }
296 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
297 }
Colin Crossc6de83c2019-03-18 12:12:48 -0700298
299 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800300}
301
302type missingDependencyError struct {
303 missingDeps []string
304}
305
306func (e missingDependencyError) Error() string {
307 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
308}
309
310func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
311 if m := SrcIsModule(s); m != "" {
312 module := ctx.GetDirectDepWithTag(m, SourceDepTag)
313 if module == nil {
314 return nil, missingDependencyError{[]string{m}}
315 }
316 if srcProducer, ok := module.(SourceFileProducer); ok {
317 moduleSrcs := srcProducer.Srcs()
318 for _, e := range expandedExcludes {
319 for j := 0; j < len(moduleSrcs); j++ {
320 if moduleSrcs[j].String() == e {
321 moduleSrcs = append(moduleSrcs[:j], moduleSrcs[j+1:]...)
322 j--
323 }
324 }
325 }
326 return moduleSrcs, nil
327 } else {
328 return nil, fmt.Errorf("path dependency %q is not a source file producing module", m)
329 }
330 } else if pathtools.IsGlob(s) {
331 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
332 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
333 } else {
334 p := pathForModuleSrc(ctx, s)
335 if exists, _, err := ctx.Fs().Exists(p.String()); err != nil {
336 reportPathErrorf(ctx, "%s: %s", p, err.Error())
337 } else if !exists {
338 reportPathErrorf(ctx, "module source path %q does not exist", p)
339 }
340
341 j := findStringInSlice(p.String(), expandedExcludes)
342 if j >= 0 {
343 return nil, nil
344 }
345 return Paths{p}, nil
346 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700347}
348
349// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
350// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800351// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700352// It intended for use in globs that only list files that exist, so it allows '$' in
353// filenames.
Dan Willemsen540a78c2018-02-26 21:50:08 -0800354func pathsForModuleSrcFromFullPath(ctx ModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800355 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700356 if prefix == "./" {
357 prefix = ""
358 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700359 ret := make(Paths, 0, len(paths))
360 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800361 if !incDirs && strings.HasSuffix(p, "/") {
362 continue
363 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700364 path := filepath.Clean(p)
Colin Crosse3924e12018-08-15 20:18:53 -0700365
Colin Crossfe4bc362018-09-12 10:02:13 -0700366 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700367 if err != nil {
368 reportPathError(ctx, err)
369 continue
370 }
371
Colin Cross07e51612019-03-05 12:46:40 -0800372 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700373
Colin Cross07e51612019-03-05 12:46:40 -0800374 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700375 }
376 return ret
377}
378
379// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800380// local source directory. If input is nil, use the default if it exists. If input is empty, returns nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700381func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800382 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700383 return PathsForModuleSrc(ctx, input)
384 }
385 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
386 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800387 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800388 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700389}
390
391// Strings returns the Paths in string form
392func (p Paths) Strings() []string {
393 if p == nil {
394 return nil
395 }
396 ret := make([]string, len(p))
397 for i, path := range p {
398 ret[i] = path.String()
399 }
400 return ret
401}
402
Colin Crossb6715442017-10-24 11:13:31 -0700403// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
404// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700405func FirstUniquePaths(list Paths) Paths {
406 k := 0
407outer:
408 for i := 0; i < len(list); i++ {
409 for j := 0; j < k; j++ {
410 if list[i] == list[j] {
411 continue outer
412 }
413 }
414 list[k] = list[i]
415 k++
416 }
417 return list[:k]
418}
419
Colin Crossb6715442017-10-24 11:13:31 -0700420// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
421// modifies the Paths slice contents in place, and returns a subslice of the original slice.
422func LastUniquePaths(list Paths) Paths {
423 totalSkip := 0
424 for i := len(list) - 1; i >= totalSkip; i-- {
425 skip := 0
426 for j := i - 1; j >= totalSkip; j-- {
427 if list[i] == list[j] {
428 skip++
429 } else {
430 list[j+skip] = list[j]
431 }
432 }
433 totalSkip += skip
434 }
435 return list[totalSkip:]
436}
437
Colin Crossa140bb02018-04-17 10:52:26 -0700438// ReversePaths returns a copy of a Paths in reverse order.
439func ReversePaths(list Paths) Paths {
440 if list == nil {
441 return nil
442 }
443 ret := make(Paths, len(list))
444 for i := range list {
445 ret[i] = list[len(list)-1-i]
446 }
447 return ret
448}
449
Jeff Gaston294356f2017-09-27 17:05:30 -0700450func indexPathList(s Path, list []Path) int {
451 for i, l := range list {
452 if l == s {
453 return i
454 }
455 }
456
457 return -1
458}
459
460func inPathList(p Path, list []Path) bool {
461 return indexPathList(p, list) != -1
462}
463
464func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
465 for _, l := range list {
466 if inPathList(l, filter) {
467 filtered = append(filtered, l)
468 } else {
469 remainder = append(remainder, l)
470 }
471 }
472
473 return
474}
475
Colin Cross93e85952017-08-15 13:34:18 -0700476// HasExt returns true of any of the paths have extension ext, otherwise false
477func (p Paths) HasExt(ext string) bool {
478 for _, path := range p {
479 if path.Ext() == ext {
480 return true
481 }
482 }
483
484 return false
485}
486
487// FilterByExt returns the subset of the paths that have extension ext
488func (p Paths) FilterByExt(ext string) Paths {
489 ret := make(Paths, 0, len(p))
490 for _, path := range p {
491 if path.Ext() == ext {
492 ret = append(ret, path)
493 }
494 }
495 return ret
496}
497
498// FilterOutByExt returns the subset of the paths that do not have extension ext
499func (p Paths) FilterOutByExt(ext string) Paths {
500 ret := make(Paths, 0, len(p))
501 for _, path := range p {
502 if path.Ext() != ext {
503 ret = append(ret, path)
504 }
505 }
506 return ret
507}
508
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700509// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
510// (including subdirectories) are in a contiguous subslice of the list, and can be found in
511// O(log(N)) time using a binary search on the directory prefix.
512type DirectorySortedPaths Paths
513
514func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
515 ret := append(DirectorySortedPaths(nil), paths...)
516 sort.Slice(ret, func(i, j int) bool {
517 return ret[i].String() < ret[j].String()
518 })
519 return ret
520}
521
522// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
523// that are in the specified directory and its subdirectories.
524func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
525 prefix := filepath.Clean(dir) + "/"
526 start := sort.Search(len(p), func(i int) bool {
527 return prefix < p[i].String()
528 })
529
530 ret := p[start:]
531
532 end := sort.Search(len(ret), func(i int) bool {
533 return !strings.HasPrefix(ret[i].String(), prefix)
534 })
535
536 ret = ret[:end]
537
538 return Paths(ret)
539}
540
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700541// WritablePaths is a slice of WritablePaths, used for multiple outputs.
542type WritablePaths []WritablePath
543
544// Strings returns the string forms of the writable paths.
545func (p WritablePaths) Strings() []string {
546 if p == nil {
547 return nil
548 }
549 ret := make([]string, len(p))
550 for i, path := range p {
551 ret[i] = path.String()
552 }
553 return ret
554}
555
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800556// Paths returns the WritablePaths as a Paths
557func (p WritablePaths) Paths() Paths {
558 if p == nil {
559 return nil
560 }
561 ret := make(Paths, len(p))
562 for i, path := range p {
563 ret[i] = path
564 }
565 return ret
566}
567
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700568type basePath struct {
569 path string
570 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800571 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700572}
573
574func (p basePath) Ext() string {
575 return filepath.Ext(p.path)
576}
577
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700578func (p basePath) Base() string {
579 return filepath.Base(p.path)
580}
581
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800582func (p basePath) Rel() string {
583 if p.rel != "" {
584 return p.rel
585 }
586 return p.path
587}
588
Colin Cross0875c522017-11-28 17:34:01 -0800589func (p basePath) String() string {
590 return p.path
591}
592
Colin Cross0db55682017-12-05 15:36:55 -0800593func (p basePath) withRel(rel string) basePath {
594 p.path = filepath.Join(p.path, rel)
595 p.rel = rel
596 return p
597}
598
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700599// SourcePath is a Path representing a file path rooted from SrcDir
600type SourcePath struct {
601 basePath
602}
603
604var _ Path = SourcePath{}
605
Colin Cross0db55682017-12-05 15:36:55 -0800606func (p SourcePath) withRel(rel string) SourcePath {
607 p.basePath = p.basePath.withRel(rel)
608 return p
609}
610
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700611// safePathForSource is for paths that we expect are safe -- only for use by go
612// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700613func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
614 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800615 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700616 if err != nil {
617 return ret, err
618 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700619
Colin Cross7b3dcc32019-01-24 13:14:39 -0800620 // absolute path already checked by validateSafePath
621 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800622 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700623 }
624
Colin Crossfe4bc362018-09-12 10:02:13 -0700625 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700626}
627
Colin Cross192e97a2018-02-22 14:21:02 -0800628// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
629func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000630 p, err := validatePath(pathComponents...)
631 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800632 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800633 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800634 }
635
Colin Cross7b3dcc32019-01-24 13:14:39 -0800636 // absolute path already checked by validatePath
637 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800638 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000639 }
640
Colin Cross192e97a2018-02-22 14:21:02 -0800641 return ret, nil
642}
643
Sam Mortimer508a57b2019-09-05 15:16:13 -0700644// pathForSourceRelaxed creates a SourcePath from pathComponents, but does not check that it exists.
645// It differs from pathForSource in that the path is allowed to exist outside of the PathContext.
646func pathForSourceRelaxed(ctx PathContext, pathComponents ...string) (SourcePath, error) {
647 p := filepath.Join(pathComponents...)
648 ret := SourcePath{basePath{p, ctx.Config(), ""}}
649
650 abs, err := filepath.Abs(ret.String())
651 if err != nil {
652 return ret, err
653 }
654 buildroot, err := filepath.Abs(ctx.Config().buildDir)
655 if err != nil {
656 return ret, err
657 }
658 if strings.HasPrefix(abs, buildroot) {
659 return ret, fmt.Errorf("source path %s is in output", abs)
660 }
661
662 if pathtools.IsGlob(ret.String()) {
663 return ret, fmt.Errorf("path may not contain a glob: %s", ret.String())
664 }
665
666 return ret, nil
667}
668
Colin Cross192e97a2018-02-22 14:21:02 -0800669// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
670// path does not exist.
671func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
672 var files []string
673
674 if gctx, ok := ctx.(PathGlobContext); ok {
675 // Use glob to produce proper dependencies, even though we only want
676 // a single file.
677 files, err = gctx.GlobWithDeps(path.String(), nil)
678 } else {
679 var deps []string
680 // We cannot add build statements in this context, so we fall back to
681 // AddNinjaFileDeps
Colin Cross3f4d1162018-09-21 15:11:48 -0700682 files, deps, err = pathtools.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800683 ctx.AddNinjaFileDeps(deps...)
684 }
685
686 if err != nil {
687 return false, fmt.Errorf("glob: %s", err.Error())
688 }
689
690 return len(files) > 0, nil
691}
692
693// PathForSource joins the provided path components and validates that the result
694// neither escapes the source dir nor is in the out dir.
695// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
696func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
697 path, err := pathForSource(ctx, pathComponents...)
698 if err != nil {
699 reportPathError(ctx, err)
700 }
701
Colin Crosse3924e12018-08-15 20:18:53 -0700702 if pathtools.IsGlob(path.String()) {
703 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
704 }
705
Colin Cross192e97a2018-02-22 14:21:02 -0800706 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
707 exists, err := existsWithDependencies(ctx, path)
708 if err != nil {
709 reportPathError(ctx, err)
710 }
711 if !exists {
712 modCtx.AddMissingDependencies([]string{path.String()})
713 }
714 } else if exists, _, err := ctx.Fs().Exists(path.String()); err != nil {
715 reportPathErrorf(ctx, "%s: %s", path, err.Error())
716 } else if !exists {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800717 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800718 }
719 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700720}
721
Sam Mortimer508a57b2019-09-05 15:16:13 -0700722// PathForSourceRelaxed joins the provided path components. Unlike PathForSource,
723// the result is allowed to exist outside of the source dir.
724// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
725func PathForSourceRelaxed(ctx PathContext, pathComponents ...string) SourcePath {
726 path, err := pathForSourceRelaxed(ctx, pathComponents...)
727 if err != nil {
728 reportPathError(ctx, err)
729 }
730
731 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
732 exists, err := existsWithDependencies(ctx, path)
733 if err != nil {
734 reportPathError(ctx, err)
735 }
736 if !exists {
737 modCtx.AddMissingDependencies([]string{path.String()})
738 }
739 } else if exists, _, err := ctx.Fs().Exists(path.String()); err != nil {
740 reportPathErrorf(ctx, "%s: %s", path, err.Error())
741 } else if !exists {
742 reportPathErrorf(ctx, "source path %s does not exist", path)
743 }
744 return path
745}
746
Jeff Gaston734e3802017-04-10 15:47:24 -0700747// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700748// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
749// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800750func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800751 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800752 if err != nil {
753 reportPathError(ctx, err)
754 return OptionalPath{}
755 }
Colin Crossc48c1432018-02-23 07:09:01 +0000756
Colin Crosse3924e12018-08-15 20:18:53 -0700757 if pathtools.IsGlob(path.String()) {
758 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
759 return OptionalPath{}
760 }
761
Colin Cross192e97a2018-02-22 14:21:02 -0800762 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000763 if err != nil {
764 reportPathError(ctx, err)
765 return OptionalPath{}
766 }
Colin Cross192e97a2018-02-22 14:21:02 -0800767 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000768 return OptionalPath{}
769 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700770 return OptionalPathForPath(path)
771}
772
773func (p SourcePath) String() string {
774 return filepath.Join(p.config.srcDir, p.path)
775}
776
777// Join creates a new SourcePath with paths... joined with the current path. The
778// provided paths... may not use '..' to escape from the current path.
779func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800780 path, err := validatePath(paths...)
781 if err != nil {
782 reportPathError(ctx, err)
783 }
Colin Cross0db55682017-12-05 15:36:55 -0800784 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700785}
786
Colin Cross2fafa3e2019-03-05 12:39:51 -0800787// join is like Join but does less path validation.
788func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
789 path, err := validateSafePath(paths...)
790 if err != nil {
791 reportPathError(ctx, err)
792 }
793 return p.withRel(path)
794}
795
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700796// OverlayPath returns the overlay for `path' if it exists. This assumes that the
797// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700798func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700799 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800800 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700801 relDir = srcPath.path
802 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800803 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700804 return OptionalPath{}
805 }
806 dir := filepath.Join(p.config.srcDir, p.path, relDir)
807 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700808 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800809 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800810 }
Colin Cross461b4452018-02-23 09:22:42 -0800811 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700812 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800813 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700814 return OptionalPath{}
815 }
816 if len(paths) == 0 {
817 return OptionalPath{}
818 }
Colin Cross43f08db2018-11-12 10:13:39 -0800819 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700820 return OptionalPathForPath(PathForSource(ctx, relPath))
821}
822
823// OutputPath is a Path representing a file path rooted from the build directory
824type OutputPath struct {
825 basePath
826}
827
Colin Cross702e0f82017-10-18 17:27:54 -0700828func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800829 p.basePath = p.basePath.withRel(rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700830 return p
831}
832
Colin Cross3063b782018-08-15 11:19:12 -0700833func (p OutputPath) WithoutRel() OutputPath {
834 p.basePath.rel = filepath.Base(p.basePath.path)
835 return p
836}
837
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700838var _ Path = OutputPath{}
839
Jeff Gaston734e3802017-04-10 15:47:24 -0700840// PathForOutput joins the provided paths and returns an OutputPath that is
841// validated to not escape the build dir.
842// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
843func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800844 path, err := validatePath(pathComponents...)
845 if err != nil {
846 reportPathError(ctx, err)
847 }
Colin Crossaabf6792017-11-29 00:27:14 -0800848 return OutputPath{basePath{path, ctx.Config(), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700849}
850
Colin Cross40e33732019-02-15 11:08:35 -0800851// PathsForOutput returns Paths rooted from buildDir
852func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
853 ret := make(WritablePaths, len(paths))
854 for i, path := range paths {
855 ret[i] = PathForOutput(ctx, path)
856 }
857 return ret
858}
859
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700860func (p OutputPath) writablePath() {}
861
862func (p OutputPath) String() string {
863 return filepath.Join(p.config.buildDir, p.path)
864}
865
Colin Crossa2344662016-03-24 13:14:12 -0700866func (p OutputPath) RelPathString() string {
867 return p.path
868}
869
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700870// Join creates a new OutputPath with paths... joined with the current path. The
871// provided paths... may not use '..' to escape from the current path.
872func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800873 path, err := validatePath(paths...)
874 if err != nil {
875 reportPathError(ctx, err)
876 }
Colin Cross0db55682017-12-05 15:36:55 -0800877 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700878}
879
Colin Cross8854a5a2019-02-11 14:14:16 -0800880// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
881func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
882 if strings.Contains(ext, "/") {
883 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
884 }
885 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800886 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800887 return ret
888}
889
Colin Cross40e33732019-02-15 11:08:35 -0800890// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
891func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
892 path, err := validatePath(paths...)
893 if err != nil {
894 reportPathError(ctx, err)
895 }
896
897 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800898 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800899 return ret
900}
901
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700902// PathForIntermediates returns an OutputPath representing the top-level
903// intermediates directory.
904func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800905 path, err := validatePath(paths...)
906 if err != nil {
907 reportPathError(ctx, err)
908 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700909 return PathForOutput(ctx, ".intermediates", path)
910}
911
Colin Cross07e51612019-03-05 12:46:40 -0800912var _ genPathProvider = SourcePath{}
913var _ objPathProvider = SourcePath{}
914var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700915
Colin Cross07e51612019-03-05 12:46:40 -0800916// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700917// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800918func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
919 p, err := validatePath(pathComponents...)
920 if err != nil {
921 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800922 }
Colin Cross8a497952019-03-05 22:25:09 -0800923 paths, err := expandOneSrcPath(ctx, p, nil)
924 if err != nil {
925 if depErr, ok := err.(missingDependencyError); ok {
926 if ctx.Config().AllowMissingDependencies() {
927 ctx.AddMissingDependencies(depErr.missingDeps)
928 } else {
929 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
930 }
931 } else {
932 reportPathError(ctx, err)
933 }
934 return nil
935 } else if len(paths) == 0 {
936 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
937 return nil
938 } else if len(paths) > 1 {
939 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
940 }
941 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700942}
943
Colin Cross07e51612019-03-05 12:46:40 -0800944func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
945 p, err := validatePath(paths...)
946 if err != nil {
947 reportPathError(ctx, err)
948 }
949
950 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
951 if err != nil {
952 reportPathError(ctx, err)
953 }
954
955 path.basePath.rel = p
956
957 return path
958}
959
Colin Cross2fafa3e2019-03-05 12:39:51 -0800960// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
961// will return the path relative to subDir in the module's source directory. If any input paths are not located
962// inside subDir then a path error will be reported.
963func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
964 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -0800965 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800966 for i, path := range paths {
967 rel := Rel(ctx, subDirFullPath.String(), path.String())
968 paths[i] = subDirFullPath.join(ctx, rel)
969 }
970 return paths
971}
972
973// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
974// module's source directory. If the input path is not located inside subDir then a path error will be reported.
975func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -0800976 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800977 rel := Rel(ctx, subDirFullPath.String(), path.String())
978 return subDirFullPath.Join(ctx, rel)
979}
980
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700981// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
982// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700983func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700984 if p == nil {
985 return OptionalPath{}
986 }
987 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
988}
989
Colin Cross07e51612019-03-05 12:46:40 -0800990func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800991 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700992}
993
Colin Cross07e51612019-03-05 12:46:40 -0800994func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800995 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700996}
997
Colin Cross07e51612019-03-05 12:46:40 -0800998func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700999 // TODO: Use full directory if the new ctx is not the current ctx?
1000 return PathForModuleRes(ctx, p.path, name)
1001}
1002
1003// ModuleOutPath is a Path representing a module's output directory.
1004type ModuleOutPath struct {
1005 OutputPath
1006}
1007
1008var _ Path = ModuleOutPath{}
1009
Colin Cross702e0f82017-10-18 17:27:54 -07001010func pathForModule(ctx ModuleContext) OutputPath {
1011 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1012}
1013
Logan Chien7eefdc42018-07-11 18:10:41 +08001014// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1015// reference abi dump for the given module. This is not guaranteed to be valid.
1016func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
1017 isLlndk, isGzip bool) OptionalPath {
1018
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001019 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001020 if len(arches) == 0 {
1021 panic("device build with no primary arch")
1022 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001023 currentArch := ctx.Arch()
1024 archNameAndVariant := currentArch.ArchType.String()
1025 if currentArch.ArchVariant != "" {
1026 archNameAndVariant += "_" + currentArch.ArchVariant
1027 }
Logan Chien5237bed2018-07-11 17:15:57 +08001028
1029 var dirName string
1030 if isLlndk {
1031 dirName = "ndk"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001032 } else {
Logan Chien5237bed2018-07-11 17:15:57 +08001033 dirName = "vndk"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001034 }
Logan Chien5237bed2018-07-11 17:15:57 +08001035
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001036 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001037
1038 var ext string
1039 if isGzip {
1040 ext = ".lsdump.gz"
1041 } else {
1042 ext = ".lsdump"
1043 }
1044
1045 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1046 version, binderBitness, archNameAndVariant, "source-based",
1047 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001048}
1049
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001050// PathForModuleOut returns a Path representing the paths... under the module's
1051// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001052func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001053 p, err := validatePath(paths...)
1054 if err != nil {
1055 reportPathError(ctx, err)
1056 }
Colin Cross702e0f82017-10-18 17:27:54 -07001057 return ModuleOutPath{
1058 OutputPath: pathForModule(ctx).withRel(p),
1059 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001060}
1061
1062// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1063// directory. Mainly used for generated sources.
1064type ModuleGenPath struct {
1065 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001066}
1067
1068var _ Path = ModuleGenPath{}
1069var _ genPathProvider = ModuleGenPath{}
1070var _ objPathProvider = ModuleGenPath{}
1071
1072// PathForModuleGen returns a Path representing the paths... under the module's
1073// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001074func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001075 p, err := validatePath(paths...)
1076 if err != nil {
1077 reportPathError(ctx, err)
1078 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001079 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001080 ModuleOutPath: ModuleOutPath{
1081 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1082 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001083 }
1084}
1085
Dan Willemsen21ec4902016-11-02 20:43:13 -07001086func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001087 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001088 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001089}
1090
Colin Cross635c3b02016-05-18 15:37:25 -07001091func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001092 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1093}
1094
1095// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1096// directory. Used for compiled objects.
1097type ModuleObjPath struct {
1098 ModuleOutPath
1099}
1100
1101var _ Path = ModuleObjPath{}
1102
1103// PathForModuleObj returns a Path representing the paths... under the module's
1104// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001105func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001106 p, err := validatePath(pathComponents...)
1107 if err != nil {
1108 reportPathError(ctx, err)
1109 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001110 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1111}
1112
1113// ModuleResPath is a a Path representing the 'res' directory in a module's
1114// output directory.
1115type ModuleResPath struct {
1116 ModuleOutPath
1117}
1118
1119var _ Path = ModuleResPath{}
1120
1121// PathForModuleRes returns a Path representing the paths... under the module's
1122// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001123func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001124 p, err := validatePath(pathComponents...)
1125 if err != nil {
1126 reportPathError(ctx, err)
1127 }
1128
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001129 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1130}
1131
1132// PathForModuleInstall returns a Path representing the install path for the
1133// module appended with paths...
Dan Willemsen00269f22017-07-06 16:59:48 -07001134func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) OutputPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001135 var outPaths []string
1136 if ctx.Device() {
Colin Cross43f08db2018-11-12 10:13:39 -08001137 partition := modulePartition(ctx)
Colin Cross6510f912017-11-29 00:27:14 -08001138 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001139 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -07001140 switch ctx.Os() {
1141 case Linux:
1142 outPaths = []string{"host", "linux-x86"}
1143 case LinuxBionic:
1144 // TODO: should this be a separate top level, or shared with linux-x86?
1145 outPaths = []string{"host", "linux_bionic-x86"}
1146 default:
1147 outPaths = []string{"host", ctx.Os().String() + "-x86"}
1148 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001149 }
Dan Willemsen782a2d12015-12-21 14:55:28 -08001150 if ctx.Debug() {
1151 outPaths = append([]string{"debug"}, outPaths...)
1152 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001153 outPaths = append(outPaths, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001154 return PathForOutput(ctx, outPaths...)
1155}
1156
Colin Cross43f08db2018-11-12 10:13:39 -08001157func InstallPathToOnDevicePath(ctx PathContext, path OutputPath) string {
1158 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1159
1160 return "/" + rel
1161}
1162
1163func modulePartition(ctx ModuleInstallPathContext) string {
1164 var partition string
1165 if ctx.InstallInData() {
1166 partition = "data"
Jaewoong Jung1ffd7932019-09-11 10:25:18 -07001167 } else if ctx.InstallInTestcases() {
1168 partition = "testcases"
Colin Cross43f08db2018-11-12 10:13:39 -08001169 } else if ctx.InstallInRecovery() {
1170 // the layout of recovery partion is the same as that of system partition
1171 partition = "recovery/root/system"
1172 } else if ctx.SocSpecific() {
1173 partition = ctx.DeviceConfig().VendorPath()
1174 } else if ctx.DeviceSpecific() {
1175 partition = ctx.DeviceConfig().OdmPath()
1176 } else if ctx.ProductSpecific() {
1177 partition = ctx.DeviceConfig().ProductPath()
1178 } else if ctx.ProductServicesSpecific() {
1179 partition = ctx.DeviceConfig().ProductServicesPath()
1180 } else {
1181 partition = "system"
1182 }
1183 if ctx.InstallInSanitizerDir() {
1184 partition = "data/asan/" + partition
1185 }
1186 return partition
1187}
1188
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001189// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001190// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001191func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001192 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001193 path := filepath.Clean(path)
Surge12235c0e5ac2020-02-04 07:25:20 +00001194 if strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001195 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001196 }
1197 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001198 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1199 // variables. '..' may remove the entire ninja variable, even if it
1200 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001201 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001202}
1203
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001204// validatePath validates that a path does not include ninja variables, and that
1205// each path component does not attempt to leave its component. Returns a joined
1206// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001207func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001208 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001209 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001210 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001211 }
1212 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001213 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001214}
Colin Cross5b529592017-05-09 13:34:34 -07001215
Colin Cross0875c522017-11-28 17:34:01 -08001216func PathForPhony(ctx PathContext, phony string) WritablePath {
1217 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001218 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001219 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001220 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001221}
1222
Colin Cross74e3fe42017-12-11 15:51:44 -08001223type PhonyPath struct {
1224 basePath
1225}
1226
1227func (p PhonyPath) writablePath() {}
1228
1229var _ Path = PhonyPath{}
1230var _ WritablePath = PhonyPath{}
1231
Colin Cross5b529592017-05-09 13:34:34 -07001232type testPath struct {
1233 basePath
1234}
1235
1236func (p testPath) String() string {
1237 return p.path
1238}
1239
Colin Cross40e33732019-02-15 11:08:35 -08001240type testWritablePath struct {
1241 testPath
1242}
1243
1244func (p testPath) writablePath() {}
1245
1246// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1247// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001248func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001249 p, err := validateSafePath(paths...)
1250 if err != nil {
1251 panic(err)
1252 }
Colin Cross5b529592017-05-09 13:34:34 -07001253 return testPath{basePath{path: p, rel: p}}
1254}
1255
Colin Cross40e33732019-02-15 11:08:35 -08001256// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1257func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001258 p := make(Paths, len(strs))
1259 for i, s := range strs {
1260 p[i] = PathForTesting(s)
1261 }
1262
1263 return p
1264}
Colin Cross43f08db2018-11-12 10:13:39 -08001265
Colin Cross40e33732019-02-15 11:08:35 -08001266// WritablePathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be
1267// used from within tests.
1268func WritablePathForTesting(paths ...string) WritablePath {
1269 p, err := validateSafePath(paths...)
1270 if err != nil {
1271 panic(err)
1272 }
1273 return testWritablePath{testPath{basePath{path: p, rel: p}}}
1274}
1275
1276// WritablePathsForTesting returns a Path constructed from each element in strs. It should only be used from within
1277// tests.
1278func WritablePathsForTesting(strs ...string) WritablePaths {
1279 p := make(WritablePaths, len(strs))
1280 for i, s := range strs {
1281 p[i] = WritablePathForTesting(s)
1282 }
1283
1284 return p
1285}
1286
1287type testPathContext struct {
1288 config Config
1289 fs pathtools.FileSystem
1290}
1291
1292func (x *testPathContext) Fs() pathtools.FileSystem { return x.fs }
1293func (x *testPathContext) Config() Config { return x.config }
1294func (x *testPathContext) AddNinjaFileDeps(...string) {}
1295
1296// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1297// PathForOutput.
1298func PathContextForTesting(config Config, fs map[string][]byte) PathContext {
1299 return &testPathContext{
1300 config: config,
1301 fs: pathtools.MockFs(fs),
1302 }
1303}
1304
Colin Cross43f08db2018-11-12 10:13:39 -08001305// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1306// targetPath is not inside basePath.
1307func Rel(ctx PathContext, basePath string, targetPath string) string {
1308 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1309 if !isRel {
1310 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1311 return ""
1312 }
1313 return rel
1314}
1315
1316// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1317// targetPath is not inside basePath.
1318func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen0ce5d052019-04-12 11:11:38 -07001319 rel, isRel, err := maybeRelErr(basePath, targetPath)
1320 if err != nil {
1321 reportPathError(ctx, err)
1322 }
1323 return rel, isRel
1324}
1325
1326func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001327 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1328 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen0ce5d052019-04-12 11:11:38 -07001329 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001330 }
1331 rel, err := filepath.Rel(basePath, targetPath)
1332 if err != nil {
Dan Willemsen0ce5d052019-04-12 11:11:38 -07001333 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001334 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen0ce5d052019-04-12 11:11:38 -07001335 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001336 }
Dan Willemsen0ce5d052019-04-12 11:11:38 -07001337 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001338}