blob: c9e7150319ca19de0e404fc2e3f7f70966d6b958 [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.
233func pathsForModuleSrcFromFullPath(ctx ModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800234 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700235 if prefix == "./" {
236 prefix = ""
237 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700238 ret := make(Paths, 0, len(paths))
239 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800240 if !incDirs && strings.HasSuffix(p, "/") {
241 continue
242 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700243 path := filepath.Clean(p)
244 if !strings.HasPrefix(path, prefix) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800245 reportPathErrorf(ctx, "Path '%s' is not in module source directory '%s'", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700246 continue
247 }
248 ret = append(ret, PathForModuleSrc(ctx, path[len(prefix):]))
249 }
250 return ret
251}
252
253// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
254// local source directory. If none are provided, use the default if it exists.
Colin Cross635c3b02016-05-18 15:37:25 -0700255func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700256 if len(input) > 0 {
257 return PathsForModuleSrc(ctx, input)
258 }
259 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
260 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800261 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800262 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700263}
264
265// Strings returns the Paths in string form
266func (p Paths) Strings() []string {
267 if p == nil {
268 return nil
269 }
270 ret := make([]string, len(p))
271 for i, path := range p {
272 ret[i] = path.String()
273 }
274 return ret
275}
276
Colin Crossb6715442017-10-24 11:13:31 -0700277// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
278// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700279func FirstUniquePaths(list Paths) Paths {
280 k := 0
281outer:
282 for i := 0; i < len(list); i++ {
283 for j := 0; j < k; j++ {
284 if list[i] == list[j] {
285 continue outer
286 }
287 }
288 list[k] = list[i]
289 k++
290 }
291 return list[:k]
292}
293
Colin Crossb6715442017-10-24 11:13:31 -0700294// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
295// modifies the Paths slice contents in place, and returns a subslice of the original slice.
296func LastUniquePaths(list Paths) Paths {
297 totalSkip := 0
298 for i := len(list) - 1; i >= totalSkip; i-- {
299 skip := 0
300 for j := i - 1; j >= totalSkip; j-- {
301 if list[i] == list[j] {
302 skip++
303 } else {
304 list[j+skip] = list[j]
305 }
306 }
307 totalSkip += skip
308 }
309 return list[totalSkip:]
310}
311
Colin Crossa140bb02018-04-17 10:52:26 -0700312// ReversePaths returns a copy of a Paths in reverse order.
313func ReversePaths(list Paths) Paths {
314 if list == nil {
315 return nil
316 }
317 ret := make(Paths, len(list))
318 for i := range list {
319 ret[i] = list[len(list)-1-i]
320 }
321 return ret
322}
323
Jeff Gaston294356f2017-09-27 17:05:30 -0700324func indexPathList(s Path, list []Path) int {
325 for i, l := range list {
326 if l == s {
327 return i
328 }
329 }
330
331 return -1
332}
333
334func inPathList(p Path, list []Path) bool {
335 return indexPathList(p, list) != -1
336}
337
338func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
339 for _, l := range list {
340 if inPathList(l, filter) {
341 filtered = append(filtered, l)
342 } else {
343 remainder = append(remainder, l)
344 }
345 }
346
347 return
348}
349
Colin Cross93e85952017-08-15 13:34:18 -0700350// HasExt returns true of any of the paths have extension ext, otherwise false
351func (p Paths) HasExt(ext string) bool {
352 for _, path := range p {
353 if path.Ext() == ext {
354 return true
355 }
356 }
357
358 return false
359}
360
361// FilterByExt returns the subset of the paths that have extension ext
362func (p Paths) FilterByExt(ext string) Paths {
363 ret := make(Paths, 0, len(p))
364 for _, path := range p {
365 if path.Ext() == ext {
366 ret = append(ret, path)
367 }
368 }
369 return ret
370}
371
372// FilterOutByExt returns the subset of the paths that do not have extension ext
373func (p Paths) FilterOutByExt(ext string) Paths {
374 ret := make(Paths, 0, len(p))
375 for _, path := range p {
376 if path.Ext() != ext {
377 ret = append(ret, path)
378 }
379 }
380 return ret
381}
382
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700383// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
384// (including subdirectories) are in a contiguous subslice of the list, and can be found in
385// O(log(N)) time using a binary search on the directory prefix.
386type DirectorySortedPaths Paths
387
388func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
389 ret := append(DirectorySortedPaths(nil), paths...)
390 sort.Slice(ret, func(i, j int) bool {
391 return ret[i].String() < ret[j].String()
392 })
393 return ret
394}
395
396// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
397// that are in the specified directory and its subdirectories.
398func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
399 prefix := filepath.Clean(dir) + "/"
400 start := sort.Search(len(p), func(i int) bool {
401 return prefix < p[i].String()
402 })
403
404 ret := p[start:]
405
406 end := sort.Search(len(ret), func(i int) bool {
407 return !strings.HasPrefix(ret[i].String(), prefix)
408 })
409
410 ret = ret[:end]
411
412 return Paths(ret)
413}
414
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700415// WritablePaths is a slice of WritablePaths, used for multiple outputs.
416type WritablePaths []WritablePath
417
418// Strings returns the string forms of the writable paths.
419func (p WritablePaths) Strings() []string {
420 if p == nil {
421 return nil
422 }
423 ret := make([]string, len(p))
424 for i, path := range p {
425 ret[i] = path.String()
426 }
427 return ret
428}
429
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800430// Paths returns the WritablePaths as a Paths
431func (p WritablePaths) Paths() Paths {
432 if p == nil {
433 return nil
434 }
435 ret := make(Paths, len(p))
436 for i, path := range p {
437 ret[i] = path
438 }
439 return ret
440}
441
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700442type basePath struct {
443 path string
444 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800445 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700446}
447
448func (p basePath) Ext() string {
449 return filepath.Ext(p.path)
450}
451
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700452func (p basePath) Base() string {
453 return filepath.Base(p.path)
454}
455
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800456func (p basePath) Rel() string {
457 if p.rel != "" {
458 return p.rel
459 }
460 return p.path
461}
462
Colin Cross0875c522017-11-28 17:34:01 -0800463func (p basePath) String() string {
464 return p.path
465}
466
Colin Cross0db55682017-12-05 15:36:55 -0800467func (p basePath) withRel(rel string) basePath {
468 p.path = filepath.Join(p.path, rel)
469 p.rel = rel
470 return p
471}
472
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700473// SourcePath is a Path representing a file path rooted from SrcDir
474type SourcePath struct {
475 basePath
476}
477
478var _ Path = SourcePath{}
479
Colin Cross0db55682017-12-05 15:36:55 -0800480func (p SourcePath) withRel(rel string) SourcePath {
481 p.basePath = p.basePath.withRel(rel)
482 return p
483}
484
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700485// safePathForSource is for paths that we expect are safe -- only for use by go
486// code that is embedding ninja variables in paths
487func safePathForSource(ctx PathContext, path string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800488 p, err := validateSafePath(path)
489 if err != nil {
490 reportPathError(ctx, err)
491 }
Colin Crossaabf6792017-11-29 00:27:14 -0800492 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700493
494 abs, err := filepath.Abs(ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700495 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800496 reportPathError(ctx, err)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700497 return ret
498 }
Colin Crossaabf6792017-11-29 00:27:14 -0800499 buildroot, err := filepath.Abs(ctx.Config().buildDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700500 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800501 reportPathError(ctx, err)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700502 return ret
503 }
504 if strings.HasPrefix(abs, buildroot) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800505 reportPathErrorf(ctx, "source path %s is in output", abs)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700506 return ret
Colin Cross6e18ca42015-07-14 18:55:36 -0700507 }
508
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700509 return ret
510}
511
Colin Cross192e97a2018-02-22 14:21:02 -0800512// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
513func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000514 p, err := validatePath(pathComponents...)
515 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800516 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800517 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800518 }
519
Colin Crossc48c1432018-02-23 07:09:01 +0000520 abs, err := filepath.Abs(ret.String())
521 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800522 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800523 }
Colin Crossc48c1432018-02-23 07:09:01 +0000524 buildroot, err := filepath.Abs(ctx.Config().buildDir)
525 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800526 return ret, err
Colin Crossc48c1432018-02-23 07:09:01 +0000527 }
528 if strings.HasPrefix(abs, buildroot) {
Colin Cross192e97a2018-02-22 14:21:02 -0800529 return ret, fmt.Errorf("source path %s is in output", abs)
Colin Crossc48c1432018-02-23 07:09:01 +0000530 }
531
Colin Cross192e97a2018-02-22 14:21:02 -0800532 if pathtools.IsGlob(ret.String()) {
533 return ret, fmt.Errorf("path may not contain a glob: %s", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000534 }
Colin Cross192e97a2018-02-22 14:21:02 -0800535
536 return ret, nil
537}
538
539// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
540// path does not exist.
541func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
542 var files []string
543
544 if gctx, ok := ctx.(PathGlobContext); ok {
545 // Use glob to produce proper dependencies, even though we only want
546 // a single file.
547 files, err = gctx.GlobWithDeps(path.String(), nil)
548 } else {
549 var deps []string
550 // We cannot add build statements in this context, so we fall back to
551 // AddNinjaFileDeps
552 files, deps, err = pathtools.Glob(path.String(), nil)
553 ctx.AddNinjaFileDeps(deps...)
554 }
555
556 if err != nil {
557 return false, fmt.Errorf("glob: %s", err.Error())
558 }
559
560 return len(files) > 0, nil
561}
562
563// PathForSource joins the provided path components and validates that the result
564// neither escapes the source dir nor is in the out dir.
565// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
566func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
567 path, err := pathForSource(ctx, pathComponents...)
568 if err != nil {
569 reportPathError(ctx, err)
570 }
571
572 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
573 exists, err := existsWithDependencies(ctx, path)
574 if err != nil {
575 reportPathError(ctx, err)
576 }
577 if !exists {
578 modCtx.AddMissingDependencies([]string{path.String()})
579 }
580 } else if exists, _, err := ctx.Fs().Exists(path.String()); err != nil {
581 reportPathErrorf(ctx, "%s: %s", path, err.Error())
582 } else if !exists {
583 reportPathErrorf(ctx, "source path %s does not exist", path)
584 }
585 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700586}
587
Jeff Gaston734e3802017-04-10 15:47:24 -0700588// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700589// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
590// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800591func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800592 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800593 if err != nil {
594 reportPathError(ctx, err)
595 return OptionalPath{}
596 }
Colin Crossc48c1432018-02-23 07:09:01 +0000597
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
623// OverlayPath returns the overlay for `path' if it exists. This assumes that the
624// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700625func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700626 var relDir string
627 if moduleSrcPath, ok := path.(ModuleSrcPath); ok {
Colin Cross7fc17db2017-02-01 14:07:55 -0800628 relDir = moduleSrcPath.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700629 } else if srcPath, ok := path.(SourcePath); ok {
630 relDir = srcPath.path
631 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800632 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700633 return OptionalPath{}
634 }
635 dir := filepath.Join(p.config.srcDir, p.path, relDir)
636 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700637 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800638 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800639 }
Colin Cross461b4452018-02-23 09:22:42 -0800640 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700641 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800642 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700643 return OptionalPath{}
644 }
645 if len(paths) == 0 {
646 return OptionalPath{}
647 }
648 relPath, err := filepath.Rel(p.config.srcDir, paths[0])
649 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800650 reportPathError(ctx, err)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700651 return OptionalPath{}
652 }
653 return OptionalPathForPath(PathForSource(ctx, relPath))
654}
655
656// OutputPath is a Path representing a file path rooted from the build directory
657type OutputPath struct {
658 basePath
659}
660
Colin Cross702e0f82017-10-18 17:27:54 -0700661func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800662 p.basePath = p.basePath.withRel(rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700663 return p
664}
665
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700666var _ Path = OutputPath{}
667
Jeff Gaston734e3802017-04-10 15:47:24 -0700668// PathForOutput joins the provided paths and returns an OutputPath that is
669// validated to not escape the build dir.
670// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
671func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800672 path, err := validatePath(pathComponents...)
673 if err != nil {
674 reportPathError(ctx, err)
675 }
Colin Crossaabf6792017-11-29 00:27:14 -0800676 return OutputPath{basePath{path, ctx.Config(), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700677}
678
679func (p OutputPath) writablePath() {}
680
681func (p OutputPath) String() string {
682 return filepath.Join(p.config.buildDir, p.path)
683}
684
Colin Crossa2344662016-03-24 13:14:12 -0700685func (p OutputPath) RelPathString() string {
686 return p.path
687}
688
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700689// Join creates a new OutputPath with paths... joined with the current path. The
690// provided paths... may not use '..' to escape from the current path.
691func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800692 path, err := validatePath(paths...)
693 if err != nil {
694 reportPathError(ctx, err)
695 }
Colin Cross0db55682017-12-05 15:36:55 -0800696 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700697}
698
699// PathForIntermediates returns an OutputPath representing the top-level
700// intermediates directory.
701func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800702 path, err := validatePath(paths...)
703 if err != nil {
704 reportPathError(ctx, err)
705 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700706 return PathForOutput(ctx, ".intermediates", path)
707}
708
Dan Willemsenbc0c5092018-03-10 16:25:53 -0800709// DistPath is a Path representing a file path rooted from the dist directory
710type DistPath struct {
711 basePath
712}
713
714func (p DistPath) withRel(rel string) DistPath {
715 p.basePath = p.basePath.withRel(rel)
716 return p
717}
718
719var _ Path = DistPath{}
720
721// PathForDist joins the provided paths and returns a DistPath that is
722// validated to not escape the dist dir.
723// On error, it will return a usable, but invalid DistPath, and report a ModuleError.
724func PathForDist(ctx PathContext, pathComponents ...string) DistPath {
725 path, err := validatePath(pathComponents...)
726 if err != nil {
727 reportPathError(ctx, err)
728 }
729 return DistPath{basePath{path, ctx.Config(), ""}}
730}
731
732func (p DistPath) writablePath() {}
733
734func (p DistPath) Valid() bool {
Dan Willemsen45133ac2018-03-09 21:22:06 -0800735 return p.config.productVariables.DistDir != nil && *p.config.productVariables.DistDir != ""
Dan Willemsenbc0c5092018-03-10 16:25:53 -0800736}
737
738func (p DistPath) String() string {
739 if !p.Valid() {
740 panic("Requesting an invalid path")
741 }
Dan Willemsen45133ac2018-03-09 21:22:06 -0800742 return filepath.Join(*p.config.productVariables.DistDir, p.path)
Dan Willemsenbc0c5092018-03-10 16:25:53 -0800743}
744
745func (p DistPath) RelPathString() string {
746 return p.path
747}
748
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700749// ModuleSrcPath is a Path representing a file rooted from a module's local source dir
750type ModuleSrcPath struct {
Colin Cross7fc17db2017-02-01 14:07:55 -0800751 SourcePath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700752}
753
754var _ Path = ModuleSrcPath{}
755var _ genPathProvider = ModuleSrcPath{}
756var _ objPathProvider = ModuleSrcPath{}
757var _ resPathProvider = ModuleSrcPath{}
758
759// PathForModuleSrc returns a ModuleSrcPath representing the paths... under the
760// module's local source directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700761func PathForModuleSrc(ctx ModuleContext, paths ...string) ModuleSrcPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800762 p, err := validatePath(paths...)
763 if err != nil {
764 reportPathError(ctx, err)
765 }
Colin Cross192e97a2018-02-22 14:21:02 -0800766
767 srcPath, err := pathForSource(ctx, ctx.ModuleDir(), p)
768 if err != nil {
769 reportPathError(ctx, err)
770 }
771
772 path := ModuleSrcPath{srcPath}
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800773 path.basePath.rel = p
Colin Cross192e97a2018-02-22 14:21:02 -0800774
775 if exists, _, err := ctx.Fs().Exists(path.String()); err != nil {
776 reportPathErrorf(ctx, "%s: %s", path, err.Error())
777 } else if !exists {
778 reportPathErrorf(ctx, "module source path %s does not exist", path)
779 }
780
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800781 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700782}
783
784// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
785// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700786func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700787 if p == nil {
788 return OptionalPath{}
789 }
790 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
791}
792
Dan Willemsen21ec4902016-11-02 20:43:13 -0700793func (p ModuleSrcPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800794 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700795}
796
Colin Cross635c3b02016-05-18 15:37:25 -0700797func (p ModuleSrcPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800798 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700799}
800
Colin Cross635c3b02016-05-18 15:37:25 -0700801func (p ModuleSrcPath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700802 // TODO: Use full directory if the new ctx is not the current ctx?
803 return PathForModuleRes(ctx, p.path, name)
804}
805
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800806func (p ModuleSrcPath) WithSubDir(ctx ModuleContext, subdir string) ModuleSrcPath {
807 subdir = PathForModuleSrc(ctx, subdir).String()
808 var err error
809 rel, err := filepath.Rel(subdir, p.path)
810 if err != nil {
811 ctx.ModuleErrorf("source file %q is not under path %q", p.path, subdir)
812 return p
813 }
814 p.rel = rel
815 return p
816}
817
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700818// ModuleOutPath is a Path representing a module's output directory.
819type ModuleOutPath struct {
820 OutputPath
821}
822
823var _ Path = ModuleOutPath{}
824
Colin Cross702e0f82017-10-18 17:27:54 -0700825func pathForModule(ctx ModuleContext) OutputPath {
826 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
827}
828
Logan Chien7eefdc42018-07-11 18:10:41 +0800829// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
830// reference abi dump for the given module. This is not guaranteed to be valid.
831func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
832 isLlndk, isGzip bool) OptionalPath {
833
Jayant Chowdharyac066c62018-02-20 10:53:31 -0800834 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +0800835 if len(arches) == 0 {
836 panic("device build with no primary arch")
837 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -0800838 currentArch := ctx.Arch()
839 archNameAndVariant := currentArch.ArchType.String()
840 if currentArch.ArchVariant != "" {
841 archNameAndVariant += "_" + currentArch.ArchVariant
842 }
Logan Chien5237bed2018-07-11 17:15:57 +0800843
844 var dirName string
845 if isLlndk {
846 dirName = "ndk"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800847 } else {
Logan Chien5237bed2018-07-11 17:15:57 +0800848 dirName = "vndk"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800849 }
Logan Chien5237bed2018-07-11 17:15:57 +0800850
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -0800851 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +0800852
853 var ext string
854 if isGzip {
855 ext = ".lsdump.gz"
856 } else {
857 ext = ".lsdump"
858 }
859
860 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
861 version, binderBitness, archNameAndVariant, "source-based",
862 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800863}
864
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700865// PathForModuleOut returns a Path representing the paths... under the module's
866// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700867func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800868 p, err := validatePath(paths...)
869 if err != nil {
870 reportPathError(ctx, err)
871 }
Colin Cross702e0f82017-10-18 17:27:54 -0700872 return ModuleOutPath{
873 OutputPath: pathForModule(ctx).withRel(p),
874 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700875}
876
877// ModuleGenPath is a Path representing the 'gen' directory in a module's output
878// directory. Mainly used for generated sources.
879type ModuleGenPath struct {
880 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700881}
882
883var _ Path = ModuleGenPath{}
884var _ genPathProvider = ModuleGenPath{}
885var _ objPathProvider = ModuleGenPath{}
886
887// PathForModuleGen returns a Path representing the paths... under the module's
888// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700889func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800890 p, err := validatePath(paths...)
891 if err != nil {
892 reportPathError(ctx, err)
893 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700894 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -0700895 ModuleOutPath: ModuleOutPath{
896 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
897 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700898 }
899}
900
Dan Willemsen21ec4902016-11-02 20:43:13 -0700901func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700902 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -0700903 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700904}
905
Colin Cross635c3b02016-05-18 15:37:25 -0700906func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700907 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
908}
909
910// ModuleObjPath is a Path representing the 'obj' directory in a module's output
911// directory. Used for compiled objects.
912type ModuleObjPath struct {
913 ModuleOutPath
914}
915
916var _ Path = ModuleObjPath{}
917
918// PathForModuleObj returns a Path representing the paths... under the module's
919// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700920func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800921 p, err := validatePath(pathComponents...)
922 if err != nil {
923 reportPathError(ctx, err)
924 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700925 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
926}
927
928// ModuleResPath is a a Path representing the 'res' directory in a module's
929// output directory.
930type ModuleResPath struct {
931 ModuleOutPath
932}
933
934var _ Path = ModuleResPath{}
935
936// PathForModuleRes returns a Path representing the paths... under the module's
937// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700938func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800939 p, err := validatePath(pathComponents...)
940 if err != nil {
941 reportPathError(ctx, err)
942 }
943
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700944 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
945}
946
947// PathForModuleInstall returns a Path representing the install path for the
948// module appended with paths...
Dan Willemsen00269f22017-07-06 16:59:48 -0700949func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) OutputPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700950 var outPaths []string
951 if ctx.Device() {
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700952 var partition string
Dan Willemsen00269f22017-07-06 16:59:48 -0700953 if ctx.InstallInData() {
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700954 partition = "data"
Jiyong Parkf9332f12018-02-01 00:54:12 +0900955 } else if ctx.InstallInRecovery() {
Jiyong Park2e674312018-05-29 13:56:37 +0900956 // the layout of recovery partion is the same as that of system partition
957 partition = "recovery/root/system"
Jiyong Park2db76922017-11-08 16:03:48 +0900958 } else if ctx.SocSpecific() {
Dan Willemsen00269f22017-07-06 16:59:48 -0700959 partition = ctx.DeviceConfig().VendorPath()
Jiyong Park2db76922017-11-08 16:03:48 +0900960 } else if ctx.DeviceSpecific() {
961 partition = ctx.DeviceConfig().OdmPath()
962 } else if ctx.ProductSpecific() {
Jaekyun Seok5cfbfbb2018-01-10 19:00:15 +0900963 partition = ctx.DeviceConfig().ProductPath()
Dario Frenifd05a742018-05-29 13:28:54 +0100964 } else if ctx.ProductServicesSpecific() {
965 partition = ctx.DeviceConfig().ProductServicesPath()
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700966 } else {
967 partition = "system"
Dan Willemsen782a2d12015-12-21 14:55:28 -0800968 }
Vishwath Mohan1dd88392017-03-29 22:00:18 -0700969
970 if ctx.InstallInSanitizerDir() {
971 partition = "data/asan/" + partition
Dan Willemsen782a2d12015-12-21 14:55:28 -0800972 }
Colin Cross6510f912017-11-29 00:27:14 -0800973 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700974 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -0700975 switch ctx.Os() {
976 case Linux:
977 outPaths = []string{"host", "linux-x86"}
978 case LinuxBionic:
979 // TODO: should this be a separate top level, or shared with linux-x86?
980 outPaths = []string{"host", "linux_bionic-x86"}
981 default:
982 outPaths = []string{"host", ctx.Os().String() + "-x86"}
983 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700984 }
Dan Willemsen782a2d12015-12-21 14:55:28 -0800985 if ctx.Debug() {
986 outPaths = append([]string{"debug"}, outPaths...)
987 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700988 outPaths = append(outPaths, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700989 return PathForOutput(ctx, outPaths...)
990}
991
992// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800993// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800994func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -0700995 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800996 path := filepath.Clean(path)
997 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800998 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800999 }
1000 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001001 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1002 // variables. '..' may remove the entire ninja variable, even if it
1003 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001004 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001005}
1006
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001007// validatePath validates that a path does not include ninja variables, and that
1008// each path component does not attempt to leave its component. Returns a joined
1009// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001010func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001011 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001012 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001013 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001014 }
1015 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001016 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001017}
Colin Cross5b529592017-05-09 13:34:34 -07001018
Colin Cross0875c522017-11-28 17:34:01 -08001019func PathForPhony(ctx PathContext, phony string) WritablePath {
1020 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001021 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001022 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001023 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001024}
1025
Colin Cross74e3fe42017-12-11 15:51:44 -08001026type PhonyPath struct {
1027 basePath
1028}
1029
1030func (p PhonyPath) writablePath() {}
1031
1032var _ Path = PhonyPath{}
1033var _ WritablePath = PhonyPath{}
1034
Colin Cross5b529592017-05-09 13:34:34 -07001035type testPath struct {
1036 basePath
1037}
1038
1039func (p testPath) String() string {
1040 return p.path
1041}
1042
1043func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001044 p, err := validateSafePath(paths...)
1045 if err != nil {
1046 panic(err)
1047 }
Colin Cross5b529592017-05-09 13:34:34 -07001048 return testPath{basePath{path: p, rel: p}}
1049}
1050
1051func PathsForTesting(strs []string) Paths {
1052 p := make(Paths, len(strs))
1053 for i, s := range strs {
1054 p[i] = PathForTesting(s)
1055 }
1056
1057 return p
1058}