blob: 20b8b823cc4673a606a218b5d8f3528fafae73dd [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
Dan Willemsen00269f22017-07-06 16:59:48 -070049}
50
51var _ ModuleInstallPathContext = ModuleContext(nil)
52
Dan Willemsen34cc69e2015-09-23 15:26:20 -070053// errorfContext is the interface containing the Errorf method matching the
54// Errorf method in blueprint.SingletonContext.
55type errorfContext interface {
56 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080057}
58
Dan Willemsen34cc69e2015-09-23 15:26:20 -070059var _ errorfContext = blueprint.SingletonContext(nil)
60
61// moduleErrorf is the interface containing the ModuleErrorf method matching
62// the ModuleErrorf method in blueprint.ModuleContext.
63type moduleErrorf interface {
64 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080065}
66
Dan Willemsen34cc69e2015-09-23 15:26:20 -070067var _ moduleErrorf = blueprint.ModuleContext(nil)
68
Dan Willemsen34cc69e2015-09-23 15:26:20 -070069// reportPathError will register an error with the attached context. It
70// attempts ctx.ModuleErrorf for a better error message first, then falls
71// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -080072func reportPathError(ctx PathContext, err error) {
73 reportPathErrorf(ctx, "%s", err.Error())
74}
75
76// reportPathErrorf will register an error with the attached context. It
77// attempts ctx.ModuleErrorf for a better error message first, then falls
78// back to ctx.Errorf.
79func reportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -070080 if mctx, ok := ctx.(moduleErrorf); ok {
81 mctx.ModuleErrorf(format, args...)
82 } else if ectx, ok := ctx.(errorfContext); ok {
83 ectx.Errorf(format, args...)
84 } else {
85 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -070086 }
87}
88
Dan Willemsen34cc69e2015-09-23 15:26:20 -070089type Path interface {
90 // Returns the path in string form
91 String() string
92
Colin Cross4f6fc9c2016-10-26 10:05:25 -070093 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -070094 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -070095
96 // Base returns the last element of the path
97 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -080098
99 // Rel returns the portion of the path relative to the directory it was created from. For
100 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800101 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800102 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700103}
104
105// WritablePath is a type of path that can be used as an output for build rules.
106type WritablePath interface {
107 Path
108
Jeff Gaston734e3802017-04-10 15:47:24 -0700109 // the writablePath method doesn't directly do anything,
110 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700111 writablePath()
112}
113
114type genPathProvider interface {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700115 genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700116}
117type objPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700118 objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700119}
120type resPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700121 resPathWithName(ctx ModuleContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700122}
123
124// GenPathWithExt derives a new file path in ctx's generated sources directory
125// from the current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700126func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700127 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700128 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700129 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800130 reportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700131 return PathForModuleGen(ctx)
132}
133
134// ObjPathWithExt derives a new file path in ctx's object directory from the
135// current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700136func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700137 if path, ok := p.(objPathProvider); ok {
138 return path.objPathWithExt(ctx, subdir, ext)
139 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800140 reportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700141 return PathForModuleObj(ctx)
142}
143
144// ResPathWithName derives a new path in ctx's output resource directory, using
145// the current path to create the directory name, and the `name` argument for
146// the filename.
Colin Cross635c3b02016-05-18 15:37:25 -0700147func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700148 if path, ok := p.(resPathProvider); ok {
149 return path.resPathWithName(ctx, name)
150 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800151 reportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700152 return PathForModuleRes(ctx)
153}
154
155// OptionalPath is a container that may or may not contain a valid Path.
156type OptionalPath struct {
157 valid bool
158 path Path
159}
160
161// OptionalPathForPath returns an OptionalPath containing the path.
162func OptionalPathForPath(path Path) OptionalPath {
163 if path == nil {
164 return OptionalPath{}
165 }
166 return OptionalPath{valid: true, path: path}
167}
168
169// Valid returns whether there is a valid path
170func (p OptionalPath) Valid() bool {
171 return p.valid
172}
173
174// Path returns the Path embedded in this OptionalPath. You must be sure that
175// there is a valid path, since this method will panic if there is not.
176func (p OptionalPath) Path() Path {
177 if !p.valid {
178 panic("Requesting an invalid path")
179 }
180 return p.path
181}
182
183// String returns the string version of the Path, or "" if it isn't valid.
184func (p OptionalPath) String() string {
185 if p.valid {
186 return p.path.String()
187 } else {
188 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700189 }
190}
Colin Cross6e18ca42015-07-14 18:55:36 -0700191
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700192// Paths is a slice of Path objects, with helpers to operate on the collection.
193type Paths []Path
194
195// PathsForSource returns Paths rooted from SrcDir
196func PathsForSource(ctx PathContext, paths []string) Paths {
197 ret := make(Paths, len(paths))
198 for i, path := range paths {
199 ret[i] = PathForSource(ctx, path)
200 }
201 return ret
202}
203
Jeff Gaston734e3802017-04-10 15:47:24 -0700204// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800205// found in the tree. If any are not found, they are omitted from the list,
206// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800207func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800208 ret := make(Paths, 0, len(paths))
209 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800210 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800211 if p.Valid() {
212 ret = append(ret, p.Path())
213 }
214 }
215 return ret
216}
217
Colin Cross41955e82019-05-29 14:40:35 -0700218// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
219// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
220// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
221// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
222// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
223// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Colin Cross635c3b02016-05-18 15:37:25 -0700224func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800225 return PathsForModuleSrcExcludes(ctx, paths, nil)
226}
227
Colin Crossba71a3f2019-03-18 12:12:48 -0700228// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700229// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
230// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
231// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
232// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
233// truethen any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
234// having missing dependencies.
Colin Cross8a497952019-03-05 22:25:09 -0800235func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700236 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
237 if ctx.Config().AllowMissingDependencies() {
238 ctx.AddMissingDependencies(missingDeps)
239 } else {
240 for _, m := range missingDeps {
241 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
242 }
243 }
244 return ret
245}
246
247// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700248// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
249// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
250// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
251// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
252// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
253// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
254// dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700255func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800256 prefix := pathForModuleSrc(ctx).String()
257
258 var expandedExcludes []string
259 if excludes != nil {
260 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700261 }
Colin Cross8a497952019-03-05 22:25:09 -0800262
Colin Crossba71a3f2019-03-18 12:12:48 -0700263 var missingExcludeDeps []string
264
Colin Cross8a497952019-03-05 22:25:09 -0800265 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700266 if m, t := SrcIsModuleWithTag(e); m != "" {
267 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800268 if module == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700269 missingExcludeDeps = append(missingExcludeDeps, m)
Colin Cross8a497952019-03-05 22:25:09 -0800270 continue
271 }
Colin Cross41955e82019-05-29 14:40:35 -0700272 if outProducer, ok := module.(OutputFileProducer); ok {
273 outputFiles, err := outProducer.OutputFiles(t)
274 if err != nil {
275 ctx.ModuleErrorf("path dependency %q: %s", e, err)
276 }
277 expandedExcludes = append(expandedExcludes, outputFiles.Strings()...)
278 } else if t != "" {
279 ctx.ModuleErrorf("path dependency %q is not an output file producing module", e)
280 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800281 expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
282 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700283 ctx.ModuleErrorf("path dependency %q is not a source file producing module", e)
Colin Cross8a497952019-03-05 22:25:09 -0800284 }
285 } else {
286 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
287 }
288 }
289
290 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700291 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800292 }
293
Colin Crossba71a3f2019-03-18 12:12:48 -0700294 var missingDeps []string
295
Colin Cross8a497952019-03-05 22:25:09 -0800296 expandedSrcFiles := make(Paths, 0, len(paths))
297 for _, s := range paths {
298 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
299 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700300 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800301 } else if err != nil {
302 reportPathError(ctx, err)
303 }
304 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
305 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700306
307 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800308}
309
310type missingDependencyError struct {
311 missingDeps []string
312}
313
314func (e missingDependencyError) Error() string {
315 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
316}
317
318func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
Colin Cross41955e82019-05-29 14:40:35 -0700319 if m, t := SrcIsModuleWithTag(s); m != "" {
320 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800321 if module == nil {
322 return nil, missingDependencyError{[]string{m}}
323 }
Colin Cross41955e82019-05-29 14:40:35 -0700324 if outProducer, ok := module.(OutputFileProducer); ok {
325 outputFiles, err := outProducer.OutputFiles(t)
326 if err != nil {
327 return nil, fmt.Errorf("path dependency %q: %s", s, err)
328 }
329 return outputFiles, nil
330 } else if t != "" {
331 return nil, fmt.Errorf("path dependency %q is not an output file producing module", s)
332 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800333 moduleSrcs := srcProducer.Srcs()
334 for _, e := range expandedExcludes {
335 for j := 0; j < len(moduleSrcs); j++ {
336 if moduleSrcs[j].String() == e {
337 moduleSrcs = append(moduleSrcs[:j], moduleSrcs[j+1:]...)
338 j--
339 }
340 }
341 }
342 return moduleSrcs, nil
343 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700344 return nil, fmt.Errorf("path dependency %q is not a source file producing module", s)
Colin Cross8a497952019-03-05 22:25:09 -0800345 }
346 } else if pathtools.IsGlob(s) {
347 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
348 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
349 } else {
350 p := pathForModuleSrc(ctx, s)
351 if exists, _, err := ctx.Fs().Exists(p.String()); err != nil {
352 reportPathErrorf(ctx, "%s: %s", p, err.Error())
353 } else if !exists {
354 reportPathErrorf(ctx, "module source path %q does not exist", p)
355 }
356
357 j := findStringInSlice(p.String(), expandedExcludes)
358 if j >= 0 {
359 return nil, nil
360 }
361 return Paths{p}, nil
362 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700363}
364
365// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
366// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800367// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700368// It intended for use in globs that only list files that exist, so it allows '$' in
369// filenames.
Colin Crossdc35e212019-06-06 16:13:11 -0700370func pathsForModuleSrcFromFullPath(ctx BaseModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800371 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700372 if prefix == "./" {
373 prefix = ""
374 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700375 ret := make(Paths, 0, len(paths))
376 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800377 if !incDirs && strings.HasSuffix(p, "/") {
378 continue
379 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700380 path := filepath.Clean(p)
381 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800382 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700383 continue
384 }
Colin Crosse3924e12018-08-15 20:18:53 -0700385
Colin Crossfe4bc362018-09-12 10:02:13 -0700386 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700387 if err != nil {
388 reportPathError(ctx, err)
389 continue
390 }
391
Colin Cross07e51612019-03-05 12:46:40 -0800392 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700393
Colin Cross07e51612019-03-05 12:46:40 -0800394 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700395 }
396 return ret
397}
398
399// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800400// 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 -0700401func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800402 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700403 return PathsForModuleSrc(ctx, input)
404 }
405 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
406 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800407 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800408 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700409}
410
411// Strings returns the Paths in string form
412func (p Paths) Strings() []string {
413 if p == nil {
414 return nil
415 }
416 ret := make([]string, len(p))
417 for i, path := range p {
418 ret[i] = path.String()
419 }
420 return ret
421}
422
Colin Crossb6715442017-10-24 11:13:31 -0700423// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
424// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700425func FirstUniquePaths(list Paths) Paths {
426 k := 0
427outer:
428 for i := 0; i < len(list); i++ {
429 for j := 0; j < k; j++ {
430 if list[i] == list[j] {
431 continue outer
432 }
433 }
434 list[k] = list[i]
435 k++
436 }
437 return list[:k]
438}
439
Colin Crossb6715442017-10-24 11:13:31 -0700440// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
441// modifies the Paths slice contents in place, and returns a subslice of the original slice.
442func LastUniquePaths(list Paths) Paths {
443 totalSkip := 0
444 for i := len(list) - 1; i >= totalSkip; i-- {
445 skip := 0
446 for j := i - 1; j >= totalSkip; j-- {
447 if list[i] == list[j] {
448 skip++
449 } else {
450 list[j+skip] = list[j]
451 }
452 }
453 totalSkip += skip
454 }
455 return list[totalSkip:]
456}
457
Colin Crossa140bb02018-04-17 10:52:26 -0700458// ReversePaths returns a copy of a Paths in reverse order.
459func ReversePaths(list Paths) Paths {
460 if list == nil {
461 return nil
462 }
463 ret := make(Paths, len(list))
464 for i := range list {
465 ret[i] = list[len(list)-1-i]
466 }
467 return ret
468}
469
Jeff Gaston294356f2017-09-27 17:05:30 -0700470func indexPathList(s Path, list []Path) int {
471 for i, l := range list {
472 if l == s {
473 return i
474 }
475 }
476
477 return -1
478}
479
480func inPathList(p Path, list []Path) bool {
481 return indexPathList(p, list) != -1
482}
483
484func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
485 for _, l := range list {
486 if inPathList(l, filter) {
487 filtered = append(filtered, l)
488 } else {
489 remainder = append(remainder, l)
490 }
491 }
492
493 return
494}
495
Colin Cross93e85952017-08-15 13:34:18 -0700496// HasExt returns true of any of the paths have extension ext, otherwise false
497func (p Paths) HasExt(ext string) bool {
498 for _, path := range p {
499 if path.Ext() == ext {
500 return true
501 }
502 }
503
504 return false
505}
506
507// FilterByExt returns the subset of the paths that have extension ext
508func (p Paths) FilterByExt(ext string) Paths {
509 ret := make(Paths, 0, len(p))
510 for _, path := range p {
511 if path.Ext() == ext {
512 ret = append(ret, path)
513 }
514 }
515 return ret
516}
517
518// FilterOutByExt returns the subset of the paths that do not have extension ext
519func (p Paths) FilterOutByExt(ext string) Paths {
520 ret := make(Paths, 0, len(p))
521 for _, path := range p {
522 if path.Ext() != ext {
523 ret = append(ret, path)
524 }
525 }
526 return ret
527}
528
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700529// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
530// (including subdirectories) are in a contiguous subslice of the list, and can be found in
531// O(log(N)) time using a binary search on the directory prefix.
532type DirectorySortedPaths Paths
533
534func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
535 ret := append(DirectorySortedPaths(nil), paths...)
536 sort.Slice(ret, func(i, j int) bool {
537 return ret[i].String() < ret[j].String()
538 })
539 return ret
540}
541
542// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
543// that are in the specified directory and its subdirectories.
544func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
545 prefix := filepath.Clean(dir) + "/"
546 start := sort.Search(len(p), func(i int) bool {
547 return prefix < p[i].String()
548 })
549
550 ret := p[start:]
551
552 end := sort.Search(len(ret), func(i int) bool {
553 return !strings.HasPrefix(ret[i].String(), prefix)
554 })
555
556 ret = ret[:end]
557
558 return Paths(ret)
559}
560
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700561// WritablePaths is a slice of WritablePaths, used for multiple outputs.
562type WritablePaths []WritablePath
563
564// Strings returns the string forms of the writable paths.
565func (p WritablePaths) Strings() []string {
566 if p == nil {
567 return nil
568 }
569 ret := make([]string, len(p))
570 for i, path := range p {
571 ret[i] = path.String()
572 }
573 return ret
574}
575
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800576// Paths returns the WritablePaths as a Paths
577func (p WritablePaths) Paths() Paths {
578 if p == nil {
579 return nil
580 }
581 ret := make(Paths, len(p))
582 for i, path := range p {
583 ret[i] = path
584 }
585 return ret
586}
587
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700588type basePath struct {
589 path string
590 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800591 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700592}
593
594func (p basePath) Ext() string {
595 return filepath.Ext(p.path)
596}
597
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700598func (p basePath) Base() string {
599 return filepath.Base(p.path)
600}
601
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800602func (p basePath) Rel() string {
603 if p.rel != "" {
604 return p.rel
605 }
606 return p.path
607}
608
Colin Cross0875c522017-11-28 17:34:01 -0800609func (p basePath) String() string {
610 return p.path
611}
612
Colin Cross0db55682017-12-05 15:36:55 -0800613func (p basePath) withRel(rel string) basePath {
614 p.path = filepath.Join(p.path, rel)
615 p.rel = rel
616 return p
617}
618
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700619// SourcePath is a Path representing a file path rooted from SrcDir
620type SourcePath struct {
621 basePath
622}
623
624var _ Path = SourcePath{}
625
Colin Cross0db55682017-12-05 15:36:55 -0800626func (p SourcePath) withRel(rel string) SourcePath {
627 p.basePath = p.basePath.withRel(rel)
628 return p
629}
630
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700631// safePathForSource is for paths that we expect are safe -- only for use by go
632// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700633func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
634 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800635 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700636 if err != nil {
637 return ret, err
638 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700639
Colin Cross7b3dcc32019-01-24 13:14:39 -0800640 // absolute path already checked by validateSafePath
641 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800642 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700643 }
644
Colin Crossfe4bc362018-09-12 10:02:13 -0700645 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700646}
647
Colin Cross192e97a2018-02-22 14:21:02 -0800648// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
649func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000650 p, err := validatePath(pathComponents...)
651 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800652 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800653 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800654 }
655
Colin Cross7b3dcc32019-01-24 13:14:39 -0800656 // absolute path already checked by validatePath
657 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800658 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000659 }
660
Colin Cross192e97a2018-02-22 14:21:02 -0800661 return ret, nil
662}
663
664// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
665// path does not exist.
666func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
667 var files []string
668
669 if gctx, ok := ctx.(PathGlobContext); ok {
670 // Use glob to produce proper dependencies, even though we only want
671 // a single file.
672 files, err = gctx.GlobWithDeps(path.String(), nil)
673 } else {
674 var deps []string
675 // We cannot add build statements in this context, so we fall back to
676 // AddNinjaFileDeps
Colin Cross3f4d1162018-09-21 15:11:48 -0700677 files, deps, err = pathtools.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800678 ctx.AddNinjaFileDeps(deps...)
679 }
680
681 if err != nil {
682 return false, fmt.Errorf("glob: %s", err.Error())
683 }
684
685 return len(files) > 0, nil
686}
687
688// PathForSource joins the provided path components and validates that the result
689// neither escapes the source dir nor is in the out dir.
690// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
691func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
692 path, err := pathForSource(ctx, pathComponents...)
693 if err != nil {
694 reportPathError(ctx, err)
695 }
696
Colin Crosse3924e12018-08-15 20:18:53 -0700697 if pathtools.IsGlob(path.String()) {
698 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
699 }
700
Colin Cross192e97a2018-02-22 14:21:02 -0800701 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
702 exists, err := existsWithDependencies(ctx, path)
703 if err != nil {
704 reportPathError(ctx, err)
705 }
706 if !exists {
707 modCtx.AddMissingDependencies([]string{path.String()})
708 }
709 } else if exists, _, err := ctx.Fs().Exists(path.String()); err != nil {
710 reportPathErrorf(ctx, "%s: %s", path, err.Error())
711 } else if !exists {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800712 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800713 }
714 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700715}
716
Jeff Gaston734e3802017-04-10 15:47:24 -0700717// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700718// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
719// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800720func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800721 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800722 if err != nil {
723 reportPathError(ctx, err)
724 return OptionalPath{}
725 }
Colin Crossc48c1432018-02-23 07:09:01 +0000726
Colin Crosse3924e12018-08-15 20:18:53 -0700727 if pathtools.IsGlob(path.String()) {
728 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
729 return OptionalPath{}
730 }
731
Colin Cross192e97a2018-02-22 14:21:02 -0800732 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000733 if err != nil {
734 reportPathError(ctx, err)
735 return OptionalPath{}
736 }
Colin Cross192e97a2018-02-22 14:21:02 -0800737 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000738 return OptionalPath{}
739 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700740 return OptionalPathForPath(path)
741}
742
743func (p SourcePath) String() string {
744 return filepath.Join(p.config.srcDir, p.path)
745}
746
747// Join creates a new SourcePath with paths... joined with the current path. The
748// provided paths... may not use '..' to escape from the current path.
749func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800750 path, err := validatePath(paths...)
751 if err != nil {
752 reportPathError(ctx, err)
753 }
Colin Cross0db55682017-12-05 15:36:55 -0800754 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700755}
756
Colin Cross2fafa3e2019-03-05 12:39:51 -0800757// join is like Join but does less path validation.
758func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
759 path, err := validateSafePath(paths...)
760 if err != nil {
761 reportPathError(ctx, err)
762 }
763 return p.withRel(path)
764}
765
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700766// OverlayPath returns the overlay for `path' if it exists. This assumes that the
767// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700768func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700769 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800770 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700771 relDir = srcPath.path
772 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800773 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700774 return OptionalPath{}
775 }
776 dir := filepath.Join(p.config.srcDir, p.path, relDir)
777 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700778 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800779 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800780 }
Colin Cross461b4452018-02-23 09:22:42 -0800781 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700782 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800783 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700784 return OptionalPath{}
785 }
786 if len(paths) == 0 {
787 return OptionalPath{}
788 }
Colin Cross43f08db2018-11-12 10:13:39 -0800789 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700790 return OptionalPathForPath(PathForSource(ctx, relPath))
791}
792
793// OutputPath is a Path representing a file path rooted from the build directory
794type OutputPath struct {
795 basePath
796}
797
Colin Cross702e0f82017-10-18 17:27:54 -0700798func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800799 p.basePath = p.basePath.withRel(rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700800 return p
801}
802
Colin Cross3063b782018-08-15 11:19:12 -0700803func (p OutputPath) WithoutRel() OutputPath {
804 p.basePath.rel = filepath.Base(p.basePath.path)
805 return p
806}
807
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700808var _ Path = OutputPath{}
809
Jeff Gaston734e3802017-04-10 15:47:24 -0700810// PathForOutput joins the provided paths and returns an OutputPath that is
811// validated to not escape the build dir.
812// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
813func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800814 path, err := validatePath(pathComponents...)
815 if err != nil {
816 reportPathError(ctx, err)
817 }
Colin Crossaabf6792017-11-29 00:27:14 -0800818 return OutputPath{basePath{path, ctx.Config(), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700819}
820
Colin Cross40e33732019-02-15 11:08:35 -0800821// PathsForOutput returns Paths rooted from buildDir
822func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
823 ret := make(WritablePaths, len(paths))
824 for i, path := range paths {
825 ret[i] = PathForOutput(ctx, path)
826 }
827 return ret
828}
829
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700830func (p OutputPath) writablePath() {}
831
832func (p OutputPath) String() string {
833 return filepath.Join(p.config.buildDir, p.path)
834}
835
Colin Crossa2344662016-03-24 13:14:12 -0700836func (p OutputPath) RelPathString() string {
837 return p.path
838}
839
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700840// Join creates a new OutputPath with paths... joined with the current path. The
841// provided paths... may not use '..' to escape from the current path.
842func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800843 path, err := validatePath(paths...)
844 if err != nil {
845 reportPathError(ctx, err)
846 }
Colin Cross0db55682017-12-05 15:36:55 -0800847 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700848}
849
Colin Cross8854a5a2019-02-11 14:14:16 -0800850// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
851func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
852 if strings.Contains(ext, "/") {
853 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
854 }
855 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800856 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800857 return ret
858}
859
Colin Cross40e33732019-02-15 11:08:35 -0800860// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
861func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
862 path, err := validatePath(paths...)
863 if err != nil {
864 reportPathError(ctx, err)
865 }
866
867 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800868 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800869 return ret
870}
871
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700872// PathForIntermediates returns an OutputPath representing the top-level
873// intermediates directory.
874func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800875 path, err := validatePath(paths...)
876 if err != nil {
877 reportPathError(ctx, err)
878 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700879 return PathForOutput(ctx, ".intermediates", path)
880}
881
Colin Cross07e51612019-03-05 12:46:40 -0800882var _ genPathProvider = SourcePath{}
883var _ objPathProvider = SourcePath{}
884var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700885
Colin Cross07e51612019-03-05 12:46:40 -0800886// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700887// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800888func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
889 p, err := validatePath(pathComponents...)
890 if err != nil {
891 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800892 }
Colin Cross8a497952019-03-05 22:25:09 -0800893 paths, err := expandOneSrcPath(ctx, p, nil)
894 if err != nil {
895 if depErr, ok := err.(missingDependencyError); ok {
896 if ctx.Config().AllowMissingDependencies() {
897 ctx.AddMissingDependencies(depErr.missingDeps)
898 } else {
899 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
900 }
901 } else {
902 reportPathError(ctx, err)
903 }
904 return nil
905 } else if len(paths) == 0 {
906 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
907 return nil
908 } else if len(paths) > 1 {
909 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
910 }
911 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700912}
913
Colin Cross07e51612019-03-05 12:46:40 -0800914func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
915 p, err := validatePath(paths...)
916 if err != nil {
917 reportPathError(ctx, err)
918 }
919
920 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
921 if err != nil {
922 reportPathError(ctx, err)
923 }
924
925 path.basePath.rel = p
926
927 return path
928}
929
Colin Cross2fafa3e2019-03-05 12:39:51 -0800930// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
931// will return the path relative to subDir in the module's source directory. If any input paths are not located
932// inside subDir then a path error will be reported.
933func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
934 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -0800935 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800936 for i, path := range paths {
937 rel := Rel(ctx, subDirFullPath.String(), path.String())
938 paths[i] = subDirFullPath.join(ctx, rel)
939 }
940 return paths
941}
942
943// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
944// module's source directory. If the input path is not located inside subDir then a path error will be reported.
945func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -0800946 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800947 rel := Rel(ctx, subDirFullPath.String(), path.String())
948 return subDirFullPath.Join(ctx, rel)
949}
950
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700951// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
952// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700953func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700954 if p == nil {
955 return OptionalPath{}
956 }
957 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
958}
959
Colin Cross07e51612019-03-05 12:46:40 -0800960func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800961 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700962}
963
Colin Cross07e51612019-03-05 12:46:40 -0800964func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800965 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700966}
967
Colin Cross07e51612019-03-05 12:46:40 -0800968func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700969 // TODO: Use full directory if the new ctx is not the current ctx?
970 return PathForModuleRes(ctx, p.path, name)
971}
972
973// ModuleOutPath is a Path representing a module's output directory.
974type ModuleOutPath struct {
975 OutputPath
976}
977
978var _ Path = ModuleOutPath{}
979
Colin Cross702e0f82017-10-18 17:27:54 -0700980func pathForModule(ctx ModuleContext) OutputPath {
981 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
982}
983
Logan Chien7eefdc42018-07-11 18:10:41 +0800984// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
985// reference abi dump for the given module. This is not guaranteed to be valid.
986func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Logan Chien41eabe62019-04-10 13:33:58 +0800987 isLlndkOrNdk, isVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +0800988
Jayant Chowdharyac066c62018-02-20 10:53:31 -0800989 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +0800990 if len(arches) == 0 {
991 panic("device build with no primary arch")
992 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -0800993 currentArch := ctx.Arch()
994 archNameAndVariant := currentArch.ArchType.String()
995 if currentArch.ArchVariant != "" {
996 archNameAndVariant += "_" + currentArch.ArchVariant
997 }
Logan Chien5237bed2018-07-11 17:15:57 +0800998
999 var dirName string
Logan Chien41eabe62019-04-10 13:33:58 +08001000 if isLlndkOrNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001001 dirName = "ndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001002 } else if isVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001003 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001004 } else {
1005 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001006 }
Logan Chien5237bed2018-07-11 17:15:57 +08001007
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001008 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001009
1010 var ext string
1011 if isGzip {
1012 ext = ".lsdump.gz"
1013 } else {
1014 ext = ".lsdump"
1015 }
1016
1017 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1018 version, binderBitness, archNameAndVariant, "source-based",
1019 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001020}
1021
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001022// PathForModuleOut returns a Path representing the paths... under the module's
1023// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001024func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001025 p, err := validatePath(paths...)
1026 if err != nil {
1027 reportPathError(ctx, err)
1028 }
Colin Cross702e0f82017-10-18 17:27:54 -07001029 return ModuleOutPath{
1030 OutputPath: pathForModule(ctx).withRel(p),
1031 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001032}
1033
1034// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1035// directory. Mainly used for generated sources.
1036type ModuleGenPath struct {
1037 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001038}
1039
1040var _ Path = ModuleGenPath{}
1041var _ genPathProvider = ModuleGenPath{}
1042var _ objPathProvider = ModuleGenPath{}
1043
1044// PathForModuleGen returns a Path representing the paths... under the module's
1045// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001046func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001047 p, err := validatePath(paths...)
1048 if err != nil {
1049 reportPathError(ctx, err)
1050 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001051 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001052 ModuleOutPath: ModuleOutPath{
1053 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1054 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001055 }
1056}
1057
Dan Willemsen21ec4902016-11-02 20:43:13 -07001058func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001059 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001060 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001061}
1062
Colin Cross635c3b02016-05-18 15:37:25 -07001063func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001064 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1065}
1066
1067// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1068// directory. Used for compiled objects.
1069type ModuleObjPath struct {
1070 ModuleOutPath
1071}
1072
1073var _ Path = ModuleObjPath{}
1074
1075// PathForModuleObj returns a Path representing the paths... under the module's
1076// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001077func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001078 p, err := validatePath(pathComponents...)
1079 if err != nil {
1080 reportPathError(ctx, err)
1081 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001082 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1083}
1084
1085// ModuleResPath is a a Path representing the 'res' directory in a module's
1086// output directory.
1087type ModuleResPath struct {
1088 ModuleOutPath
1089}
1090
1091var _ Path = ModuleResPath{}
1092
1093// PathForModuleRes returns a Path representing the paths... under the module's
1094// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001095func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001096 p, err := validatePath(pathComponents...)
1097 if err != nil {
1098 reportPathError(ctx, err)
1099 }
1100
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001101 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1102}
1103
1104// PathForModuleInstall returns a Path representing the install path for the
1105// module appended with paths...
Dan Willemsen00269f22017-07-06 16:59:48 -07001106func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) OutputPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001107 var outPaths []string
1108 if ctx.Device() {
Colin Cross43f08db2018-11-12 10:13:39 -08001109 partition := modulePartition(ctx)
Colin Cross6510f912017-11-29 00:27:14 -08001110 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001111 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -07001112 switch ctx.Os() {
1113 case Linux:
1114 outPaths = []string{"host", "linux-x86"}
1115 case LinuxBionic:
1116 // TODO: should this be a separate top level, or shared with linux-x86?
1117 outPaths = []string{"host", "linux_bionic-x86"}
1118 default:
1119 outPaths = []string{"host", ctx.Os().String() + "-x86"}
1120 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001121 }
Dan Willemsen782a2d12015-12-21 14:55:28 -08001122 if ctx.Debug() {
1123 outPaths = append([]string{"debug"}, outPaths...)
1124 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001125 outPaths = append(outPaths, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001126 return PathForOutput(ctx, outPaths...)
1127}
1128
Colin Cross43f08db2018-11-12 10:13:39 -08001129func InstallPathToOnDevicePath(ctx PathContext, path OutputPath) string {
1130 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1131
1132 return "/" + rel
1133}
1134
1135func modulePartition(ctx ModuleInstallPathContext) string {
1136 var partition string
1137 if ctx.InstallInData() {
1138 partition = "data"
1139 } else if ctx.InstallInRecovery() {
1140 // the layout of recovery partion is the same as that of system partition
1141 partition = "recovery/root/system"
1142 } else if ctx.SocSpecific() {
1143 partition = ctx.DeviceConfig().VendorPath()
1144 } else if ctx.DeviceSpecific() {
1145 partition = ctx.DeviceConfig().OdmPath()
1146 } else if ctx.ProductSpecific() {
1147 partition = ctx.DeviceConfig().ProductPath()
1148 } else if ctx.ProductServicesSpecific() {
1149 partition = ctx.DeviceConfig().ProductServicesPath()
1150 } else {
1151 partition = "system"
1152 }
1153 if ctx.InstallInSanitizerDir() {
1154 partition = "data/asan/" + partition
1155 }
1156 return partition
1157}
1158
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001159// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001160// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001161func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001162 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001163 path := filepath.Clean(path)
1164 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001165 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001166 }
1167 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001168 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1169 // variables. '..' may remove the entire ninja variable, even if it
1170 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001171 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001172}
1173
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001174// validatePath validates that a path does not include ninja variables, and that
1175// each path component does not attempt to leave its component. Returns a joined
1176// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001177func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001178 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001179 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001180 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001181 }
1182 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001183 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001184}
Colin Cross5b529592017-05-09 13:34:34 -07001185
Colin Cross0875c522017-11-28 17:34:01 -08001186func PathForPhony(ctx PathContext, phony string) WritablePath {
1187 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001188 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001189 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001190 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001191}
1192
Colin Cross74e3fe42017-12-11 15:51:44 -08001193type PhonyPath struct {
1194 basePath
1195}
1196
1197func (p PhonyPath) writablePath() {}
1198
1199var _ Path = PhonyPath{}
1200var _ WritablePath = PhonyPath{}
1201
Colin Cross5b529592017-05-09 13:34:34 -07001202type testPath struct {
1203 basePath
1204}
1205
1206func (p testPath) String() string {
1207 return p.path
1208}
1209
Colin Cross40e33732019-02-15 11:08:35 -08001210type testWritablePath struct {
1211 testPath
1212}
1213
1214func (p testPath) writablePath() {}
1215
1216// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1217// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001218func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001219 p, err := validateSafePath(paths...)
1220 if err != nil {
1221 panic(err)
1222 }
Colin Cross5b529592017-05-09 13:34:34 -07001223 return testPath{basePath{path: p, rel: p}}
1224}
1225
Colin Cross40e33732019-02-15 11:08:35 -08001226// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1227func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001228 p := make(Paths, len(strs))
1229 for i, s := range strs {
1230 p[i] = PathForTesting(s)
1231 }
1232
1233 return p
1234}
Colin Cross43f08db2018-11-12 10:13:39 -08001235
Colin Cross40e33732019-02-15 11:08:35 -08001236// WritablePathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be
1237// used from within tests.
1238func WritablePathForTesting(paths ...string) WritablePath {
1239 p, err := validateSafePath(paths...)
1240 if err != nil {
1241 panic(err)
1242 }
1243 return testWritablePath{testPath{basePath{path: p, rel: p}}}
1244}
1245
1246// WritablePathsForTesting returns a Path constructed from each element in strs. It should only be used from within
1247// tests.
1248func WritablePathsForTesting(strs ...string) WritablePaths {
1249 p := make(WritablePaths, len(strs))
1250 for i, s := range strs {
1251 p[i] = WritablePathForTesting(s)
1252 }
1253
1254 return p
1255}
1256
1257type testPathContext struct {
1258 config Config
1259 fs pathtools.FileSystem
1260}
1261
1262func (x *testPathContext) Fs() pathtools.FileSystem { return x.fs }
1263func (x *testPathContext) Config() Config { return x.config }
1264func (x *testPathContext) AddNinjaFileDeps(...string) {}
1265
1266// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1267// PathForOutput.
1268func PathContextForTesting(config Config, fs map[string][]byte) PathContext {
1269 return &testPathContext{
1270 config: config,
1271 fs: pathtools.MockFs(fs),
1272 }
1273}
1274
Colin Cross43f08db2018-11-12 10:13:39 -08001275// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1276// targetPath is not inside basePath.
1277func Rel(ctx PathContext, basePath string, targetPath string) string {
1278 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1279 if !isRel {
1280 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1281 return ""
1282 }
1283 return rel
1284}
1285
1286// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1287// targetPath is not inside basePath.
1288func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001289 rel, isRel, err := maybeRelErr(basePath, targetPath)
1290 if err != nil {
1291 reportPathError(ctx, err)
1292 }
1293 return rel, isRel
1294}
1295
1296func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001297 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1298 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001299 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001300 }
1301 rel, err := filepath.Rel(basePath, targetPath)
1302 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001303 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001304 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001305 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001306 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001307 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001308}