blob: 0d999185d27897db974e2b4199442ac7c9f40608 [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
47 InstallInSanitizerDir() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +090048 InstallInRecovery() bool
Colin Cross607d8582019-07-29 16:44:46 -070049 InstallBypassMake() bool
Dan Willemsen00269f22017-07-06 16:59:48 -070050}
51
52var _ ModuleInstallPathContext = ModuleContext(nil)
53
Dan Willemsen34cc69e2015-09-23 15:26:20 -070054// errorfContext is the interface containing the Errorf method matching the
55// Errorf method in blueprint.SingletonContext.
56type errorfContext interface {
57 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080058}
59
Dan Willemsen34cc69e2015-09-23 15:26:20 -070060var _ errorfContext = blueprint.SingletonContext(nil)
61
62// moduleErrorf is the interface containing the ModuleErrorf method matching
63// the ModuleErrorf method in blueprint.ModuleContext.
64type moduleErrorf interface {
65 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080066}
67
Dan Willemsen34cc69e2015-09-23 15:26:20 -070068var _ moduleErrorf = blueprint.ModuleContext(nil)
69
Dan Willemsen34cc69e2015-09-23 15:26:20 -070070// reportPathError will register an error with the attached context. It
71// attempts ctx.ModuleErrorf for a better error message first, then falls
72// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -080073func reportPathError(ctx PathContext, err error) {
74 reportPathErrorf(ctx, "%s", err.Error())
75}
76
77// reportPathErrorf will register an error with the attached context. It
78// attempts ctx.ModuleErrorf for a better error message first, then falls
79// back to ctx.Errorf.
80func reportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -070081 if mctx, ok := ctx.(moduleErrorf); ok {
82 mctx.ModuleErrorf(format, args...)
83 } else if ectx, ok := ctx.(errorfContext); ok {
84 ectx.Errorf(format, args...)
85 } else {
86 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -070087 }
88}
89
Dan Willemsen34cc69e2015-09-23 15:26:20 -070090type Path interface {
91 // Returns the path in string form
92 String() string
93
Colin Cross4f6fc9c2016-10-26 10:05:25 -070094 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -070095 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -070096
97 // Base returns the last element of the path
98 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -080099
100 // Rel returns the portion of the path relative to the directory it was created from. For
101 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800102 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800103 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700104}
105
106// WritablePath is a type of path that can be used as an output for build rules.
107type WritablePath interface {
108 Path
109
Jeff Gaston734e3802017-04-10 15:47:24 -0700110 // the writablePath method doesn't directly do anything,
111 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700112 writablePath()
113}
114
115type genPathProvider interface {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700116 genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700117}
118type objPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700119 objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700120}
121type resPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700122 resPathWithName(ctx ModuleContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700123}
124
125// GenPathWithExt derives a new file path in ctx's generated sources directory
126// from the current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700127func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700128 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700129 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700130 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800131 reportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700132 return PathForModuleGen(ctx)
133}
134
135// ObjPathWithExt derives a new file path in ctx's object directory from the
136// current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700137func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700138 if path, ok := p.(objPathProvider); ok {
139 return path.objPathWithExt(ctx, subdir, ext)
140 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800141 reportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700142 return PathForModuleObj(ctx)
143}
144
145// ResPathWithName derives a new path in ctx's output resource directory, using
146// the current path to create the directory name, and the `name` argument for
147// the filename.
Colin Cross635c3b02016-05-18 15:37:25 -0700148func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700149 if path, ok := p.(resPathProvider); ok {
150 return path.resPathWithName(ctx, name)
151 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800152 reportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700153 return PathForModuleRes(ctx)
154}
155
156// OptionalPath is a container that may or may not contain a valid Path.
157type OptionalPath struct {
158 valid bool
159 path Path
160}
161
162// OptionalPathForPath returns an OptionalPath containing the path.
163func OptionalPathForPath(path Path) OptionalPath {
164 if path == nil {
165 return OptionalPath{}
166 }
167 return OptionalPath{valid: true, path: path}
168}
169
170// Valid returns whether there is a valid path
171func (p OptionalPath) Valid() bool {
172 return p.valid
173}
174
175// Path returns the Path embedded in this OptionalPath. You must be sure that
176// there is a valid path, since this method will panic if there is not.
177func (p OptionalPath) Path() Path {
178 if !p.valid {
179 panic("Requesting an invalid path")
180 }
181 return p.path
182}
183
184// String returns the string version of the Path, or "" if it isn't valid.
185func (p OptionalPath) String() string {
186 if p.valid {
187 return p.path.String()
188 } else {
189 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700190 }
191}
Colin Cross6e18ca42015-07-14 18:55:36 -0700192
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700193// Paths is a slice of Path objects, with helpers to operate on the collection.
194type Paths []Path
195
196// PathsForSource returns Paths rooted from SrcDir
197func PathsForSource(ctx PathContext, paths []string) Paths {
198 ret := make(Paths, len(paths))
199 for i, path := range paths {
200 ret[i] = PathForSource(ctx, path)
201 }
202 return ret
203}
204
Jeff Gaston734e3802017-04-10 15:47:24 -0700205// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800206// found in the tree. If any are not found, they are omitted from the list,
207// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800208func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800209 ret := make(Paths, 0, len(paths))
210 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800211 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800212 if p.Valid() {
213 ret = append(ret, p.Path())
214 }
215 }
216 return ret
217}
218
Colin Cross41955e82019-05-29 14:40:35 -0700219// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
220// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
221// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
222// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
223// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
224// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Colin Cross635c3b02016-05-18 15:37:25 -0700225func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800226 return PathsForModuleSrcExcludes(ctx, paths, nil)
227}
228
Colin Crossba71a3f2019-03-18 12:12:48 -0700229// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700230// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
231// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
232// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
233// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100234// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700235// having missing dependencies.
Colin Cross8a497952019-03-05 22:25:09 -0800236func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700237 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
238 if ctx.Config().AllowMissingDependencies() {
239 ctx.AddMissingDependencies(missingDeps)
240 } else {
241 for _, m := range missingDeps {
242 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
243 }
244 }
245 return ret
246}
247
248// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700249// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
250// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
251// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
252// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
253// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
254// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
255// dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700256func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800257 prefix := pathForModuleSrc(ctx).String()
258
259 var expandedExcludes []string
260 if excludes != nil {
261 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700262 }
Colin Cross8a497952019-03-05 22:25:09 -0800263
Colin Crossba71a3f2019-03-18 12:12:48 -0700264 var missingExcludeDeps []string
265
Colin Cross8a497952019-03-05 22:25:09 -0800266 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700267 if m, t := SrcIsModuleWithTag(e); m != "" {
268 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800269 if module == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700270 missingExcludeDeps = append(missingExcludeDeps, m)
Colin Cross8a497952019-03-05 22:25:09 -0800271 continue
272 }
Colin Cross41955e82019-05-29 14:40:35 -0700273 if outProducer, ok := module.(OutputFileProducer); ok {
274 outputFiles, err := outProducer.OutputFiles(t)
275 if err != nil {
276 ctx.ModuleErrorf("path dependency %q: %s", e, err)
277 }
278 expandedExcludes = append(expandedExcludes, outputFiles.Strings()...)
279 } else if t != "" {
280 ctx.ModuleErrorf("path dependency %q is not an output file producing module", e)
281 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800282 expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
283 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700284 ctx.ModuleErrorf("path dependency %q is not a source file producing module", e)
Colin Cross8a497952019-03-05 22:25:09 -0800285 }
286 } else {
287 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
288 }
289 }
290
291 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700292 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800293 }
294
Colin Crossba71a3f2019-03-18 12:12:48 -0700295 var missingDeps []string
296
Colin Cross8a497952019-03-05 22:25:09 -0800297 expandedSrcFiles := make(Paths, 0, len(paths))
298 for _, s := range paths {
299 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
300 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700301 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800302 } else if err != nil {
303 reportPathError(ctx, err)
304 }
305 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
306 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700307
308 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800309}
310
311type missingDependencyError struct {
312 missingDeps []string
313}
314
315func (e missingDependencyError) Error() string {
316 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
317}
318
319func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
Colin Cross41955e82019-05-29 14:40:35 -0700320 if m, t := SrcIsModuleWithTag(s); m != "" {
321 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800322 if module == nil {
323 return nil, missingDependencyError{[]string{m}}
324 }
Colin Cross41955e82019-05-29 14:40:35 -0700325 if outProducer, ok := module.(OutputFileProducer); ok {
326 outputFiles, err := outProducer.OutputFiles(t)
327 if err != nil {
328 return nil, fmt.Errorf("path dependency %q: %s", s, err)
329 }
330 return outputFiles, nil
331 } else if t != "" {
332 return nil, fmt.Errorf("path dependency %q is not an output file producing module", s)
333 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800334 moduleSrcs := srcProducer.Srcs()
335 for _, e := range expandedExcludes {
336 for j := 0; j < len(moduleSrcs); j++ {
337 if moduleSrcs[j].String() == e {
338 moduleSrcs = append(moduleSrcs[:j], moduleSrcs[j+1:]...)
339 j--
340 }
341 }
342 }
343 return moduleSrcs, nil
344 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700345 return nil, fmt.Errorf("path dependency %q is not a source file producing module", s)
Colin Cross8a497952019-03-05 22:25:09 -0800346 }
347 } else if pathtools.IsGlob(s) {
348 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
349 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
350 } else {
351 p := pathForModuleSrc(ctx, s)
352 if exists, _, err := ctx.Fs().Exists(p.String()); err != nil {
353 reportPathErrorf(ctx, "%s: %s", p, err.Error())
354 } else if !exists {
355 reportPathErrorf(ctx, "module source path %q does not exist", p)
356 }
357
358 j := findStringInSlice(p.String(), expandedExcludes)
359 if j >= 0 {
360 return nil, nil
361 }
362 return Paths{p}, nil
363 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700364}
365
366// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
367// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800368// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700369// It intended for use in globs that only list files that exist, so it allows '$' in
370// filenames.
Colin Crossdc35e212019-06-06 16:13:11 -0700371func pathsForModuleSrcFromFullPath(ctx BaseModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800372 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700373 if prefix == "./" {
374 prefix = ""
375 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700376 ret := make(Paths, 0, len(paths))
377 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800378 if !incDirs && strings.HasSuffix(p, "/") {
379 continue
380 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700381 path := filepath.Clean(p)
382 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800383 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700384 continue
385 }
Colin Crosse3924e12018-08-15 20:18:53 -0700386
Colin Crossfe4bc362018-09-12 10:02:13 -0700387 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700388 if err != nil {
389 reportPathError(ctx, err)
390 continue
391 }
392
Colin Cross07e51612019-03-05 12:46:40 -0800393 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700394
Colin Cross07e51612019-03-05 12:46:40 -0800395 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700396 }
397 return ret
398}
399
400// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800401// 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 -0700402func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800403 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700404 return PathsForModuleSrc(ctx, input)
405 }
406 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
407 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800408 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800409 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700410}
411
412// Strings returns the Paths in string form
413func (p Paths) Strings() []string {
414 if p == nil {
415 return nil
416 }
417 ret := make([]string, len(p))
418 for i, path := range p {
419 ret[i] = path.String()
420 }
421 return ret
422}
423
Colin Crossb6715442017-10-24 11:13:31 -0700424// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
425// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700426func FirstUniquePaths(list Paths) Paths {
427 k := 0
428outer:
429 for i := 0; i < len(list); i++ {
430 for j := 0; j < k; j++ {
431 if list[i] == list[j] {
432 continue outer
433 }
434 }
435 list[k] = list[i]
436 k++
437 }
438 return list[:k]
439}
440
Colin Crossb6715442017-10-24 11:13:31 -0700441// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
442// modifies the Paths slice contents in place, and returns a subslice of the original slice.
443func LastUniquePaths(list Paths) Paths {
444 totalSkip := 0
445 for i := len(list) - 1; i >= totalSkip; i-- {
446 skip := 0
447 for j := i - 1; j >= totalSkip; j-- {
448 if list[i] == list[j] {
449 skip++
450 } else {
451 list[j+skip] = list[j]
452 }
453 }
454 totalSkip += skip
455 }
456 return list[totalSkip:]
457}
458
Colin Crossa140bb02018-04-17 10:52:26 -0700459// ReversePaths returns a copy of a Paths in reverse order.
460func ReversePaths(list Paths) Paths {
461 if list == nil {
462 return nil
463 }
464 ret := make(Paths, len(list))
465 for i := range list {
466 ret[i] = list[len(list)-1-i]
467 }
468 return ret
469}
470
Jeff Gaston294356f2017-09-27 17:05:30 -0700471func indexPathList(s Path, list []Path) int {
472 for i, l := range list {
473 if l == s {
474 return i
475 }
476 }
477
478 return -1
479}
480
481func inPathList(p Path, list []Path) bool {
482 return indexPathList(p, list) != -1
483}
484
485func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
486 for _, l := range list {
487 if inPathList(l, filter) {
488 filtered = append(filtered, l)
489 } else {
490 remainder = append(remainder, l)
491 }
492 }
493
494 return
495}
496
Colin Cross93e85952017-08-15 13:34:18 -0700497// HasExt returns true of any of the paths have extension ext, otherwise false
498func (p Paths) HasExt(ext string) bool {
499 for _, path := range p {
500 if path.Ext() == ext {
501 return true
502 }
503 }
504
505 return false
506}
507
508// FilterByExt returns the subset of the paths that have extension ext
509func (p Paths) FilterByExt(ext string) Paths {
510 ret := make(Paths, 0, len(p))
511 for _, path := range p {
512 if path.Ext() == ext {
513 ret = append(ret, path)
514 }
515 }
516 return ret
517}
518
519// FilterOutByExt returns the subset of the paths that do not have extension ext
520func (p Paths) FilterOutByExt(ext string) Paths {
521 ret := make(Paths, 0, len(p))
522 for _, path := range p {
523 if path.Ext() != ext {
524 ret = append(ret, path)
525 }
526 }
527 return ret
528}
529
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700530// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
531// (including subdirectories) are in a contiguous subslice of the list, and can be found in
532// O(log(N)) time using a binary search on the directory prefix.
533type DirectorySortedPaths Paths
534
535func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
536 ret := append(DirectorySortedPaths(nil), paths...)
537 sort.Slice(ret, func(i, j int) bool {
538 return ret[i].String() < ret[j].String()
539 })
540 return ret
541}
542
543// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
544// that are in the specified directory and its subdirectories.
545func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
546 prefix := filepath.Clean(dir) + "/"
547 start := sort.Search(len(p), func(i int) bool {
548 return prefix < p[i].String()
549 })
550
551 ret := p[start:]
552
553 end := sort.Search(len(ret), func(i int) bool {
554 return !strings.HasPrefix(ret[i].String(), prefix)
555 })
556
557 ret = ret[:end]
558
559 return Paths(ret)
560}
561
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700562// WritablePaths is a slice of WritablePaths, used for multiple outputs.
563type WritablePaths []WritablePath
564
565// Strings returns the string forms of the writable paths.
566func (p WritablePaths) Strings() []string {
567 if p == nil {
568 return nil
569 }
570 ret := make([]string, len(p))
571 for i, path := range p {
572 ret[i] = path.String()
573 }
574 return ret
575}
576
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800577// Paths returns the WritablePaths as a Paths
578func (p WritablePaths) Paths() Paths {
579 if p == nil {
580 return nil
581 }
582 ret := make(Paths, len(p))
583 for i, path := range p {
584 ret[i] = path
585 }
586 return ret
587}
588
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700589type basePath struct {
590 path string
591 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800592 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700593}
594
595func (p basePath) Ext() string {
596 return filepath.Ext(p.path)
597}
598
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700599func (p basePath) Base() string {
600 return filepath.Base(p.path)
601}
602
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800603func (p basePath) Rel() string {
604 if p.rel != "" {
605 return p.rel
606 }
607 return p.path
608}
609
Colin Cross0875c522017-11-28 17:34:01 -0800610func (p basePath) String() string {
611 return p.path
612}
613
Colin Cross0db55682017-12-05 15:36:55 -0800614func (p basePath) withRel(rel string) basePath {
615 p.path = filepath.Join(p.path, rel)
616 p.rel = rel
617 return p
618}
619
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700620// SourcePath is a Path representing a file path rooted from SrcDir
621type SourcePath struct {
622 basePath
623}
624
625var _ Path = SourcePath{}
626
Colin Cross0db55682017-12-05 15:36:55 -0800627func (p SourcePath) withRel(rel string) SourcePath {
628 p.basePath = p.basePath.withRel(rel)
629 return p
630}
631
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700632// safePathForSource is for paths that we expect are safe -- only for use by go
633// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700634func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
635 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800636 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700637 if err != nil {
638 return ret, err
639 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700640
Colin Cross7b3dcc32019-01-24 13:14:39 -0800641 // absolute path already checked by validateSafePath
642 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800643 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700644 }
645
Colin Crossfe4bc362018-09-12 10:02:13 -0700646 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700647}
648
Colin Cross192e97a2018-02-22 14:21:02 -0800649// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
650func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000651 p, err := validatePath(pathComponents...)
652 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800653 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800654 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800655 }
656
Colin Cross7b3dcc32019-01-24 13:14:39 -0800657 // absolute path already checked by validatePath
658 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800659 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000660 }
661
Colin Cross192e97a2018-02-22 14:21:02 -0800662 return ret, nil
663}
664
665// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
666// path does not exist.
667func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
668 var files []string
669
670 if gctx, ok := ctx.(PathGlobContext); ok {
671 // Use glob to produce proper dependencies, even though we only want
672 // a single file.
673 files, err = gctx.GlobWithDeps(path.String(), nil)
674 } else {
675 var deps []string
676 // We cannot add build statements in this context, so we fall back to
677 // AddNinjaFileDeps
Colin Cross3f4d1162018-09-21 15:11:48 -0700678 files, deps, err = pathtools.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800679 ctx.AddNinjaFileDeps(deps...)
680 }
681
682 if err != nil {
683 return false, fmt.Errorf("glob: %s", err.Error())
684 }
685
686 return len(files) > 0, nil
687}
688
689// PathForSource joins the provided path components and validates that the result
690// neither escapes the source dir nor is in the out dir.
691// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
692func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
693 path, err := pathForSource(ctx, pathComponents...)
694 if err != nil {
695 reportPathError(ctx, err)
696 }
697
Colin Crosse3924e12018-08-15 20:18:53 -0700698 if pathtools.IsGlob(path.String()) {
699 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
700 }
701
Colin Cross192e97a2018-02-22 14:21:02 -0800702 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
703 exists, err := existsWithDependencies(ctx, path)
704 if err != nil {
705 reportPathError(ctx, err)
706 }
707 if !exists {
708 modCtx.AddMissingDependencies([]string{path.String()})
709 }
710 } else if exists, _, err := ctx.Fs().Exists(path.String()); err != nil {
711 reportPathErrorf(ctx, "%s: %s", path, err.Error())
712 } else if !exists {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800713 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800714 }
715 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700716}
717
Jeff Gaston734e3802017-04-10 15:47:24 -0700718// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700719// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
720// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800721func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800722 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800723 if err != nil {
724 reportPathError(ctx, err)
725 return OptionalPath{}
726 }
Colin Crossc48c1432018-02-23 07:09:01 +0000727
Colin Crosse3924e12018-08-15 20:18:53 -0700728 if pathtools.IsGlob(path.String()) {
729 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
730 return OptionalPath{}
731 }
732
Colin Cross192e97a2018-02-22 14:21:02 -0800733 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000734 if err != nil {
735 reportPathError(ctx, err)
736 return OptionalPath{}
737 }
Colin Cross192e97a2018-02-22 14:21:02 -0800738 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000739 return OptionalPath{}
740 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700741 return OptionalPathForPath(path)
742}
743
744func (p SourcePath) String() string {
745 return filepath.Join(p.config.srcDir, p.path)
746}
747
748// Join creates a new SourcePath with paths... joined with the current path. The
749// provided paths... may not use '..' to escape from the current path.
750func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800751 path, err := validatePath(paths...)
752 if err != nil {
753 reportPathError(ctx, err)
754 }
Colin Cross0db55682017-12-05 15:36:55 -0800755 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700756}
757
Colin Cross2fafa3e2019-03-05 12:39:51 -0800758// join is like Join but does less path validation.
759func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
760 path, err := validateSafePath(paths...)
761 if err != nil {
762 reportPathError(ctx, err)
763 }
764 return p.withRel(path)
765}
766
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700767// OverlayPath returns the overlay for `path' if it exists. This assumes that the
768// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700769func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700770 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800771 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700772 relDir = srcPath.path
773 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800774 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700775 return OptionalPath{}
776 }
777 dir := filepath.Join(p.config.srcDir, p.path, relDir)
778 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700779 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800780 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800781 }
Colin Cross461b4452018-02-23 09:22:42 -0800782 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700783 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800784 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700785 return OptionalPath{}
786 }
787 if len(paths) == 0 {
788 return OptionalPath{}
789 }
Colin Cross43f08db2018-11-12 10:13:39 -0800790 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700791 return OptionalPathForPath(PathForSource(ctx, relPath))
792}
793
794// OutputPath is a Path representing a file path rooted from the build directory
795type OutputPath struct {
796 basePath
797}
798
Colin Cross702e0f82017-10-18 17:27:54 -0700799func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800800 p.basePath = p.basePath.withRel(rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700801 return p
802}
803
Colin Cross3063b782018-08-15 11:19:12 -0700804func (p OutputPath) WithoutRel() OutputPath {
805 p.basePath.rel = filepath.Base(p.basePath.path)
806 return p
807}
808
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700809var _ Path = OutputPath{}
810
Jeff Gaston734e3802017-04-10 15:47:24 -0700811// PathForOutput joins the provided paths and returns an OutputPath that is
812// validated to not escape the build dir.
813// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
814func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800815 path, err := validatePath(pathComponents...)
816 if err != nil {
817 reportPathError(ctx, err)
818 }
Colin Crossaabf6792017-11-29 00:27:14 -0800819 return OutputPath{basePath{path, ctx.Config(), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700820}
821
Colin Cross607d8582019-07-29 16:44:46 -0700822// pathForInstallInMakeDir is used by PathForModuleInstall when the module returns true
823// for InstallBypassMake to produce an OutputPath that installs to $OUT_DIR instead of
824// $OUT_DIR/soong.
825func pathForInstallInMakeDir(ctx PathContext, pathComponents ...string) OutputPath {
826 path, err := validatePath(pathComponents...)
827 if err != nil {
828 reportPathError(ctx, err)
829 }
830 return OutputPath{basePath{"../" + path, ctx.Config(), ""}}
831}
832
Colin Cross40e33732019-02-15 11:08:35 -0800833// PathsForOutput returns Paths rooted from buildDir
834func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
835 ret := make(WritablePaths, len(paths))
836 for i, path := range paths {
837 ret[i] = PathForOutput(ctx, path)
838 }
839 return ret
840}
841
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700842func (p OutputPath) writablePath() {}
843
844func (p OutputPath) String() string {
845 return filepath.Join(p.config.buildDir, p.path)
846}
847
Colin Crossa2344662016-03-24 13:14:12 -0700848func (p OutputPath) RelPathString() string {
849 return p.path
850}
851
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700852// Join creates a new OutputPath with paths... joined with the current path. The
853// provided paths... may not use '..' to escape from the current path.
854func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800855 path, err := validatePath(paths...)
856 if err != nil {
857 reportPathError(ctx, err)
858 }
Colin Cross0db55682017-12-05 15:36:55 -0800859 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700860}
861
Colin Cross8854a5a2019-02-11 14:14:16 -0800862// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
863func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
864 if strings.Contains(ext, "/") {
865 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
866 }
867 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800868 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800869 return ret
870}
871
Colin Cross40e33732019-02-15 11:08:35 -0800872// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
873func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
874 path, err := validatePath(paths...)
875 if err != nil {
876 reportPathError(ctx, err)
877 }
878
879 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800880 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800881 return ret
882}
883
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700884// PathForIntermediates returns an OutputPath representing the top-level
885// intermediates directory.
886func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800887 path, err := validatePath(paths...)
888 if err != nil {
889 reportPathError(ctx, err)
890 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700891 return PathForOutput(ctx, ".intermediates", path)
892}
893
Colin Cross07e51612019-03-05 12:46:40 -0800894var _ genPathProvider = SourcePath{}
895var _ objPathProvider = SourcePath{}
896var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700897
Colin Cross07e51612019-03-05 12:46:40 -0800898// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700899// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800900func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
901 p, err := validatePath(pathComponents...)
902 if err != nil {
903 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800904 }
Colin Cross8a497952019-03-05 22:25:09 -0800905 paths, err := expandOneSrcPath(ctx, p, nil)
906 if err != nil {
907 if depErr, ok := err.(missingDependencyError); ok {
908 if ctx.Config().AllowMissingDependencies() {
909 ctx.AddMissingDependencies(depErr.missingDeps)
910 } else {
911 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
912 }
913 } else {
914 reportPathError(ctx, err)
915 }
916 return nil
917 } else if len(paths) == 0 {
918 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
919 return nil
920 } else if len(paths) > 1 {
921 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
922 }
923 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700924}
925
Colin Cross07e51612019-03-05 12:46:40 -0800926func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
927 p, err := validatePath(paths...)
928 if err != nil {
929 reportPathError(ctx, err)
930 }
931
932 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
933 if err != nil {
934 reportPathError(ctx, err)
935 }
936
937 path.basePath.rel = p
938
939 return path
940}
941
Colin Cross2fafa3e2019-03-05 12:39:51 -0800942// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
943// will return the path relative to subDir in the module's source directory. If any input paths are not located
944// inside subDir then a path error will be reported.
945func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
946 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -0800947 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800948 for i, path := range paths {
949 rel := Rel(ctx, subDirFullPath.String(), path.String())
950 paths[i] = subDirFullPath.join(ctx, rel)
951 }
952 return paths
953}
954
955// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
956// module's source directory. If the input path is not located inside subDir then a path error will be reported.
957func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -0800958 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800959 rel := Rel(ctx, subDirFullPath.String(), path.String())
960 return subDirFullPath.Join(ctx, rel)
961}
962
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700963// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
964// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700965func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700966 if p == nil {
967 return OptionalPath{}
968 }
969 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
970}
971
Colin Cross07e51612019-03-05 12:46:40 -0800972func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800973 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700974}
975
Colin Cross07e51612019-03-05 12:46:40 -0800976func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800977 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700978}
979
Colin Cross07e51612019-03-05 12:46:40 -0800980func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700981 // TODO: Use full directory if the new ctx is not the current ctx?
982 return PathForModuleRes(ctx, p.path, name)
983}
984
985// ModuleOutPath is a Path representing a module's output directory.
986type ModuleOutPath struct {
987 OutputPath
988}
989
990var _ Path = ModuleOutPath{}
991
Colin Cross702e0f82017-10-18 17:27:54 -0700992func pathForModule(ctx ModuleContext) OutputPath {
993 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
994}
995
Logan Chien7eefdc42018-07-11 18:10:41 +0800996// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
997// reference abi dump for the given module. This is not guaranteed to be valid.
998func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Logan Chien41eabe62019-04-10 13:33:58 +0800999 isLlndkOrNdk, isVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001000
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001001 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001002 if len(arches) == 0 {
1003 panic("device build with no primary arch")
1004 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001005 currentArch := ctx.Arch()
1006 archNameAndVariant := currentArch.ArchType.String()
1007 if currentArch.ArchVariant != "" {
1008 archNameAndVariant += "_" + currentArch.ArchVariant
1009 }
Logan Chien5237bed2018-07-11 17:15:57 +08001010
1011 var dirName string
Logan Chien41eabe62019-04-10 13:33:58 +08001012 if isLlndkOrNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001013 dirName = "ndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001014 } else if isVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001015 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001016 } else {
1017 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001018 }
Logan Chien5237bed2018-07-11 17:15:57 +08001019
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001020 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001021
1022 var ext string
1023 if isGzip {
1024 ext = ".lsdump.gz"
1025 } else {
1026 ext = ".lsdump"
1027 }
1028
1029 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1030 version, binderBitness, archNameAndVariant, "source-based",
1031 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001032}
1033
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001034// PathForModuleOut returns a Path representing the paths... under the module's
1035// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001036func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001037 p, err := validatePath(paths...)
1038 if err != nil {
1039 reportPathError(ctx, err)
1040 }
Colin Cross702e0f82017-10-18 17:27:54 -07001041 return ModuleOutPath{
1042 OutputPath: pathForModule(ctx).withRel(p),
1043 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001044}
1045
1046// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1047// directory. Mainly used for generated sources.
1048type ModuleGenPath struct {
1049 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001050}
1051
1052var _ Path = ModuleGenPath{}
1053var _ genPathProvider = ModuleGenPath{}
1054var _ objPathProvider = ModuleGenPath{}
1055
1056// PathForModuleGen returns a Path representing the paths... under the module's
1057// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001058func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001059 p, err := validatePath(paths...)
1060 if err != nil {
1061 reportPathError(ctx, err)
1062 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001063 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001064 ModuleOutPath: ModuleOutPath{
1065 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1066 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001067 }
1068}
1069
Dan Willemsen21ec4902016-11-02 20:43:13 -07001070func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001071 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001072 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001073}
1074
Colin Cross635c3b02016-05-18 15:37:25 -07001075func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001076 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1077}
1078
1079// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1080// directory. Used for compiled objects.
1081type ModuleObjPath struct {
1082 ModuleOutPath
1083}
1084
1085var _ Path = ModuleObjPath{}
1086
1087// PathForModuleObj returns a Path representing the paths... under the module's
1088// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001089func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001090 p, err := validatePath(pathComponents...)
1091 if err != nil {
1092 reportPathError(ctx, err)
1093 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001094 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1095}
1096
1097// ModuleResPath is a a Path representing the 'res' directory in a module's
1098// output directory.
1099type ModuleResPath struct {
1100 ModuleOutPath
1101}
1102
1103var _ Path = ModuleResPath{}
1104
1105// PathForModuleRes returns a Path representing the paths... under the module's
1106// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001107func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001108 p, err := validatePath(pathComponents...)
1109 if err != nil {
1110 reportPathError(ctx, err)
1111 }
1112
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001113 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1114}
1115
1116// PathForModuleInstall returns a Path representing the install path for the
1117// module appended with paths...
Dan Willemsen00269f22017-07-06 16:59:48 -07001118func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) OutputPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001119 var outPaths []string
1120 if ctx.Device() {
Colin Cross43f08db2018-11-12 10:13:39 -08001121 partition := modulePartition(ctx)
Colin Cross6510f912017-11-29 00:27:14 -08001122 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001123 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -07001124 switch ctx.Os() {
1125 case Linux:
1126 outPaths = []string{"host", "linux-x86"}
1127 case LinuxBionic:
1128 // TODO: should this be a separate top level, or shared with linux-x86?
1129 outPaths = []string{"host", "linux_bionic-x86"}
1130 default:
1131 outPaths = []string{"host", ctx.Os().String() + "-x86"}
1132 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001133 }
Dan Willemsen782a2d12015-12-21 14:55:28 -08001134 if ctx.Debug() {
1135 outPaths = append([]string{"debug"}, outPaths...)
1136 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001137 outPaths = append(outPaths, pathComponents...)
Colin Cross607d8582019-07-29 16:44:46 -07001138 if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
1139 return pathForInstallInMakeDir(ctx, outPaths...)
1140 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001141 return PathForOutput(ctx, outPaths...)
1142}
1143
Colin Cross43f08db2018-11-12 10:13:39 -08001144func InstallPathToOnDevicePath(ctx PathContext, path OutputPath) string {
1145 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1146
1147 return "/" + rel
1148}
1149
1150func modulePartition(ctx ModuleInstallPathContext) string {
1151 var partition string
1152 if ctx.InstallInData() {
1153 partition = "data"
1154 } else if ctx.InstallInRecovery() {
1155 // the layout of recovery partion is the same as that of system partition
1156 partition = "recovery/root/system"
1157 } else if ctx.SocSpecific() {
1158 partition = ctx.DeviceConfig().VendorPath()
1159 } else if ctx.DeviceSpecific() {
1160 partition = ctx.DeviceConfig().OdmPath()
1161 } else if ctx.ProductSpecific() {
1162 partition = ctx.DeviceConfig().ProductPath()
Justin Yund5f6c822019-06-25 16:47:17 +09001163 } else if ctx.SystemExtSpecific() {
1164 partition = ctx.DeviceConfig().SystemExtPath()
Colin Cross43f08db2018-11-12 10:13:39 -08001165 } else {
1166 partition = "system"
1167 }
1168 if ctx.InstallInSanitizerDir() {
1169 partition = "data/asan/" + partition
1170 }
1171 return partition
1172}
1173
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001174// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001175// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001176func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001177 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001178 path := filepath.Clean(path)
1179 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001180 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001181 }
1182 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001183 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1184 // variables. '..' may remove the entire ninja variable, even if it
1185 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001186 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001187}
1188
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001189// validatePath validates that a path does not include ninja variables, and that
1190// each path component does not attempt to leave its component. Returns a joined
1191// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001192func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001193 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001194 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001195 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001196 }
1197 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001198 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001199}
Colin Cross5b529592017-05-09 13:34:34 -07001200
Colin Cross0875c522017-11-28 17:34:01 -08001201func PathForPhony(ctx PathContext, phony string) WritablePath {
1202 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001203 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001204 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001205 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001206}
1207
Colin Cross74e3fe42017-12-11 15:51:44 -08001208type PhonyPath struct {
1209 basePath
1210}
1211
1212func (p PhonyPath) writablePath() {}
1213
1214var _ Path = PhonyPath{}
1215var _ WritablePath = PhonyPath{}
1216
Colin Cross5b529592017-05-09 13:34:34 -07001217type testPath struct {
1218 basePath
1219}
1220
1221func (p testPath) String() string {
1222 return p.path
1223}
1224
Colin Cross40e33732019-02-15 11:08:35 -08001225type testWritablePath struct {
1226 testPath
1227}
1228
1229func (p testPath) writablePath() {}
1230
1231// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1232// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001233func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001234 p, err := validateSafePath(paths...)
1235 if err != nil {
1236 panic(err)
1237 }
Colin Cross5b529592017-05-09 13:34:34 -07001238 return testPath{basePath{path: p, rel: p}}
1239}
1240
Colin Cross40e33732019-02-15 11:08:35 -08001241// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1242func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001243 p := make(Paths, len(strs))
1244 for i, s := range strs {
1245 p[i] = PathForTesting(s)
1246 }
1247
1248 return p
1249}
Colin Cross43f08db2018-11-12 10:13:39 -08001250
Colin Cross40e33732019-02-15 11:08:35 -08001251// WritablePathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be
1252// used from within tests.
1253func WritablePathForTesting(paths ...string) WritablePath {
1254 p, err := validateSafePath(paths...)
1255 if err != nil {
1256 panic(err)
1257 }
1258 return testWritablePath{testPath{basePath{path: p, rel: p}}}
1259}
1260
1261// WritablePathsForTesting returns a Path constructed from each element in strs. It should only be used from within
1262// tests.
1263func WritablePathsForTesting(strs ...string) WritablePaths {
1264 p := make(WritablePaths, len(strs))
1265 for i, s := range strs {
1266 p[i] = WritablePathForTesting(s)
1267 }
1268
1269 return p
1270}
1271
1272type testPathContext struct {
1273 config Config
1274 fs pathtools.FileSystem
1275}
1276
1277func (x *testPathContext) Fs() pathtools.FileSystem { return x.fs }
1278func (x *testPathContext) Config() Config { return x.config }
1279func (x *testPathContext) AddNinjaFileDeps(...string) {}
1280
1281// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1282// PathForOutput.
1283func PathContextForTesting(config Config, fs map[string][]byte) PathContext {
1284 return &testPathContext{
1285 config: config,
1286 fs: pathtools.MockFs(fs),
1287 }
1288}
1289
Colin Cross43f08db2018-11-12 10:13:39 -08001290// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1291// targetPath is not inside basePath.
1292func Rel(ctx PathContext, basePath string, targetPath string) string {
1293 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1294 if !isRel {
1295 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1296 return ""
1297 }
1298 return rel
1299}
1300
1301// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1302// targetPath is not inside basePath.
1303func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001304 rel, isRel, err := maybeRelErr(basePath, targetPath)
1305 if err != nil {
1306 reportPathError(ctx, err)
1307 }
1308 return rel, isRel
1309}
1310
1311func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001312 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1313 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001314 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001315 }
1316 rel, err := filepath.Rel(basePath, targetPath)
1317 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001318 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001319 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001320 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001321 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001322 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001323}