blob: cdcb7192e24c80d88e7a2b17c572439e41d49c46 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Colin Cross6e18ca42015-07-14 18:55:36 -070018 "fmt"
Colin Cross6a745c62015-06-16 16:38:10 -070019 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070020 "reflect"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070021 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070022 "strings"
23
24 "github.com/google/blueprint"
25 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080026)
27
Dan Willemsen34cc69e2015-09-23 15:26:20 -070028// PathContext is the subset of a (Module|Singleton)Context required by the
29// Path methods.
30type PathContext interface {
Colin Cross294941b2017-02-01 14:10:36 -080031 Fs() pathtools.FileSystem
Colin Crossaabf6792017-11-29 00:27:14 -080032 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080033 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080034}
35
Colin Cross7f19f372016-11-01 11:10:25 -070036type PathGlobContext interface {
37 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
38}
39
Colin Crossaabf6792017-11-29 00:27:14 -080040var _ PathContext = SingletonContext(nil)
41var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070042
Dan Willemsen00269f22017-07-06 16:59:48 -070043type ModuleInstallPathContext interface {
44 PathContext
45
46 androidBaseContext
47
48 InstallInData() bool
49 InstallInSanitizerDir() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +090050 InstallInRecovery() bool
Dan Willemsen00269f22017-07-06 16:59:48 -070051}
52
53var _ ModuleInstallPathContext = ModuleContext(nil)
54
Dan Willemsen34cc69e2015-09-23 15:26:20 -070055// errorfContext is the interface containing the Errorf method matching the
56// Errorf method in blueprint.SingletonContext.
57type errorfContext interface {
58 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080059}
60
Dan Willemsen34cc69e2015-09-23 15:26:20 -070061var _ errorfContext = blueprint.SingletonContext(nil)
62
63// moduleErrorf is the interface containing the ModuleErrorf method matching
64// the ModuleErrorf method in blueprint.ModuleContext.
65type moduleErrorf interface {
66 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080067}
68
Dan Willemsen34cc69e2015-09-23 15:26:20 -070069var _ moduleErrorf = blueprint.ModuleContext(nil)
70
Dan Willemsen34cc69e2015-09-23 15:26:20 -070071// reportPathError will register an error with the attached context. It
72// attempts ctx.ModuleErrorf for a better error message first, then falls
73// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -080074func reportPathError(ctx PathContext, err error) {
75 reportPathErrorf(ctx, "%s", err.Error())
76}
77
78// reportPathErrorf 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 reportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -070082 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
Colin Cross0db55682017-12-05 15:36:55 -0800103 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800104 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 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800132 reportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700133 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 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800142 reportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700143 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 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800153 reportPathErrorf(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 {
199 ret := make(Paths, len(paths))
200 for i, path := range paths {
201 ret[i] = PathForSource(ctx, path)
202 }
203 return ret
204}
205
Jeff Gaston734e3802017-04-10 15:47:24 -0700206// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800207// found in the tree. If any are not found, they are omitted from the list,
208// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800209func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800210 ret := make(Paths, 0, len(paths))
211 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800212 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800213 if p.Valid() {
214 ret = append(ret, p.Path())
215 }
216 }
217 return ret
218}
219
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700220// PathsForModuleSrc returns Paths rooted from the module's local source
221// directory
Colin Cross635c3b02016-05-18 15:37:25 -0700222func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800223 return PathsForModuleSrcExcludes(ctx, paths, nil)
224}
225
226func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
227 prefix := pathForModuleSrc(ctx).String()
228
229 var expandedExcludes []string
230 if excludes != nil {
231 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700232 }
Colin Cross8a497952019-03-05 22:25:09 -0800233
234 for _, e := range excludes {
235 if m := SrcIsModule(e); m != "" {
236 module := ctx.GetDirectDepWithTag(m, SourceDepTag)
237 if module == nil {
238 if ctx.Config().AllowMissingDependencies() {
239 ctx.AddMissingDependencies([]string{m})
240 } else {
241 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
242 }
243 continue
244 }
245 if srcProducer, ok := module.(SourceFileProducer); ok {
246 expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
247 } else {
248 ctx.ModuleErrorf("srcs dependency %q is not a source file producing module", m)
249 }
250 } else {
251 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
252 }
253 }
254
255 if paths == nil {
256 return nil
257 }
258
259 expandedSrcFiles := make(Paths, 0, len(paths))
260 for _, s := range paths {
261 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
262 if depErr, ok := err.(missingDependencyError); ok {
263 if ctx.Config().AllowMissingDependencies() {
264 ctx.AddMissingDependencies(depErr.missingDeps)
265 } else {
266 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
267 }
268 } else if err != nil {
269 reportPathError(ctx, err)
270 }
271 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
272 }
273 return expandedSrcFiles
274}
275
276type missingDependencyError struct {
277 missingDeps []string
278}
279
280func (e missingDependencyError) Error() string {
281 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
282}
283
284func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
285 if m := SrcIsModule(s); m != "" {
286 module := ctx.GetDirectDepWithTag(m, SourceDepTag)
287 if module == nil {
288 return nil, missingDependencyError{[]string{m}}
289 }
290 if srcProducer, ok := module.(SourceFileProducer); ok {
291 moduleSrcs := srcProducer.Srcs()
292 for _, e := range expandedExcludes {
293 for j := 0; j < len(moduleSrcs); j++ {
294 if moduleSrcs[j].String() == e {
295 moduleSrcs = append(moduleSrcs[:j], moduleSrcs[j+1:]...)
296 j--
297 }
298 }
299 }
300 return moduleSrcs, nil
301 } else {
302 return nil, fmt.Errorf("path dependency %q is not a source file producing module", m)
303 }
304 } else if pathtools.IsGlob(s) {
305 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
306 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
307 } else {
308 p := pathForModuleSrc(ctx, s)
309 if exists, _, err := ctx.Fs().Exists(p.String()); err != nil {
310 reportPathErrorf(ctx, "%s: %s", p, err.Error())
311 } else if !exists {
312 reportPathErrorf(ctx, "module source path %q does not exist", p)
313 }
314
315 j := findStringInSlice(p.String(), expandedExcludes)
316 if j >= 0 {
317 return nil, nil
318 }
319 return Paths{p}, nil
320 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700321}
322
323// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
324// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800325// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700326// It intended for use in globs that only list files that exist, so it allows '$' in
327// filenames.
Dan Willemsen540a78c2018-02-26 21:50:08 -0800328func pathsForModuleSrcFromFullPath(ctx ModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800329 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700330 if prefix == "./" {
331 prefix = ""
332 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700333 ret := make(Paths, 0, len(paths))
334 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800335 if !incDirs && strings.HasSuffix(p, "/") {
336 continue
337 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700338 path := filepath.Clean(p)
339 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800340 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700341 continue
342 }
Colin Crosse3924e12018-08-15 20:18:53 -0700343
Colin Crossfe4bc362018-09-12 10:02:13 -0700344 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700345 if err != nil {
346 reportPathError(ctx, err)
347 continue
348 }
349
Colin Cross07e51612019-03-05 12:46:40 -0800350 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700351
Colin Cross07e51612019-03-05 12:46:40 -0800352 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700353 }
354 return ret
355}
356
357// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800358// local source directory. If input is nil, use the default if it exists. If input is empty, returns nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700359func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800360 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700361 return PathsForModuleSrc(ctx, input)
362 }
363 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
364 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800365 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800366 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700367}
368
369// Strings returns the Paths in string form
370func (p Paths) Strings() []string {
371 if p == nil {
372 return nil
373 }
374 ret := make([]string, len(p))
375 for i, path := range p {
376 ret[i] = path.String()
377 }
378 return ret
379}
380
Colin Crossb6715442017-10-24 11:13:31 -0700381// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
382// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700383func FirstUniquePaths(list Paths) Paths {
384 k := 0
385outer:
386 for i := 0; i < len(list); i++ {
387 for j := 0; j < k; j++ {
388 if list[i] == list[j] {
389 continue outer
390 }
391 }
392 list[k] = list[i]
393 k++
394 }
395 return list[:k]
396}
397
Colin Crossb6715442017-10-24 11:13:31 -0700398// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
399// modifies the Paths slice contents in place, and returns a subslice of the original slice.
400func LastUniquePaths(list Paths) Paths {
401 totalSkip := 0
402 for i := len(list) - 1; i >= totalSkip; i-- {
403 skip := 0
404 for j := i - 1; j >= totalSkip; j-- {
405 if list[i] == list[j] {
406 skip++
407 } else {
408 list[j+skip] = list[j]
409 }
410 }
411 totalSkip += skip
412 }
413 return list[totalSkip:]
414}
415
Colin Crossa140bb02018-04-17 10:52:26 -0700416// ReversePaths returns a copy of a Paths in reverse order.
417func ReversePaths(list Paths) Paths {
418 if list == nil {
419 return nil
420 }
421 ret := make(Paths, len(list))
422 for i := range list {
423 ret[i] = list[len(list)-1-i]
424 }
425 return ret
426}
427
Jeff Gaston294356f2017-09-27 17:05:30 -0700428func indexPathList(s Path, list []Path) int {
429 for i, l := range list {
430 if l == s {
431 return i
432 }
433 }
434
435 return -1
436}
437
438func inPathList(p Path, list []Path) bool {
439 return indexPathList(p, list) != -1
440}
441
442func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
443 for _, l := range list {
444 if inPathList(l, filter) {
445 filtered = append(filtered, l)
446 } else {
447 remainder = append(remainder, l)
448 }
449 }
450
451 return
452}
453
Colin Cross93e85952017-08-15 13:34:18 -0700454// HasExt returns true of any of the paths have extension ext, otherwise false
455func (p Paths) HasExt(ext string) bool {
456 for _, path := range p {
457 if path.Ext() == ext {
458 return true
459 }
460 }
461
462 return false
463}
464
465// FilterByExt returns the subset of the paths that have extension ext
466func (p Paths) FilterByExt(ext string) Paths {
467 ret := make(Paths, 0, len(p))
468 for _, path := range p {
469 if path.Ext() == ext {
470 ret = append(ret, path)
471 }
472 }
473 return ret
474}
475
476// FilterOutByExt returns the subset of the paths that do not have extension ext
477func (p Paths) FilterOutByExt(ext string) Paths {
478 ret := make(Paths, 0, len(p))
479 for _, path := range p {
480 if path.Ext() != ext {
481 ret = append(ret, path)
482 }
483 }
484 return ret
485}
486
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700487// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
488// (including subdirectories) are in a contiguous subslice of the list, and can be found in
489// O(log(N)) time using a binary search on the directory prefix.
490type DirectorySortedPaths Paths
491
492func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
493 ret := append(DirectorySortedPaths(nil), paths...)
494 sort.Slice(ret, func(i, j int) bool {
495 return ret[i].String() < ret[j].String()
496 })
497 return ret
498}
499
500// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
501// that are in the specified directory and its subdirectories.
502func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
503 prefix := filepath.Clean(dir) + "/"
504 start := sort.Search(len(p), func(i int) bool {
505 return prefix < p[i].String()
506 })
507
508 ret := p[start:]
509
510 end := sort.Search(len(ret), func(i int) bool {
511 return !strings.HasPrefix(ret[i].String(), prefix)
512 })
513
514 ret = ret[:end]
515
516 return Paths(ret)
517}
518
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700519// WritablePaths is a slice of WritablePaths, used for multiple outputs.
520type WritablePaths []WritablePath
521
522// Strings returns the string forms of the writable paths.
523func (p WritablePaths) Strings() []string {
524 if p == nil {
525 return nil
526 }
527 ret := make([]string, len(p))
528 for i, path := range p {
529 ret[i] = path.String()
530 }
531 return ret
532}
533
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800534// Paths returns the WritablePaths as a Paths
535func (p WritablePaths) Paths() Paths {
536 if p == nil {
537 return nil
538 }
539 ret := make(Paths, len(p))
540 for i, path := range p {
541 ret[i] = path
542 }
543 return ret
544}
545
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700546type basePath struct {
547 path string
548 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800549 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700550}
551
552func (p basePath) Ext() string {
553 return filepath.Ext(p.path)
554}
555
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700556func (p basePath) Base() string {
557 return filepath.Base(p.path)
558}
559
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800560func (p basePath) Rel() string {
561 if p.rel != "" {
562 return p.rel
563 }
564 return p.path
565}
566
Colin Cross0875c522017-11-28 17:34:01 -0800567func (p basePath) String() string {
568 return p.path
569}
570
Colin Cross0db55682017-12-05 15:36:55 -0800571func (p basePath) withRel(rel string) basePath {
572 p.path = filepath.Join(p.path, rel)
573 p.rel = rel
574 return p
575}
576
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700577// SourcePath is a Path representing a file path rooted from SrcDir
578type SourcePath struct {
579 basePath
580}
581
582var _ Path = SourcePath{}
583
Colin Cross0db55682017-12-05 15:36:55 -0800584func (p SourcePath) withRel(rel string) SourcePath {
585 p.basePath = p.basePath.withRel(rel)
586 return p
587}
588
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700589// safePathForSource is for paths that we expect are safe -- only for use by go
590// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700591func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
592 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800593 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700594 if err != nil {
595 return ret, err
596 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700597
Colin Cross7b3dcc32019-01-24 13:14:39 -0800598 // absolute path already checked by validateSafePath
599 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800600 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700601 }
602
Colin Crossfe4bc362018-09-12 10:02:13 -0700603 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700604}
605
Colin Cross192e97a2018-02-22 14:21:02 -0800606// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
607func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000608 p, err := validatePath(pathComponents...)
609 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800610 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800611 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800612 }
613
Colin Cross7b3dcc32019-01-24 13:14:39 -0800614 // absolute path already checked by validatePath
615 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800616 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000617 }
618
Colin Cross192e97a2018-02-22 14:21:02 -0800619 return ret, nil
620}
621
622// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
623// path does not exist.
624func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
625 var files []string
626
627 if gctx, ok := ctx.(PathGlobContext); ok {
628 // Use glob to produce proper dependencies, even though we only want
629 // a single file.
630 files, err = gctx.GlobWithDeps(path.String(), nil)
631 } else {
632 var deps []string
633 // We cannot add build statements in this context, so we fall back to
634 // AddNinjaFileDeps
Colin Cross3f4d1162018-09-21 15:11:48 -0700635 files, deps, err = pathtools.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800636 ctx.AddNinjaFileDeps(deps...)
637 }
638
639 if err != nil {
640 return false, fmt.Errorf("glob: %s", err.Error())
641 }
642
643 return len(files) > 0, nil
644}
645
646// PathForSource joins the provided path components and validates that the result
647// neither escapes the source dir nor is in the out dir.
648// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
649func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
650 path, err := pathForSource(ctx, pathComponents...)
651 if err != nil {
652 reportPathError(ctx, err)
653 }
654
Colin Crosse3924e12018-08-15 20:18:53 -0700655 if pathtools.IsGlob(path.String()) {
656 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
657 }
658
Colin Cross192e97a2018-02-22 14:21:02 -0800659 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
660 exists, err := existsWithDependencies(ctx, path)
661 if err != nil {
662 reportPathError(ctx, err)
663 }
664 if !exists {
665 modCtx.AddMissingDependencies([]string{path.String()})
666 }
667 } else if exists, _, err := ctx.Fs().Exists(path.String()); err != nil {
668 reportPathErrorf(ctx, "%s: %s", path, err.Error())
669 } else if !exists {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800670 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800671 }
672 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700673}
674
Jeff Gaston734e3802017-04-10 15:47:24 -0700675// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700676// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
677// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800678func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800679 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800680 if err != nil {
681 reportPathError(ctx, err)
682 return OptionalPath{}
683 }
Colin Crossc48c1432018-02-23 07:09:01 +0000684
Colin Crosse3924e12018-08-15 20:18:53 -0700685 if pathtools.IsGlob(path.String()) {
686 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
687 return OptionalPath{}
688 }
689
Colin Cross192e97a2018-02-22 14:21:02 -0800690 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000691 if err != nil {
692 reportPathError(ctx, err)
693 return OptionalPath{}
694 }
Colin Cross192e97a2018-02-22 14:21:02 -0800695 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000696 return OptionalPath{}
697 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700698 return OptionalPathForPath(path)
699}
700
701func (p SourcePath) String() string {
702 return filepath.Join(p.config.srcDir, p.path)
703}
704
705// Join creates a new SourcePath with paths... joined with the current path. The
706// provided paths... may not use '..' to escape from the current path.
707func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800708 path, err := validatePath(paths...)
709 if err != nil {
710 reportPathError(ctx, err)
711 }
Colin Cross0db55682017-12-05 15:36:55 -0800712 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700713}
714
Colin Cross2fafa3e2019-03-05 12:39:51 -0800715// join is like Join but does less path validation.
716func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
717 path, err := validateSafePath(paths...)
718 if err != nil {
719 reportPathError(ctx, err)
720 }
721 return p.withRel(path)
722}
723
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700724// OverlayPath returns the overlay for `path' if it exists. This assumes that the
725// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700726func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700727 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800728 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700729 relDir = srcPath.path
730 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800731 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700732 return OptionalPath{}
733 }
734 dir := filepath.Join(p.config.srcDir, p.path, relDir)
735 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700736 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800737 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800738 }
Colin Cross461b4452018-02-23 09:22:42 -0800739 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700740 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800741 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700742 return OptionalPath{}
743 }
744 if len(paths) == 0 {
745 return OptionalPath{}
746 }
Colin Cross43f08db2018-11-12 10:13:39 -0800747 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700748 return OptionalPathForPath(PathForSource(ctx, relPath))
749}
750
751// OutputPath is a Path representing a file path rooted from the build directory
752type OutputPath struct {
753 basePath
754}
755
Colin Cross702e0f82017-10-18 17:27:54 -0700756func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800757 p.basePath = p.basePath.withRel(rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700758 return p
759}
760
Colin Cross3063b782018-08-15 11:19:12 -0700761func (p OutputPath) WithoutRel() OutputPath {
762 p.basePath.rel = filepath.Base(p.basePath.path)
763 return p
764}
765
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700766var _ Path = OutputPath{}
767
Jeff Gaston734e3802017-04-10 15:47:24 -0700768// PathForOutput joins the provided paths and returns an OutputPath that is
769// validated to not escape the build dir.
770// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
771func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800772 path, err := validatePath(pathComponents...)
773 if err != nil {
774 reportPathError(ctx, err)
775 }
Colin Crossaabf6792017-11-29 00:27:14 -0800776 return OutputPath{basePath{path, ctx.Config(), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700777}
778
Colin Cross40e33732019-02-15 11:08:35 -0800779// PathsForOutput returns Paths rooted from buildDir
780func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
781 ret := make(WritablePaths, len(paths))
782 for i, path := range paths {
783 ret[i] = PathForOutput(ctx, path)
784 }
785 return ret
786}
787
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700788func (p OutputPath) writablePath() {}
789
790func (p OutputPath) String() string {
791 return filepath.Join(p.config.buildDir, p.path)
792}
793
Colin Crossa2344662016-03-24 13:14:12 -0700794func (p OutputPath) RelPathString() string {
795 return p.path
796}
797
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700798// Join creates a new OutputPath with paths... joined with the current path. The
799// provided paths... may not use '..' to escape from the current path.
800func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800801 path, err := validatePath(paths...)
802 if err != nil {
803 reportPathError(ctx, err)
804 }
Colin Cross0db55682017-12-05 15:36:55 -0800805 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700806}
807
Colin Cross8854a5a2019-02-11 14:14:16 -0800808// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
809func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
810 if strings.Contains(ext, "/") {
811 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
812 }
813 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800814 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800815 return ret
816}
817
Colin Cross40e33732019-02-15 11:08:35 -0800818// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
819func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
820 path, err := validatePath(paths...)
821 if err != nil {
822 reportPathError(ctx, err)
823 }
824
825 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800826 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800827 return ret
828}
829
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700830// PathForIntermediates returns an OutputPath representing the top-level
831// intermediates directory.
832func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800833 path, err := validatePath(paths...)
834 if err != nil {
835 reportPathError(ctx, err)
836 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700837 return PathForOutput(ctx, ".intermediates", path)
838}
839
Colin Cross07e51612019-03-05 12:46:40 -0800840var _ genPathProvider = SourcePath{}
841var _ objPathProvider = SourcePath{}
842var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700843
Colin Cross07e51612019-03-05 12:46:40 -0800844// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700845// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800846func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
847 p, err := validatePath(pathComponents...)
848 if err != nil {
849 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800850 }
Colin Cross8a497952019-03-05 22:25:09 -0800851 paths, err := expandOneSrcPath(ctx, p, nil)
852 if err != nil {
853 if depErr, ok := err.(missingDependencyError); ok {
854 if ctx.Config().AllowMissingDependencies() {
855 ctx.AddMissingDependencies(depErr.missingDeps)
856 } else {
857 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
858 }
859 } else {
860 reportPathError(ctx, err)
861 }
862 return nil
863 } else if len(paths) == 0 {
864 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
865 return nil
866 } else if len(paths) > 1 {
867 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
868 }
869 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700870}
871
Colin Cross07e51612019-03-05 12:46:40 -0800872func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
873 p, err := validatePath(paths...)
874 if err != nil {
875 reportPathError(ctx, err)
876 }
877
878 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
879 if err != nil {
880 reportPathError(ctx, err)
881 }
882
883 path.basePath.rel = p
884
885 return path
886}
887
Colin Cross2fafa3e2019-03-05 12:39:51 -0800888// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
889// will return the path relative to subDir in the module's source directory. If any input paths are not located
890// inside subDir then a path error will be reported.
891func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
892 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -0800893 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800894 for i, path := range paths {
895 rel := Rel(ctx, subDirFullPath.String(), path.String())
896 paths[i] = subDirFullPath.join(ctx, rel)
897 }
898 return paths
899}
900
901// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
902// module's source directory. If the input path is not located inside subDir then a path error will be reported.
903func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -0800904 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800905 rel := Rel(ctx, subDirFullPath.String(), path.String())
906 return subDirFullPath.Join(ctx, rel)
907}
908
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700909// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
910// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700911func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700912 if p == nil {
913 return OptionalPath{}
914 }
915 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
916}
917
Colin Cross07e51612019-03-05 12:46:40 -0800918func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800919 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700920}
921
Colin Cross07e51612019-03-05 12:46:40 -0800922func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800923 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700924}
925
Colin Cross07e51612019-03-05 12:46:40 -0800926func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700927 // TODO: Use full directory if the new ctx is not the current ctx?
928 return PathForModuleRes(ctx, p.path, name)
929}
930
931// ModuleOutPath is a Path representing a module's output directory.
932type ModuleOutPath struct {
933 OutputPath
934}
935
936var _ Path = ModuleOutPath{}
937
Colin Cross702e0f82017-10-18 17:27:54 -0700938func pathForModule(ctx ModuleContext) OutputPath {
939 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
940}
941
Logan Chien7eefdc42018-07-11 18:10:41 +0800942// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
943// reference abi dump for the given module. This is not guaranteed to be valid.
944func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
945 isLlndk, isGzip bool) OptionalPath {
946
Jayant Chowdharyac066c62018-02-20 10:53:31 -0800947 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +0800948 if len(arches) == 0 {
949 panic("device build with no primary arch")
950 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -0800951 currentArch := ctx.Arch()
952 archNameAndVariant := currentArch.ArchType.String()
953 if currentArch.ArchVariant != "" {
954 archNameAndVariant += "_" + currentArch.ArchVariant
955 }
Logan Chien5237bed2018-07-11 17:15:57 +0800956
957 var dirName string
958 if isLlndk {
959 dirName = "ndk"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800960 } else {
Logan Chien5237bed2018-07-11 17:15:57 +0800961 dirName = "vndk"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800962 }
Logan Chien5237bed2018-07-11 17:15:57 +0800963
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -0800964 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +0800965
966 var ext string
967 if isGzip {
968 ext = ".lsdump.gz"
969 } else {
970 ext = ".lsdump"
971 }
972
973 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
974 version, binderBitness, archNameAndVariant, "source-based",
975 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800976}
977
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700978// PathForModuleOut returns a Path representing the paths... under the module's
979// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700980func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800981 p, err := validatePath(paths...)
982 if err != nil {
983 reportPathError(ctx, err)
984 }
Colin Cross702e0f82017-10-18 17:27:54 -0700985 return ModuleOutPath{
986 OutputPath: pathForModule(ctx).withRel(p),
987 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700988}
989
990// ModuleGenPath is a Path representing the 'gen' directory in a module's output
991// directory. Mainly used for generated sources.
992type ModuleGenPath struct {
993 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700994}
995
996var _ Path = ModuleGenPath{}
997var _ genPathProvider = ModuleGenPath{}
998var _ objPathProvider = ModuleGenPath{}
999
1000// PathForModuleGen returns a Path representing the paths... under the module's
1001// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001002func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001003 p, err := validatePath(paths...)
1004 if err != nil {
1005 reportPathError(ctx, err)
1006 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001007 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001008 ModuleOutPath: ModuleOutPath{
1009 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1010 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001011 }
1012}
1013
Dan Willemsen21ec4902016-11-02 20:43:13 -07001014func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001015 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001016 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001017}
1018
Colin Cross635c3b02016-05-18 15:37:25 -07001019func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001020 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1021}
1022
1023// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1024// directory. Used for compiled objects.
1025type ModuleObjPath struct {
1026 ModuleOutPath
1027}
1028
1029var _ Path = ModuleObjPath{}
1030
1031// PathForModuleObj returns a Path representing the paths... under the module's
1032// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001033func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001034 p, err := validatePath(pathComponents...)
1035 if err != nil {
1036 reportPathError(ctx, err)
1037 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001038 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1039}
1040
1041// ModuleResPath is a a Path representing the 'res' directory in a module's
1042// output directory.
1043type ModuleResPath struct {
1044 ModuleOutPath
1045}
1046
1047var _ Path = ModuleResPath{}
1048
1049// PathForModuleRes returns a Path representing the paths... under the module's
1050// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001051func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001052 p, err := validatePath(pathComponents...)
1053 if err != nil {
1054 reportPathError(ctx, err)
1055 }
1056
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001057 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1058}
1059
1060// PathForModuleInstall returns a Path representing the install path for the
1061// module appended with paths...
Dan Willemsen00269f22017-07-06 16:59:48 -07001062func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) OutputPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001063 var outPaths []string
1064 if ctx.Device() {
Colin Cross43f08db2018-11-12 10:13:39 -08001065 partition := modulePartition(ctx)
Colin Cross6510f912017-11-29 00:27:14 -08001066 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001067 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -07001068 switch ctx.Os() {
1069 case Linux:
1070 outPaths = []string{"host", "linux-x86"}
1071 case LinuxBionic:
1072 // TODO: should this be a separate top level, or shared with linux-x86?
1073 outPaths = []string{"host", "linux_bionic-x86"}
1074 default:
1075 outPaths = []string{"host", ctx.Os().String() + "-x86"}
1076 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001077 }
Dan Willemsen782a2d12015-12-21 14:55:28 -08001078 if ctx.Debug() {
1079 outPaths = append([]string{"debug"}, outPaths...)
1080 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001081 outPaths = append(outPaths, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001082 return PathForOutput(ctx, outPaths...)
1083}
1084
Colin Cross43f08db2018-11-12 10:13:39 -08001085func InstallPathToOnDevicePath(ctx PathContext, path OutputPath) string {
1086 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1087
1088 return "/" + rel
1089}
1090
1091func modulePartition(ctx ModuleInstallPathContext) string {
1092 var partition string
1093 if ctx.InstallInData() {
1094 partition = "data"
1095 } else if ctx.InstallInRecovery() {
1096 // the layout of recovery partion is the same as that of system partition
1097 partition = "recovery/root/system"
1098 } else if ctx.SocSpecific() {
1099 partition = ctx.DeviceConfig().VendorPath()
1100 } else if ctx.DeviceSpecific() {
1101 partition = ctx.DeviceConfig().OdmPath()
1102 } else if ctx.ProductSpecific() {
1103 partition = ctx.DeviceConfig().ProductPath()
1104 } else if ctx.ProductServicesSpecific() {
1105 partition = ctx.DeviceConfig().ProductServicesPath()
1106 } else {
1107 partition = "system"
1108 }
1109 if ctx.InstallInSanitizerDir() {
1110 partition = "data/asan/" + partition
1111 }
1112 return partition
1113}
1114
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001115// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001116// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001117func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001118 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001119 path := filepath.Clean(path)
1120 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001121 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001122 }
1123 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001124 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1125 // variables. '..' may remove the entire ninja variable, even if it
1126 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001127 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001128}
1129
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001130// validatePath validates that a path does not include ninja variables, and that
1131// each path component does not attempt to leave its component. Returns a joined
1132// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001133func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001134 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001135 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001136 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001137 }
1138 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001139 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001140}
Colin Cross5b529592017-05-09 13:34:34 -07001141
Colin Cross0875c522017-11-28 17:34:01 -08001142func PathForPhony(ctx PathContext, phony string) WritablePath {
1143 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001144 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001145 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001146 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001147}
1148
Colin Cross74e3fe42017-12-11 15:51:44 -08001149type PhonyPath struct {
1150 basePath
1151}
1152
1153func (p PhonyPath) writablePath() {}
1154
1155var _ Path = PhonyPath{}
1156var _ WritablePath = PhonyPath{}
1157
Colin Cross5b529592017-05-09 13:34:34 -07001158type testPath struct {
1159 basePath
1160}
1161
1162func (p testPath) String() string {
1163 return p.path
1164}
1165
Colin Cross40e33732019-02-15 11:08:35 -08001166type testWritablePath struct {
1167 testPath
1168}
1169
1170func (p testPath) writablePath() {}
1171
1172// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1173// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001174func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001175 p, err := validateSafePath(paths...)
1176 if err != nil {
1177 panic(err)
1178 }
Colin Cross5b529592017-05-09 13:34:34 -07001179 return testPath{basePath{path: p, rel: p}}
1180}
1181
Colin Cross40e33732019-02-15 11:08:35 -08001182// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1183func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001184 p := make(Paths, len(strs))
1185 for i, s := range strs {
1186 p[i] = PathForTesting(s)
1187 }
1188
1189 return p
1190}
Colin Cross43f08db2018-11-12 10:13:39 -08001191
Colin Cross40e33732019-02-15 11:08:35 -08001192// WritablePathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be
1193// used from within tests.
1194func WritablePathForTesting(paths ...string) WritablePath {
1195 p, err := validateSafePath(paths...)
1196 if err != nil {
1197 panic(err)
1198 }
1199 return testWritablePath{testPath{basePath{path: p, rel: p}}}
1200}
1201
1202// WritablePathsForTesting returns a Path constructed from each element in strs. It should only be used from within
1203// tests.
1204func WritablePathsForTesting(strs ...string) WritablePaths {
1205 p := make(WritablePaths, len(strs))
1206 for i, s := range strs {
1207 p[i] = WritablePathForTesting(s)
1208 }
1209
1210 return p
1211}
1212
1213type testPathContext struct {
1214 config Config
1215 fs pathtools.FileSystem
1216}
1217
1218func (x *testPathContext) Fs() pathtools.FileSystem { return x.fs }
1219func (x *testPathContext) Config() Config { return x.config }
1220func (x *testPathContext) AddNinjaFileDeps(...string) {}
1221
1222// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1223// PathForOutput.
1224func PathContextForTesting(config Config, fs map[string][]byte) PathContext {
1225 return &testPathContext{
1226 config: config,
1227 fs: pathtools.MockFs(fs),
1228 }
1229}
1230
Colin Cross43f08db2018-11-12 10:13:39 -08001231// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1232// targetPath is not inside basePath.
1233func Rel(ctx PathContext, basePath string, targetPath string) string {
1234 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1235 if !isRel {
1236 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1237 return ""
1238 }
1239 return rel
1240}
1241
1242// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1243// targetPath is not inside basePath.
1244func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
1245 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1246 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
1247 return "", false
1248 }
1249 rel, err := filepath.Rel(basePath, targetPath)
1250 if err != nil {
1251 reportPathError(ctx, err)
1252 return "", false
1253 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
1254 return "", false
1255 }
1256 return rel, true
1257}