blob: b2ee627567262966468fd6514450522ac57b9999 [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
Colin Cross0875c522017-11-28 17:34:01 -0800452func (p basePath) String() string {
453 return p.path
454}
455
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700456// SourcePath is a Path representing a file path rooted from SrcDir
457type SourcePath struct {
458 basePath
459}
460
461var _ Path = SourcePath{}
462
463// safePathForSource is for paths that we expect are safe -- only for use by go
464// code that is embedding ninja variables in paths
465func safePathForSource(ctx PathContext, path string) SourcePath {
466 p := validateSafePath(ctx, path)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800467 ret := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700468
469 abs, err := filepath.Abs(ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700470 if err != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700471 reportPathError(ctx, "%s", err.Error())
472 return ret
473 }
474 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
475 if err != nil {
476 reportPathError(ctx, "%s", err.Error())
477 return ret
478 }
479 if strings.HasPrefix(abs, buildroot) {
480 reportPathError(ctx, "source path %s is in output", abs)
481 return ret
Colin Cross6e18ca42015-07-14 18:55:36 -0700482 }
483
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700484 return ret
485}
486
Jeff Gaston734e3802017-04-10 15:47:24 -0700487// PathForSource joins the provided path components and validates that the result
488// neither escapes the source dir nor is in the out dir.
489// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
490func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
491 p := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800492 ret := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700493
494 abs, err := filepath.Abs(ret.String())
495 if err != nil {
496 reportPathError(ctx, "%s", err.Error())
497 return ret
498 }
499 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
500 if err != nil {
501 reportPathError(ctx, "%s", err.Error())
502 return ret
503 }
504 if strings.HasPrefix(abs, buildroot) {
505 reportPathError(ctx, "source path %s is in output", abs)
506 return ret
507 }
508
Colin Cross294941b2017-02-01 14:10:36 -0800509 if exists, _, err := ctx.Fs().Exists(ret.String()); err != nil {
510 reportPathError(ctx, "%s: %s", ret, err.Error())
511 } else if !exists {
512 reportPathError(ctx, "source path %s does not exist", ret)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700513 }
514 return ret
515}
516
Jeff Gaston734e3802017-04-10 15:47:24 -0700517// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700518// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
519// so that the ninja file will be regenerated if the state of the path changes.
Jeff Gaston734e3802017-04-10 15:47:24 -0700520func ExistentPathForSource(ctx PathContext, intermediates string, pathComponents ...string) OptionalPath {
521 if len(pathComponents) == 0 {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800522 // For when someone forgets the 'intermediates' argument
523 panic("Missing path(s)")
524 }
525
Jeff Gaston734e3802017-04-10 15:47:24 -0700526 p := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800527 path := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700528
529 abs, err := filepath.Abs(path.String())
530 if err != nil {
531 reportPathError(ctx, "%s", err.Error())
532 return OptionalPath{}
533 }
534 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
535 if err != nil {
536 reportPathError(ctx, "%s", err.Error())
537 return OptionalPath{}
538 }
539 if strings.HasPrefix(abs, buildroot) {
540 reportPathError(ctx, "source path %s is in output", abs)
541 return OptionalPath{}
542 }
543
Colin Cross7f19f372016-11-01 11:10:25 -0700544 if pathtools.IsGlob(path.String()) {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800545 reportPathError(ctx, "path may not contain a glob: %s", path.String())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700546 return OptionalPath{}
547 }
548
Colin Cross7f19f372016-11-01 11:10:25 -0700549 if gctx, ok := ctx.(PathGlobContext); ok {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800550 // Use glob to produce proper dependencies, even though we only want
551 // a single file.
Colin Cross7f19f372016-11-01 11:10:25 -0700552 files, err := gctx.GlobWithDeps(path.String(), nil)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800553 if err != nil {
554 reportPathError(ctx, "glob: %s", err.Error())
555 return OptionalPath{}
556 }
557
558 if len(files) == 0 {
559 return OptionalPath{}
560 }
561 } else {
562 // We cannot add build statements in this context, so we fall back to
563 // AddNinjaFileDeps
Colin Cross294941b2017-02-01 14:10:36 -0800564 files, dirs, err := pathtools.Glob(path.String(), nil)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800565 if err != nil {
566 reportPathError(ctx, "glob: %s", err.Error())
567 return OptionalPath{}
568 }
569
570 ctx.AddNinjaFileDeps(dirs...)
571
572 if len(files) == 0 {
573 return OptionalPath{}
574 }
575
576 ctx.AddNinjaFileDeps(path.String())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700577 }
578 return OptionalPathForPath(path)
579}
580
581func (p SourcePath) String() string {
582 return filepath.Join(p.config.srcDir, p.path)
583}
584
585// Join creates a new SourcePath with paths... joined with the current path. The
586// provided paths... may not use '..' to escape from the current path.
587func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
588 path := validatePath(ctx, paths...)
589 return PathForSource(ctx, p.path, path)
590}
591
592// OverlayPath returns the overlay for `path' if it exists. This assumes that the
593// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700594func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700595 var relDir string
596 if moduleSrcPath, ok := path.(ModuleSrcPath); ok {
Colin Cross7fc17db2017-02-01 14:07:55 -0800597 relDir = moduleSrcPath.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700598 } else if srcPath, ok := path.(SourcePath); ok {
599 relDir = srcPath.path
600 } else {
601 reportPathError(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
602 return OptionalPath{}
603 }
604 dir := filepath.Join(p.config.srcDir, p.path, relDir)
605 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700606 if pathtools.IsGlob(dir) {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800607 reportPathError(ctx, "Path may not contain a glob: %s", dir)
608 }
Colin Cross7f19f372016-11-01 11:10:25 -0700609 paths, err := ctx.GlobWithDeps(dir, []string{})
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700610 if err != nil {
611 reportPathError(ctx, "glob: %s", err.Error())
612 return OptionalPath{}
613 }
614 if len(paths) == 0 {
615 return OptionalPath{}
616 }
617 relPath, err := filepath.Rel(p.config.srcDir, paths[0])
618 if err != nil {
619 reportPathError(ctx, "%s", err.Error())
620 return OptionalPath{}
621 }
622 return OptionalPathForPath(PathForSource(ctx, relPath))
623}
624
625// OutputPath is a Path representing a file path rooted from the build directory
626type OutputPath struct {
627 basePath
628}
629
Colin Cross702e0f82017-10-18 17:27:54 -0700630func (p OutputPath) withRel(rel string) OutputPath {
631 p.basePath.path = filepath.Join(p.basePath.path, rel)
632 p.basePath.rel = rel
633 return p
634}
635
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700636var _ Path = OutputPath{}
637
Jeff Gaston734e3802017-04-10 15:47:24 -0700638// PathForOutput joins the provided paths and returns an OutputPath that is
639// validated to not escape the build dir.
640// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
641func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
642 path := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800643 return OutputPath{basePath{path, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700644}
645
646func (p OutputPath) writablePath() {}
647
648func (p OutputPath) String() string {
649 return filepath.Join(p.config.buildDir, p.path)
650}
651
Colin Crossa2344662016-03-24 13:14:12 -0700652func (p OutputPath) RelPathString() string {
653 return p.path
654}
655
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700656// Join creates a new OutputPath with paths... joined with the current path. The
657// provided paths... may not use '..' to escape from the current path.
658func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
659 path := validatePath(ctx, paths...)
660 return PathForOutput(ctx, p.path, path)
661}
662
663// PathForIntermediates returns an OutputPath representing the top-level
664// intermediates directory.
665func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
666 path := validatePath(ctx, paths...)
667 return PathForOutput(ctx, ".intermediates", path)
668}
669
670// ModuleSrcPath is a Path representing a file rooted from a module's local source dir
671type ModuleSrcPath struct {
Colin Cross7fc17db2017-02-01 14:07:55 -0800672 SourcePath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700673}
674
675var _ Path = ModuleSrcPath{}
676var _ genPathProvider = ModuleSrcPath{}
677var _ objPathProvider = ModuleSrcPath{}
678var _ resPathProvider = ModuleSrcPath{}
679
680// PathForModuleSrc returns a ModuleSrcPath representing the paths... under the
681// module's local source directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700682func PathForModuleSrc(ctx ModuleContext, paths ...string) ModuleSrcPath {
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800683 p := validatePath(ctx, paths...)
684 path := ModuleSrcPath{PathForSource(ctx, ctx.ModuleDir(), p)}
685 path.basePath.rel = p
686 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700687}
688
689// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
690// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700691func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700692 if p == nil {
693 return OptionalPath{}
694 }
695 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
696}
697
Dan Willemsen21ec4902016-11-02 20:43:13 -0700698func (p ModuleSrcPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800699 return PathForModuleGen(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) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800703 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700704}
705
Colin Cross635c3b02016-05-18 15:37:25 -0700706func (p ModuleSrcPath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700707 // TODO: Use full directory if the new ctx is not the current ctx?
708 return PathForModuleRes(ctx, p.path, name)
709}
710
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800711func (p ModuleSrcPath) WithSubDir(ctx ModuleContext, subdir string) ModuleSrcPath {
712 subdir = PathForModuleSrc(ctx, subdir).String()
713 var err error
714 rel, err := filepath.Rel(subdir, p.path)
715 if err != nil {
716 ctx.ModuleErrorf("source file %q is not under path %q", p.path, subdir)
717 return p
718 }
719 p.rel = rel
720 return p
721}
722
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700723// ModuleOutPath is a Path representing a module's output directory.
724type ModuleOutPath struct {
725 OutputPath
726}
727
728var _ Path = ModuleOutPath{}
729
Colin Cross702e0f82017-10-18 17:27:54 -0700730func pathForModule(ctx ModuleContext) OutputPath {
731 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
732}
733
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800734// PathForVndkRefDump returns an OptionalPath representing the path of the reference
735// abi dump for the given module. This is not guaranteed to be valid.
736func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string, vndkOrNdk, isSourceDump bool) OptionalPath {
737 archName := ctx.Arch().ArchType.Name
738 var sourceOrBinaryDir string
739 var vndkOrNdkDir string
740 var ext string
741 if isSourceDump {
Jayant Chowdhary715cac32017-04-20 06:53:59 -0700742 ext = ".lsdump.gz"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800743 sourceOrBinaryDir = "source-based"
744 } else {
Jayant Chowdhary715cac32017-04-20 06:53:59 -0700745 ext = ".bdump.gz"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800746 sourceOrBinaryDir = "binary-based"
747 }
748 if vndkOrNdk {
749 vndkOrNdkDir = "vndk"
750 } else {
751 vndkOrNdkDir = "ndk"
752 }
753 refDumpFileStr := "prebuilts/abi-dumps/" + vndkOrNdkDir + "/" + version + "/" +
754 archName + "/" + sourceOrBinaryDir + "/" + fileName + ext
Jeff Gaston734e3802017-04-10 15:47:24 -0700755 return ExistentPathForSource(ctx, "", refDumpFileStr)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800756}
757
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700758// PathForModuleOut returns a Path representing the paths... under the module's
759// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700760func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700761 p := validatePath(ctx, paths...)
Colin Cross702e0f82017-10-18 17:27:54 -0700762 return ModuleOutPath{
763 OutputPath: pathForModule(ctx).withRel(p),
764 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700765}
766
767// ModuleGenPath is a Path representing the 'gen' directory in a module's output
768// directory. Mainly used for generated sources.
769type ModuleGenPath struct {
770 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700771}
772
773var _ Path = ModuleGenPath{}
774var _ genPathProvider = ModuleGenPath{}
775var _ objPathProvider = ModuleGenPath{}
776
777// PathForModuleGen returns a Path representing the paths... under the module's
778// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700779func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700780 p := validatePath(ctx, paths...)
781 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -0700782 ModuleOutPath: ModuleOutPath{
783 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
784 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700785 }
786}
787
Dan Willemsen21ec4902016-11-02 20:43:13 -0700788func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700789 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -0700790 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700791}
792
Colin Cross635c3b02016-05-18 15:37:25 -0700793func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700794 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
795}
796
797// ModuleObjPath is a Path representing the 'obj' directory in a module's output
798// directory. Used for compiled objects.
799type ModuleObjPath struct {
800 ModuleOutPath
801}
802
803var _ Path = ModuleObjPath{}
804
805// PathForModuleObj returns a Path representing the paths... under the module's
806// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700807func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
808 p := validatePath(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700809 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
810}
811
812// ModuleResPath is a a Path representing the 'res' directory in a module's
813// output directory.
814type ModuleResPath struct {
815 ModuleOutPath
816}
817
818var _ Path = ModuleResPath{}
819
820// PathForModuleRes returns a Path representing the paths... under the module's
821// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700822func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
823 p := validatePath(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700824 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
825}
826
827// PathForModuleInstall returns a Path representing the install path for the
828// module appended with paths...
Dan Willemsen00269f22017-07-06 16:59:48 -0700829func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) OutputPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700830 var outPaths []string
831 if ctx.Device() {
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700832 var partition string
Dan Willemsen00269f22017-07-06 16:59:48 -0700833 if ctx.InstallInData() {
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700834 partition = "data"
Jeff Gastonaf3cc2d2017-09-27 17:01:44 -0700835 } else if ctx.InstallOnVendorPartition() {
Dan Willemsen00269f22017-07-06 16:59:48 -0700836 partition = ctx.DeviceConfig().VendorPath()
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700837 } else {
838 partition = "system"
Dan Willemsen782a2d12015-12-21 14:55:28 -0800839 }
Vishwath Mohan1dd88392017-03-29 22:00:18 -0700840
841 if ctx.InstallInSanitizerDir() {
842 partition = "data/asan/" + partition
Dan Willemsen782a2d12015-12-21 14:55:28 -0800843 }
844 outPaths = []string{"target", "product", ctx.AConfig().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700845 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -0700846 switch ctx.Os() {
847 case Linux:
848 outPaths = []string{"host", "linux-x86"}
849 case LinuxBionic:
850 // TODO: should this be a separate top level, or shared with linux-x86?
851 outPaths = []string{"host", "linux_bionic-x86"}
852 default:
853 outPaths = []string{"host", ctx.Os().String() + "-x86"}
854 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700855 }
Dan Willemsen782a2d12015-12-21 14:55:28 -0800856 if ctx.Debug() {
857 outPaths = append([]string{"debug"}, outPaths...)
858 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700859 outPaths = append(outPaths, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700860 return PathForOutput(ctx, outPaths...)
861}
862
863// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800864// Ensures that each path component does not attempt to leave its component.
Jeff Gaston734e3802017-04-10 15:47:24 -0700865func validateSafePath(ctx PathContext, pathComponents ...string) string {
866 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800867 path := filepath.Clean(path)
868 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
869 reportPathError(ctx, "Path is outside directory: %s", path)
870 return ""
871 }
872 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700873 // TODO: filepath.Join isn't necessarily correct with embedded ninja
874 // variables. '..' may remove the entire ninja variable, even if it
875 // will be expanded to multiple nested directories.
Jeff Gaston734e3802017-04-10 15:47:24 -0700876 return filepath.Join(pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700877}
878
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800879// validatePath validates that a path does not include ninja variables, and that
880// each path component does not attempt to leave its component. Returns a joined
881// version of each path component.
Jeff Gaston734e3802017-04-10 15:47:24 -0700882func validatePath(ctx PathContext, pathComponents ...string) string {
883 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700884 if strings.Contains(path, "$") {
885 reportPathError(ctx, "Path contains invalid character($): %s", path)
886 return ""
887 }
888 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700889 return validateSafePath(ctx, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -0700890}
Colin Cross5b529592017-05-09 13:34:34 -0700891
Colin Cross0875c522017-11-28 17:34:01 -0800892func PathForPhony(ctx PathContext, phony string) WritablePath {
893 if strings.ContainsAny(phony, "$/") {
894 reportPathError(ctx, "Phony target contains invalid character ($ or /): %s", phony)
895 }
896 return OutputPath{basePath{phony, pathConfig(ctx), ""}}
897}
898
Colin Cross5b529592017-05-09 13:34:34 -0700899type testPath struct {
900 basePath
901}
902
903func (p testPath) String() string {
904 return p.path
905}
906
907func PathForTesting(paths ...string) Path {
908 p := validateSafePath(nil, paths...)
909 return testPath{basePath{path: p, rel: p}}
910}
911
912func PathsForTesting(strs []string) Paths {
913 p := make(Paths, len(strs))
914 for i, s := range strs {
915 p[i] = PathForTesting(s)
916 }
917
918 return p
919}