blob: 71049eeb16bfa56db2942cb31347cf1945aae2b3 [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
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800431// Paths returns the WritablePaths as a Paths
432func (p WritablePaths) Paths() Paths {
433 if p == nil {
434 return nil
435 }
436 ret := make(Paths, len(p))
437 for i, path := range p {
438 ret[i] = path
439 }
440 return ret
441}
442
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700443type basePath struct {
444 path string
445 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800446 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700447}
448
449func (p basePath) Ext() string {
450 return filepath.Ext(p.path)
451}
452
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700453func (p basePath) Base() string {
454 return filepath.Base(p.path)
455}
456
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800457func (p basePath) Rel() string {
458 if p.rel != "" {
459 return p.rel
460 }
461 return p.path
462}
463
Colin Cross0875c522017-11-28 17:34:01 -0800464func (p basePath) String() string {
465 return p.path
466}
467
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700468// SourcePath is a Path representing a file path rooted from SrcDir
469type SourcePath struct {
470 basePath
471}
472
473var _ Path = SourcePath{}
474
475// safePathForSource is for paths that we expect are safe -- only for use by go
476// code that is embedding ninja variables in paths
477func safePathForSource(ctx PathContext, path string) SourcePath {
478 p := validateSafePath(ctx, path)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800479 ret := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700480
481 abs, err := filepath.Abs(ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700482 if err != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700483 reportPathError(ctx, "%s", err.Error())
484 return ret
485 }
486 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
487 if err != nil {
488 reportPathError(ctx, "%s", err.Error())
489 return ret
490 }
491 if strings.HasPrefix(abs, buildroot) {
492 reportPathError(ctx, "source path %s is in output", abs)
493 return ret
Colin Cross6e18ca42015-07-14 18:55:36 -0700494 }
495
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700496 return ret
497}
498
Jeff Gaston734e3802017-04-10 15:47:24 -0700499// PathForSource joins the provided path components and validates that the result
500// neither escapes the source dir nor is in the out dir.
501// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
502func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
503 p := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800504 ret := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700505
506 abs, err := filepath.Abs(ret.String())
507 if err != nil {
508 reportPathError(ctx, "%s", err.Error())
509 return ret
510 }
511 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
512 if err != nil {
513 reportPathError(ctx, "%s", err.Error())
514 return ret
515 }
516 if strings.HasPrefix(abs, buildroot) {
517 reportPathError(ctx, "source path %s is in output", abs)
518 return ret
519 }
520
Colin Cross294941b2017-02-01 14:10:36 -0800521 if exists, _, err := ctx.Fs().Exists(ret.String()); err != nil {
522 reportPathError(ctx, "%s: %s", ret, err.Error())
523 } else if !exists {
524 reportPathError(ctx, "source path %s does not exist", ret)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700525 }
526 return ret
527}
528
Jeff Gaston734e3802017-04-10 15:47:24 -0700529// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700530// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
531// so that the ninja file will be regenerated if the state of the path changes.
Jeff Gaston734e3802017-04-10 15:47:24 -0700532func ExistentPathForSource(ctx PathContext, intermediates string, pathComponents ...string) OptionalPath {
533 if len(pathComponents) == 0 {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800534 // For when someone forgets the 'intermediates' argument
535 panic("Missing path(s)")
536 }
537
Jeff Gaston734e3802017-04-10 15:47:24 -0700538 p := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800539 path := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700540
541 abs, err := filepath.Abs(path.String())
542 if err != nil {
543 reportPathError(ctx, "%s", err.Error())
544 return OptionalPath{}
545 }
546 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
547 if err != nil {
548 reportPathError(ctx, "%s", err.Error())
549 return OptionalPath{}
550 }
551 if strings.HasPrefix(abs, buildroot) {
552 reportPathError(ctx, "source path %s is in output", abs)
553 return OptionalPath{}
554 }
555
Colin Cross7f19f372016-11-01 11:10:25 -0700556 if pathtools.IsGlob(path.String()) {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800557 reportPathError(ctx, "path may not contain a glob: %s", path.String())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700558 return OptionalPath{}
559 }
560
Colin Cross7f19f372016-11-01 11:10:25 -0700561 if gctx, ok := ctx.(PathGlobContext); ok {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800562 // Use glob to produce proper dependencies, even though we only want
563 // a single file.
Colin Cross7f19f372016-11-01 11:10:25 -0700564 files, err := gctx.GlobWithDeps(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 if len(files) == 0 {
571 return OptionalPath{}
572 }
573 } else {
574 // We cannot add build statements in this context, so we fall back to
575 // AddNinjaFileDeps
Colin Cross294941b2017-02-01 14:10:36 -0800576 files, dirs, err := pathtools.Glob(path.String(), nil)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800577 if err != nil {
578 reportPathError(ctx, "glob: %s", err.Error())
579 return OptionalPath{}
580 }
581
582 ctx.AddNinjaFileDeps(dirs...)
583
584 if len(files) == 0 {
585 return OptionalPath{}
586 }
587
588 ctx.AddNinjaFileDeps(path.String())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700589 }
590 return OptionalPathForPath(path)
591}
592
593func (p SourcePath) String() string {
594 return filepath.Join(p.config.srcDir, p.path)
595}
596
597// Join creates a new SourcePath with paths... joined with the current path. The
598// provided paths... may not use '..' to escape from the current path.
599func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
600 path := validatePath(ctx, paths...)
601 return PathForSource(ctx, p.path, path)
602}
603
604// OverlayPath returns the overlay for `path' if it exists. This assumes that the
605// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700606func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700607 var relDir string
608 if moduleSrcPath, ok := path.(ModuleSrcPath); ok {
Colin Cross7fc17db2017-02-01 14:07:55 -0800609 relDir = moduleSrcPath.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700610 } else if srcPath, ok := path.(SourcePath); ok {
611 relDir = srcPath.path
612 } else {
613 reportPathError(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
614 return OptionalPath{}
615 }
616 dir := filepath.Join(p.config.srcDir, p.path, relDir)
617 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700618 if pathtools.IsGlob(dir) {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800619 reportPathError(ctx, "Path may not contain a glob: %s", dir)
620 }
Colin Cross7f19f372016-11-01 11:10:25 -0700621 paths, err := ctx.GlobWithDeps(dir, []string{})
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700622 if err != nil {
623 reportPathError(ctx, "glob: %s", err.Error())
624 return OptionalPath{}
625 }
626 if len(paths) == 0 {
627 return OptionalPath{}
628 }
629 relPath, err := filepath.Rel(p.config.srcDir, paths[0])
630 if err != nil {
631 reportPathError(ctx, "%s", err.Error())
632 return OptionalPath{}
633 }
634 return OptionalPathForPath(PathForSource(ctx, relPath))
635}
636
637// OutputPath is a Path representing a file path rooted from the build directory
638type OutputPath struct {
639 basePath
640}
641
Colin Cross702e0f82017-10-18 17:27:54 -0700642func (p OutputPath) withRel(rel string) OutputPath {
643 p.basePath.path = filepath.Join(p.basePath.path, rel)
644 p.basePath.rel = rel
645 return p
646}
647
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700648var _ Path = OutputPath{}
649
Jeff Gaston734e3802017-04-10 15:47:24 -0700650// PathForOutput joins the provided paths and returns an OutputPath that is
651// validated to not escape the build dir.
652// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
653func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
654 path := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800655 return OutputPath{basePath{path, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700656}
657
658func (p OutputPath) writablePath() {}
659
660func (p OutputPath) String() string {
661 return filepath.Join(p.config.buildDir, p.path)
662}
663
Colin Crossa2344662016-03-24 13:14:12 -0700664func (p OutputPath) RelPathString() string {
665 return p.path
666}
667
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700668// Join creates a new OutputPath with paths... joined with the current path. The
669// provided paths... may not use '..' to escape from the current path.
670func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
671 path := validatePath(ctx, paths...)
672 return PathForOutput(ctx, p.path, path)
673}
674
675// PathForIntermediates returns an OutputPath representing the top-level
676// intermediates directory.
677func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
678 path := validatePath(ctx, paths...)
679 return PathForOutput(ctx, ".intermediates", path)
680}
681
682// ModuleSrcPath is a Path representing a file rooted from a module's local source dir
683type ModuleSrcPath struct {
Colin Cross7fc17db2017-02-01 14:07:55 -0800684 SourcePath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700685}
686
687var _ Path = ModuleSrcPath{}
688var _ genPathProvider = ModuleSrcPath{}
689var _ objPathProvider = ModuleSrcPath{}
690var _ resPathProvider = ModuleSrcPath{}
691
692// PathForModuleSrc returns a ModuleSrcPath representing the paths... under the
693// module's local source directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700694func PathForModuleSrc(ctx ModuleContext, paths ...string) ModuleSrcPath {
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800695 p := validatePath(ctx, paths...)
696 path := ModuleSrcPath{PathForSource(ctx, ctx.ModuleDir(), p)}
697 path.basePath.rel = p
698 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700699}
700
701// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
702// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700703func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700704 if p == nil {
705 return OptionalPath{}
706 }
707 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
708}
709
Dan Willemsen21ec4902016-11-02 20:43:13 -0700710func (p ModuleSrcPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800711 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700712}
713
Colin Cross635c3b02016-05-18 15:37:25 -0700714func (p ModuleSrcPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800715 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700716}
717
Colin Cross635c3b02016-05-18 15:37:25 -0700718func (p ModuleSrcPath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700719 // TODO: Use full directory if the new ctx is not the current ctx?
720 return PathForModuleRes(ctx, p.path, name)
721}
722
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800723func (p ModuleSrcPath) WithSubDir(ctx ModuleContext, subdir string) ModuleSrcPath {
724 subdir = PathForModuleSrc(ctx, subdir).String()
725 var err error
726 rel, err := filepath.Rel(subdir, p.path)
727 if err != nil {
728 ctx.ModuleErrorf("source file %q is not under path %q", p.path, subdir)
729 return p
730 }
731 p.rel = rel
732 return p
733}
734
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700735// ModuleOutPath is a Path representing a module's output directory.
736type ModuleOutPath struct {
737 OutputPath
738}
739
740var _ Path = ModuleOutPath{}
741
Colin Cross702e0f82017-10-18 17:27:54 -0700742func pathForModule(ctx ModuleContext) OutputPath {
743 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
744}
745
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800746// PathForVndkRefDump returns an OptionalPath representing the path of the reference
747// abi dump for the given module. This is not guaranteed to be valid.
748func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string, vndkOrNdk, isSourceDump bool) OptionalPath {
749 archName := ctx.Arch().ArchType.Name
750 var sourceOrBinaryDir string
751 var vndkOrNdkDir string
752 var ext string
753 if isSourceDump {
Jayant Chowdhary715cac32017-04-20 06:53:59 -0700754 ext = ".lsdump.gz"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800755 sourceOrBinaryDir = "source-based"
756 } else {
Jayant Chowdhary715cac32017-04-20 06:53:59 -0700757 ext = ".bdump.gz"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800758 sourceOrBinaryDir = "binary-based"
759 }
760 if vndkOrNdk {
761 vndkOrNdkDir = "vndk"
762 } else {
763 vndkOrNdkDir = "ndk"
764 }
765 refDumpFileStr := "prebuilts/abi-dumps/" + vndkOrNdkDir + "/" + version + "/" +
766 archName + "/" + sourceOrBinaryDir + "/" + fileName + ext
Jeff Gaston734e3802017-04-10 15:47:24 -0700767 return ExistentPathForSource(ctx, "", refDumpFileStr)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800768}
769
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700770// PathForModuleOut returns a Path representing the paths... under the module's
771// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700772func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700773 p := validatePath(ctx, paths...)
Colin Cross702e0f82017-10-18 17:27:54 -0700774 return ModuleOutPath{
775 OutputPath: pathForModule(ctx).withRel(p),
776 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700777}
778
779// ModuleGenPath is a Path representing the 'gen' directory in a module's output
780// directory. Mainly used for generated sources.
781type ModuleGenPath struct {
782 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700783}
784
785var _ Path = ModuleGenPath{}
786var _ genPathProvider = ModuleGenPath{}
787var _ objPathProvider = ModuleGenPath{}
788
789// PathForModuleGen returns a Path representing the paths... under the module's
790// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700791func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700792 p := validatePath(ctx, paths...)
793 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -0700794 ModuleOutPath: ModuleOutPath{
795 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
796 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700797 }
798}
799
Dan Willemsen21ec4902016-11-02 20:43:13 -0700800func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700801 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -0700802 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700803}
804
Colin Cross635c3b02016-05-18 15:37:25 -0700805func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700806 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
807}
808
809// ModuleObjPath is a Path representing the 'obj' directory in a module's output
810// directory. Used for compiled objects.
811type ModuleObjPath struct {
812 ModuleOutPath
813}
814
815var _ Path = ModuleObjPath{}
816
817// PathForModuleObj returns a Path representing the paths... under the module's
818// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700819func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
820 p := validatePath(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700821 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
822}
823
824// ModuleResPath is a a Path representing the 'res' directory in a module's
825// output directory.
826type ModuleResPath struct {
827 ModuleOutPath
828}
829
830var _ Path = ModuleResPath{}
831
832// PathForModuleRes returns a Path representing the paths... under the module's
833// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700834func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
835 p := validatePath(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700836 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
837}
838
839// PathForModuleInstall returns a Path representing the install path for the
840// module appended with paths...
Dan Willemsen00269f22017-07-06 16:59:48 -0700841func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) OutputPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700842 var outPaths []string
843 if ctx.Device() {
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700844 var partition string
Dan Willemsen00269f22017-07-06 16:59:48 -0700845 if ctx.InstallInData() {
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700846 partition = "data"
Jeff Gastonaf3cc2d2017-09-27 17:01:44 -0700847 } else if ctx.InstallOnVendorPartition() {
Dan Willemsen00269f22017-07-06 16:59:48 -0700848 partition = ctx.DeviceConfig().VendorPath()
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700849 } else {
850 partition = "system"
Dan Willemsen782a2d12015-12-21 14:55:28 -0800851 }
Vishwath Mohan1dd88392017-03-29 22:00:18 -0700852
853 if ctx.InstallInSanitizerDir() {
854 partition = "data/asan/" + partition
Dan Willemsen782a2d12015-12-21 14:55:28 -0800855 }
856 outPaths = []string{"target", "product", ctx.AConfig().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700857 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -0700858 switch ctx.Os() {
859 case Linux:
860 outPaths = []string{"host", "linux-x86"}
861 case LinuxBionic:
862 // TODO: should this be a separate top level, or shared with linux-x86?
863 outPaths = []string{"host", "linux_bionic-x86"}
864 default:
865 outPaths = []string{"host", ctx.Os().String() + "-x86"}
866 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700867 }
Dan Willemsen782a2d12015-12-21 14:55:28 -0800868 if ctx.Debug() {
869 outPaths = append([]string{"debug"}, outPaths...)
870 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700871 outPaths = append(outPaths, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700872 return PathForOutput(ctx, outPaths...)
873}
874
875// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800876// Ensures that each path component does not attempt to leave its component.
Jeff Gaston734e3802017-04-10 15:47:24 -0700877func validateSafePath(ctx PathContext, pathComponents ...string) string {
878 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800879 path := filepath.Clean(path)
880 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
881 reportPathError(ctx, "Path is outside directory: %s", path)
882 return ""
883 }
884 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700885 // TODO: filepath.Join isn't necessarily correct with embedded ninja
886 // variables. '..' may remove the entire ninja variable, even if it
887 // will be expanded to multiple nested directories.
Jeff Gaston734e3802017-04-10 15:47:24 -0700888 return filepath.Join(pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700889}
890
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800891// validatePath validates that a path does not include ninja variables, and that
892// each path component does not attempt to leave its component. Returns a joined
893// version of each path component.
Jeff Gaston734e3802017-04-10 15:47:24 -0700894func validatePath(ctx PathContext, pathComponents ...string) string {
895 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700896 if strings.Contains(path, "$") {
897 reportPathError(ctx, "Path contains invalid character($): %s", path)
898 return ""
899 }
900 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700901 return validateSafePath(ctx, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -0700902}
Colin Cross5b529592017-05-09 13:34:34 -0700903
Colin Cross0875c522017-11-28 17:34:01 -0800904func PathForPhony(ctx PathContext, phony string) WritablePath {
905 if strings.ContainsAny(phony, "$/") {
906 reportPathError(ctx, "Phony target contains invalid character ($ or /): %s", phony)
907 }
908 return OutputPath{basePath{phony, pathConfig(ctx), ""}}
909}
910
Colin Cross5b529592017-05-09 13:34:34 -0700911type testPath struct {
912 basePath
913}
914
915func (p testPath) String() string {
916 return p.path
917}
918
919func PathForTesting(paths ...string) Path {
920 p := validateSafePath(nil, paths...)
921 return testPath{basePath{path: p, rel: p}}
922}
923
924func PathsForTesting(strs []string) Paths {
925 p := make(Paths, len(strs))
926 for i, s := range strs {
927 p[i] = PathForTesting(s)
928 }
929
930 return p
931}