blob: 44d26df66e50b0feeab1f9f5dbe551293f7dcf7d [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 Cross988414c2020-01-11 01:11:46 +000019 "io/ioutil"
20 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070021 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070022 "reflect"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070023 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070024 "strings"
25
26 "github.com/google/blueprint"
27 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080028)
29
Colin Cross988414c2020-01-11 01:11:46 +000030var absSrcDir string
31
Dan Willemsen34cc69e2015-09-23 15:26:20 -070032// PathContext is the subset of a (Module|Singleton)Context required by the
33// Path methods.
34type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080035 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080036 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080037}
38
Colin Cross7f19f372016-11-01 11:10:25 -070039type PathGlobContext interface {
40 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
41}
42
Colin Crossaabf6792017-11-29 00:27:14 -080043var _ PathContext = SingletonContext(nil)
44var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070045
Dan Willemsen00269f22017-07-06 16:59:48 -070046type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -070047 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -070048
49 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -070050 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -070051 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -080052 InstallInRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +090053 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -070054 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -070055 InstallBypassMake() bool
Dan Willemsen00269f22017-07-06 16:59:48 -070056}
57
58var _ ModuleInstallPathContext = ModuleContext(nil)
59
Dan Willemsen34cc69e2015-09-23 15:26:20 -070060// errorfContext is the interface containing the Errorf method matching the
61// Errorf method in blueprint.SingletonContext.
62type errorfContext interface {
63 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080064}
65
Dan Willemsen34cc69e2015-09-23 15:26:20 -070066var _ errorfContext = blueprint.SingletonContext(nil)
67
68// moduleErrorf is the interface containing the ModuleErrorf method matching
69// the ModuleErrorf method in blueprint.ModuleContext.
70type moduleErrorf interface {
71 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080072}
73
Dan Willemsen34cc69e2015-09-23 15:26:20 -070074var _ moduleErrorf = blueprint.ModuleContext(nil)
75
Dan Willemsen34cc69e2015-09-23 15:26:20 -070076// reportPathError will register an error with the attached context. It
77// attempts ctx.ModuleErrorf for a better error message first, then falls
78// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -080079func reportPathError(ctx PathContext, err error) {
80 reportPathErrorf(ctx, "%s", err.Error())
81}
82
83// reportPathErrorf will register an error with the attached context. It
84// attempts ctx.ModuleErrorf for a better error message first, then falls
85// back to ctx.Errorf.
86func reportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -070087 if mctx, ok := ctx.(moduleErrorf); ok {
88 mctx.ModuleErrorf(format, args...)
89 } else if ectx, ok := ctx.(errorfContext); ok {
90 ectx.Errorf(format, args...)
91 } else {
92 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -070093 }
94}
95
Colin Cross5e708052019-08-06 13:59:50 -070096func pathContextName(ctx PathContext, module blueprint.Module) string {
97 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
98 return x.ModuleName(module)
99 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
100 return x.OtherModuleName(module)
101 }
102 return "unknown"
103}
104
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700105type Path interface {
106 // Returns the path in string form
107 String() string
108
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700109 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700110 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700111
112 // Base returns the last element of the path
113 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800114
115 // Rel returns the portion of the path relative to the directory it was created from. For
116 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800117 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800118 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700119}
120
121// WritablePath is a type of path that can be used as an output for build rules.
122type WritablePath interface {
123 Path
124
Paul Duffin9b478b02019-12-10 13:41:51 +0000125 // return the path to the build directory.
126 buildDir() string
127
Jeff Gaston734e3802017-04-10 15:47:24 -0700128 // the writablePath method doesn't directly do anything,
129 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700130 writablePath()
131}
132
133type genPathProvider interface {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700134 genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700135}
136type objPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700137 objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700138}
139type resPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700140 resPathWithName(ctx ModuleContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700141}
142
143// GenPathWithExt derives a new file path in ctx's generated sources directory
144// from the current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700145func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700146 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700147 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700148 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800149 reportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700150 return PathForModuleGen(ctx)
151}
152
153// ObjPathWithExt derives a new file path in ctx's object directory from the
154// current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700155func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700156 if path, ok := p.(objPathProvider); ok {
157 return path.objPathWithExt(ctx, subdir, ext)
158 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800159 reportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700160 return PathForModuleObj(ctx)
161}
162
163// ResPathWithName derives a new path in ctx's output resource directory, using
164// the current path to create the directory name, and the `name` argument for
165// the filename.
Colin Cross635c3b02016-05-18 15:37:25 -0700166func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700167 if path, ok := p.(resPathProvider); ok {
168 return path.resPathWithName(ctx, name)
169 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800170 reportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700171 return PathForModuleRes(ctx)
172}
173
174// OptionalPath is a container that may or may not contain a valid Path.
175type OptionalPath struct {
176 valid bool
177 path Path
178}
179
180// OptionalPathForPath returns an OptionalPath containing the path.
181func OptionalPathForPath(path Path) OptionalPath {
182 if path == nil {
183 return OptionalPath{}
184 }
185 return OptionalPath{valid: true, path: path}
186}
187
188// Valid returns whether there is a valid path
189func (p OptionalPath) Valid() bool {
190 return p.valid
191}
192
193// Path returns the Path embedded in this OptionalPath. You must be sure that
194// there is a valid path, since this method will panic if there is not.
195func (p OptionalPath) Path() Path {
196 if !p.valid {
197 panic("Requesting an invalid path")
198 }
199 return p.path
200}
201
202// String returns the string version of the Path, or "" if it isn't valid.
203func (p OptionalPath) String() string {
204 if p.valid {
205 return p.path.String()
206 } else {
207 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700208 }
209}
Colin Cross6e18ca42015-07-14 18:55:36 -0700210
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700211// Paths is a slice of Path objects, with helpers to operate on the collection.
212type Paths []Path
213
214// PathsForSource returns Paths rooted from SrcDir
215func PathsForSource(ctx PathContext, paths []string) Paths {
216 ret := make(Paths, len(paths))
217 for i, path := range paths {
218 ret[i] = PathForSource(ctx, path)
219 }
220 return ret
221}
222
Jeff Gaston734e3802017-04-10 15:47:24 -0700223// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800224// found in the tree. If any are not found, they are omitted from the list,
225// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800226func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800227 ret := make(Paths, 0, len(paths))
228 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800229 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800230 if p.Valid() {
231 ret = append(ret, p.Path())
232 }
233 }
234 return ret
235}
236
Colin Cross41955e82019-05-29 14:40:35 -0700237// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
238// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
239// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
240// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
241// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
242// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Colin Cross635c3b02016-05-18 15:37:25 -0700243func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800244 return PathsForModuleSrcExcludes(ctx, paths, nil)
245}
246
Colin Crossba71a3f2019-03-18 12:12:48 -0700247// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700248// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
249// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
250// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
251// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100252// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700253// having missing dependencies.
Colin Cross8a497952019-03-05 22:25:09 -0800254func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700255 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
256 if ctx.Config().AllowMissingDependencies() {
257 ctx.AddMissingDependencies(missingDeps)
258 } else {
259 for _, m := range missingDeps {
260 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
261 }
262 }
263 return ret
264}
265
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000266// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
267type OutputPaths []OutputPath
268
269// Paths returns the OutputPaths as a Paths
270func (p OutputPaths) Paths() Paths {
271 if p == nil {
272 return nil
273 }
274 ret := make(Paths, len(p))
275 for i, path := range p {
276 ret[i] = path
277 }
278 return ret
279}
280
281// Strings returns the string forms of the writable paths.
282func (p OutputPaths) Strings() []string {
283 if p == nil {
284 return nil
285 }
286 ret := make([]string, len(p))
287 for i, path := range p {
288 ret[i] = path.String()
289 }
290 return ret
291}
292
Colin Crossba71a3f2019-03-18 12:12:48 -0700293// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700294// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
295// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
296// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
297// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
298// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
299// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
300// dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700301func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800302 prefix := pathForModuleSrc(ctx).String()
303
304 var expandedExcludes []string
305 if excludes != nil {
306 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700307 }
Colin Cross8a497952019-03-05 22:25:09 -0800308
Colin Crossba71a3f2019-03-18 12:12:48 -0700309 var missingExcludeDeps []string
310
Colin Cross8a497952019-03-05 22:25:09 -0800311 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700312 if m, t := SrcIsModuleWithTag(e); m != "" {
313 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800314 if module == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700315 missingExcludeDeps = append(missingExcludeDeps, m)
Colin Cross8a497952019-03-05 22:25:09 -0800316 continue
317 }
Colin Cross41955e82019-05-29 14:40:35 -0700318 if outProducer, ok := module.(OutputFileProducer); ok {
319 outputFiles, err := outProducer.OutputFiles(t)
320 if err != nil {
321 ctx.ModuleErrorf("path dependency %q: %s", e, err)
322 }
323 expandedExcludes = append(expandedExcludes, outputFiles.Strings()...)
324 } else if t != "" {
325 ctx.ModuleErrorf("path dependency %q is not an output file producing module", e)
326 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800327 expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
328 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700329 ctx.ModuleErrorf("path dependency %q is not a source file producing module", e)
Colin Cross8a497952019-03-05 22:25:09 -0800330 }
331 } else {
332 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
333 }
334 }
335
336 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700337 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800338 }
339
Colin Crossba71a3f2019-03-18 12:12:48 -0700340 var missingDeps []string
341
Colin Cross8a497952019-03-05 22:25:09 -0800342 expandedSrcFiles := make(Paths, 0, len(paths))
343 for _, s := range paths {
344 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
345 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700346 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800347 } else if err != nil {
348 reportPathError(ctx, err)
349 }
350 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
351 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700352
353 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800354}
355
356type missingDependencyError struct {
357 missingDeps []string
358}
359
360func (e missingDependencyError) Error() string {
361 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
362}
363
364func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
Colin Cross41955e82019-05-29 14:40:35 -0700365 if m, t := SrcIsModuleWithTag(s); m != "" {
366 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800367 if module == nil {
368 return nil, missingDependencyError{[]string{m}}
369 }
Colin Cross41955e82019-05-29 14:40:35 -0700370 if outProducer, ok := module.(OutputFileProducer); ok {
371 outputFiles, err := outProducer.OutputFiles(t)
372 if err != nil {
373 return nil, fmt.Errorf("path dependency %q: %s", s, err)
374 }
375 return outputFiles, nil
376 } else if t != "" {
377 return nil, fmt.Errorf("path dependency %q is not an output file producing module", s)
378 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800379 moduleSrcs := srcProducer.Srcs()
380 for _, e := range expandedExcludes {
381 for j := 0; j < len(moduleSrcs); j++ {
382 if moduleSrcs[j].String() == e {
383 moduleSrcs = append(moduleSrcs[:j], moduleSrcs[j+1:]...)
384 j--
385 }
386 }
387 }
388 return moduleSrcs, nil
389 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700390 return nil, fmt.Errorf("path dependency %q is not a source file producing module", s)
Colin Cross8a497952019-03-05 22:25:09 -0800391 }
392 } else if pathtools.IsGlob(s) {
393 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
394 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
395 } else {
396 p := pathForModuleSrc(ctx, s)
Colin Cross988414c2020-01-11 01:11:46 +0000397 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Colin Cross8a497952019-03-05 22:25:09 -0800398 reportPathErrorf(ctx, "%s: %s", p, err.Error())
Colin Crossf77c7202020-06-07 16:56:32 -0700399 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Colin Cross8a497952019-03-05 22:25:09 -0800400 reportPathErrorf(ctx, "module source path %q does not exist", p)
401 }
402
403 j := findStringInSlice(p.String(), expandedExcludes)
404 if j >= 0 {
405 return nil, nil
406 }
407 return Paths{p}, nil
408 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700409}
410
411// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
412// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800413// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700414// It intended for use in globs that only list files that exist, so it allows '$' in
415// filenames.
Colin Cross1184b642019-12-30 18:43:07 -0800416func pathsForModuleSrcFromFullPath(ctx EarlyModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800417 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700418 if prefix == "./" {
419 prefix = ""
420 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700421 ret := make(Paths, 0, len(paths))
422 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800423 if !incDirs && strings.HasSuffix(p, "/") {
424 continue
425 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700426 path := filepath.Clean(p)
427 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800428 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700429 continue
430 }
Colin Crosse3924e12018-08-15 20:18:53 -0700431
Colin Crossfe4bc362018-09-12 10:02:13 -0700432 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700433 if err != nil {
434 reportPathError(ctx, err)
435 continue
436 }
437
Colin Cross07e51612019-03-05 12:46:40 -0800438 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700439
Colin Cross07e51612019-03-05 12:46:40 -0800440 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700441 }
442 return ret
443}
444
445// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800446// 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 -0700447func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800448 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700449 return PathsForModuleSrc(ctx, input)
450 }
451 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
452 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800453 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800454 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700455}
456
457// Strings returns the Paths in string form
458func (p Paths) Strings() []string {
459 if p == nil {
460 return nil
461 }
462 ret := make([]string, len(p))
463 for i, path := range p {
464 ret[i] = path.String()
465 }
466 return ret
467}
468
Colin Cross1d11c872020-07-03 11:56:24 -0700469func CopyOfPaths(paths Paths) Paths {
470 return append(Paths(nil), paths...)
471}
472
Colin Crossb6715442017-10-24 11:13:31 -0700473// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
474// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700475func FirstUniquePaths(list Paths) Paths {
476 k := 0
477outer:
478 for i := 0; i < len(list); i++ {
479 for j := 0; j < k; j++ {
480 if list[i] == list[j] {
481 continue outer
482 }
483 }
484 list[k] = list[i]
485 k++
486 }
487 return list[:k]
488}
489
Jiyong Park402ace62020-05-29 22:00:16 +0900490// SortedUniquePaths returns what its name says
491func SortedUniquePaths(list Paths) Paths {
492 unique := FirstUniquePaths(list)
493 sort.Slice(unique, func(i, j int) bool {
494 return unique[i].String() < unique[j].String()
495 })
496 return unique
497}
498
Colin Crossb6715442017-10-24 11:13:31 -0700499// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
500// modifies the Paths slice contents in place, and returns a subslice of the original slice.
501func LastUniquePaths(list Paths) Paths {
502 totalSkip := 0
503 for i := len(list) - 1; i >= totalSkip; i-- {
504 skip := 0
505 for j := i - 1; j >= totalSkip; j-- {
506 if list[i] == list[j] {
507 skip++
508 } else {
509 list[j+skip] = list[j]
510 }
511 }
512 totalSkip += skip
513 }
514 return list[totalSkip:]
515}
516
Colin Crossa140bb02018-04-17 10:52:26 -0700517// ReversePaths returns a copy of a Paths in reverse order.
518func ReversePaths(list Paths) Paths {
519 if list == nil {
520 return nil
521 }
522 ret := make(Paths, len(list))
523 for i := range list {
524 ret[i] = list[len(list)-1-i]
525 }
526 return ret
527}
528
Jeff Gaston294356f2017-09-27 17:05:30 -0700529func indexPathList(s Path, list []Path) int {
530 for i, l := range list {
531 if l == s {
532 return i
533 }
534 }
535
536 return -1
537}
538
539func inPathList(p Path, list []Path) bool {
540 return indexPathList(p, list) != -1
541}
542
543func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000544 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
545}
546
547func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700548 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000549 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700550 filtered = append(filtered, l)
551 } else {
552 remainder = append(remainder, l)
553 }
554 }
555
556 return
557}
558
Colin Cross93e85952017-08-15 13:34:18 -0700559// HasExt returns true of any of the paths have extension ext, otherwise false
560func (p Paths) HasExt(ext string) bool {
561 for _, path := range p {
562 if path.Ext() == ext {
563 return true
564 }
565 }
566
567 return false
568}
569
570// FilterByExt returns the subset of the paths that have extension ext
571func (p Paths) FilterByExt(ext string) Paths {
572 ret := make(Paths, 0, len(p))
573 for _, path := range p {
574 if path.Ext() == ext {
575 ret = append(ret, path)
576 }
577 }
578 return ret
579}
580
581// FilterOutByExt returns the subset of the paths that do not have extension ext
582func (p Paths) FilterOutByExt(ext string) Paths {
583 ret := make(Paths, 0, len(p))
584 for _, path := range p {
585 if path.Ext() != ext {
586 ret = append(ret, path)
587 }
588 }
589 return ret
590}
591
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700592// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
593// (including subdirectories) are in a contiguous subslice of the list, and can be found in
594// O(log(N)) time using a binary search on the directory prefix.
595type DirectorySortedPaths Paths
596
597func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
598 ret := append(DirectorySortedPaths(nil), paths...)
599 sort.Slice(ret, func(i, j int) bool {
600 return ret[i].String() < ret[j].String()
601 })
602 return ret
603}
604
605// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
606// that are in the specified directory and its subdirectories.
607func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
608 prefix := filepath.Clean(dir) + "/"
609 start := sort.Search(len(p), func(i int) bool {
610 return prefix < p[i].String()
611 })
612
613 ret := p[start:]
614
615 end := sort.Search(len(ret), func(i int) bool {
616 return !strings.HasPrefix(ret[i].String(), prefix)
617 })
618
619 ret = ret[:end]
620
621 return Paths(ret)
622}
623
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700624// WritablePaths is a slice of WritablePaths, used for multiple outputs.
625type WritablePaths []WritablePath
626
627// Strings returns the string forms of the writable paths.
628func (p WritablePaths) Strings() []string {
629 if p == nil {
630 return nil
631 }
632 ret := make([]string, len(p))
633 for i, path := range p {
634 ret[i] = path.String()
635 }
636 return ret
637}
638
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800639// Paths returns the WritablePaths as a Paths
640func (p WritablePaths) Paths() Paths {
641 if p == nil {
642 return nil
643 }
644 ret := make(Paths, len(p))
645 for i, path := range p {
646 ret[i] = path
647 }
648 return ret
649}
650
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700651type basePath struct {
652 path string
653 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800654 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700655}
656
657func (p basePath) Ext() string {
658 return filepath.Ext(p.path)
659}
660
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700661func (p basePath) Base() string {
662 return filepath.Base(p.path)
663}
664
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800665func (p basePath) Rel() string {
666 if p.rel != "" {
667 return p.rel
668 }
669 return p.path
670}
671
Colin Cross0875c522017-11-28 17:34:01 -0800672func (p basePath) String() string {
673 return p.path
674}
675
Colin Cross0db55682017-12-05 15:36:55 -0800676func (p basePath) withRel(rel string) basePath {
677 p.path = filepath.Join(p.path, rel)
678 p.rel = rel
679 return p
680}
681
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700682// SourcePath is a Path representing a file path rooted from SrcDir
683type SourcePath struct {
684 basePath
685}
686
687var _ Path = SourcePath{}
688
Colin Cross0db55682017-12-05 15:36:55 -0800689func (p SourcePath) withRel(rel string) SourcePath {
690 p.basePath = p.basePath.withRel(rel)
691 return p
692}
693
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700694// safePathForSource is for paths that we expect are safe -- only for use by go
695// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700696func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
697 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800698 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700699 if err != nil {
700 return ret, err
701 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700702
Colin Cross7b3dcc32019-01-24 13:14:39 -0800703 // absolute path already checked by validateSafePath
704 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800705 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700706 }
707
Colin Crossfe4bc362018-09-12 10:02:13 -0700708 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700709}
710
Colin Cross192e97a2018-02-22 14:21:02 -0800711// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
712func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000713 p, err := validatePath(pathComponents...)
714 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800715 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800716 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800717 }
718
Colin Cross7b3dcc32019-01-24 13:14:39 -0800719 // absolute path already checked by validatePath
720 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800721 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000722 }
723
Colin Cross192e97a2018-02-22 14:21:02 -0800724 return ret, nil
725}
726
Sam Mortimerf25f77c2019-09-05 15:16:13 -0700727// pathForSourceRelaxed creates a SourcePath from pathComponents, but does not check that it exists.
728// It differs from pathForSource in that the path is allowed to exist outside of the PathContext.
729func pathForSourceRelaxed(ctx PathContext, pathComponents ...string) (SourcePath, error) {
730 p := filepath.Join(pathComponents...)
731 ret := SourcePath{basePath{p, ctx.Config(), ""}}
732
733 abs, err := filepath.Abs(ret.String())
734 if err != nil {
735 return ret, err
736 }
737 buildroot, err := filepath.Abs(ctx.Config().buildDir)
738 if err != nil {
739 return ret, err
740 }
741 if strings.HasPrefix(abs, buildroot) {
742 return ret, fmt.Errorf("source path %s is in output", abs)
743 }
744
745 if pathtools.IsGlob(ret.String()) {
746 return ret, fmt.Errorf("path may not contain a glob: %s", ret.String())
747 }
748
749 return ret, nil
750}
751
Colin Cross192e97a2018-02-22 14:21:02 -0800752// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
753// path does not exist.
754func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
755 var files []string
756
757 if gctx, ok := ctx.(PathGlobContext); ok {
758 // Use glob to produce proper dependencies, even though we only want
759 // a single file.
760 files, err = gctx.GlobWithDeps(path.String(), nil)
761 } else {
762 var deps []string
763 // We cannot add build statements in this context, so we fall back to
764 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +0000765 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800766 ctx.AddNinjaFileDeps(deps...)
767 }
768
769 if err != nil {
770 return false, fmt.Errorf("glob: %s", err.Error())
771 }
772
773 return len(files) > 0, nil
774}
775
776// PathForSource joins the provided path components and validates that the result
777// neither escapes the source dir nor is in the out dir.
778// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
779func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
780 path, err := pathForSource(ctx, pathComponents...)
781 if err != nil {
782 reportPathError(ctx, err)
783 }
784
Colin Crosse3924e12018-08-15 20:18:53 -0700785 if pathtools.IsGlob(path.String()) {
786 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
787 }
788
Colin Cross192e97a2018-02-22 14:21:02 -0800789 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
790 exists, err := existsWithDependencies(ctx, path)
791 if err != nil {
792 reportPathError(ctx, err)
793 }
794 if !exists {
795 modCtx.AddMissingDependencies([]string{path.String()})
796 }
Colin Cross988414c2020-01-11 01:11:46 +0000797 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800798 reportPathErrorf(ctx, "%s: %s", path, err.Error())
Colin Crossf77c7202020-06-07 16:56:32 -0700799 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800800 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800801 }
802 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700803}
804
Sam Mortimerf25f77c2019-09-05 15:16:13 -0700805// PathForSourceRelaxed joins the provided path components. Unlike PathForSource,
806// the result is allowed to exist outside of the source dir.
807// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
808func PathForSourceRelaxed(ctx PathContext, pathComponents ...string) SourcePath {
809 path, err := pathForSourceRelaxed(ctx, pathComponents...)
810 if err != nil {
811 reportPathError(ctx, err)
812 }
813
814 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
815 exists, err := existsWithDependencies(ctx, path)
816 if err != nil {
817 reportPathError(ctx, err)
818 }
819 if !exists {
820 modCtx.AddMissingDependencies([]string{path.String()})
821 }
822 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
823 reportPathErrorf(ctx, "%s: %s", path, err.Error())
824 } else if !exists {
825 reportPathErrorf(ctx, "source path %s does not exist", path)
826 }
827 return path
828}
829
Jeff Gaston734e3802017-04-10 15:47:24 -0700830// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700831// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
832// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800833func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800834 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800835 if err != nil {
836 reportPathError(ctx, err)
837 return OptionalPath{}
838 }
Colin Crossc48c1432018-02-23 07:09:01 +0000839
Colin Crosse3924e12018-08-15 20:18:53 -0700840 if pathtools.IsGlob(path.String()) {
841 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
842 return OptionalPath{}
843 }
844
Colin Cross192e97a2018-02-22 14:21:02 -0800845 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000846 if err != nil {
847 reportPathError(ctx, err)
848 return OptionalPath{}
849 }
Colin Cross192e97a2018-02-22 14:21:02 -0800850 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000851 return OptionalPath{}
852 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700853 return OptionalPathForPath(path)
854}
855
856func (p SourcePath) String() string {
857 return filepath.Join(p.config.srcDir, p.path)
858}
859
860// Join creates a new SourcePath with paths... joined with the current path. The
861// provided paths... may not use '..' to escape from the current path.
862func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800863 path, err := validatePath(paths...)
864 if err != nil {
865 reportPathError(ctx, err)
866 }
Colin Cross0db55682017-12-05 15:36:55 -0800867 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700868}
869
Colin Cross2fafa3e2019-03-05 12:39:51 -0800870// join is like Join but does less path validation.
871func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
872 path, err := validateSafePath(paths...)
873 if err != nil {
874 reportPathError(ctx, err)
875 }
876 return p.withRel(path)
877}
878
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700879// OverlayPath returns the overlay for `path' if it exists. This assumes that the
880// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700881func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700882 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800883 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700884 relDir = srcPath.path
885 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800886 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700887 return OptionalPath{}
888 }
889 dir := filepath.Join(p.config.srcDir, p.path, relDir)
890 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700891 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800892 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800893 }
Colin Cross461b4452018-02-23 09:22:42 -0800894 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700895 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800896 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700897 return OptionalPath{}
898 }
899 if len(paths) == 0 {
900 return OptionalPath{}
901 }
Colin Cross43f08db2018-11-12 10:13:39 -0800902 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700903 return OptionalPathForPath(PathForSource(ctx, relPath))
904}
905
Colin Cross70dda7e2019-10-01 22:05:35 -0700906// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700907type OutputPath struct {
908 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -0800909 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700910}
911
Colin Cross702e0f82017-10-18 17:27:54 -0700912func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800913 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -0800914 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700915 return p
916}
917
Colin Cross3063b782018-08-15 11:19:12 -0700918func (p OutputPath) WithoutRel() OutputPath {
919 p.basePath.rel = filepath.Base(p.basePath.path)
920 return p
921}
922
Paul Duffin9b478b02019-12-10 13:41:51 +0000923func (p OutputPath) buildDir() string {
924 return p.config.buildDir
925}
926
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700927var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +0000928var _ WritablePath = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700929
Jeff Gaston734e3802017-04-10 15:47:24 -0700930// PathForOutput joins the provided paths and returns an OutputPath that is
931// validated to not escape the build dir.
932// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
933func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800934 path, err := validatePath(pathComponents...)
935 if err != nil {
936 reportPathError(ctx, err)
937 }
Colin Crossd63c9a72020-01-29 16:52:50 -0800938 fullPath := filepath.Join(ctx.Config().buildDir, path)
939 path = fullPath[len(fullPath)-len(path):]
940 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700941}
942
Colin Cross40e33732019-02-15 11:08:35 -0800943// PathsForOutput returns Paths rooted from buildDir
944func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
945 ret := make(WritablePaths, len(paths))
946 for i, path := range paths {
947 ret[i] = PathForOutput(ctx, path)
948 }
949 return ret
950}
951
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700952func (p OutputPath) writablePath() {}
953
954func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -0800955 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700956}
957
958// Join creates a new OutputPath with paths... joined with the current path. The
959// provided paths... may not use '..' to escape from the current path.
960func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800961 path, err := validatePath(paths...)
962 if err != nil {
963 reportPathError(ctx, err)
964 }
Colin Cross0db55682017-12-05 15:36:55 -0800965 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700966}
967
Colin Cross8854a5a2019-02-11 14:14:16 -0800968// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
969func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
970 if strings.Contains(ext, "/") {
971 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
972 }
973 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800974 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800975 return ret
976}
977
Colin Cross40e33732019-02-15 11:08:35 -0800978// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
979func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
980 path, err := validatePath(paths...)
981 if err != nil {
982 reportPathError(ctx, err)
983 }
984
985 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800986 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800987 return ret
988}
989
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700990// PathForIntermediates returns an OutputPath representing the top-level
991// intermediates directory.
992func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800993 path, err := validatePath(paths...)
994 if err != nil {
995 reportPathError(ctx, err)
996 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700997 return PathForOutput(ctx, ".intermediates", path)
998}
999
Colin Cross07e51612019-03-05 12:46:40 -08001000var _ genPathProvider = SourcePath{}
1001var _ objPathProvider = SourcePath{}
1002var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001003
Colin Cross07e51612019-03-05 12:46:40 -08001004// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001005// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -08001006func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
1007 p, err := validatePath(pathComponents...)
1008 if err != nil {
1009 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001010 }
Colin Cross8a497952019-03-05 22:25:09 -08001011 paths, err := expandOneSrcPath(ctx, p, nil)
1012 if err != nil {
1013 if depErr, ok := err.(missingDependencyError); ok {
1014 if ctx.Config().AllowMissingDependencies() {
1015 ctx.AddMissingDependencies(depErr.missingDeps)
1016 } else {
1017 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1018 }
1019 } else {
1020 reportPathError(ctx, err)
1021 }
1022 return nil
1023 } else if len(paths) == 0 {
1024 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
1025 return nil
1026 } else if len(paths) > 1 {
1027 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
1028 }
1029 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001030}
1031
Colin Cross07e51612019-03-05 12:46:40 -08001032func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
1033 p, err := validatePath(paths...)
1034 if err != nil {
1035 reportPathError(ctx, err)
1036 }
1037
1038 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1039 if err != nil {
1040 reportPathError(ctx, err)
1041 }
1042
1043 path.basePath.rel = p
1044
1045 return path
1046}
1047
Colin Cross2fafa3e2019-03-05 12:39:51 -08001048// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1049// will return the path relative to subDir in the module's source directory. If any input paths are not located
1050// inside subDir then a path error will be reported.
1051func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
1052 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001053 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001054 for i, path := range paths {
1055 rel := Rel(ctx, subDirFullPath.String(), path.String())
1056 paths[i] = subDirFullPath.join(ctx, rel)
1057 }
1058 return paths
1059}
1060
1061// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1062// module's source directory. If the input path is not located inside subDir then a path error will be reported.
1063func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001064 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001065 rel := Rel(ctx, subDirFullPath.String(), path.String())
1066 return subDirFullPath.Join(ctx, rel)
1067}
1068
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001069// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1070// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -07001071func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001072 if p == nil {
1073 return OptionalPath{}
1074 }
1075 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1076}
1077
Colin Cross07e51612019-03-05 12:46:40 -08001078func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001079 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001080}
1081
Colin Cross07e51612019-03-05 12:46:40 -08001082func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001083 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001084}
1085
Colin Cross07e51612019-03-05 12:46:40 -08001086func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001087 // TODO: Use full directory if the new ctx is not the current ctx?
1088 return PathForModuleRes(ctx, p.path, name)
1089}
1090
1091// ModuleOutPath is a Path representing a module's output directory.
1092type ModuleOutPath struct {
1093 OutputPath
1094}
1095
1096var _ Path = ModuleOutPath{}
1097
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001098func (p ModuleOutPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
1099 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1100}
1101
Colin Cross702e0f82017-10-18 17:27:54 -07001102func pathForModule(ctx ModuleContext) OutputPath {
1103 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1104}
1105
Logan Chien7eefdc42018-07-11 18:10:41 +08001106// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1107// reference abi dump for the given module. This is not guaranteed to be valid.
1108func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001109 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001110
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001111 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001112 if len(arches) == 0 {
1113 panic("device build with no primary arch")
1114 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001115 currentArch := ctx.Arch()
1116 archNameAndVariant := currentArch.ArchType.String()
1117 if currentArch.ArchVariant != "" {
1118 archNameAndVariant += "_" + currentArch.ArchVariant
1119 }
Logan Chien5237bed2018-07-11 17:15:57 +08001120
1121 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001122 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001123 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001124 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001125 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001126 } else {
1127 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001128 }
Logan Chien5237bed2018-07-11 17:15:57 +08001129
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001130 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001131
1132 var ext string
1133 if isGzip {
1134 ext = ".lsdump.gz"
1135 } else {
1136 ext = ".lsdump"
1137 }
1138
1139 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1140 version, binderBitness, archNameAndVariant, "source-based",
1141 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001142}
1143
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001144// PathForModuleOut returns a Path representing the paths... under the module's
1145// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001146func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001147 p, err := validatePath(paths...)
1148 if err != nil {
1149 reportPathError(ctx, err)
1150 }
Colin Cross702e0f82017-10-18 17:27:54 -07001151 return ModuleOutPath{
1152 OutputPath: pathForModule(ctx).withRel(p),
1153 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001154}
1155
1156// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1157// directory. Mainly used for generated sources.
1158type ModuleGenPath struct {
1159 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001160}
1161
1162var _ Path = ModuleGenPath{}
1163var _ genPathProvider = ModuleGenPath{}
1164var _ objPathProvider = ModuleGenPath{}
1165
1166// PathForModuleGen returns a Path representing the paths... under the module's
1167// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001168func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001169 p, err := validatePath(paths...)
1170 if err != nil {
1171 reportPathError(ctx, err)
1172 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001173 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001174 ModuleOutPath: ModuleOutPath{
1175 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1176 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001177 }
1178}
1179
Dan Willemsen21ec4902016-11-02 20:43:13 -07001180func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001181 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001182 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001183}
1184
Colin Cross635c3b02016-05-18 15:37:25 -07001185func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001186 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1187}
1188
1189// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1190// directory. Used for compiled objects.
1191type ModuleObjPath struct {
1192 ModuleOutPath
1193}
1194
1195var _ Path = ModuleObjPath{}
1196
1197// PathForModuleObj returns a Path representing the paths... under the module's
1198// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001199func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001200 p, err := validatePath(pathComponents...)
1201 if err != nil {
1202 reportPathError(ctx, err)
1203 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001204 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1205}
1206
1207// ModuleResPath is a a Path representing the 'res' directory in a module's
1208// output directory.
1209type ModuleResPath struct {
1210 ModuleOutPath
1211}
1212
1213var _ Path = ModuleResPath{}
1214
1215// PathForModuleRes returns a Path representing the paths... under the module's
1216// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001217func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001218 p, err := validatePath(pathComponents...)
1219 if err != nil {
1220 reportPathError(ctx, err)
1221 }
1222
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001223 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1224}
1225
Colin Cross70dda7e2019-10-01 22:05:35 -07001226// InstallPath is a Path representing a installed file path rooted from the build directory
1227type InstallPath struct {
1228 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001229
1230 baseDir string // "../" for Make paths to convert "out/soong" to "out", "" for Soong paths
Colin Cross70dda7e2019-10-01 22:05:35 -07001231}
1232
Paul Duffin9b478b02019-12-10 13:41:51 +00001233func (p InstallPath) buildDir() string {
1234 return p.config.buildDir
1235}
1236
1237var _ Path = InstallPath{}
1238var _ WritablePath = InstallPath{}
1239
Colin Cross70dda7e2019-10-01 22:05:35 -07001240func (p InstallPath) writablePath() {}
1241
1242func (p InstallPath) String() string {
Colin Crossff6c33d2019-10-02 16:01:35 -07001243 return filepath.Join(p.config.buildDir, p.baseDir, p.path)
Colin Cross70dda7e2019-10-01 22:05:35 -07001244}
1245
1246// Join creates a new InstallPath with paths... joined with the current path. The
1247// provided paths... may not use '..' to escape from the current path.
1248func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1249 path, err := validatePath(paths...)
1250 if err != nil {
1251 reportPathError(ctx, err)
1252 }
1253 return p.withRel(path)
1254}
1255
1256func (p InstallPath) withRel(rel string) InstallPath {
1257 p.basePath = p.basePath.withRel(rel)
1258 return p
1259}
1260
Colin Crossff6c33d2019-10-02 16:01:35 -07001261// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1262// i.e. out/ instead of out/soong/.
1263func (p InstallPath) ToMakePath() InstallPath {
1264 p.baseDir = "../"
1265 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001266}
1267
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001268// PathForModuleInstall returns a Path representing the install path for the
1269// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001270func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001271 var outPaths []string
1272 if ctx.Device() {
Colin Cross43f08db2018-11-12 10:13:39 -08001273 partition := modulePartition(ctx)
Colin Cross6510f912017-11-29 00:27:14 -08001274 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001275 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -07001276 switch ctx.Os() {
1277 case Linux:
1278 outPaths = []string{"host", "linux-x86"}
1279 case LinuxBionic:
1280 // TODO: should this be a separate top level, or shared with linux-x86?
1281 outPaths = []string{"host", "linux_bionic-x86"}
1282 default:
1283 outPaths = []string{"host", ctx.Os().String() + "-x86"}
1284 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001285 }
Dan Willemsen782a2d12015-12-21 14:55:28 -08001286 if ctx.Debug() {
1287 outPaths = append([]string{"debug"}, outPaths...)
1288 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001289 outPaths = append(outPaths, pathComponents...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001290
1291 path, err := validatePath(outPaths...)
1292 if err != nil {
1293 reportPathError(ctx, err)
1294 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001295
1296 ret := InstallPath{basePath{path, ctx.Config(), ""}, ""}
1297 if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
1298 ret = ret.ToMakePath()
1299 }
1300
1301 return ret
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001302}
1303
Nicolas Geoffraya40f0b52020-02-27 13:45:35 +00001304func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
1305 paths = append([]string{prefix}, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001306 path, err := validatePath(paths...)
1307 if err != nil {
1308 reportPathError(ctx, err)
1309 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001310 return InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Cross70dda7e2019-10-01 22:05:35 -07001311}
1312
Nicolas Geoffraya40f0b52020-02-27 13:45:35 +00001313func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1314 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1315}
1316
1317func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1318 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1319}
1320
Colin Cross70dda7e2019-10-01 22:05:35 -07001321func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001322 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1323
1324 return "/" + rel
1325}
1326
1327func modulePartition(ctx ModuleInstallPathContext) string {
1328 var partition string
1329 if ctx.InstallInData() {
1330 partition = "data"
Jaewoong Jung0949f312019-09-11 10:25:18 -07001331 } else if ctx.InstallInTestcases() {
1332 partition = "testcases"
Yifan Hong1b3348d2020-01-21 15:53:22 -08001333 } else if ctx.InstallInRamdisk() {
Yifan Hong82db7352020-01-21 16:12:26 -08001334 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1335 partition = "recovery/root/first_stage_ramdisk"
1336 } else {
1337 partition = "ramdisk"
1338 }
1339 if !ctx.InstallInRoot() {
1340 partition += "/system"
1341 }
Colin Cross43f08db2018-11-12 10:13:39 -08001342 } else if ctx.InstallInRecovery() {
Colin Cross90ba5f42019-10-02 11:10:58 -07001343 if ctx.InstallInRoot() {
1344 partition = "recovery/root"
1345 } else {
1346 // the layout of recovery partion is the same as that of system partition
1347 partition = "recovery/root/system"
1348 }
Colin Cross43f08db2018-11-12 10:13:39 -08001349 } else if ctx.SocSpecific() {
1350 partition = ctx.DeviceConfig().VendorPath()
1351 } else if ctx.DeviceSpecific() {
1352 partition = ctx.DeviceConfig().OdmPath()
1353 } else if ctx.ProductSpecific() {
1354 partition = ctx.DeviceConfig().ProductPath()
Justin Yund5f6c822019-06-25 16:47:17 +09001355 } else if ctx.SystemExtSpecific() {
1356 partition = ctx.DeviceConfig().SystemExtPath()
Colin Cross90ba5f42019-10-02 11:10:58 -07001357 } else if ctx.InstallInRoot() {
1358 partition = "root"
Colin Cross43f08db2018-11-12 10:13:39 -08001359 } else {
1360 partition = "system"
1361 }
1362 if ctx.InstallInSanitizerDir() {
1363 partition = "data/asan/" + partition
1364 }
1365 return partition
1366}
1367
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001368// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001369// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001370func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001371 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001372 path := filepath.Clean(path)
1373 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001374 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001375 }
1376 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001377 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1378 // variables. '..' may remove the entire ninja variable, even if it
1379 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001380 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001381}
1382
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001383// validatePath validates that a path does not include ninja variables, and that
1384// each path component does not attempt to leave its component. Returns a joined
1385// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001386func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001387 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001388 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001389 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001390 }
1391 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001392 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001393}
Colin Cross5b529592017-05-09 13:34:34 -07001394
Colin Cross0875c522017-11-28 17:34:01 -08001395func PathForPhony(ctx PathContext, phony string) WritablePath {
1396 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001397 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001398 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001399 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001400}
1401
Colin Cross74e3fe42017-12-11 15:51:44 -08001402type PhonyPath struct {
1403 basePath
1404}
1405
1406func (p PhonyPath) writablePath() {}
1407
Paul Duffin9b478b02019-12-10 13:41:51 +00001408func (p PhonyPath) buildDir() string {
1409 return p.config.buildDir
1410}
1411
Colin Cross74e3fe42017-12-11 15:51:44 -08001412var _ Path = PhonyPath{}
1413var _ WritablePath = PhonyPath{}
1414
Colin Cross5b529592017-05-09 13:34:34 -07001415type testPath struct {
1416 basePath
1417}
1418
1419func (p testPath) String() string {
1420 return p.path
1421}
1422
Colin Cross40e33732019-02-15 11:08:35 -08001423// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1424// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001425func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001426 p, err := validateSafePath(paths...)
1427 if err != nil {
1428 panic(err)
1429 }
Colin Cross5b529592017-05-09 13:34:34 -07001430 return testPath{basePath{path: p, rel: p}}
1431}
1432
Colin Cross40e33732019-02-15 11:08:35 -08001433// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1434func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001435 p := make(Paths, len(strs))
1436 for i, s := range strs {
1437 p[i] = PathForTesting(s)
1438 }
1439
1440 return p
1441}
Colin Cross43f08db2018-11-12 10:13:39 -08001442
Colin Cross40e33732019-02-15 11:08:35 -08001443type testPathContext struct {
1444 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001445}
1446
Colin Cross40e33732019-02-15 11:08:35 -08001447func (x *testPathContext) Config() Config { return x.config }
1448func (x *testPathContext) AddNinjaFileDeps(...string) {}
1449
1450// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1451// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001452func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001453 return &testPathContext{
1454 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001455 }
1456}
1457
Colin Cross43f08db2018-11-12 10:13:39 -08001458// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1459// targetPath is not inside basePath.
1460func Rel(ctx PathContext, basePath string, targetPath string) string {
1461 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1462 if !isRel {
1463 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1464 return ""
1465 }
1466 return rel
1467}
1468
1469// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1470// targetPath is not inside basePath.
1471func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001472 rel, isRel, err := maybeRelErr(basePath, targetPath)
1473 if err != nil {
1474 reportPathError(ctx, err)
1475 }
1476 return rel, isRel
1477}
1478
1479func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001480 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1481 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001482 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001483 }
1484 rel, err := filepath.Rel(basePath, targetPath)
1485 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001486 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001487 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001488 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001489 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001490 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001491}
Colin Cross988414c2020-01-11 01:11:46 +00001492
1493// Writes a file to the output directory. Attempting to write directly to the output directory
1494// will fail due to the sandbox of the soong_build process.
1495func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1496 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1497}
1498
1499func absolutePath(path string) string {
1500 if filepath.IsAbs(path) {
1501 return path
1502 }
1503 return filepath.Join(absSrcDir, path)
1504}