blob: 8bd2c61e78d521d85446116210c23f50a77b6c42 [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 {
Colin Cross0ea8ba82019-06-06 14:33:29 -070044 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -070045
46 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -070047 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -070048 InstallInSanitizerDir() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +090049 InstallInRecovery() bool
Colin Cross607d8582019-07-29 16:44:46 -070050 InstallBypassMake() 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
Colin Cross41955e82019-05-29 14:40:35 -0700220// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
221// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
222// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
223// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
224// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
225// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Colin Cross635c3b02016-05-18 15:37:25 -0700226func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800227 return PathsForModuleSrcExcludes(ctx, paths, nil)
228}
229
Colin Crossba71a3f2019-03-18 12:12:48 -0700230// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700231// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
232// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
233// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
234// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100235// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700236// having missing dependencies.
Colin Cross8a497952019-03-05 22:25:09 -0800237func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700238 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
239 if ctx.Config().AllowMissingDependencies() {
240 ctx.AddMissingDependencies(missingDeps)
241 } else {
242 for _, m := range missingDeps {
243 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
244 }
245 }
246 return ret
247}
248
249// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700250// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
251// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
252// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
253// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
254// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
255// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
256// dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700257func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800258 prefix := pathForModuleSrc(ctx).String()
259
260 var expandedExcludes []string
261 if excludes != nil {
262 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700263 }
Colin Cross8a497952019-03-05 22:25:09 -0800264
Colin Crossba71a3f2019-03-18 12:12:48 -0700265 var missingExcludeDeps []string
266
Colin Cross8a497952019-03-05 22:25:09 -0800267 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700268 if m, t := SrcIsModuleWithTag(e); m != "" {
269 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800270 if module == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700271 missingExcludeDeps = append(missingExcludeDeps, m)
Colin Cross8a497952019-03-05 22:25:09 -0800272 continue
273 }
Colin Cross41955e82019-05-29 14:40:35 -0700274 if outProducer, ok := module.(OutputFileProducer); ok {
275 outputFiles, err := outProducer.OutputFiles(t)
276 if err != nil {
277 ctx.ModuleErrorf("path dependency %q: %s", e, err)
278 }
279 expandedExcludes = append(expandedExcludes, outputFiles.Strings()...)
280 } else if t != "" {
281 ctx.ModuleErrorf("path dependency %q is not an output file producing module", e)
282 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800283 expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
284 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700285 ctx.ModuleErrorf("path dependency %q is not a source file producing module", e)
Colin Cross8a497952019-03-05 22:25:09 -0800286 }
287 } else {
288 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
289 }
290 }
291
292 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700293 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800294 }
295
Colin Crossba71a3f2019-03-18 12:12:48 -0700296 var missingDeps []string
297
Colin Cross8a497952019-03-05 22:25:09 -0800298 expandedSrcFiles := make(Paths, 0, len(paths))
299 for _, s := range paths {
300 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
301 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700302 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800303 } else if err != nil {
304 reportPathError(ctx, err)
305 }
306 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
307 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700308
309 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800310}
311
312type missingDependencyError struct {
313 missingDeps []string
314}
315
316func (e missingDependencyError) Error() string {
317 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
318}
319
320func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
Colin Cross41955e82019-05-29 14:40:35 -0700321 if m, t := SrcIsModuleWithTag(s); m != "" {
322 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800323 if module == nil {
324 return nil, missingDependencyError{[]string{m}}
325 }
Colin Cross41955e82019-05-29 14:40:35 -0700326 if outProducer, ok := module.(OutputFileProducer); ok {
327 outputFiles, err := outProducer.OutputFiles(t)
328 if err != nil {
329 return nil, fmt.Errorf("path dependency %q: %s", s, err)
330 }
331 return outputFiles, nil
332 } else if t != "" {
333 return nil, fmt.Errorf("path dependency %q is not an output file producing module", s)
334 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800335 moduleSrcs := srcProducer.Srcs()
336 for _, e := range expandedExcludes {
337 for j := 0; j < len(moduleSrcs); j++ {
338 if moduleSrcs[j].String() == e {
339 moduleSrcs = append(moduleSrcs[:j], moduleSrcs[j+1:]...)
340 j--
341 }
342 }
343 }
344 return moduleSrcs, nil
345 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700346 return nil, fmt.Errorf("path dependency %q is not a source file producing module", s)
Colin Cross8a497952019-03-05 22:25:09 -0800347 }
348 } else if pathtools.IsGlob(s) {
349 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
350 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
351 } else {
352 p := pathForModuleSrc(ctx, s)
353 if exists, _, err := ctx.Fs().Exists(p.String()); err != nil {
354 reportPathErrorf(ctx, "%s: %s", p, err.Error())
355 } else if !exists {
356 reportPathErrorf(ctx, "module source path %q does not exist", p)
357 }
358
359 j := findStringInSlice(p.String(), expandedExcludes)
360 if j >= 0 {
361 return nil, nil
362 }
363 return Paths{p}, nil
364 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700365}
366
367// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
368// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800369// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700370// It intended for use in globs that only list files that exist, so it allows '$' in
371// filenames.
Colin Crossdc35e212019-06-06 16:13:11 -0700372func pathsForModuleSrcFromFullPath(ctx BaseModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800373 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700374 if prefix == "./" {
375 prefix = ""
376 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700377 ret := make(Paths, 0, len(paths))
378 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800379 if !incDirs && strings.HasSuffix(p, "/") {
380 continue
381 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700382 path := filepath.Clean(p)
383 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800384 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700385 continue
386 }
Colin Crosse3924e12018-08-15 20:18:53 -0700387
Colin Crossfe4bc362018-09-12 10:02:13 -0700388 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700389 if err != nil {
390 reportPathError(ctx, err)
391 continue
392 }
393
Colin Cross07e51612019-03-05 12:46:40 -0800394 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700395
Colin Cross07e51612019-03-05 12:46:40 -0800396 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700397 }
398 return ret
399}
400
401// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800402// 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 -0700403func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800404 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700405 return PathsForModuleSrc(ctx, input)
406 }
407 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
408 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800409 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800410 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700411}
412
413// Strings returns the Paths in string form
414func (p Paths) Strings() []string {
415 if p == nil {
416 return nil
417 }
418 ret := make([]string, len(p))
419 for i, path := range p {
420 ret[i] = path.String()
421 }
422 return ret
423}
424
Colin Crossb6715442017-10-24 11:13:31 -0700425// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
426// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700427func FirstUniquePaths(list Paths) Paths {
428 k := 0
429outer:
430 for i := 0; i < len(list); i++ {
431 for j := 0; j < k; j++ {
432 if list[i] == list[j] {
433 continue outer
434 }
435 }
436 list[k] = list[i]
437 k++
438 }
439 return list[:k]
440}
441
Colin Crossb6715442017-10-24 11:13:31 -0700442// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
443// modifies the Paths slice contents in place, and returns a subslice of the original slice.
444func LastUniquePaths(list Paths) Paths {
445 totalSkip := 0
446 for i := len(list) - 1; i >= totalSkip; i-- {
447 skip := 0
448 for j := i - 1; j >= totalSkip; j-- {
449 if list[i] == list[j] {
450 skip++
451 } else {
452 list[j+skip] = list[j]
453 }
454 }
455 totalSkip += skip
456 }
457 return list[totalSkip:]
458}
459
Colin Crossa140bb02018-04-17 10:52:26 -0700460// ReversePaths returns a copy of a Paths in reverse order.
461func ReversePaths(list Paths) Paths {
462 if list == nil {
463 return nil
464 }
465 ret := make(Paths, len(list))
466 for i := range list {
467 ret[i] = list[len(list)-1-i]
468 }
469 return ret
470}
471
Jeff Gaston294356f2017-09-27 17:05:30 -0700472func indexPathList(s Path, list []Path) int {
473 for i, l := range list {
474 if l == s {
475 return i
476 }
477 }
478
479 return -1
480}
481
482func inPathList(p Path, list []Path) bool {
483 return indexPathList(p, list) != -1
484}
485
486func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
487 for _, l := range list {
488 if inPathList(l, filter) {
489 filtered = append(filtered, l)
490 } else {
491 remainder = append(remainder, l)
492 }
493 }
494
495 return
496}
497
Colin Cross93e85952017-08-15 13:34:18 -0700498// HasExt returns true of any of the paths have extension ext, otherwise false
499func (p Paths) HasExt(ext string) bool {
500 for _, path := range p {
501 if path.Ext() == ext {
502 return true
503 }
504 }
505
506 return false
507}
508
509// FilterByExt returns the subset of the paths that have extension ext
510func (p Paths) FilterByExt(ext string) Paths {
511 ret := make(Paths, 0, len(p))
512 for _, path := range p {
513 if path.Ext() == ext {
514 ret = append(ret, path)
515 }
516 }
517 return ret
518}
519
520// FilterOutByExt returns the subset of the paths that do not have extension ext
521func (p Paths) FilterOutByExt(ext string) Paths {
522 ret := make(Paths, 0, len(p))
523 for _, path := range p {
524 if path.Ext() != ext {
525 ret = append(ret, path)
526 }
527 }
528 return ret
529}
530
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700531// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
532// (including subdirectories) are in a contiguous subslice of the list, and can be found in
533// O(log(N)) time using a binary search on the directory prefix.
534type DirectorySortedPaths Paths
535
536func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
537 ret := append(DirectorySortedPaths(nil), paths...)
538 sort.Slice(ret, func(i, j int) bool {
539 return ret[i].String() < ret[j].String()
540 })
541 return ret
542}
543
544// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
545// that are in the specified directory and its subdirectories.
546func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
547 prefix := filepath.Clean(dir) + "/"
548 start := sort.Search(len(p), func(i int) bool {
549 return prefix < p[i].String()
550 })
551
552 ret := p[start:]
553
554 end := sort.Search(len(ret), func(i int) bool {
555 return !strings.HasPrefix(ret[i].String(), prefix)
556 })
557
558 ret = ret[:end]
559
560 return Paths(ret)
561}
562
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700563// WritablePaths is a slice of WritablePaths, used for multiple outputs.
564type WritablePaths []WritablePath
565
566// Strings returns the string forms of the writable paths.
567func (p WritablePaths) Strings() []string {
568 if p == nil {
569 return nil
570 }
571 ret := make([]string, len(p))
572 for i, path := range p {
573 ret[i] = path.String()
574 }
575 return ret
576}
577
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800578// Paths returns the WritablePaths as a Paths
579func (p WritablePaths) Paths() Paths {
580 if p == nil {
581 return nil
582 }
583 ret := make(Paths, len(p))
584 for i, path := range p {
585 ret[i] = path
586 }
587 return ret
588}
589
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700590type basePath struct {
591 path string
592 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800593 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700594}
595
596func (p basePath) Ext() string {
597 return filepath.Ext(p.path)
598}
599
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700600func (p basePath) Base() string {
601 return filepath.Base(p.path)
602}
603
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800604func (p basePath) Rel() string {
605 if p.rel != "" {
606 return p.rel
607 }
608 return p.path
609}
610
Colin Cross0875c522017-11-28 17:34:01 -0800611func (p basePath) String() string {
612 return p.path
613}
614
Colin Cross0db55682017-12-05 15:36:55 -0800615func (p basePath) withRel(rel string) basePath {
616 p.path = filepath.Join(p.path, rel)
617 p.rel = rel
618 return p
619}
620
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700621// SourcePath is a Path representing a file path rooted from SrcDir
622type SourcePath struct {
623 basePath
624}
625
626var _ Path = SourcePath{}
627
Colin Cross0db55682017-12-05 15:36:55 -0800628func (p SourcePath) withRel(rel string) SourcePath {
629 p.basePath = p.basePath.withRel(rel)
630 return p
631}
632
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700633// safePathForSource is for paths that we expect are safe -- only for use by go
634// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700635func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
636 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800637 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700638 if err != nil {
639 return ret, err
640 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700641
Colin Cross7b3dcc32019-01-24 13:14:39 -0800642 // absolute path already checked by validateSafePath
643 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800644 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700645 }
646
Colin Crossfe4bc362018-09-12 10:02:13 -0700647 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700648}
649
Colin Cross192e97a2018-02-22 14:21:02 -0800650// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
651func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000652 p, err := validatePath(pathComponents...)
653 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800654 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800655 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800656 }
657
Colin Cross7b3dcc32019-01-24 13:14:39 -0800658 // absolute path already checked by validatePath
659 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800660 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000661 }
662
Colin Cross192e97a2018-02-22 14:21:02 -0800663 return ret, nil
664}
665
666// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
667// path does not exist.
668func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
669 var files []string
670
671 if gctx, ok := ctx.(PathGlobContext); ok {
672 // Use glob to produce proper dependencies, even though we only want
673 // a single file.
674 files, err = gctx.GlobWithDeps(path.String(), nil)
675 } else {
676 var deps []string
677 // We cannot add build statements in this context, so we fall back to
678 // AddNinjaFileDeps
Colin Cross3f4d1162018-09-21 15:11:48 -0700679 files, deps, err = pathtools.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800680 ctx.AddNinjaFileDeps(deps...)
681 }
682
683 if err != nil {
684 return false, fmt.Errorf("glob: %s", err.Error())
685 }
686
687 return len(files) > 0, nil
688}
689
690// PathForSource joins the provided path components and validates that the result
691// neither escapes the source dir nor is in the out dir.
692// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
693func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
694 path, err := pathForSource(ctx, pathComponents...)
695 if err != nil {
696 reportPathError(ctx, err)
697 }
698
Colin Crosse3924e12018-08-15 20:18:53 -0700699 if pathtools.IsGlob(path.String()) {
700 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
701 }
702
Colin Cross192e97a2018-02-22 14:21:02 -0800703 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
704 exists, err := existsWithDependencies(ctx, path)
705 if err != nil {
706 reportPathError(ctx, err)
707 }
708 if !exists {
709 modCtx.AddMissingDependencies([]string{path.String()})
710 }
711 } else if exists, _, err := ctx.Fs().Exists(path.String()); err != nil {
712 reportPathErrorf(ctx, "%s: %s", path, err.Error())
713 } else if !exists {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800714 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800715 }
716 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700717}
718
Jeff Gaston734e3802017-04-10 15:47:24 -0700719// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700720// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
721// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800722func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800723 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800724 if err != nil {
725 reportPathError(ctx, err)
726 return OptionalPath{}
727 }
Colin Crossc48c1432018-02-23 07:09:01 +0000728
Colin Crosse3924e12018-08-15 20:18:53 -0700729 if pathtools.IsGlob(path.String()) {
730 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
731 return OptionalPath{}
732 }
733
Colin Cross192e97a2018-02-22 14:21:02 -0800734 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000735 if err != nil {
736 reportPathError(ctx, err)
737 return OptionalPath{}
738 }
Colin Cross192e97a2018-02-22 14:21:02 -0800739 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000740 return OptionalPath{}
741 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700742 return OptionalPathForPath(path)
743}
744
745func (p SourcePath) String() string {
746 return filepath.Join(p.config.srcDir, p.path)
747}
748
749// Join creates a new SourcePath with paths... joined with the current path. The
750// provided paths... may not use '..' to escape from the current path.
751func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800752 path, err := validatePath(paths...)
753 if err != nil {
754 reportPathError(ctx, err)
755 }
Colin Cross0db55682017-12-05 15:36:55 -0800756 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700757}
758
Colin Cross2fafa3e2019-03-05 12:39:51 -0800759// join is like Join but does less path validation.
760func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
761 path, err := validateSafePath(paths...)
762 if err != nil {
763 reportPathError(ctx, err)
764 }
765 return p.withRel(path)
766}
767
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700768// OverlayPath returns the overlay for `path' if it exists. This assumes that the
769// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700770func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700771 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800772 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700773 relDir = srcPath.path
774 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800775 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700776 return OptionalPath{}
777 }
778 dir := filepath.Join(p.config.srcDir, p.path, relDir)
779 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700780 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800781 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800782 }
Colin Cross461b4452018-02-23 09:22:42 -0800783 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700784 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800785 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700786 return OptionalPath{}
787 }
788 if len(paths) == 0 {
789 return OptionalPath{}
790 }
Colin Cross43f08db2018-11-12 10:13:39 -0800791 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700792 return OptionalPathForPath(PathForSource(ctx, relPath))
793}
794
795// OutputPath is a Path representing a file path rooted from the build directory
796type OutputPath struct {
797 basePath
798}
799
Colin Cross702e0f82017-10-18 17:27:54 -0700800func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800801 p.basePath = p.basePath.withRel(rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700802 return p
803}
804
Colin Cross3063b782018-08-15 11:19:12 -0700805func (p OutputPath) WithoutRel() OutputPath {
806 p.basePath.rel = filepath.Base(p.basePath.path)
807 return p
808}
809
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700810var _ Path = OutputPath{}
811
Jeff Gaston734e3802017-04-10 15:47:24 -0700812// PathForOutput joins the provided paths and returns an OutputPath that is
813// validated to not escape the build dir.
814// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
815func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800816 path, err := validatePath(pathComponents...)
817 if err != nil {
818 reportPathError(ctx, err)
819 }
Colin Crossaabf6792017-11-29 00:27:14 -0800820 return OutputPath{basePath{path, ctx.Config(), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700821}
822
Colin Cross607d8582019-07-29 16:44:46 -0700823// pathForInstallInMakeDir is used by PathForModuleInstall when the module returns true
824// for InstallBypassMake to produce an OutputPath that installs to $OUT_DIR instead of
825// $OUT_DIR/soong.
826func pathForInstallInMakeDir(ctx PathContext, pathComponents ...string) OutputPath {
827 path, err := validatePath(pathComponents...)
828 if err != nil {
829 reportPathError(ctx, err)
830 }
831 return OutputPath{basePath{"../" + path, ctx.Config(), ""}}
832}
833
Colin Cross40e33732019-02-15 11:08:35 -0800834// PathsForOutput returns Paths rooted from buildDir
835func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
836 ret := make(WritablePaths, len(paths))
837 for i, path := range paths {
838 ret[i] = PathForOutput(ctx, path)
839 }
840 return ret
841}
842
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700843func (p OutputPath) writablePath() {}
844
845func (p OutputPath) String() string {
846 return filepath.Join(p.config.buildDir, p.path)
847}
848
Colin Crossa2344662016-03-24 13:14:12 -0700849func (p OutputPath) RelPathString() string {
850 return p.path
851}
852
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700853// Join creates a new OutputPath with paths... joined with the current path. The
854// provided paths... may not use '..' to escape from the current path.
855func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800856 path, err := validatePath(paths...)
857 if err != nil {
858 reportPathError(ctx, err)
859 }
Colin Cross0db55682017-12-05 15:36:55 -0800860 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700861}
862
Colin Cross8854a5a2019-02-11 14:14:16 -0800863// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
864func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
865 if strings.Contains(ext, "/") {
866 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
867 }
868 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800869 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800870 return ret
871}
872
Colin Cross40e33732019-02-15 11:08:35 -0800873// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
874func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
875 path, err := validatePath(paths...)
876 if err != nil {
877 reportPathError(ctx, err)
878 }
879
880 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800881 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800882 return ret
883}
884
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700885// PathForIntermediates returns an OutputPath representing the top-level
886// intermediates directory.
887func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800888 path, err := validatePath(paths...)
889 if err != nil {
890 reportPathError(ctx, err)
891 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700892 return PathForOutput(ctx, ".intermediates", path)
893}
894
Colin Cross07e51612019-03-05 12:46:40 -0800895var _ genPathProvider = SourcePath{}
896var _ objPathProvider = SourcePath{}
897var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700898
Colin Cross07e51612019-03-05 12:46:40 -0800899// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700900// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800901func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
902 p, err := validatePath(pathComponents...)
903 if err != nil {
904 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800905 }
Colin Cross8a497952019-03-05 22:25:09 -0800906 paths, err := expandOneSrcPath(ctx, p, nil)
907 if err != nil {
908 if depErr, ok := err.(missingDependencyError); ok {
909 if ctx.Config().AllowMissingDependencies() {
910 ctx.AddMissingDependencies(depErr.missingDeps)
911 } else {
912 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
913 }
914 } else {
915 reportPathError(ctx, err)
916 }
917 return nil
918 } else if len(paths) == 0 {
919 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
920 return nil
921 } else if len(paths) > 1 {
922 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
923 }
924 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700925}
926
Colin Cross07e51612019-03-05 12:46:40 -0800927func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
928 p, err := validatePath(paths...)
929 if err != nil {
930 reportPathError(ctx, err)
931 }
932
933 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
934 if err != nil {
935 reportPathError(ctx, err)
936 }
937
938 path.basePath.rel = p
939
940 return path
941}
942
Colin Cross2fafa3e2019-03-05 12:39:51 -0800943// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
944// will return the path relative to subDir in the module's source directory. If any input paths are not located
945// inside subDir then a path error will be reported.
946func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
947 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -0800948 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800949 for i, path := range paths {
950 rel := Rel(ctx, subDirFullPath.String(), path.String())
951 paths[i] = subDirFullPath.join(ctx, rel)
952 }
953 return paths
954}
955
956// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
957// module's source directory. If the input path is not located inside subDir then a path error will be reported.
958func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -0800959 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800960 rel := Rel(ctx, subDirFullPath.String(), path.String())
961 return subDirFullPath.Join(ctx, rel)
962}
963
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700964// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
965// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700966func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700967 if p == nil {
968 return OptionalPath{}
969 }
970 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
971}
972
Colin Cross07e51612019-03-05 12:46:40 -0800973func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800974 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700975}
976
Colin Cross07e51612019-03-05 12:46:40 -0800977func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800978 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700979}
980
Colin Cross07e51612019-03-05 12:46:40 -0800981func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700982 // TODO: Use full directory if the new ctx is not the current ctx?
983 return PathForModuleRes(ctx, p.path, name)
984}
985
986// ModuleOutPath is a Path representing a module's output directory.
987type ModuleOutPath struct {
988 OutputPath
989}
990
991var _ Path = ModuleOutPath{}
992
Pete Bentleyfcf55bf2019-08-16 20:14:32 +0100993func (p ModuleOutPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
994 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
995}
996
Colin Cross702e0f82017-10-18 17:27:54 -0700997func pathForModule(ctx ModuleContext) OutputPath {
998 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
999}
1000
Logan Chien7eefdc42018-07-11 18:10:41 +08001001// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1002// reference abi dump for the given module. This is not guaranteed to be valid.
1003func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001004 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001005
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001006 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001007 if len(arches) == 0 {
1008 panic("device build with no primary arch")
1009 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001010 currentArch := ctx.Arch()
1011 archNameAndVariant := currentArch.ArchType.String()
1012 if currentArch.ArchVariant != "" {
1013 archNameAndVariant += "_" + currentArch.ArchVariant
1014 }
Logan Chien5237bed2018-07-11 17:15:57 +08001015
1016 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001017 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001018 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001019 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001020 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001021 } else {
1022 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001023 }
Logan Chien5237bed2018-07-11 17:15:57 +08001024
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001025 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001026
1027 var ext string
1028 if isGzip {
1029 ext = ".lsdump.gz"
1030 } else {
1031 ext = ".lsdump"
1032 }
1033
1034 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1035 version, binderBitness, archNameAndVariant, "source-based",
1036 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001037}
1038
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001039// PathForModuleOut returns a Path representing the paths... under the module's
1040// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001041func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001042 p, err := validatePath(paths...)
1043 if err != nil {
1044 reportPathError(ctx, err)
1045 }
Colin Cross702e0f82017-10-18 17:27:54 -07001046 return ModuleOutPath{
1047 OutputPath: pathForModule(ctx).withRel(p),
1048 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001049}
1050
1051// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1052// directory. Mainly used for generated sources.
1053type ModuleGenPath struct {
1054 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001055}
1056
1057var _ Path = ModuleGenPath{}
1058var _ genPathProvider = ModuleGenPath{}
1059var _ objPathProvider = ModuleGenPath{}
1060
1061// PathForModuleGen returns a Path representing the paths... under the module's
1062// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001063func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001064 p, err := validatePath(paths...)
1065 if err != nil {
1066 reportPathError(ctx, err)
1067 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001068 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001069 ModuleOutPath: ModuleOutPath{
1070 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1071 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001072 }
1073}
1074
Dan Willemsen21ec4902016-11-02 20:43:13 -07001075func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001076 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001077 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001078}
1079
Colin Cross635c3b02016-05-18 15:37:25 -07001080func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001081 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1082}
1083
1084// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1085// directory. Used for compiled objects.
1086type ModuleObjPath struct {
1087 ModuleOutPath
1088}
1089
1090var _ Path = ModuleObjPath{}
1091
1092// PathForModuleObj returns a Path representing the paths... under the module's
1093// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001094func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001095 p, err := validatePath(pathComponents...)
1096 if err != nil {
1097 reportPathError(ctx, err)
1098 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001099 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1100}
1101
1102// ModuleResPath is a a Path representing the 'res' directory in a module's
1103// output directory.
1104type ModuleResPath struct {
1105 ModuleOutPath
1106}
1107
1108var _ Path = ModuleResPath{}
1109
1110// PathForModuleRes returns a Path representing the paths... under the module's
1111// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001112func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001113 p, err := validatePath(pathComponents...)
1114 if err != nil {
1115 reportPathError(ctx, err)
1116 }
1117
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001118 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1119}
1120
1121// PathForModuleInstall returns a Path representing the install path for the
1122// module appended with paths...
Dan Willemsen00269f22017-07-06 16:59:48 -07001123func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) OutputPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001124 var outPaths []string
1125 if ctx.Device() {
Colin Cross43f08db2018-11-12 10:13:39 -08001126 partition := modulePartition(ctx)
Colin Cross6510f912017-11-29 00:27:14 -08001127 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001128 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -07001129 switch ctx.Os() {
1130 case Linux:
1131 outPaths = []string{"host", "linux-x86"}
1132 case LinuxBionic:
1133 // TODO: should this be a separate top level, or shared with linux-x86?
1134 outPaths = []string{"host", "linux_bionic-x86"}
1135 default:
1136 outPaths = []string{"host", ctx.Os().String() + "-x86"}
1137 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001138 }
Dan Willemsen782a2d12015-12-21 14:55:28 -08001139 if ctx.Debug() {
1140 outPaths = append([]string{"debug"}, outPaths...)
1141 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001142 outPaths = append(outPaths, pathComponents...)
Colin Cross607d8582019-07-29 16:44:46 -07001143 if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
1144 return pathForInstallInMakeDir(ctx, outPaths...)
1145 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001146 return PathForOutput(ctx, outPaths...)
1147}
1148
Colin Cross43f08db2018-11-12 10:13:39 -08001149func InstallPathToOnDevicePath(ctx PathContext, path OutputPath) string {
1150 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1151
1152 return "/" + rel
1153}
1154
1155func modulePartition(ctx ModuleInstallPathContext) string {
1156 var partition string
1157 if ctx.InstallInData() {
1158 partition = "data"
Jaewoong Jung0949f312019-09-11 10:25:18 -07001159 } else if ctx.InstallInTestcases() {
1160 partition = "testcases"
Colin Cross43f08db2018-11-12 10:13:39 -08001161 } else if ctx.InstallInRecovery() {
1162 // the layout of recovery partion is the same as that of system partition
1163 partition = "recovery/root/system"
1164 } else if ctx.SocSpecific() {
1165 partition = ctx.DeviceConfig().VendorPath()
1166 } else if ctx.DeviceSpecific() {
1167 partition = ctx.DeviceConfig().OdmPath()
1168 } else if ctx.ProductSpecific() {
1169 partition = ctx.DeviceConfig().ProductPath()
Justin Yund5f6c822019-06-25 16:47:17 +09001170 } else if ctx.SystemExtSpecific() {
1171 partition = ctx.DeviceConfig().SystemExtPath()
Colin Cross43f08db2018-11-12 10:13:39 -08001172 } else {
1173 partition = "system"
1174 }
1175 if ctx.InstallInSanitizerDir() {
1176 partition = "data/asan/" + partition
1177 }
1178 return partition
1179}
1180
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001181// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001182// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001183func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001184 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001185 path := filepath.Clean(path)
1186 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001187 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001188 }
1189 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001190 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1191 // variables. '..' may remove the entire ninja variable, even if it
1192 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001193 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001194}
1195
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001196// validatePath validates that a path does not include ninja variables, and that
1197// each path component does not attempt to leave its component. Returns a joined
1198// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001199func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001200 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001201 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001202 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001203 }
1204 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001205 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001206}
Colin Cross5b529592017-05-09 13:34:34 -07001207
Colin Cross0875c522017-11-28 17:34:01 -08001208func PathForPhony(ctx PathContext, phony string) WritablePath {
1209 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001210 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001211 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001212 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001213}
1214
Colin Cross74e3fe42017-12-11 15:51:44 -08001215type PhonyPath struct {
1216 basePath
1217}
1218
1219func (p PhonyPath) writablePath() {}
1220
1221var _ Path = PhonyPath{}
1222var _ WritablePath = PhonyPath{}
1223
Colin Cross5b529592017-05-09 13:34:34 -07001224type testPath struct {
1225 basePath
1226}
1227
1228func (p testPath) String() string {
1229 return p.path
1230}
1231
Colin Cross40e33732019-02-15 11:08:35 -08001232type testWritablePath struct {
1233 testPath
1234}
1235
1236func (p testPath) writablePath() {}
1237
1238// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1239// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001240func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001241 p, err := validateSafePath(paths...)
1242 if err != nil {
1243 panic(err)
1244 }
Colin Cross5b529592017-05-09 13:34:34 -07001245 return testPath{basePath{path: p, rel: p}}
1246}
1247
Colin Cross40e33732019-02-15 11:08:35 -08001248// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1249func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001250 p := make(Paths, len(strs))
1251 for i, s := range strs {
1252 p[i] = PathForTesting(s)
1253 }
1254
1255 return p
1256}
Colin Cross43f08db2018-11-12 10:13:39 -08001257
Colin Cross40e33732019-02-15 11:08:35 -08001258// WritablePathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be
1259// used from within tests.
1260func WritablePathForTesting(paths ...string) WritablePath {
1261 p, err := validateSafePath(paths...)
1262 if err != nil {
1263 panic(err)
1264 }
1265 return testWritablePath{testPath{basePath{path: p, rel: p}}}
1266}
1267
1268// WritablePathsForTesting returns a Path constructed from each element in strs. It should only be used from within
1269// tests.
1270func WritablePathsForTesting(strs ...string) WritablePaths {
1271 p := make(WritablePaths, len(strs))
1272 for i, s := range strs {
1273 p[i] = WritablePathForTesting(s)
1274 }
1275
1276 return p
1277}
1278
1279type testPathContext struct {
1280 config Config
1281 fs pathtools.FileSystem
1282}
1283
1284func (x *testPathContext) Fs() pathtools.FileSystem { return x.fs }
1285func (x *testPathContext) Config() Config { return x.config }
1286func (x *testPathContext) AddNinjaFileDeps(...string) {}
1287
1288// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1289// PathForOutput.
1290func PathContextForTesting(config Config, fs map[string][]byte) PathContext {
1291 return &testPathContext{
1292 config: config,
1293 fs: pathtools.MockFs(fs),
1294 }
1295}
1296
Colin Cross43f08db2018-11-12 10:13:39 -08001297// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1298// targetPath is not inside basePath.
1299func Rel(ctx PathContext, basePath string, targetPath string) string {
1300 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1301 if !isRel {
1302 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1303 return ""
1304 }
1305 return rel
1306}
1307
1308// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1309// targetPath is not inside basePath.
1310func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001311 rel, isRel, err := maybeRelErr(basePath, targetPath)
1312 if err != nil {
1313 reportPathError(ctx, err)
1314 }
1315 return rel, isRel
1316}
1317
1318func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001319 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1320 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001321 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001322 }
1323 rel, err := filepath.Rel(basePath, targetPath)
1324 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001325 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001326 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001327 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001328 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001329 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001330}