blob: 4adaa2d835a6a1273eed0faa869831f5c25ae8b5 [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
Dan Willemsen34cc69e2015-09-23 15:26:20 -070032 Config() interface{}
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
Dan Willemsen34cc69e2015-09-23 15:26:20 -070040var _ PathContext = blueprint.SingletonContext(nil)
41var _ PathContext = blueprint.ModuleContext(nil)
42
Dan Willemsen00269f22017-07-06 16:59:48 -070043type ModuleInstallPathContext interface {
44 PathContext
45
46 androidBaseContext
47
48 InstallInData() bool
49 InstallInSanitizerDir() bool
50}
51
52var _ ModuleInstallPathContext = ModuleContext(nil)
53
Dan Willemsen34cc69e2015-09-23 15:26:20 -070054// errorfContext is the interface containing the Errorf method matching the
55// Errorf method in blueprint.SingletonContext.
56type errorfContext interface {
57 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080058}
59
Dan Willemsen34cc69e2015-09-23 15:26:20 -070060var _ errorfContext = blueprint.SingletonContext(nil)
61
62// moduleErrorf is the interface containing the ModuleErrorf method matching
63// the ModuleErrorf method in blueprint.ModuleContext.
64type moduleErrorf interface {
65 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080066}
67
Dan Willemsen34cc69e2015-09-23 15:26:20 -070068var _ moduleErrorf = blueprint.ModuleContext(nil)
69
70// pathConfig returns the android Config interface associated to the context.
71// Panics if the context isn't affiliated with an android build.
72func pathConfig(ctx PathContext) Config {
73 if ret, ok := ctx.Config().(Config); ok {
74 return ret
75 }
76 panic("Paths may only be used on Soong builds")
Colin Cross3f40fa42015-01-30 17:27:36 -080077}
78
Dan Willemsen34cc69e2015-09-23 15:26:20 -070079// reportPathError 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 reportPathError(ctx PathContext, format string, args ...interface{}) {
83 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
104 // directory.
105 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 }
133 reportPathError(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
134 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 }
143 reportPathError(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
144 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 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700154 reportPathError(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 {
Dan Willemsene23dfb72016-03-11 15:02:46 -0800200 if pathConfig(ctx).AllowMissingDependencies() {
Colin Cross635c3b02016-05-18 15:37:25 -0700201 if modCtx, ok := ctx.(ModuleContext); ok {
Dan Willemsene23dfb72016-03-11 15:02:46 -0800202 ret := make(Paths, 0, len(paths))
Colin Cross702e0f82017-10-18 17:27:54 -0700203 intermediates := pathForModule(modCtx).withRel("missing")
Dan Willemsene23dfb72016-03-11 15:02:46 -0800204 for _, path := range paths {
Colin Cross702e0f82017-10-18 17:27:54 -0700205 p := ExistentPathForSource(ctx, intermediates.String(), path)
Dan Willemsene23dfb72016-03-11 15:02:46 -0800206 if p.Valid() {
207 ret = append(ret, p.Path())
208 } else {
209 modCtx.AddMissingDependencies([]string{path})
210 }
211 }
212 return ret
213 }
214 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700215 ret := make(Paths, len(paths))
216 for i, path := range paths {
217 ret[i] = PathForSource(ctx, path)
218 }
219 return ret
220}
221
Jeff Gaston734e3802017-04-10 15:47:24 -0700222// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800223// found in the tree. If any are not found, they are omitted from the list,
224// and dependencies are added so that we're re-run when they are added.
Jeff Gaston734e3802017-04-10 15:47:24 -0700225func ExistentPathsForSources(ctx PathContext, intermediates string, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800226 ret := make(Paths, 0, len(paths))
227 for _, path := range paths {
Jeff Gaston734e3802017-04-10 15:47:24 -0700228 p := ExistentPathForSource(ctx, intermediates, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800229 if p.Valid() {
230 ret = append(ret, p.Path())
231 }
232 }
233 return ret
234}
235
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700236// PathsForModuleSrc returns Paths rooted from the module's local source
237// directory
Colin Cross635c3b02016-05-18 15:37:25 -0700238func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700239 ret := make(Paths, len(paths))
240 for i, path := range paths {
241 ret[i] = PathForModuleSrc(ctx, path)
242 }
243 return ret
244}
245
246// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
247// source directory, but strip the local source directory from the beginning of
248// each string.
Colin Cross635c3b02016-05-18 15:37:25 -0700249func pathsForModuleSrcFromFullPath(ctx ModuleContext, paths []string) Paths {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700250 prefix := filepath.Join(ctx.AConfig().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700251 if prefix == "./" {
252 prefix = ""
253 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700254 ret := make(Paths, 0, len(paths))
255 for _, p := range paths {
256 path := filepath.Clean(p)
257 if !strings.HasPrefix(path, prefix) {
258 reportPathError(ctx, "Path '%s' is not in module source directory '%s'", p, prefix)
259 continue
260 }
261 ret = append(ret, PathForModuleSrc(ctx, path[len(prefix):]))
262 }
263 return ret
264}
265
266// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
267// local source directory. If none are provided, use the default if it exists.
Colin Cross635c3b02016-05-18 15:37:25 -0700268func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700269 if len(input) > 0 {
270 return PathsForModuleSrc(ctx, input)
271 }
272 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
273 // is created, we're run again.
274 path := filepath.Join(ctx.AConfig().srcDir, ctx.ModuleDir(), def)
Colin Cross7f19f372016-11-01 11:10:25 -0700275 return ctx.Glob(path, []string{})
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700276}
277
278// Strings returns the Paths in string form
279func (p Paths) Strings() []string {
280 if p == nil {
281 return nil
282 }
283 ret := make([]string, len(p))
284 for i, path := range p {
285 ret[i] = path.String()
286 }
287 return ret
288}
289
Colin Crossb6715442017-10-24 11:13:31 -0700290// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
291// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700292func FirstUniquePaths(list Paths) Paths {
293 k := 0
294outer:
295 for i := 0; i < len(list); i++ {
296 for j := 0; j < k; j++ {
297 if list[i] == list[j] {
298 continue outer
299 }
300 }
301 list[k] = list[i]
302 k++
303 }
304 return list[:k]
305}
306
Colin Crossb6715442017-10-24 11:13:31 -0700307// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
308// modifies the Paths slice contents in place, and returns a subslice of the original slice.
309func LastUniquePaths(list Paths) Paths {
310 totalSkip := 0
311 for i := len(list) - 1; i >= totalSkip; i-- {
312 skip := 0
313 for j := i - 1; j >= totalSkip; j-- {
314 if list[i] == list[j] {
315 skip++
316 } else {
317 list[j+skip] = list[j]
318 }
319 }
320 totalSkip += skip
321 }
322 return list[totalSkip:]
323}
324
Jeff Gaston294356f2017-09-27 17:05:30 -0700325func indexPathList(s Path, list []Path) int {
326 for i, l := range list {
327 if l == s {
328 return i
329 }
330 }
331
332 return -1
333}
334
335func inPathList(p Path, list []Path) bool {
336 return indexPathList(p, list) != -1
337}
338
339func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
340 for _, l := range list {
341 if inPathList(l, filter) {
342 filtered = append(filtered, l)
343 } else {
344 remainder = append(remainder, l)
345 }
346 }
347
348 return
349}
350
Colin Cross93e85952017-08-15 13:34:18 -0700351// HasExt returns true of any of the paths have extension ext, otherwise false
352func (p Paths) HasExt(ext string) bool {
353 for _, path := range p {
354 if path.Ext() == ext {
355 return true
356 }
357 }
358
359 return false
360}
361
362// FilterByExt returns the subset of the paths that have extension ext
363func (p Paths) FilterByExt(ext string) Paths {
364 ret := make(Paths, 0, len(p))
365 for _, path := range p {
366 if path.Ext() == ext {
367 ret = append(ret, path)
368 }
369 }
370 return ret
371}
372
373// FilterOutByExt returns the subset of the paths that do not have extension ext
374func (p Paths) FilterOutByExt(ext string) Paths {
375 ret := make(Paths, 0, len(p))
376 for _, path := range p {
377 if path.Ext() != ext {
378 ret = append(ret, path)
379 }
380 }
381 return ret
382}
383
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700384// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
385// (including subdirectories) are in a contiguous subslice of the list, and can be found in
386// O(log(N)) time using a binary search on the directory prefix.
387type DirectorySortedPaths Paths
388
389func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
390 ret := append(DirectorySortedPaths(nil), paths...)
391 sort.Slice(ret, func(i, j int) bool {
392 return ret[i].String() < ret[j].String()
393 })
394 return ret
395}
396
397// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
398// that are in the specified directory and its subdirectories.
399func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
400 prefix := filepath.Clean(dir) + "/"
401 start := sort.Search(len(p), func(i int) bool {
402 return prefix < p[i].String()
403 })
404
405 ret := p[start:]
406
407 end := sort.Search(len(ret), func(i int) bool {
408 return !strings.HasPrefix(ret[i].String(), prefix)
409 })
410
411 ret = ret[:end]
412
413 return Paths(ret)
414}
415
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700416// WritablePaths is a slice of WritablePaths, used for multiple outputs.
417type WritablePaths []WritablePath
418
419// Strings returns the string forms of the writable paths.
420func (p WritablePaths) Strings() []string {
421 if p == nil {
422 return nil
423 }
424 ret := make([]string, len(p))
425 for i, path := range p {
426 ret[i] = path.String()
427 }
428 return ret
429}
430
431type basePath struct {
432 path string
433 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800434 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700435}
436
437func (p basePath) Ext() string {
438 return filepath.Ext(p.path)
439}
440
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700441func (p basePath) Base() string {
442 return filepath.Base(p.path)
443}
444
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800445func (p basePath) Rel() string {
446 if p.rel != "" {
447 return p.rel
448 }
449 return p.path
450}
451
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700452// SourcePath is a Path representing a file path rooted from SrcDir
453type SourcePath struct {
454 basePath
455}
456
457var _ Path = SourcePath{}
458
459// safePathForSource is for paths that we expect are safe -- only for use by go
460// code that is embedding ninja variables in paths
461func safePathForSource(ctx PathContext, path string) SourcePath {
462 p := validateSafePath(ctx, path)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800463 ret := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700464
465 abs, err := filepath.Abs(ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700466 if err != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700467 reportPathError(ctx, "%s", err.Error())
468 return ret
469 }
470 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
471 if err != nil {
472 reportPathError(ctx, "%s", err.Error())
473 return ret
474 }
475 if strings.HasPrefix(abs, buildroot) {
476 reportPathError(ctx, "source path %s is in output", abs)
477 return ret
Colin Cross6e18ca42015-07-14 18:55:36 -0700478 }
479
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700480 return ret
481}
482
Jeff Gaston734e3802017-04-10 15:47:24 -0700483// PathForSource joins the provided path components and validates that the result
484// neither escapes the source dir nor is in the out dir.
485// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
486func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
487 p := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800488 ret := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700489
490 abs, err := filepath.Abs(ret.String())
491 if err != nil {
492 reportPathError(ctx, "%s", err.Error())
493 return ret
494 }
495 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
496 if err != nil {
497 reportPathError(ctx, "%s", err.Error())
498 return ret
499 }
500 if strings.HasPrefix(abs, buildroot) {
501 reportPathError(ctx, "source path %s is in output", abs)
502 return ret
503 }
504
Colin Cross294941b2017-02-01 14:10:36 -0800505 if exists, _, err := ctx.Fs().Exists(ret.String()); err != nil {
506 reportPathError(ctx, "%s: %s", ret, err.Error())
507 } else if !exists {
508 reportPathError(ctx, "source path %s does not exist", ret)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700509 }
510 return ret
511}
512
Jeff Gaston734e3802017-04-10 15:47:24 -0700513// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700514// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
515// so that the ninja file will be regenerated if the state of the path changes.
Jeff Gaston734e3802017-04-10 15:47:24 -0700516func ExistentPathForSource(ctx PathContext, intermediates string, pathComponents ...string) OptionalPath {
517 if len(pathComponents) == 0 {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800518 // For when someone forgets the 'intermediates' argument
519 panic("Missing path(s)")
520 }
521
Jeff Gaston734e3802017-04-10 15:47:24 -0700522 p := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800523 path := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700524
525 abs, err := filepath.Abs(path.String())
526 if err != nil {
527 reportPathError(ctx, "%s", err.Error())
528 return OptionalPath{}
529 }
530 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
531 if err != nil {
532 reportPathError(ctx, "%s", err.Error())
533 return OptionalPath{}
534 }
535 if strings.HasPrefix(abs, buildroot) {
536 reportPathError(ctx, "source path %s is in output", abs)
537 return OptionalPath{}
538 }
539
Colin Cross7f19f372016-11-01 11:10:25 -0700540 if pathtools.IsGlob(path.String()) {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800541 reportPathError(ctx, "path may not contain a glob: %s", path.String())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700542 return OptionalPath{}
543 }
544
Colin Cross7f19f372016-11-01 11:10:25 -0700545 if gctx, ok := ctx.(PathGlobContext); ok {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800546 // Use glob to produce proper dependencies, even though we only want
547 // a single file.
Colin Cross7f19f372016-11-01 11:10:25 -0700548 files, err := gctx.GlobWithDeps(path.String(), nil)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800549 if err != nil {
550 reportPathError(ctx, "glob: %s", err.Error())
551 return OptionalPath{}
552 }
553
554 if len(files) == 0 {
555 return OptionalPath{}
556 }
557 } else {
558 // We cannot add build statements in this context, so we fall back to
559 // AddNinjaFileDeps
Colin Cross294941b2017-02-01 14:10:36 -0800560 files, dirs, err := pathtools.Glob(path.String(), nil)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800561 if err != nil {
562 reportPathError(ctx, "glob: %s", err.Error())
563 return OptionalPath{}
564 }
565
566 ctx.AddNinjaFileDeps(dirs...)
567
568 if len(files) == 0 {
569 return OptionalPath{}
570 }
571
572 ctx.AddNinjaFileDeps(path.String())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700573 }
574 return OptionalPathForPath(path)
575}
576
577func (p SourcePath) String() string {
578 return filepath.Join(p.config.srcDir, p.path)
579}
580
581// Join creates a new SourcePath with paths... joined with the current path. The
582// provided paths... may not use '..' to escape from the current path.
583func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
584 path := validatePath(ctx, paths...)
585 return PathForSource(ctx, p.path, path)
586}
587
588// OverlayPath returns the overlay for `path' if it exists. This assumes that the
589// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700590func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700591 var relDir string
592 if moduleSrcPath, ok := path.(ModuleSrcPath); ok {
Colin Cross7fc17db2017-02-01 14:07:55 -0800593 relDir = moduleSrcPath.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700594 } else if srcPath, ok := path.(SourcePath); ok {
595 relDir = srcPath.path
596 } else {
597 reportPathError(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
598 return OptionalPath{}
599 }
600 dir := filepath.Join(p.config.srcDir, p.path, relDir)
601 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700602 if pathtools.IsGlob(dir) {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800603 reportPathError(ctx, "Path may not contain a glob: %s", dir)
604 }
Colin Cross7f19f372016-11-01 11:10:25 -0700605 paths, err := ctx.GlobWithDeps(dir, []string{})
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700606 if err != nil {
607 reportPathError(ctx, "glob: %s", err.Error())
608 return OptionalPath{}
609 }
610 if len(paths) == 0 {
611 return OptionalPath{}
612 }
613 relPath, err := filepath.Rel(p.config.srcDir, paths[0])
614 if err != nil {
615 reportPathError(ctx, "%s", err.Error())
616 return OptionalPath{}
617 }
618 return OptionalPathForPath(PathForSource(ctx, relPath))
619}
620
621// OutputPath is a Path representing a file path rooted from the build directory
622type OutputPath struct {
623 basePath
624}
625
Colin Cross702e0f82017-10-18 17:27:54 -0700626func (p OutputPath) withRel(rel string) OutputPath {
627 p.basePath.path = filepath.Join(p.basePath.path, rel)
628 p.basePath.rel = rel
629 return p
630}
631
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700632var _ Path = OutputPath{}
633
Jeff Gaston734e3802017-04-10 15:47:24 -0700634// PathForOutput joins the provided paths and returns an OutputPath that is
635// validated to not escape the build dir.
636// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
637func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
638 path := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800639 return OutputPath{basePath{path, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700640}
641
642func (p OutputPath) writablePath() {}
643
644func (p OutputPath) String() string {
645 return filepath.Join(p.config.buildDir, p.path)
646}
647
Colin Crossa2344662016-03-24 13:14:12 -0700648func (p OutputPath) RelPathString() string {
649 return p.path
650}
651
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700652// Join creates a new OutputPath with paths... joined with the current path. The
653// provided paths... may not use '..' to escape from the current path.
654func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
655 path := validatePath(ctx, paths...)
656 return PathForOutput(ctx, p.path, path)
657}
658
659// PathForIntermediates returns an OutputPath representing the top-level
660// intermediates directory.
661func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
662 path := validatePath(ctx, paths...)
663 return PathForOutput(ctx, ".intermediates", path)
664}
665
666// ModuleSrcPath is a Path representing a file rooted from a module's local source dir
667type ModuleSrcPath struct {
Colin Cross7fc17db2017-02-01 14:07:55 -0800668 SourcePath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700669}
670
671var _ Path = ModuleSrcPath{}
672var _ genPathProvider = ModuleSrcPath{}
673var _ objPathProvider = ModuleSrcPath{}
674var _ resPathProvider = ModuleSrcPath{}
675
676// PathForModuleSrc returns a ModuleSrcPath representing the paths... under the
677// module's local source directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700678func PathForModuleSrc(ctx ModuleContext, paths ...string) ModuleSrcPath {
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800679 p := validatePath(ctx, paths...)
680 path := ModuleSrcPath{PathForSource(ctx, ctx.ModuleDir(), p)}
681 path.basePath.rel = p
682 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700683}
684
685// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
686// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700687func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700688 if p == nil {
689 return OptionalPath{}
690 }
691 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
692}
693
Dan Willemsen21ec4902016-11-02 20:43:13 -0700694func (p ModuleSrcPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800695 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700696}
697
Colin Cross635c3b02016-05-18 15:37:25 -0700698func (p ModuleSrcPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800699 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700700}
701
Colin Cross635c3b02016-05-18 15:37:25 -0700702func (p ModuleSrcPath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700703 // TODO: Use full directory if the new ctx is not the current ctx?
704 return PathForModuleRes(ctx, p.path, name)
705}
706
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800707func (p ModuleSrcPath) WithSubDir(ctx ModuleContext, subdir string) ModuleSrcPath {
708 subdir = PathForModuleSrc(ctx, subdir).String()
709 var err error
710 rel, err := filepath.Rel(subdir, p.path)
711 if err != nil {
712 ctx.ModuleErrorf("source file %q is not under path %q", p.path, subdir)
713 return p
714 }
715 p.rel = rel
716 return p
717}
718
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700719// ModuleOutPath is a Path representing a module's output directory.
720type ModuleOutPath struct {
721 OutputPath
722}
723
724var _ Path = ModuleOutPath{}
725
Colin Cross702e0f82017-10-18 17:27:54 -0700726func pathForModule(ctx ModuleContext) OutputPath {
727 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
728}
729
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800730// PathForVndkRefDump returns an OptionalPath representing the path of the reference
731// abi dump for the given module. This is not guaranteed to be valid.
732func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string, vndkOrNdk, isSourceDump bool) OptionalPath {
733 archName := ctx.Arch().ArchType.Name
734 var sourceOrBinaryDir string
735 var vndkOrNdkDir string
736 var ext string
737 if isSourceDump {
Jayant Chowdhary715cac32017-04-20 06:53:59 -0700738 ext = ".lsdump.gz"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800739 sourceOrBinaryDir = "source-based"
740 } else {
Jayant Chowdhary715cac32017-04-20 06:53:59 -0700741 ext = ".bdump.gz"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800742 sourceOrBinaryDir = "binary-based"
743 }
744 if vndkOrNdk {
745 vndkOrNdkDir = "vndk"
746 } else {
747 vndkOrNdkDir = "ndk"
748 }
749 refDumpFileStr := "prebuilts/abi-dumps/" + vndkOrNdkDir + "/" + version + "/" +
750 archName + "/" + sourceOrBinaryDir + "/" + fileName + ext
Jeff Gaston734e3802017-04-10 15:47:24 -0700751 return ExistentPathForSource(ctx, "", refDumpFileStr)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800752}
753
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700754// PathForModuleOut returns a Path representing the paths... under the module's
755// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700756func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700757 p := validatePath(ctx, paths...)
Colin Cross702e0f82017-10-18 17:27:54 -0700758 return ModuleOutPath{
759 OutputPath: pathForModule(ctx).withRel(p),
760 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700761}
762
763// ModuleGenPath is a Path representing the 'gen' directory in a module's output
764// directory. Mainly used for generated sources.
765type ModuleGenPath struct {
766 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700767}
768
769var _ Path = ModuleGenPath{}
770var _ genPathProvider = ModuleGenPath{}
771var _ objPathProvider = ModuleGenPath{}
772
773// PathForModuleGen returns a Path representing the paths... under the module's
774// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700775func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700776 p := validatePath(ctx, paths...)
777 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -0700778 ModuleOutPath: ModuleOutPath{
779 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
780 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700781 }
782}
783
Dan Willemsen21ec4902016-11-02 20:43:13 -0700784func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700785 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -0700786 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700787}
788
Colin Cross635c3b02016-05-18 15:37:25 -0700789func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700790 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
791}
792
793// ModuleObjPath is a Path representing the 'obj' directory in a module's output
794// directory. Used for compiled objects.
795type ModuleObjPath struct {
796 ModuleOutPath
797}
798
799var _ Path = ModuleObjPath{}
800
801// PathForModuleObj returns a Path representing the paths... under the module's
802// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700803func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
804 p := validatePath(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700805 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
806}
807
808// ModuleResPath is a a Path representing the 'res' directory in a module's
809// output directory.
810type ModuleResPath struct {
811 ModuleOutPath
812}
813
814var _ Path = ModuleResPath{}
815
816// PathForModuleRes returns a Path representing the paths... under the module's
817// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700818func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
819 p := validatePath(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700820 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
821}
822
823// PathForModuleInstall returns a Path representing the install path for the
824// module appended with paths...
Dan Willemsen00269f22017-07-06 16:59:48 -0700825func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) OutputPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700826 var outPaths []string
827 if ctx.Device() {
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700828 var partition string
Dan Willemsen00269f22017-07-06 16:59:48 -0700829 if ctx.InstallInData() {
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700830 partition = "data"
Jeff Gastonaf3cc2d2017-09-27 17:01:44 -0700831 } else if ctx.InstallOnVendorPartition() {
Dan Willemsen00269f22017-07-06 16:59:48 -0700832 partition = ctx.DeviceConfig().VendorPath()
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700833 } else {
834 partition = "system"
Dan Willemsen782a2d12015-12-21 14:55:28 -0800835 }
Vishwath Mohan1dd88392017-03-29 22:00:18 -0700836
837 if ctx.InstallInSanitizerDir() {
838 partition = "data/asan/" + partition
Dan Willemsen782a2d12015-12-21 14:55:28 -0800839 }
840 outPaths = []string{"target", "product", ctx.AConfig().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700841 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -0700842 switch ctx.Os() {
843 case Linux:
844 outPaths = []string{"host", "linux-x86"}
845 case LinuxBionic:
846 // TODO: should this be a separate top level, or shared with linux-x86?
847 outPaths = []string{"host", "linux_bionic-x86"}
848 default:
849 outPaths = []string{"host", ctx.Os().String() + "-x86"}
850 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700851 }
Dan Willemsen782a2d12015-12-21 14:55:28 -0800852 if ctx.Debug() {
853 outPaths = append([]string{"debug"}, outPaths...)
854 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700855 outPaths = append(outPaths, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700856 return PathForOutput(ctx, outPaths...)
857}
858
859// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800860// Ensures that each path component does not attempt to leave its component.
Jeff Gaston734e3802017-04-10 15:47:24 -0700861func validateSafePath(ctx PathContext, pathComponents ...string) string {
862 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800863 path := filepath.Clean(path)
864 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
865 reportPathError(ctx, "Path is outside directory: %s", path)
866 return ""
867 }
868 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700869 // TODO: filepath.Join isn't necessarily correct with embedded ninja
870 // variables. '..' may remove the entire ninja variable, even if it
871 // will be expanded to multiple nested directories.
Jeff Gaston734e3802017-04-10 15:47:24 -0700872 return filepath.Join(pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700873}
874
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800875// validatePath validates that a path does not include ninja variables, and that
876// each path component does not attempt to leave its component. Returns a joined
877// version of each path component.
Jeff Gaston734e3802017-04-10 15:47:24 -0700878func validatePath(ctx PathContext, pathComponents ...string) string {
879 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700880 if strings.Contains(path, "$") {
881 reportPathError(ctx, "Path contains invalid character($): %s", path)
882 return ""
883 }
884 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700885 return validateSafePath(ctx, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -0700886}
Colin Cross5b529592017-05-09 13:34:34 -0700887
888type testPath struct {
889 basePath
890}
891
892func (p testPath) String() string {
893 return p.path
894}
895
896func PathForTesting(paths ...string) Path {
897 p := validateSafePath(nil, paths...)
898 return testPath{basePath{path: p, rel: p}}
899}
900
901func PathsForTesting(strs []string) Paths {
902 p := make(Paths, len(strs))
903 for i, s := range strs {
904 p[i] = PathForTesting(s)
905 }
906
907 return p
908}