blob: d6a1c668469c91a62a00133ec4b4adf92e8e9504 [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"
21 "strings"
22
23 "github.com/google/blueprint"
24 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080025)
26
Dan Willemsen34cc69e2015-09-23 15:26:20 -070027// PathContext is the subset of a (Module|Singleton)Context required by the
28// Path methods.
29type PathContext interface {
Colin Cross294941b2017-02-01 14:10:36 -080030 Fs() pathtools.FileSystem
Dan Willemsen34cc69e2015-09-23 15:26:20 -070031 Config() interface{}
Dan Willemsen7b310ee2015-12-18 15:11:17 -080032 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080033}
34
Colin Cross7f19f372016-11-01 11:10:25 -070035type PathGlobContext interface {
36 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
37}
38
Dan Willemsen34cc69e2015-09-23 15:26:20 -070039var _ PathContext = blueprint.SingletonContext(nil)
40var _ PathContext = blueprint.ModuleContext(nil)
41
Dan Willemsen00269f22017-07-06 16:59:48 -070042type ModuleInstallPathContext interface {
43 PathContext
44
45 androidBaseContext
46
47 InstallInData() bool
48 InstallInSanitizerDir() bool
49}
50
51var _ ModuleInstallPathContext = ModuleContext(nil)
52
Dan Willemsen34cc69e2015-09-23 15:26:20 -070053// errorfContext is the interface containing the Errorf method matching the
54// Errorf method in blueprint.SingletonContext.
55type errorfContext interface {
56 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080057}
58
Dan Willemsen34cc69e2015-09-23 15:26:20 -070059var _ errorfContext = blueprint.SingletonContext(nil)
60
61// moduleErrorf is the interface containing the ModuleErrorf method matching
62// the ModuleErrorf method in blueprint.ModuleContext.
63type moduleErrorf interface {
64 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080065}
66
Dan Willemsen34cc69e2015-09-23 15:26:20 -070067var _ moduleErrorf = blueprint.ModuleContext(nil)
68
69// pathConfig returns the android Config interface associated to the context.
70// Panics if the context isn't affiliated with an android build.
71func pathConfig(ctx PathContext) Config {
72 if ret, ok := ctx.Config().(Config); ok {
73 return ret
74 }
75 panic("Paths may only be used on Soong builds")
Colin Cross3f40fa42015-01-30 17:27:36 -080076}
77
Dan Willemsen34cc69e2015-09-23 15:26:20 -070078// reportPathError will register an error with the attached context. It
79// attempts ctx.ModuleErrorf for a better error message first, then falls
80// back to ctx.Errorf.
81func reportPathError(ctx PathContext, format string, args ...interface{}) {
82 if mctx, ok := ctx.(moduleErrorf); ok {
83 mctx.ModuleErrorf(format, args...)
84 } else if ectx, ok := ctx.(errorfContext); ok {
85 ectx.Errorf(format, args...)
86 } else {
87 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -070088 }
89}
90
Dan Willemsen34cc69e2015-09-23 15:26:20 -070091type Path interface {
92 // Returns the path in string form
93 String() string
94
Colin Cross4f6fc9c2016-10-26 10:05:25 -070095 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -070096 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -070097
98 // Base returns the last element of the path
99 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800100
101 // Rel returns the portion of the path relative to the directory it was created from. For
102 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
103 // directory.
104 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700105}
106
107// WritablePath is a type of path that can be used as an output for build rules.
108type WritablePath interface {
109 Path
110
Jeff Gaston734e3802017-04-10 15:47:24 -0700111 // the writablePath method doesn't directly do anything,
112 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700113 writablePath()
114}
115
116type genPathProvider interface {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700117 genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700118}
119type objPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700120 objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700121}
122type resPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700123 resPathWithName(ctx ModuleContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700124}
125
126// GenPathWithExt derives a new file path in ctx's generated sources directory
127// from the current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700128func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700129 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700130 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700131 }
132 reportPathError(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
133 return PathForModuleGen(ctx)
134}
135
136// ObjPathWithExt derives a new file path in ctx's object directory from the
137// current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700138func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700139 if path, ok := p.(objPathProvider); ok {
140 return path.objPathWithExt(ctx, subdir, ext)
141 }
142 reportPathError(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
143 return PathForModuleObj(ctx)
144}
145
146// ResPathWithName derives a new path in ctx's output resource directory, using
147// the current path to create the directory name, and the `name` argument for
148// the filename.
Colin Cross635c3b02016-05-18 15:37:25 -0700149func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700150 if path, ok := p.(resPathProvider); ok {
151 return path.resPathWithName(ctx, name)
152 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700153 reportPathError(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700154 return PathForModuleRes(ctx)
155}
156
157// OptionalPath is a container that may or may not contain a valid Path.
158type OptionalPath struct {
159 valid bool
160 path Path
161}
162
163// OptionalPathForPath returns an OptionalPath containing the path.
164func OptionalPathForPath(path Path) OptionalPath {
165 if path == nil {
166 return OptionalPath{}
167 }
168 return OptionalPath{valid: true, path: path}
169}
170
171// Valid returns whether there is a valid path
172func (p OptionalPath) Valid() bool {
173 return p.valid
174}
175
176// Path returns the Path embedded in this OptionalPath. You must be sure that
177// there is a valid path, since this method will panic if there is not.
178func (p OptionalPath) Path() Path {
179 if !p.valid {
180 panic("Requesting an invalid path")
181 }
182 return p.path
183}
184
185// String returns the string version of the Path, or "" if it isn't valid.
186func (p OptionalPath) String() string {
187 if p.valid {
188 return p.path.String()
189 } else {
190 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700191 }
192}
Colin Cross6e18ca42015-07-14 18:55:36 -0700193
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700194// Paths is a slice of Path objects, with helpers to operate on the collection.
195type Paths []Path
196
197// PathsForSource returns Paths rooted from SrcDir
198func PathsForSource(ctx PathContext, paths []string) Paths {
Dan Willemsene23dfb72016-03-11 15:02:46 -0800199 if pathConfig(ctx).AllowMissingDependencies() {
Colin Cross635c3b02016-05-18 15:37:25 -0700200 if modCtx, ok := ctx.(ModuleContext); ok {
Dan Willemsene23dfb72016-03-11 15:02:46 -0800201 ret := make(Paths, 0, len(paths))
Colin Cross702e0f82017-10-18 17:27:54 -0700202 intermediates := pathForModule(modCtx).withRel("missing")
Dan Willemsene23dfb72016-03-11 15:02:46 -0800203 for _, path := range paths {
Colin Cross702e0f82017-10-18 17:27:54 -0700204 p := ExistentPathForSource(ctx, intermediates.String(), path)
Dan Willemsene23dfb72016-03-11 15:02:46 -0800205 if p.Valid() {
206 ret = append(ret, p.Path())
207 } else {
208 modCtx.AddMissingDependencies([]string{path})
209 }
210 }
211 return ret
212 }
213 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700214 ret := make(Paths, len(paths))
215 for i, path := range paths {
216 ret[i] = PathForSource(ctx, path)
217 }
218 return ret
219}
220
Jeff Gaston734e3802017-04-10 15:47:24 -0700221// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800222// found in the tree. If any are not found, they are omitted from the list,
223// and dependencies are added so that we're re-run when they are added.
Jeff Gaston734e3802017-04-10 15:47:24 -0700224func ExistentPathsForSources(ctx PathContext, intermediates string, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800225 ret := make(Paths, 0, len(paths))
226 for _, path := range paths {
Jeff Gaston734e3802017-04-10 15:47:24 -0700227 p := ExistentPathForSource(ctx, intermediates, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800228 if p.Valid() {
229 ret = append(ret, p.Path())
230 }
231 }
232 return ret
233}
234
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700235// PathsForModuleSrc returns Paths rooted from the module's local source
236// directory
Colin Cross635c3b02016-05-18 15:37:25 -0700237func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700238 ret := make(Paths, len(paths))
239 for i, path := range paths {
240 ret[i] = PathForModuleSrc(ctx, path)
241 }
242 return ret
243}
244
245// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
246// source directory, but strip the local source directory from the beginning of
247// each string.
Colin Cross635c3b02016-05-18 15:37:25 -0700248func pathsForModuleSrcFromFullPath(ctx ModuleContext, paths []string) Paths {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700249 prefix := filepath.Join(ctx.AConfig().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700250 if prefix == "./" {
251 prefix = ""
252 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700253 ret := make(Paths, 0, len(paths))
254 for _, p := range paths {
255 path := filepath.Clean(p)
256 if !strings.HasPrefix(path, prefix) {
257 reportPathError(ctx, "Path '%s' is not in module source directory '%s'", p, prefix)
258 continue
259 }
260 ret = append(ret, PathForModuleSrc(ctx, path[len(prefix):]))
261 }
262 return ret
263}
264
265// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
266// local source directory. If none are provided, use the default if it exists.
Colin Cross635c3b02016-05-18 15:37:25 -0700267func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700268 if len(input) > 0 {
269 return PathsForModuleSrc(ctx, input)
270 }
271 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
272 // is created, we're run again.
273 path := filepath.Join(ctx.AConfig().srcDir, ctx.ModuleDir(), def)
Colin Cross7f19f372016-11-01 11:10:25 -0700274 return ctx.Glob(path, []string{})
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700275}
276
277// Strings returns the Paths in string form
278func (p Paths) Strings() []string {
279 if p == nil {
280 return nil
281 }
282 ret := make([]string, len(p))
283 for i, path := range p {
284 ret[i] = path.String()
285 }
286 return ret
287}
288
Colin Crossb6715442017-10-24 11:13:31 -0700289// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
290// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700291func FirstUniquePaths(list Paths) Paths {
292 k := 0
293outer:
294 for i := 0; i < len(list); i++ {
295 for j := 0; j < k; j++ {
296 if list[i] == list[j] {
297 continue outer
298 }
299 }
300 list[k] = list[i]
301 k++
302 }
303 return list[:k]
304}
305
Colin Crossb6715442017-10-24 11:13:31 -0700306// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
307// modifies the Paths slice contents in place, and returns a subslice of the original slice.
308func LastUniquePaths(list Paths) Paths {
309 totalSkip := 0
310 for i := len(list) - 1; i >= totalSkip; i-- {
311 skip := 0
312 for j := i - 1; j >= totalSkip; j-- {
313 if list[i] == list[j] {
314 skip++
315 } else {
316 list[j+skip] = list[j]
317 }
318 }
319 totalSkip += skip
320 }
321 return list[totalSkip:]
322}
323
Jeff Gaston294356f2017-09-27 17:05:30 -0700324func indexPathList(s Path, list []Path) int {
325 for i, l := range list {
326 if l == s {
327 return i
328 }
329 }
330
331 return -1
332}
333
334func inPathList(p Path, list []Path) bool {
335 return indexPathList(p, list) != -1
336}
337
338func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
339 for _, l := range list {
340 if inPathList(l, filter) {
341 filtered = append(filtered, l)
342 } else {
343 remainder = append(remainder, l)
344 }
345 }
346
347 return
348}
349
Colin Cross93e85952017-08-15 13:34:18 -0700350// HasExt returns true of any of the paths have extension ext, otherwise false
351func (p Paths) HasExt(ext string) bool {
352 for _, path := range p {
353 if path.Ext() == ext {
354 return true
355 }
356 }
357
358 return false
359}
360
361// FilterByExt returns the subset of the paths that have extension ext
362func (p Paths) FilterByExt(ext string) Paths {
363 ret := make(Paths, 0, len(p))
364 for _, path := range p {
365 if path.Ext() == ext {
366 ret = append(ret, path)
367 }
368 }
369 return ret
370}
371
372// FilterOutByExt returns the subset of the paths that do not have extension ext
373func (p Paths) FilterOutByExt(ext string) Paths {
374 ret := make(Paths, 0, len(p))
375 for _, path := range p {
376 if path.Ext() != ext {
377 ret = append(ret, path)
378 }
379 }
380 return ret
381}
382
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700383// WritablePaths is a slice of WritablePaths, used for multiple outputs.
384type WritablePaths []WritablePath
385
386// Strings returns the string forms of the writable paths.
387func (p WritablePaths) Strings() []string {
388 if p == nil {
389 return nil
390 }
391 ret := make([]string, len(p))
392 for i, path := range p {
393 ret[i] = path.String()
394 }
395 return ret
396}
397
398type basePath struct {
399 path string
400 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800401 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700402}
403
404func (p basePath) Ext() string {
405 return filepath.Ext(p.path)
406}
407
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700408func (p basePath) Base() string {
409 return filepath.Base(p.path)
410}
411
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800412func (p basePath) Rel() string {
413 if p.rel != "" {
414 return p.rel
415 }
416 return p.path
417}
418
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700419// SourcePath is a Path representing a file path rooted from SrcDir
420type SourcePath struct {
421 basePath
422}
423
424var _ Path = SourcePath{}
425
426// safePathForSource is for paths that we expect are safe -- only for use by go
427// code that is embedding ninja variables in paths
428func safePathForSource(ctx PathContext, path string) SourcePath {
429 p := validateSafePath(ctx, path)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800430 ret := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700431
432 abs, err := filepath.Abs(ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700433 if err != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700434 reportPathError(ctx, "%s", err.Error())
435 return ret
436 }
437 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
438 if err != nil {
439 reportPathError(ctx, "%s", err.Error())
440 return ret
441 }
442 if strings.HasPrefix(abs, buildroot) {
443 reportPathError(ctx, "source path %s is in output", abs)
444 return ret
Colin Cross6e18ca42015-07-14 18:55:36 -0700445 }
446
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700447 return ret
448}
449
Jeff Gaston734e3802017-04-10 15:47:24 -0700450// PathForSource joins the provided path components and validates that the result
451// neither escapes the source dir nor is in the out dir.
452// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
453func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
454 p := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800455 ret := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700456
457 abs, err := filepath.Abs(ret.String())
458 if err != nil {
459 reportPathError(ctx, "%s", err.Error())
460 return ret
461 }
462 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
463 if err != nil {
464 reportPathError(ctx, "%s", err.Error())
465 return ret
466 }
467 if strings.HasPrefix(abs, buildroot) {
468 reportPathError(ctx, "source path %s is in output", abs)
469 return ret
470 }
471
Colin Cross294941b2017-02-01 14:10:36 -0800472 if exists, _, err := ctx.Fs().Exists(ret.String()); err != nil {
473 reportPathError(ctx, "%s: %s", ret, err.Error())
474 } else if !exists {
475 reportPathError(ctx, "source path %s does not exist", ret)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700476 }
477 return ret
478}
479
Jeff Gaston734e3802017-04-10 15:47:24 -0700480// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700481// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
482// so that the ninja file will be regenerated if the state of the path changes.
Jeff Gaston734e3802017-04-10 15:47:24 -0700483func ExistentPathForSource(ctx PathContext, intermediates string, pathComponents ...string) OptionalPath {
484 if len(pathComponents) == 0 {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800485 // For when someone forgets the 'intermediates' argument
486 panic("Missing path(s)")
487 }
488
Jeff Gaston734e3802017-04-10 15:47:24 -0700489 p := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800490 path := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700491
492 abs, err := filepath.Abs(path.String())
493 if err != nil {
494 reportPathError(ctx, "%s", err.Error())
495 return OptionalPath{}
496 }
497 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
498 if err != nil {
499 reportPathError(ctx, "%s", err.Error())
500 return OptionalPath{}
501 }
502 if strings.HasPrefix(abs, buildroot) {
503 reportPathError(ctx, "source path %s is in output", abs)
504 return OptionalPath{}
505 }
506
Colin Cross7f19f372016-11-01 11:10:25 -0700507 if pathtools.IsGlob(path.String()) {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800508 reportPathError(ctx, "path may not contain a glob: %s", path.String())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700509 return OptionalPath{}
510 }
511
Colin Cross7f19f372016-11-01 11:10:25 -0700512 if gctx, ok := ctx.(PathGlobContext); ok {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800513 // Use glob to produce proper dependencies, even though we only want
514 // a single file.
Colin Cross7f19f372016-11-01 11:10:25 -0700515 files, err := gctx.GlobWithDeps(path.String(), nil)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800516 if err != nil {
517 reportPathError(ctx, "glob: %s", err.Error())
518 return OptionalPath{}
519 }
520
521 if len(files) == 0 {
522 return OptionalPath{}
523 }
524 } else {
525 // We cannot add build statements in this context, so we fall back to
526 // AddNinjaFileDeps
Colin Cross294941b2017-02-01 14:10:36 -0800527 files, dirs, err := pathtools.Glob(path.String(), nil)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800528 if err != nil {
529 reportPathError(ctx, "glob: %s", err.Error())
530 return OptionalPath{}
531 }
532
533 ctx.AddNinjaFileDeps(dirs...)
534
535 if len(files) == 0 {
536 return OptionalPath{}
537 }
538
539 ctx.AddNinjaFileDeps(path.String())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700540 }
541 return OptionalPathForPath(path)
542}
543
544func (p SourcePath) String() string {
545 return filepath.Join(p.config.srcDir, p.path)
546}
547
548// Join creates a new SourcePath with paths... joined with the current path. The
549// provided paths... may not use '..' to escape from the current path.
550func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
551 path := validatePath(ctx, paths...)
552 return PathForSource(ctx, p.path, path)
553}
554
555// OverlayPath returns the overlay for `path' if it exists. This assumes that the
556// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700557func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700558 var relDir string
559 if moduleSrcPath, ok := path.(ModuleSrcPath); ok {
Colin Cross7fc17db2017-02-01 14:07:55 -0800560 relDir = moduleSrcPath.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700561 } else if srcPath, ok := path.(SourcePath); ok {
562 relDir = srcPath.path
563 } else {
564 reportPathError(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
565 return OptionalPath{}
566 }
567 dir := filepath.Join(p.config.srcDir, p.path, relDir)
568 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700569 if pathtools.IsGlob(dir) {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800570 reportPathError(ctx, "Path may not contain a glob: %s", dir)
571 }
Colin Cross7f19f372016-11-01 11:10:25 -0700572 paths, err := ctx.GlobWithDeps(dir, []string{})
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700573 if err != nil {
574 reportPathError(ctx, "glob: %s", err.Error())
575 return OptionalPath{}
576 }
577 if len(paths) == 0 {
578 return OptionalPath{}
579 }
580 relPath, err := filepath.Rel(p.config.srcDir, paths[0])
581 if err != nil {
582 reportPathError(ctx, "%s", err.Error())
583 return OptionalPath{}
584 }
585 return OptionalPathForPath(PathForSource(ctx, relPath))
586}
587
588// OutputPath is a Path representing a file path rooted from the build directory
589type OutputPath struct {
590 basePath
591}
592
Colin Cross702e0f82017-10-18 17:27:54 -0700593func (p OutputPath) withRel(rel string) OutputPath {
594 p.basePath.path = filepath.Join(p.basePath.path, rel)
595 p.basePath.rel = rel
596 return p
597}
598
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700599var _ Path = OutputPath{}
600
Jeff Gaston734e3802017-04-10 15:47:24 -0700601// PathForOutput joins the provided paths and returns an OutputPath that is
602// validated to not escape the build dir.
603// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
604func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
605 path := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800606 return OutputPath{basePath{path, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700607}
608
609func (p OutputPath) writablePath() {}
610
611func (p OutputPath) String() string {
612 return filepath.Join(p.config.buildDir, p.path)
613}
614
Colin Crossa2344662016-03-24 13:14:12 -0700615func (p OutputPath) RelPathString() string {
616 return p.path
617}
618
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700619// Join creates a new OutputPath with paths... joined with the current path. The
620// provided paths... may not use '..' to escape from the current path.
621func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
622 path := validatePath(ctx, paths...)
623 return PathForOutput(ctx, p.path, path)
624}
625
626// PathForIntermediates returns an OutputPath representing the top-level
627// intermediates directory.
628func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
629 path := validatePath(ctx, paths...)
630 return PathForOutput(ctx, ".intermediates", path)
631}
632
633// ModuleSrcPath is a Path representing a file rooted from a module's local source dir
634type ModuleSrcPath struct {
Colin Cross7fc17db2017-02-01 14:07:55 -0800635 SourcePath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700636}
637
638var _ Path = ModuleSrcPath{}
639var _ genPathProvider = ModuleSrcPath{}
640var _ objPathProvider = ModuleSrcPath{}
641var _ resPathProvider = ModuleSrcPath{}
642
643// PathForModuleSrc returns a ModuleSrcPath representing the paths... under the
644// module's local source directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700645func PathForModuleSrc(ctx ModuleContext, paths ...string) ModuleSrcPath {
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800646 p := validatePath(ctx, paths...)
647 path := ModuleSrcPath{PathForSource(ctx, ctx.ModuleDir(), p)}
648 path.basePath.rel = p
649 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700650}
651
652// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
653// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700654func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700655 if p == nil {
656 return OptionalPath{}
657 }
658 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
659}
660
Dan Willemsen21ec4902016-11-02 20:43:13 -0700661func (p ModuleSrcPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800662 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700663}
664
Colin Cross635c3b02016-05-18 15:37:25 -0700665func (p ModuleSrcPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800666 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700667}
668
Colin Cross635c3b02016-05-18 15:37:25 -0700669func (p ModuleSrcPath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700670 // TODO: Use full directory if the new ctx is not the current ctx?
671 return PathForModuleRes(ctx, p.path, name)
672}
673
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800674func (p ModuleSrcPath) WithSubDir(ctx ModuleContext, subdir string) ModuleSrcPath {
675 subdir = PathForModuleSrc(ctx, subdir).String()
676 var err error
677 rel, err := filepath.Rel(subdir, p.path)
678 if err != nil {
679 ctx.ModuleErrorf("source file %q is not under path %q", p.path, subdir)
680 return p
681 }
682 p.rel = rel
683 return p
684}
685
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700686// ModuleOutPath is a Path representing a module's output directory.
687type ModuleOutPath struct {
688 OutputPath
689}
690
691var _ Path = ModuleOutPath{}
692
Colin Cross702e0f82017-10-18 17:27:54 -0700693func pathForModule(ctx ModuleContext) OutputPath {
694 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
695}
696
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800697// PathForVndkRefDump returns an OptionalPath representing the path of the reference
698// abi dump for the given module. This is not guaranteed to be valid.
699func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string, vndkOrNdk, isSourceDump bool) OptionalPath {
700 archName := ctx.Arch().ArchType.Name
701 var sourceOrBinaryDir string
702 var vndkOrNdkDir string
703 var ext string
704 if isSourceDump {
Jayant Chowdhary715cac32017-04-20 06:53:59 -0700705 ext = ".lsdump.gz"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800706 sourceOrBinaryDir = "source-based"
707 } else {
Jayant Chowdhary715cac32017-04-20 06:53:59 -0700708 ext = ".bdump.gz"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800709 sourceOrBinaryDir = "binary-based"
710 }
711 if vndkOrNdk {
712 vndkOrNdkDir = "vndk"
713 } else {
714 vndkOrNdkDir = "ndk"
715 }
716 refDumpFileStr := "prebuilts/abi-dumps/" + vndkOrNdkDir + "/" + version + "/" +
717 archName + "/" + sourceOrBinaryDir + "/" + fileName + ext
Jeff Gaston734e3802017-04-10 15:47:24 -0700718 return ExistentPathForSource(ctx, "", refDumpFileStr)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800719}
720
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700721// PathForModuleOut returns a Path representing the paths... under the module's
722// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700723func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700724 p := validatePath(ctx, paths...)
Colin Cross702e0f82017-10-18 17:27:54 -0700725 return ModuleOutPath{
726 OutputPath: pathForModule(ctx).withRel(p),
727 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700728}
729
730// ModuleGenPath is a Path representing the 'gen' directory in a module's output
731// directory. Mainly used for generated sources.
732type ModuleGenPath struct {
733 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700734}
735
736var _ Path = ModuleGenPath{}
737var _ genPathProvider = ModuleGenPath{}
738var _ objPathProvider = ModuleGenPath{}
739
740// PathForModuleGen returns a Path representing the paths... under the module's
741// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700742func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700743 p := validatePath(ctx, paths...)
744 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -0700745 ModuleOutPath: ModuleOutPath{
746 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
747 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700748 }
749}
750
Dan Willemsen21ec4902016-11-02 20:43:13 -0700751func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700752 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -0700753 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700754}
755
Colin Cross635c3b02016-05-18 15:37:25 -0700756func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700757 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
758}
759
760// ModuleObjPath is a Path representing the 'obj' directory in a module's output
761// directory. Used for compiled objects.
762type ModuleObjPath struct {
763 ModuleOutPath
764}
765
766var _ Path = ModuleObjPath{}
767
768// PathForModuleObj returns a Path representing the paths... under the module's
769// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700770func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
771 p := validatePath(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700772 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
773}
774
775// ModuleResPath is a a Path representing the 'res' directory in a module's
776// output directory.
777type ModuleResPath struct {
778 ModuleOutPath
779}
780
781var _ Path = ModuleResPath{}
782
783// PathForModuleRes returns a Path representing the paths... under the module's
784// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700785func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
786 p := validatePath(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700787 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
788}
789
790// PathForModuleInstall returns a Path representing the install path for the
791// module appended with paths...
Dan Willemsen00269f22017-07-06 16:59:48 -0700792func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) OutputPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700793 var outPaths []string
794 if ctx.Device() {
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700795 var partition string
Dan Willemsen00269f22017-07-06 16:59:48 -0700796 if ctx.InstallInData() {
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700797 partition = "data"
Jeff Gastonaf3cc2d2017-09-27 17:01:44 -0700798 } else if ctx.InstallOnVendorPartition() {
Dan Willemsen00269f22017-07-06 16:59:48 -0700799 partition = ctx.DeviceConfig().VendorPath()
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700800 } else {
801 partition = "system"
Dan Willemsen782a2d12015-12-21 14:55:28 -0800802 }
Vishwath Mohan1dd88392017-03-29 22:00:18 -0700803
804 if ctx.InstallInSanitizerDir() {
805 partition = "data/asan/" + partition
Dan Willemsen782a2d12015-12-21 14:55:28 -0800806 }
807 outPaths = []string{"target", "product", ctx.AConfig().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700808 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -0700809 switch ctx.Os() {
810 case Linux:
811 outPaths = []string{"host", "linux-x86"}
812 case LinuxBionic:
813 // TODO: should this be a separate top level, or shared with linux-x86?
814 outPaths = []string{"host", "linux_bionic-x86"}
815 default:
816 outPaths = []string{"host", ctx.Os().String() + "-x86"}
817 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700818 }
Dan Willemsen782a2d12015-12-21 14:55:28 -0800819 if ctx.Debug() {
820 outPaths = append([]string{"debug"}, outPaths...)
821 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700822 outPaths = append(outPaths, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700823 return PathForOutput(ctx, outPaths...)
824}
825
826// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800827// Ensures that each path component does not attempt to leave its component.
Jeff Gaston734e3802017-04-10 15:47:24 -0700828func validateSafePath(ctx PathContext, pathComponents ...string) string {
829 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800830 path := filepath.Clean(path)
831 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
832 reportPathError(ctx, "Path is outside directory: %s", path)
833 return ""
834 }
835 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700836 // TODO: filepath.Join isn't necessarily correct with embedded ninja
837 // variables. '..' may remove the entire ninja variable, even if it
838 // will be expanded to multiple nested directories.
Jeff Gaston734e3802017-04-10 15:47:24 -0700839 return filepath.Join(pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700840}
841
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800842// validatePath validates that a path does not include ninja variables, and that
843// each path component does not attempt to leave its component. Returns a joined
844// version of each path component.
Jeff Gaston734e3802017-04-10 15:47:24 -0700845func validatePath(ctx PathContext, pathComponents ...string) string {
846 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700847 if strings.Contains(path, "$") {
848 reportPathError(ctx, "Path contains invalid character($): %s", path)
849 return ""
850 }
851 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700852 return validateSafePath(ctx, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -0700853}
Colin Cross5b529592017-05-09 13:34:34 -0700854
855type testPath struct {
856 basePath
857}
858
859func (p testPath) String() string {
860 return p.path
861}
862
863func PathForTesting(paths ...string) Path {
864 p := validateSafePath(nil, paths...)
865 return testPath{basePath{path: p, rel: p}}
866}
867
868func PathsForTesting(strs []string) Paths {
869 p := make(Paths, len(strs))
870 for i, s := range strs {
871 p[i] = PathForTesting(s)
872 }
873
874 return p
875}