blob: 3915ff4149f1a8850f5922b467a0585425dbce53 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Colin Cross6e18ca42015-07-14 18:55:36 -070018 "fmt"
Colin Cross6a745c62015-06-16 16:38:10 -070019 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070020 "reflect"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070021 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070022 "strings"
23
24 "github.com/google/blueprint"
25 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080026)
27
Dan Willemsen34cc69e2015-09-23 15:26:20 -070028// PathContext is the subset of a (Module|Singleton)Context required by the
29// Path methods.
30type PathContext interface {
Colin Cross294941b2017-02-01 14:10:36 -080031 Fs() pathtools.FileSystem
Colin Crossaabf6792017-11-29 00:27:14 -080032 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080033 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080034}
35
Colin Cross7f19f372016-11-01 11:10:25 -070036type PathGlobContext interface {
37 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
38}
39
Colin Crossaabf6792017-11-29 00:27:14 -080040var _ PathContext = SingletonContext(nil)
41var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070042
Dan Willemsen00269f22017-07-06 16:59:48 -070043type ModuleInstallPathContext interface {
44 PathContext
45
46 androidBaseContext
47
48 InstallInData() bool
49 InstallInSanitizerDir() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +090050 InstallInRecovery() bool
Dan Willemsen00269f22017-07-06 16:59:48 -070051}
52
53var _ ModuleInstallPathContext = ModuleContext(nil)
54
Dan Willemsen34cc69e2015-09-23 15:26:20 -070055// errorfContext is the interface containing the Errorf method matching the
56// Errorf method in blueprint.SingletonContext.
57type errorfContext interface {
58 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080059}
60
Dan Willemsen34cc69e2015-09-23 15:26:20 -070061var _ errorfContext = blueprint.SingletonContext(nil)
62
63// moduleErrorf is the interface containing the ModuleErrorf method matching
64// the ModuleErrorf method in blueprint.ModuleContext.
65type moduleErrorf interface {
66 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080067}
68
Dan Willemsen34cc69e2015-09-23 15:26:20 -070069var _ moduleErrorf = blueprint.ModuleContext(nil)
70
Dan Willemsen34cc69e2015-09-23 15:26:20 -070071// reportPathError will register an error with the attached context. It
72// attempts ctx.ModuleErrorf for a better error message first, then falls
73// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -080074func reportPathError(ctx PathContext, err error) {
75 reportPathErrorf(ctx, "%s", err.Error())
76}
77
78// reportPathErrorf will register an error with the attached context. It
79// attempts ctx.ModuleErrorf for a better error message first, then falls
80// back to ctx.Errorf.
81func reportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -070082 if mctx, ok := ctx.(moduleErrorf); ok {
83 mctx.ModuleErrorf(format, args...)
84 } else if ectx, ok := ctx.(errorfContext); ok {
85 ectx.Errorf(format, args...)
86 } else {
87 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -070088 }
89}
90
Dan Willemsen34cc69e2015-09-23 15:26:20 -070091type Path interface {
92 // Returns the path in string form
93 String() string
94
Colin Cross4f6fc9c2016-10-26 10:05:25 -070095 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -070096 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -070097
98 // Base returns the last element of the path
99 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800100
101 // Rel returns the portion of the path relative to the directory it was created from. For
102 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800103 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800104 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700105}
106
107// WritablePath is a type of path that can be used as an output for build rules.
108type WritablePath interface {
109 Path
110
Jeff Gaston734e3802017-04-10 15:47:24 -0700111 // the writablePath method doesn't directly do anything,
112 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700113 writablePath()
114}
115
116type genPathProvider interface {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700117 genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700118}
119type objPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700120 objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700121}
122type resPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700123 resPathWithName(ctx ModuleContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700124}
125
126// GenPathWithExt derives a new file path in ctx's generated sources directory
127// from the current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700128func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700129 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700130 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700131 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800132 reportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700133 return PathForModuleGen(ctx)
134}
135
136// ObjPathWithExt derives a new file path in ctx's object directory from the
137// current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700138func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700139 if path, ok := p.(objPathProvider); ok {
140 return path.objPathWithExt(ctx, subdir, ext)
141 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800142 reportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700143 return PathForModuleObj(ctx)
144}
145
146// ResPathWithName derives a new path in ctx's output resource directory, using
147// the current path to create the directory name, and the `name` argument for
148// the filename.
Colin Cross635c3b02016-05-18 15:37:25 -0700149func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700150 if path, ok := p.(resPathProvider); ok {
151 return path.resPathWithName(ctx, name)
152 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800153 reportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700154 return PathForModuleRes(ctx)
155}
156
157// OptionalPath is a container that may or may not contain a valid Path.
158type OptionalPath struct {
159 valid bool
160 path Path
161}
162
163// OptionalPathForPath returns an OptionalPath containing the path.
164func OptionalPathForPath(path Path) OptionalPath {
165 if path == nil {
166 return OptionalPath{}
167 }
168 return OptionalPath{valid: true, path: path}
169}
170
171// Valid returns whether there is a valid path
172func (p OptionalPath) Valid() bool {
173 return p.valid
174}
175
176// Path returns the Path embedded in this OptionalPath. You must be sure that
177// there is a valid path, since this method will panic if there is not.
178func (p OptionalPath) Path() Path {
179 if !p.valid {
180 panic("Requesting an invalid path")
181 }
182 return p.path
183}
184
185// String returns the string version of the Path, or "" if it isn't valid.
186func (p OptionalPath) String() string {
187 if p.valid {
188 return p.path.String()
189 } else {
190 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700191 }
192}
Colin Cross6e18ca42015-07-14 18:55:36 -0700193
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700194// Paths is a slice of Path objects, with helpers to operate on the collection.
195type Paths []Path
196
197// PathsForSource returns Paths rooted from SrcDir
198func PathsForSource(ctx PathContext, paths []string) Paths {
199 ret := make(Paths, len(paths))
200 for i, path := range paths {
201 ret[i] = PathForSource(ctx, path)
202 }
203 return ret
204}
205
Jeff Gaston734e3802017-04-10 15:47:24 -0700206// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800207// found in the tree. If any are not found, they are omitted from the list,
208// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800209func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800210 ret := make(Paths, 0, len(paths))
211 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800212 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800213 if p.Valid() {
214 ret = append(ret, p.Path())
215 }
216 }
217 return ret
218}
219
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
235// truethen any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
236// 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.
Dan Willemsen540a78c2018-02-26 21:50:08 -0800372func pathsForModuleSrcFromFullPath(ctx ModuleContext, 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 Cross40e33732019-02-15 11:08:35 -0800823// PathsForOutput returns Paths rooted from buildDir
824func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
825 ret := make(WritablePaths, len(paths))
826 for i, path := range paths {
827 ret[i] = PathForOutput(ctx, path)
828 }
829 return ret
830}
831
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700832func (p OutputPath) writablePath() {}
833
834func (p OutputPath) String() string {
835 return filepath.Join(p.config.buildDir, p.path)
836}
837
Colin Crossa2344662016-03-24 13:14:12 -0700838func (p OutputPath) RelPathString() string {
839 return p.path
840}
841
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700842// Join creates a new OutputPath with paths... joined with the current path. The
843// provided paths... may not use '..' to escape from the current path.
844func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800845 path, err := validatePath(paths...)
846 if err != nil {
847 reportPathError(ctx, err)
848 }
Colin Cross0db55682017-12-05 15:36:55 -0800849 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700850}
851
Colin Cross8854a5a2019-02-11 14:14:16 -0800852// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
853func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
854 if strings.Contains(ext, "/") {
855 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
856 }
857 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800858 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800859 return ret
860}
861
Colin Cross40e33732019-02-15 11:08:35 -0800862// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
863func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
864 path, err := validatePath(paths...)
865 if err != nil {
866 reportPathError(ctx, err)
867 }
868
869 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800870 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800871 return ret
872}
873
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700874// PathForIntermediates returns an OutputPath representing the top-level
875// intermediates directory.
876func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800877 path, err := validatePath(paths...)
878 if err != nil {
879 reportPathError(ctx, err)
880 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700881 return PathForOutput(ctx, ".intermediates", path)
882}
883
Colin Cross07e51612019-03-05 12:46:40 -0800884var _ genPathProvider = SourcePath{}
885var _ objPathProvider = SourcePath{}
886var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700887
Colin Cross07e51612019-03-05 12:46:40 -0800888// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700889// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800890func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
891 p, err := validatePath(pathComponents...)
892 if err != nil {
893 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800894 }
Colin Cross8a497952019-03-05 22:25:09 -0800895 paths, err := expandOneSrcPath(ctx, p, nil)
896 if err != nil {
897 if depErr, ok := err.(missingDependencyError); ok {
898 if ctx.Config().AllowMissingDependencies() {
899 ctx.AddMissingDependencies(depErr.missingDeps)
900 } else {
901 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
902 }
903 } else {
904 reportPathError(ctx, err)
905 }
906 return nil
907 } else if len(paths) == 0 {
908 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
909 return nil
910 } else if len(paths) > 1 {
911 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
912 }
913 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700914}
915
Colin Cross07e51612019-03-05 12:46:40 -0800916func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
917 p, err := validatePath(paths...)
918 if err != nil {
919 reportPathError(ctx, err)
920 }
921
922 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
923 if err != nil {
924 reportPathError(ctx, err)
925 }
926
927 path.basePath.rel = p
928
929 return path
930}
931
Colin Cross2fafa3e2019-03-05 12:39:51 -0800932// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
933// will return the path relative to subDir in the module's source directory. If any input paths are not located
934// inside subDir then a path error will be reported.
935func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
936 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -0800937 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800938 for i, path := range paths {
939 rel := Rel(ctx, subDirFullPath.String(), path.String())
940 paths[i] = subDirFullPath.join(ctx, rel)
941 }
942 return paths
943}
944
945// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
946// module's source directory. If the input path is not located inside subDir then a path error will be reported.
947func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -0800948 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800949 rel := Rel(ctx, subDirFullPath.String(), path.String())
950 return subDirFullPath.Join(ctx, rel)
951}
952
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700953// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
954// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700955func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700956 if p == nil {
957 return OptionalPath{}
958 }
959 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
960}
961
Colin Cross07e51612019-03-05 12:46:40 -0800962func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800963 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700964}
965
Colin Cross07e51612019-03-05 12:46:40 -0800966func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800967 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700968}
969
Colin Cross07e51612019-03-05 12:46:40 -0800970func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700971 // TODO: Use full directory if the new ctx is not the current ctx?
972 return PathForModuleRes(ctx, p.path, name)
973}
974
975// ModuleOutPath is a Path representing a module's output directory.
976type ModuleOutPath struct {
977 OutputPath
978}
979
980var _ Path = ModuleOutPath{}
981
Colin Cross702e0f82017-10-18 17:27:54 -0700982func pathForModule(ctx ModuleContext) OutputPath {
983 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
984}
985
Logan Chien7eefdc42018-07-11 18:10:41 +0800986// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
987// reference abi dump for the given module. This is not guaranteed to be valid.
988func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Logan Chien41eabe62019-04-10 13:33:58 +0800989 isLlndkOrNdk, isVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +0800990
Jayant Chowdharyac066c62018-02-20 10:53:31 -0800991 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +0800992 if len(arches) == 0 {
993 panic("device build with no primary arch")
994 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -0800995 currentArch := ctx.Arch()
996 archNameAndVariant := currentArch.ArchType.String()
997 if currentArch.ArchVariant != "" {
998 archNameAndVariant += "_" + currentArch.ArchVariant
999 }
Logan Chien5237bed2018-07-11 17:15:57 +08001000
1001 var dirName string
Logan Chien41eabe62019-04-10 13:33:58 +08001002 if isLlndkOrNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001003 dirName = "ndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001004 } else if isVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001005 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001006 } else {
1007 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001008 }
Logan Chien5237bed2018-07-11 17:15:57 +08001009
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001010 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001011
1012 var ext string
1013 if isGzip {
1014 ext = ".lsdump.gz"
1015 } else {
1016 ext = ".lsdump"
1017 }
1018
1019 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1020 version, binderBitness, archNameAndVariant, "source-based",
1021 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001022}
1023
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001024// PathForModuleOut returns a Path representing the paths... under the module's
1025// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001026func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001027 p, err := validatePath(paths...)
1028 if err != nil {
1029 reportPathError(ctx, err)
1030 }
Colin Cross702e0f82017-10-18 17:27:54 -07001031 return ModuleOutPath{
1032 OutputPath: pathForModule(ctx).withRel(p),
1033 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001034}
1035
1036// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1037// directory. Mainly used for generated sources.
1038type ModuleGenPath struct {
1039 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001040}
1041
1042var _ Path = ModuleGenPath{}
1043var _ genPathProvider = ModuleGenPath{}
1044var _ objPathProvider = ModuleGenPath{}
1045
1046// PathForModuleGen returns a Path representing the paths... under the module's
1047// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001048func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001049 p, err := validatePath(paths...)
1050 if err != nil {
1051 reportPathError(ctx, err)
1052 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001053 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001054 ModuleOutPath: ModuleOutPath{
1055 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1056 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001057 }
1058}
1059
Dan Willemsen21ec4902016-11-02 20:43:13 -07001060func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001061 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001062 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001063}
1064
Colin Cross635c3b02016-05-18 15:37:25 -07001065func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001066 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1067}
1068
1069// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1070// directory. Used for compiled objects.
1071type ModuleObjPath struct {
1072 ModuleOutPath
1073}
1074
1075var _ Path = ModuleObjPath{}
1076
1077// PathForModuleObj returns a Path representing the paths... under the module's
1078// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001079func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001080 p, err := validatePath(pathComponents...)
1081 if err != nil {
1082 reportPathError(ctx, err)
1083 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001084 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1085}
1086
1087// ModuleResPath is a a Path representing the 'res' directory in a module's
1088// output directory.
1089type ModuleResPath struct {
1090 ModuleOutPath
1091}
1092
1093var _ Path = ModuleResPath{}
1094
1095// PathForModuleRes returns a Path representing the paths... under the module's
1096// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001097func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001098 p, err := validatePath(pathComponents...)
1099 if err != nil {
1100 reportPathError(ctx, err)
1101 }
1102
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001103 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1104}
1105
1106// PathForModuleInstall returns a Path representing the install path for the
1107// module appended with paths...
Dan Willemsen00269f22017-07-06 16:59:48 -07001108func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) OutputPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001109 var outPaths []string
1110 if ctx.Device() {
Colin Cross43f08db2018-11-12 10:13:39 -08001111 partition := modulePartition(ctx)
Colin Cross6510f912017-11-29 00:27:14 -08001112 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001113 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -07001114 switch ctx.Os() {
1115 case Linux:
1116 outPaths = []string{"host", "linux-x86"}
1117 case LinuxBionic:
1118 // TODO: should this be a separate top level, or shared with linux-x86?
1119 outPaths = []string{"host", "linux_bionic-x86"}
1120 default:
1121 outPaths = []string{"host", ctx.Os().String() + "-x86"}
1122 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001123 }
Dan Willemsen782a2d12015-12-21 14:55:28 -08001124 if ctx.Debug() {
1125 outPaths = append([]string{"debug"}, outPaths...)
1126 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001127 outPaths = append(outPaths, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001128 return PathForOutput(ctx, outPaths...)
1129}
1130
Colin Cross43f08db2018-11-12 10:13:39 -08001131func InstallPathToOnDevicePath(ctx PathContext, path OutputPath) string {
1132 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1133
1134 return "/" + rel
1135}
1136
1137func modulePartition(ctx ModuleInstallPathContext) string {
1138 var partition string
1139 if ctx.InstallInData() {
1140 partition = "data"
1141 } else if ctx.InstallInRecovery() {
1142 // the layout of recovery partion is the same as that of system partition
1143 partition = "recovery/root/system"
1144 } else if ctx.SocSpecific() {
1145 partition = ctx.DeviceConfig().VendorPath()
1146 } else if ctx.DeviceSpecific() {
1147 partition = ctx.DeviceConfig().OdmPath()
1148 } else if ctx.ProductSpecific() {
1149 partition = ctx.DeviceConfig().ProductPath()
1150 } else if ctx.ProductServicesSpecific() {
1151 partition = ctx.DeviceConfig().ProductServicesPath()
1152 } else {
1153 partition = "system"
1154 }
1155 if ctx.InstallInSanitizerDir() {
1156 partition = "data/asan/" + partition
1157 }
1158 return partition
1159}
1160
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001161// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001162// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001163func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001164 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001165 path := filepath.Clean(path)
1166 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001167 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001168 }
1169 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001170 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1171 // variables. '..' may remove the entire ninja variable, even if it
1172 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001173 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001174}
1175
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001176// validatePath validates that a path does not include ninja variables, and that
1177// each path component does not attempt to leave its component. Returns a joined
1178// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001179func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001180 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001181 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001182 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001183 }
1184 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001185 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001186}
Colin Cross5b529592017-05-09 13:34:34 -07001187
Colin Cross0875c522017-11-28 17:34:01 -08001188func PathForPhony(ctx PathContext, phony string) WritablePath {
1189 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001190 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001191 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001192 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001193}
1194
Colin Cross74e3fe42017-12-11 15:51:44 -08001195type PhonyPath struct {
1196 basePath
1197}
1198
1199func (p PhonyPath) writablePath() {}
1200
1201var _ Path = PhonyPath{}
1202var _ WritablePath = PhonyPath{}
1203
Colin Cross5b529592017-05-09 13:34:34 -07001204type testPath struct {
1205 basePath
1206}
1207
1208func (p testPath) String() string {
1209 return p.path
1210}
1211
Colin Cross40e33732019-02-15 11:08:35 -08001212type testWritablePath struct {
1213 testPath
1214}
1215
1216func (p testPath) writablePath() {}
1217
1218// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1219// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001220func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001221 p, err := validateSafePath(paths...)
1222 if err != nil {
1223 panic(err)
1224 }
Colin Cross5b529592017-05-09 13:34:34 -07001225 return testPath{basePath{path: p, rel: p}}
1226}
1227
Colin Cross40e33732019-02-15 11:08:35 -08001228// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1229func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001230 p := make(Paths, len(strs))
1231 for i, s := range strs {
1232 p[i] = PathForTesting(s)
1233 }
1234
1235 return p
1236}
Colin Cross43f08db2018-11-12 10:13:39 -08001237
Colin Cross40e33732019-02-15 11:08:35 -08001238// WritablePathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be
1239// used from within tests.
1240func WritablePathForTesting(paths ...string) WritablePath {
1241 p, err := validateSafePath(paths...)
1242 if err != nil {
1243 panic(err)
1244 }
1245 return testWritablePath{testPath{basePath{path: p, rel: p}}}
1246}
1247
1248// WritablePathsForTesting returns a Path constructed from each element in strs. It should only be used from within
1249// tests.
1250func WritablePathsForTesting(strs ...string) WritablePaths {
1251 p := make(WritablePaths, len(strs))
1252 for i, s := range strs {
1253 p[i] = WritablePathForTesting(s)
1254 }
1255
1256 return p
1257}
1258
1259type testPathContext struct {
1260 config Config
1261 fs pathtools.FileSystem
1262}
1263
1264func (x *testPathContext) Fs() pathtools.FileSystem { return x.fs }
1265func (x *testPathContext) Config() Config { return x.config }
1266func (x *testPathContext) AddNinjaFileDeps(...string) {}
1267
1268// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1269// PathForOutput.
1270func PathContextForTesting(config Config, fs map[string][]byte) PathContext {
1271 return &testPathContext{
1272 config: config,
1273 fs: pathtools.MockFs(fs),
1274 }
1275}
1276
Colin Cross43f08db2018-11-12 10:13:39 -08001277// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1278// targetPath is not inside basePath.
1279func Rel(ctx PathContext, basePath string, targetPath string) string {
1280 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1281 if !isRel {
1282 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1283 return ""
1284 }
1285 return rel
1286}
1287
1288// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1289// targetPath is not inside basePath.
1290func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001291 rel, isRel, err := maybeRelErr(basePath, targetPath)
1292 if err != nil {
1293 reportPathError(ctx, err)
1294 }
1295 return rel, isRel
1296}
1297
1298func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001299 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1300 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001301 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001302 }
1303 rel, err := filepath.Rel(basePath, targetPath)
1304 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001305 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001306 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001307 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001308 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001309 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001310}