blob: a0ea7535bc17511346633d0ac80604c9156dee86 [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 {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700223 ret := make(Paths, len(paths))
224 for i, path := range paths {
225 ret[i] = PathForModuleSrc(ctx, path)
226 }
227 return ret
228}
229
230// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
231// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800232// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700233// It intended for use in globs that only list files that exist, so it allows '$' in
234// filenames.
Dan Willemsen540a78c2018-02-26 21:50:08 -0800235func pathsForModuleSrcFromFullPath(ctx ModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800236 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700237 if prefix == "./" {
238 prefix = ""
239 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700240 ret := make(Paths, 0, len(paths))
241 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800242 if !incDirs && strings.HasSuffix(p, "/") {
243 continue
244 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700245 path := filepath.Clean(p)
246 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800247 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700248 continue
249 }
Colin Crosse3924e12018-08-15 20:18:53 -0700250
Colin Crossfe4bc362018-09-12 10:02:13 -0700251 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700252 if err != nil {
253 reportPathError(ctx, err)
254 continue
255 }
256
257 moduleSrcPath := ModuleSrcPath{srcPath}
258 moduleSrcPath.basePath.rel = srcPath.path
259
260 ret = append(ret, moduleSrcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700261 }
262 return ret
263}
264
265// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800266// 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 -0700267func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800268 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700269 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.
Colin Cross6510f912017-11-29 00:27:14 -0800273 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800274 return ctx.Glob(path, nil)
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
Colin Crossa140bb02018-04-17 10:52:26 -0700324// ReversePaths returns a copy of a Paths in reverse order.
325func ReversePaths(list Paths) Paths {
326 if list == nil {
327 return nil
328 }
329 ret := make(Paths, len(list))
330 for i := range list {
331 ret[i] = list[len(list)-1-i]
332 }
333 return ret
334}
335
Jeff Gaston294356f2017-09-27 17:05:30 -0700336func indexPathList(s Path, list []Path) int {
337 for i, l := range list {
338 if l == s {
339 return i
340 }
341 }
342
343 return -1
344}
345
346func inPathList(p Path, list []Path) bool {
347 return indexPathList(p, list) != -1
348}
349
350func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
351 for _, l := range list {
352 if inPathList(l, filter) {
353 filtered = append(filtered, l)
354 } else {
355 remainder = append(remainder, l)
356 }
357 }
358
359 return
360}
361
Colin Cross93e85952017-08-15 13:34:18 -0700362// HasExt returns true of any of the paths have extension ext, otherwise false
363func (p Paths) HasExt(ext string) bool {
364 for _, path := range p {
365 if path.Ext() == ext {
366 return true
367 }
368 }
369
370 return false
371}
372
373// FilterByExt returns the subset of the paths that have extension ext
374func (p Paths) FilterByExt(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
384// FilterOutByExt returns the subset of the paths that do not have extension ext
385func (p Paths) FilterOutByExt(ext string) Paths {
386 ret := make(Paths, 0, len(p))
387 for _, path := range p {
388 if path.Ext() != ext {
389 ret = append(ret, path)
390 }
391 }
392 return ret
393}
394
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700395// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
396// (including subdirectories) are in a contiguous subslice of the list, and can be found in
397// O(log(N)) time using a binary search on the directory prefix.
398type DirectorySortedPaths Paths
399
400func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
401 ret := append(DirectorySortedPaths(nil), paths...)
402 sort.Slice(ret, func(i, j int) bool {
403 return ret[i].String() < ret[j].String()
404 })
405 return ret
406}
407
408// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
409// that are in the specified directory and its subdirectories.
410func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
411 prefix := filepath.Clean(dir) + "/"
412 start := sort.Search(len(p), func(i int) bool {
413 return prefix < p[i].String()
414 })
415
416 ret := p[start:]
417
418 end := sort.Search(len(ret), func(i int) bool {
419 return !strings.HasPrefix(ret[i].String(), prefix)
420 })
421
422 ret = ret[:end]
423
424 return Paths(ret)
425}
426
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700427// WritablePaths is a slice of WritablePaths, used for multiple outputs.
428type WritablePaths []WritablePath
429
430// Strings returns the string forms of the writable paths.
431func (p WritablePaths) Strings() []string {
432 if p == nil {
433 return nil
434 }
435 ret := make([]string, len(p))
436 for i, path := range p {
437 ret[i] = path.String()
438 }
439 return ret
440}
441
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800442// Paths returns the WritablePaths as a Paths
443func (p WritablePaths) Paths() Paths {
444 if p == nil {
445 return nil
446 }
447 ret := make(Paths, len(p))
448 for i, path := range p {
449 ret[i] = path
450 }
451 return ret
452}
453
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700454type basePath struct {
455 path string
456 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800457 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700458}
459
460func (p basePath) Ext() string {
461 return filepath.Ext(p.path)
462}
463
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700464func (p basePath) Base() string {
465 return filepath.Base(p.path)
466}
467
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800468func (p basePath) Rel() string {
469 if p.rel != "" {
470 return p.rel
471 }
472 return p.path
473}
474
Colin Cross0875c522017-11-28 17:34:01 -0800475func (p basePath) String() string {
476 return p.path
477}
478
Colin Cross0db55682017-12-05 15:36:55 -0800479func (p basePath) withRel(rel string) basePath {
480 p.path = filepath.Join(p.path, rel)
481 p.rel = rel
482 return p
483}
484
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700485// SourcePath is a Path representing a file path rooted from SrcDir
486type SourcePath struct {
487 basePath
488}
489
490var _ Path = SourcePath{}
491
Colin Cross0db55682017-12-05 15:36:55 -0800492func (p SourcePath) withRel(rel string) SourcePath {
493 p.basePath = p.basePath.withRel(rel)
494 return p
495}
496
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700497// safePathForSource is for paths that we expect are safe -- only for use by go
498// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700499func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
500 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800501 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700502 if err != nil {
503 return ret, err
504 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700505
Colin Cross7b3dcc32019-01-24 13:14:39 -0800506 // absolute path already checked by validateSafePath
507 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800508 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700509 }
510
Colin Crossfe4bc362018-09-12 10:02:13 -0700511 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700512}
513
Colin Cross192e97a2018-02-22 14:21:02 -0800514// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
515func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000516 p, err := validatePath(pathComponents...)
517 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800518 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800519 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800520 }
521
Colin Cross7b3dcc32019-01-24 13:14:39 -0800522 // absolute path already checked by validatePath
523 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800524 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000525 }
526
Colin Cross192e97a2018-02-22 14:21:02 -0800527 return ret, nil
528}
529
530// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
531// path does not exist.
532func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
533 var files []string
534
535 if gctx, ok := ctx.(PathGlobContext); ok {
536 // Use glob to produce proper dependencies, even though we only want
537 // a single file.
538 files, err = gctx.GlobWithDeps(path.String(), nil)
539 } else {
540 var deps []string
541 // We cannot add build statements in this context, so we fall back to
542 // AddNinjaFileDeps
Colin Cross3f4d1162018-09-21 15:11:48 -0700543 files, deps, err = pathtools.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800544 ctx.AddNinjaFileDeps(deps...)
545 }
546
547 if err != nil {
548 return false, fmt.Errorf("glob: %s", err.Error())
549 }
550
551 return len(files) > 0, nil
552}
553
554// PathForSource joins the provided path components and validates that the result
555// neither escapes the source dir nor is in the out dir.
556// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
557func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
558 path, err := pathForSource(ctx, pathComponents...)
559 if err != nil {
560 reportPathError(ctx, err)
561 }
562
Colin Crosse3924e12018-08-15 20:18:53 -0700563 if pathtools.IsGlob(path.String()) {
564 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
565 }
566
Colin Cross192e97a2018-02-22 14:21:02 -0800567 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
568 exists, err := existsWithDependencies(ctx, path)
569 if err != nil {
570 reportPathError(ctx, err)
571 }
572 if !exists {
573 modCtx.AddMissingDependencies([]string{path.String()})
574 }
575 } else if exists, _, err := ctx.Fs().Exists(path.String()); err != nil {
576 reportPathErrorf(ctx, "%s: %s", path, err.Error())
577 } else if !exists {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800578 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800579 }
580 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700581}
582
Jeff Gaston734e3802017-04-10 15:47:24 -0700583// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700584// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
585// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800586func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800587 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800588 if err != nil {
589 reportPathError(ctx, err)
590 return OptionalPath{}
591 }
Colin Crossc48c1432018-02-23 07:09:01 +0000592
Colin Crosse3924e12018-08-15 20:18:53 -0700593 if pathtools.IsGlob(path.String()) {
594 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
595 return OptionalPath{}
596 }
597
Colin Cross192e97a2018-02-22 14:21:02 -0800598 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000599 if err != nil {
600 reportPathError(ctx, err)
601 return OptionalPath{}
602 }
Colin Cross192e97a2018-02-22 14:21:02 -0800603 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000604 return OptionalPath{}
605 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700606 return OptionalPathForPath(path)
607}
608
609func (p SourcePath) String() string {
610 return filepath.Join(p.config.srcDir, p.path)
611}
612
613// Join creates a new SourcePath with paths... joined with the current path. The
614// provided paths... may not use '..' to escape from the current path.
615func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800616 path, err := validatePath(paths...)
617 if err != nil {
618 reportPathError(ctx, err)
619 }
Colin Cross0db55682017-12-05 15:36:55 -0800620 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700621}
622
Colin Cross2fafa3e2019-03-05 12:39:51 -0800623// join is like Join but does less path validation.
624func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
625 path, err := validateSafePath(paths...)
626 if err != nil {
627 reportPathError(ctx, err)
628 }
629 return p.withRel(path)
630}
631
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700632// OverlayPath returns the overlay for `path' if it exists. This assumes that the
633// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700634func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700635 var relDir string
636 if moduleSrcPath, ok := path.(ModuleSrcPath); ok {
Colin Cross7fc17db2017-02-01 14:07:55 -0800637 relDir = moduleSrcPath.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700638 } else if srcPath, ok := path.(SourcePath); ok {
639 relDir = srcPath.path
640 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800641 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700642 return OptionalPath{}
643 }
644 dir := filepath.Join(p.config.srcDir, p.path, relDir)
645 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700646 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800647 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800648 }
Colin Cross461b4452018-02-23 09:22:42 -0800649 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700650 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800651 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700652 return OptionalPath{}
653 }
654 if len(paths) == 0 {
655 return OptionalPath{}
656 }
Colin Cross43f08db2018-11-12 10:13:39 -0800657 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700658 return OptionalPathForPath(PathForSource(ctx, relPath))
659}
660
661// OutputPath is a Path representing a file path rooted from the build directory
662type OutputPath struct {
663 basePath
664}
665
Colin Cross702e0f82017-10-18 17:27:54 -0700666func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800667 p.basePath = p.basePath.withRel(rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700668 return p
669}
670
Colin Cross3063b782018-08-15 11:19:12 -0700671func (p OutputPath) WithoutRel() OutputPath {
672 p.basePath.rel = filepath.Base(p.basePath.path)
673 return p
674}
675
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700676var _ Path = OutputPath{}
677
Jeff Gaston734e3802017-04-10 15:47:24 -0700678// PathForOutput joins the provided paths and returns an OutputPath that is
679// validated to not escape the build dir.
680// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
681func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800682 path, err := validatePath(pathComponents...)
683 if err != nil {
684 reportPathError(ctx, err)
685 }
Colin Crossaabf6792017-11-29 00:27:14 -0800686 return OutputPath{basePath{path, ctx.Config(), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700687}
688
Colin Cross40e33732019-02-15 11:08:35 -0800689// PathsForOutput returns Paths rooted from buildDir
690func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
691 ret := make(WritablePaths, len(paths))
692 for i, path := range paths {
693 ret[i] = PathForOutput(ctx, path)
694 }
695 return ret
696}
697
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700698func (p OutputPath) writablePath() {}
699
700func (p OutputPath) String() string {
701 return filepath.Join(p.config.buildDir, p.path)
702}
703
Colin Crossa2344662016-03-24 13:14:12 -0700704func (p OutputPath) RelPathString() string {
705 return p.path
706}
707
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700708// Join creates a new OutputPath with paths... joined with the current path. The
709// provided paths... may not use '..' to escape from the current path.
710func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800711 path, err := validatePath(paths...)
712 if err != nil {
713 reportPathError(ctx, err)
714 }
Colin Cross0db55682017-12-05 15:36:55 -0800715 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700716}
717
Colin Cross8854a5a2019-02-11 14:14:16 -0800718// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
719func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
720 if strings.Contains(ext, "/") {
721 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
722 }
723 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800724 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800725 return ret
726}
727
Colin Cross40e33732019-02-15 11:08:35 -0800728// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
729func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
730 path, err := validatePath(paths...)
731 if err != nil {
732 reportPathError(ctx, err)
733 }
734
735 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800736 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800737 return ret
738}
739
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700740// PathForIntermediates returns an OutputPath representing the top-level
741// intermediates directory.
742func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800743 path, err := validatePath(paths...)
744 if err != nil {
745 reportPathError(ctx, err)
746 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700747 return PathForOutput(ctx, ".intermediates", path)
748}
749
750// ModuleSrcPath is a Path representing a file rooted from a module's local source dir
751type ModuleSrcPath struct {
Colin Cross7fc17db2017-02-01 14:07:55 -0800752 SourcePath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700753}
754
755var _ Path = ModuleSrcPath{}
756var _ genPathProvider = ModuleSrcPath{}
757var _ objPathProvider = ModuleSrcPath{}
758var _ resPathProvider = ModuleSrcPath{}
759
760// PathForModuleSrc returns a ModuleSrcPath representing the paths... under the
761// module's local source directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700762func PathForModuleSrc(ctx ModuleContext, paths ...string) ModuleSrcPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800763 p, err := validatePath(paths...)
764 if err != nil {
765 reportPathError(ctx, err)
766 }
Colin Cross192e97a2018-02-22 14:21:02 -0800767
768 srcPath, err := pathForSource(ctx, ctx.ModuleDir(), p)
769 if err != nil {
770 reportPathError(ctx, err)
771 }
772
Colin Crosse3924e12018-08-15 20:18:53 -0700773 if pathtools.IsGlob(srcPath.String()) {
774 reportPathErrorf(ctx, "path may not contain a glob: %s", srcPath.String())
775 }
776
Colin Cross192e97a2018-02-22 14:21:02 -0800777 path := ModuleSrcPath{srcPath}
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800778 path.basePath.rel = p
Colin Cross192e97a2018-02-22 14:21:02 -0800779
780 if exists, _, err := ctx.Fs().Exists(path.String()); err != nil {
781 reportPathErrorf(ctx, "%s: %s", path, err.Error())
782 } else if !exists {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800783 reportPathErrorf(ctx, "module source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800784 }
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800785 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700786}
787
Colin Cross2fafa3e2019-03-05 12:39:51 -0800788// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
789// will return the path relative to subDir in the module's source directory. If any input paths are not located
790// inside subDir then a path error will be reported.
791func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
792 paths = append(Paths(nil), paths...)
793 subDirFullPath := PathForModuleSrc(ctx, subDir)
794 for i, path := range paths {
795 rel := Rel(ctx, subDirFullPath.String(), path.String())
796 paths[i] = subDirFullPath.join(ctx, rel)
797 }
798 return paths
799}
800
801// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
802// module's source directory. If the input path is not located inside subDir then a path error will be reported.
803func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
804 subDirFullPath := PathForModuleSrc(ctx, subDir)
805 rel := Rel(ctx, subDirFullPath.String(), path.String())
806 return subDirFullPath.Join(ctx, rel)
807}
808
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700809// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
810// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700811func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700812 if p == nil {
813 return OptionalPath{}
814 }
815 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
816}
817
Dan Willemsen21ec4902016-11-02 20:43:13 -0700818func (p ModuleSrcPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800819 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700820}
821
Colin Cross635c3b02016-05-18 15:37:25 -0700822func (p ModuleSrcPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800823 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700824}
825
Colin Cross635c3b02016-05-18 15:37:25 -0700826func (p ModuleSrcPath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700827 // TODO: Use full directory if the new ctx is not the current ctx?
828 return PathForModuleRes(ctx, p.path, name)
829}
830
831// ModuleOutPath is a Path representing a module's output directory.
832type ModuleOutPath struct {
833 OutputPath
834}
835
836var _ Path = ModuleOutPath{}
837
Colin Cross702e0f82017-10-18 17:27:54 -0700838func pathForModule(ctx ModuleContext) OutputPath {
839 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
840}
841
Logan Chien7eefdc42018-07-11 18:10:41 +0800842// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
843// reference abi dump for the given module. This is not guaranteed to be valid.
844func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
845 isLlndk, isGzip bool) OptionalPath {
846
Jayant Chowdharyac066c62018-02-20 10:53:31 -0800847 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +0800848 if len(arches) == 0 {
849 panic("device build with no primary arch")
850 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -0800851 currentArch := ctx.Arch()
852 archNameAndVariant := currentArch.ArchType.String()
853 if currentArch.ArchVariant != "" {
854 archNameAndVariant += "_" + currentArch.ArchVariant
855 }
Logan Chien5237bed2018-07-11 17:15:57 +0800856
857 var dirName string
858 if isLlndk {
859 dirName = "ndk"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800860 } else {
Logan Chien5237bed2018-07-11 17:15:57 +0800861 dirName = "vndk"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800862 }
Logan Chien5237bed2018-07-11 17:15:57 +0800863
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -0800864 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +0800865
866 var ext string
867 if isGzip {
868 ext = ".lsdump.gz"
869 } else {
870 ext = ".lsdump"
871 }
872
873 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
874 version, binderBitness, archNameAndVariant, "source-based",
875 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800876}
877
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700878// PathForModuleOut returns a Path representing the paths... under the module's
879// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700880func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800881 p, err := validatePath(paths...)
882 if err != nil {
883 reportPathError(ctx, err)
884 }
Colin Cross702e0f82017-10-18 17:27:54 -0700885 return ModuleOutPath{
886 OutputPath: pathForModule(ctx).withRel(p),
887 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700888}
889
890// ModuleGenPath is a Path representing the 'gen' directory in a module's output
891// directory. Mainly used for generated sources.
892type ModuleGenPath struct {
893 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700894}
895
896var _ Path = ModuleGenPath{}
897var _ genPathProvider = ModuleGenPath{}
898var _ objPathProvider = ModuleGenPath{}
899
900// PathForModuleGen returns a Path representing the paths... under the module's
901// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700902func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800903 p, err := validatePath(paths...)
904 if err != nil {
905 reportPathError(ctx, err)
906 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700907 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -0700908 ModuleOutPath: ModuleOutPath{
909 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
910 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700911 }
912}
913
Dan Willemsen21ec4902016-11-02 20:43:13 -0700914func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700915 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -0700916 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700917}
918
Colin Cross635c3b02016-05-18 15:37:25 -0700919func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700920 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
921}
922
923// ModuleObjPath is a Path representing the 'obj' directory in a module's output
924// directory. Used for compiled objects.
925type ModuleObjPath struct {
926 ModuleOutPath
927}
928
929var _ Path = ModuleObjPath{}
930
931// PathForModuleObj returns a Path representing the paths... under the module's
932// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700933func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800934 p, err := validatePath(pathComponents...)
935 if err != nil {
936 reportPathError(ctx, err)
937 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700938 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
939}
940
941// ModuleResPath is a a Path representing the 'res' directory in a module's
942// output directory.
943type ModuleResPath struct {
944 ModuleOutPath
945}
946
947var _ Path = ModuleResPath{}
948
949// PathForModuleRes returns a Path representing the paths... under the module's
950// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700951func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800952 p, err := validatePath(pathComponents...)
953 if err != nil {
954 reportPathError(ctx, err)
955 }
956
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700957 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
958}
959
960// PathForModuleInstall returns a Path representing the install path for the
961// module appended with paths...
Dan Willemsen00269f22017-07-06 16:59:48 -0700962func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) OutputPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700963 var outPaths []string
964 if ctx.Device() {
Colin Cross43f08db2018-11-12 10:13:39 -0800965 partition := modulePartition(ctx)
Colin Cross6510f912017-11-29 00:27:14 -0800966 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700967 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -0700968 switch ctx.Os() {
969 case Linux:
970 outPaths = []string{"host", "linux-x86"}
971 case LinuxBionic:
972 // TODO: should this be a separate top level, or shared with linux-x86?
973 outPaths = []string{"host", "linux_bionic-x86"}
974 default:
975 outPaths = []string{"host", ctx.Os().String() + "-x86"}
976 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700977 }
Dan Willemsen782a2d12015-12-21 14:55:28 -0800978 if ctx.Debug() {
979 outPaths = append([]string{"debug"}, outPaths...)
980 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700981 outPaths = append(outPaths, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700982 return PathForOutput(ctx, outPaths...)
983}
984
Colin Cross43f08db2018-11-12 10:13:39 -0800985func InstallPathToOnDevicePath(ctx PathContext, path OutputPath) string {
986 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
987
988 return "/" + rel
989}
990
991func modulePartition(ctx ModuleInstallPathContext) string {
992 var partition string
993 if ctx.InstallInData() {
994 partition = "data"
995 } else if ctx.InstallInRecovery() {
996 // the layout of recovery partion is the same as that of system partition
997 partition = "recovery/root/system"
998 } else if ctx.SocSpecific() {
999 partition = ctx.DeviceConfig().VendorPath()
1000 } else if ctx.DeviceSpecific() {
1001 partition = ctx.DeviceConfig().OdmPath()
1002 } else if ctx.ProductSpecific() {
1003 partition = ctx.DeviceConfig().ProductPath()
1004 } else if ctx.ProductServicesSpecific() {
1005 partition = ctx.DeviceConfig().ProductServicesPath()
1006 } else {
1007 partition = "system"
1008 }
1009 if ctx.InstallInSanitizerDir() {
1010 partition = "data/asan/" + partition
1011 }
1012 return partition
1013}
1014
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001015// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001016// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001017func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001018 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001019 path := filepath.Clean(path)
1020 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001021 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001022 }
1023 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001024 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1025 // variables. '..' may remove the entire ninja variable, even if it
1026 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001027 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001028}
1029
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001030// validatePath validates that a path does not include ninja variables, and that
1031// each path component does not attempt to leave its component. Returns a joined
1032// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001033func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001034 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001035 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001036 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001037 }
1038 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001039 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001040}
Colin Cross5b529592017-05-09 13:34:34 -07001041
Colin Cross0875c522017-11-28 17:34:01 -08001042func PathForPhony(ctx PathContext, phony string) WritablePath {
1043 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001044 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001045 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001046 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001047}
1048
Colin Cross74e3fe42017-12-11 15:51:44 -08001049type PhonyPath struct {
1050 basePath
1051}
1052
1053func (p PhonyPath) writablePath() {}
1054
1055var _ Path = PhonyPath{}
1056var _ WritablePath = PhonyPath{}
1057
Colin Cross5b529592017-05-09 13:34:34 -07001058type testPath struct {
1059 basePath
1060}
1061
1062func (p testPath) String() string {
1063 return p.path
1064}
1065
Colin Cross40e33732019-02-15 11:08:35 -08001066type testWritablePath struct {
1067 testPath
1068}
1069
1070func (p testPath) writablePath() {}
1071
1072// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1073// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001074func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001075 p, err := validateSafePath(paths...)
1076 if err != nil {
1077 panic(err)
1078 }
Colin Cross5b529592017-05-09 13:34:34 -07001079 return testPath{basePath{path: p, rel: p}}
1080}
1081
Colin Cross40e33732019-02-15 11:08:35 -08001082// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1083func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001084 p := make(Paths, len(strs))
1085 for i, s := range strs {
1086 p[i] = PathForTesting(s)
1087 }
1088
1089 return p
1090}
Colin Cross43f08db2018-11-12 10:13:39 -08001091
Colin Cross40e33732019-02-15 11:08:35 -08001092// WritablePathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be
1093// used from within tests.
1094func WritablePathForTesting(paths ...string) WritablePath {
1095 p, err := validateSafePath(paths...)
1096 if err != nil {
1097 panic(err)
1098 }
1099 return testWritablePath{testPath{basePath{path: p, rel: p}}}
1100}
1101
1102// WritablePathsForTesting returns a Path constructed from each element in strs. It should only be used from within
1103// tests.
1104func WritablePathsForTesting(strs ...string) WritablePaths {
1105 p := make(WritablePaths, len(strs))
1106 for i, s := range strs {
1107 p[i] = WritablePathForTesting(s)
1108 }
1109
1110 return p
1111}
1112
1113type testPathContext struct {
1114 config Config
1115 fs pathtools.FileSystem
1116}
1117
1118func (x *testPathContext) Fs() pathtools.FileSystem { return x.fs }
1119func (x *testPathContext) Config() Config { return x.config }
1120func (x *testPathContext) AddNinjaFileDeps(...string) {}
1121
1122// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1123// PathForOutput.
1124func PathContextForTesting(config Config, fs map[string][]byte) PathContext {
1125 return &testPathContext{
1126 config: config,
1127 fs: pathtools.MockFs(fs),
1128 }
1129}
1130
Colin Cross43f08db2018-11-12 10:13:39 -08001131// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1132// targetPath is not inside basePath.
1133func Rel(ctx PathContext, basePath string, targetPath string) string {
1134 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1135 if !isRel {
1136 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1137 return ""
1138 }
1139 return rel
1140}
1141
1142// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1143// targetPath is not inside basePath.
1144func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
1145 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1146 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
1147 return "", false
1148 }
1149 rel, err := filepath.Rel(basePath, targetPath)
1150 if err != nil {
1151 reportPathError(ctx, err)
1152 return "", false
1153 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
1154 return "", false
1155 }
1156 return rel, true
1157}