blob: fcea65c55f865298861f749552052be0b4b8880c [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Colin Cross6e18ca42015-07-14 18:55:36 -070018 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000019 "io/ioutil"
20 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070021 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070022 "reflect"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070023 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070024 "strings"
25
26 "github.com/google/blueprint"
27 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080028)
29
Colin Cross988414c2020-01-11 01:11:46 +000030var absSrcDir string
31
Dan Willemsen34cc69e2015-09-23 15:26:20 -070032// PathContext is the subset of a (Module|Singleton)Context required by the
33// Path methods.
34type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080035 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080036 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080037}
38
Colin Cross7f19f372016-11-01 11:10:25 -070039type PathGlobContext interface {
40 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
41}
42
Colin Crossaabf6792017-11-29 00:27:14 -080043var _ PathContext = SingletonContext(nil)
44var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070045
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010046// "Null" path context is a minimal path context for a given config.
47type NullPathContext struct {
48 config Config
49}
50
51func (NullPathContext) AddNinjaFileDeps(...string) {}
52func (ctx NullPathContext) Config() Config { return ctx.config }
53
Dan Willemsen00269f22017-07-06 16:59:48 -070054type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -070055 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -070056
57 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -070058 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -070059 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -080060 InstallInRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +090061 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -070062 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -070063 InstallBypassMake() bool
Colin Cross6e359402020-02-10 15:29:54 -080064 InstallForceOS() *OsType
Dan Willemsen00269f22017-07-06 16:59:48 -070065}
66
67var _ ModuleInstallPathContext = ModuleContext(nil)
68
Dan Willemsen34cc69e2015-09-23 15:26:20 -070069// errorfContext is the interface containing the Errorf method matching the
70// Errorf method in blueprint.SingletonContext.
71type errorfContext interface {
72 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080073}
74
Dan Willemsen34cc69e2015-09-23 15:26:20 -070075var _ errorfContext = blueprint.SingletonContext(nil)
76
77// moduleErrorf is the interface containing the ModuleErrorf method matching
78// the ModuleErrorf method in blueprint.ModuleContext.
79type moduleErrorf interface {
80 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080081}
82
Dan Willemsen34cc69e2015-09-23 15:26:20 -070083var _ moduleErrorf = blueprint.ModuleContext(nil)
84
Dan Willemsen34cc69e2015-09-23 15:26:20 -070085// reportPathError will register an error with the attached context. It
86// attempts ctx.ModuleErrorf for a better error message first, then falls
87// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -080088func reportPathError(ctx PathContext, err error) {
89 reportPathErrorf(ctx, "%s", err.Error())
90}
91
92// reportPathErrorf will register an error with the attached context. It
93// attempts ctx.ModuleErrorf for a better error message first, then falls
94// back to ctx.Errorf.
95func reportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -070096 if mctx, ok := ctx.(moduleErrorf); ok {
97 mctx.ModuleErrorf(format, args...)
98 } else if ectx, ok := ctx.(errorfContext); ok {
99 ectx.Errorf(format, args...)
100 } else {
101 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700102 }
103}
104
Colin Cross5e708052019-08-06 13:59:50 -0700105func pathContextName(ctx PathContext, module blueprint.Module) string {
106 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
107 return x.ModuleName(module)
108 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
109 return x.OtherModuleName(module)
110 }
111 return "unknown"
112}
113
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700114type Path interface {
115 // Returns the path in string form
116 String() string
117
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700118 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700119 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700120
121 // Base returns the last element of the path
122 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800123
124 // Rel returns the portion of the path relative to the directory it was created from. For
125 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800126 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800127 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700128}
129
130// WritablePath is a type of path that can be used as an output for build rules.
131type WritablePath interface {
132 Path
133
Paul Duffin9b478b02019-12-10 13:41:51 +0000134 // return the path to the build directory.
135 buildDir() string
136
Jeff Gaston734e3802017-04-10 15:47:24 -0700137 // the writablePath method doesn't directly do anything,
138 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700139 writablePath()
140}
141
142type genPathProvider interface {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700143 genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700144}
145type objPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700146 objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700147}
148type resPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700149 resPathWithName(ctx ModuleContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700150}
151
152// GenPathWithExt derives a new file path in ctx's generated sources directory
153// from the current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700154func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700155 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700156 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700157 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800158 reportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700159 return PathForModuleGen(ctx)
160}
161
162// ObjPathWithExt derives a new file path in ctx's object directory from the
163// current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700164func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700165 if path, ok := p.(objPathProvider); ok {
166 return path.objPathWithExt(ctx, subdir, ext)
167 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800168 reportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700169 return PathForModuleObj(ctx)
170}
171
172// ResPathWithName derives a new path in ctx's output resource directory, using
173// the current path to create the directory name, and the `name` argument for
174// the filename.
Colin Cross635c3b02016-05-18 15:37:25 -0700175func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700176 if path, ok := p.(resPathProvider); ok {
177 return path.resPathWithName(ctx, name)
178 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800179 reportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700180 return PathForModuleRes(ctx)
181}
182
183// OptionalPath is a container that may or may not contain a valid Path.
184type OptionalPath struct {
185 valid bool
186 path Path
187}
188
189// OptionalPathForPath returns an OptionalPath containing the path.
190func OptionalPathForPath(path Path) OptionalPath {
191 if path == nil {
192 return OptionalPath{}
193 }
194 return OptionalPath{valid: true, path: path}
195}
196
197// Valid returns whether there is a valid path
198func (p OptionalPath) Valid() bool {
199 return p.valid
200}
201
202// Path returns the Path embedded in this OptionalPath. You must be sure that
203// there is a valid path, since this method will panic if there is not.
204func (p OptionalPath) Path() Path {
205 if !p.valid {
206 panic("Requesting an invalid path")
207 }
208 return p.path
209}
210
211// String returns the string version of the Path, or "" if it isn't valid.
212func (p OptionalPath) String() string {
213 if p.valid {
214 return p.path.String()
215 } else {
216 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700217 }
218}
Colin Cross6e18ca42015-07-14 18:55:36 -0700219
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700220// Paths is a slice of Path objects, with helpers to operate on the collection.
221type Paths []Path
222
223// PathsForSource returns Paths rooted from SrcDir
224func PathsForSource(ctx PathContext, paths []string) Paths {
225 ret := make(Paths, len(paths))
226 for i, path := range paths {
227 ret[i] = PathForSource(ctx, path)
228 }
229 return ret
230}
231
Jeff Gaston734e3802017-04-10 15:47:24 -0700232// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800233// found in the tree. If any are not found, they are omitted from the list,
234// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800235func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800236 ret := make(Paths, 0, len(paths))
237 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800238 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800239 if p.Valid() {
240 ret = append(ret, p.Path())
241 }
242 }
243 return ret
244}
245
Colin Cross41955e82019-05-29 14:40:35 -0700246// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
247// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
248// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
249// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
250// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
251// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Colin Cross635c3b02016-05-18 15:37:25 -0700252func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800253 return PathsForModuleSrcExcludes(ctx, paths, nil)
254}
255
Colin Crossba71a3f2019-03-18 12:12:48 -0700256// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700257// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
258// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
259// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
260// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100261// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700262// having missing dependencies.
Colin Cross8a497952019-03-05 22:25:09 -0800263func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700264 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
265 if ctx.Config().AllowMissingDependencies() {
266 ctx.AddMissingDependencies(missingDeps)
267 } else {
268 for _, m := range missingDeps {
269 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
270 }
271 }
272 return ret
273}
274
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000275// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
276type OutputPaths []OutputPath
277
278// Paths returns the OutputPaths as a Paths
279func (p OutputPaths) Paths() Paths {
280 if p == nil {
281 return nil
282 }
283 ret := make(Paths, len(p))
284 for i, path := range p {
285 ret[i] = path
286 }
287 return ret
288}
289
290// Strings returns the string forms of the writable paths.
291func (p OutputPaths) Strings() []string {
292 if p == nil {
293 return nil
294 }
295 ret := make([]string, len(p))
296 for i, path := range p {
297 ret[i] = path.String()
298 }
299 return ret
300}
301
Colin Crossba71a3f2019-03-18 12:12:48 -0700302// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700303// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
304// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
305// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
306// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
307// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
308// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
309// dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700310func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800311 prefix := pathForModuleSrc(ctx).String()
312
313 var expandedExcludes []string
314 if excludes != nil {
315 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700316 }
Colin Cross8a497952019-03-05 22:25:09 -0800317
Colin Crossba71a3f2019-03-18 12:12:48 -0700318 var missingExcludeDeps []string
319
Colin Cross8a497952019-03-05 22:25:09 -0800320 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700321 if m, t := SrcIsModuleWithTag(e); m != "" {
322 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800323 if module == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700324 missingExcludeDeps = append(missingExcludeDeps, m)
Colin Cross8a497952019-03-05 22:25:09 -0800325 continue
326 }
Colin Cross41955e82019-05-29 14:40:35 -0700327 if outProducer, ok := module.(OutputFileProducer); ok {
328 outputFiles, err := outProducer.OutputFiles(t)
329 if err != nil {
330 ctx.ModuleErrorf("path dependency %q: %s", e, err)
331 }
332 expandedExcludes = append(expandedExcludes, outputFiles.Strings()...)
333 } else if t != "" {
334 ctx.ModuleErrorf("path dependency %q is not an output file producing module", e)
335 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800336 expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
337 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700338 ctx.ModuleErrorf("path dependency %q is not a source file producing module", e)
Colin Cross8a497952019-03-05 22:25:09 -0800339 }
340 } else {
341 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
342 }
343 }
344
345 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700346 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800347 }
348
Colin Crossba71a3f2019-03-18 12:12:48 -0700349 var missingDeps []string
350
Colin Cross8a497952019-03-05 22:25:09 -0800351 expandedSrcFiles := make(Paths, 0, len(paths))
352 for _, s := range paths {
353 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
354 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700355 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800356 } else if err != nil {
357 reportPathError(ctx, err)
358 }
359 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
360 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700361
362 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800363}
364
365type missingDependencyError struct {
366 missingDeps []string
367}
368
369func (e missingDependencyError) Error() string {
370 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
371}
372
373func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
Colin Cross41955e82019-05-29 14:40:35 -0700374 if m, t := SrcIsModuleWithTag(s); m != "" {
375 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800376 if module == nil {
377 return nil, missingDependencyError{[]string{m}}
378 }
Colin Cross41955e82019-05-29 14:40:35 -0700379 if outProducer, ok := module.(OutputFileProducer); ok {
380 outputFiles, err := outProducer.OutputFiles(t)
381 if err != nil {
382 return nil, fmt.Errorf("path dependency %q: %s", s, err)
383 }
384 return outputFiles, nil
385 } else if t != "" {
386 return nil, fmt.Errorf("path dependency %q is not an output file producing module", s)
387 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800388 moduleSrcs := srcProducer.Srcs()
389 for _, e := range expandedExcludes {
390 for j := 0; j < len(moduleSrcs); j++ {
391 if moduleSrcs[j].String() == e {
392 moduleSrcs = append(moduleSrcs[:j], moduleSrcs[j+1:]...)
393 j--
394 }
395 }
396 }
397 return moduleSrcs, nil
398 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700399 return nil, fmt.Errorf("path dependency %q is not a source file producing module", s)
Colin Cross8a497952019-03-05 22:25:09 -0800400 }
401 } else if pathtools.IsGlob(s) {
402 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
403 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
404 } else {
405 p := pathForModuleSrc(ctx, s)
Colin Cross988414c2020-01-11 01:11:46 +0000406 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Colin Cross8a497952019-03-05 22:25:09 -0800407 reportPathErrorf(ctx, "%s: %s", p, err.Error())
408 } else if !exists {
409 reportPathErrorf(ctx, "module source path %q does not exist", p)
410 }
411
412 j := findStringInSlice(p.String(), expandedExcludes)
413 if j >= 0 {
414 return nil, nil
415 }
416 return Paths{p}, nil
417 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700418}
419
420// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
421// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800422// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700423// It intended for use in globs that only list files that exist, so it allows '$' in
424// filenames.
Colin Cross1184b642019-12-30 18:43:07 -0800425func pathsForModuleSrcFromFullPath(ctx EarlyModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800426 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700427 if prefix == "./" {
428 prefix = ""
429 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700430 ret := make(Paths, 0, len(paths))
431 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800432 if !incDirs && strings.HasSuffix(p, "/") {
433 continue
434 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700435 path := filepath.Clean(p)
436 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800437 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700438 continue
439 }
Colin Crosse3924e12018-08-15 20:18:53 -0700440
Colin Crossfe4bc362018-09-12 10:02:13 -0700441 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700442 if err != nil {
443 reportPathError(ctx, err)
444 continue
445 }
446
Colin Cross07e51612019-03-05 12:46:40 -0800447 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700448
Colin Cross07e51612019-03-05 12:46:40 -0800449 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700450 }
451 return ret
452}
453
454// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800455// 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 -0700456func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800457 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700458 return PathsForModuleSrc(ctx, input)
459 }
460 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
461 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800462 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800463 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700464}
465
466// Strings returns the Paths in string form
467func (p Paths) Strings() []string {
468 if p == nil {
469 return nil
470 }
471 ret := make([]string, len(p))
472 for i, path := range p {
473 ret[i] = path.String()
474 }
475 return ret
476}
477
Colin Crossb6715442017-10-24 11:13:31 -0700478// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
479// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700480func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800481 // 128 was chosen based on BenchmarkFirstUniquePaths results.
482 if len(list) > 128 {
483 return firstUniquePathsMap(list)
484 }
485 return firstUniquePathsList(list)
486}
487
488func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700489 k := 0
490outer:
491 for i := 0; i < len(list); i++ {
492 for j := 0; j < k; j++ {
493 if list[i] == list[j] {
494 continue outer
495 }
496 }
497 list[k] = list[i]
498 k++
499 }
500 return list[:k]
501}
502
Colin Cross27027c72020-02-28 15:34:17 -0800503func firstUniquePathsMap(list Paths) Paths {
504 k := 0
505 seen := make(map[Path]bool, len(list))
506 for i := 0; i < len(list); i++ {
507 if seen[list[i]] {
508 continue
509 }
510 seen[list[i]] = true
511 list[k] = list[i]
512 k++
513 }
514 return list[:k]
515}
516
Colin Crossb6715442017-10-24 11:13:31 -0700517// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
518// modifies the Paths slice contents in place, and returns a subslice of the original slice.
519func LastUniquePaths(list Paths) Paths {
520 totalSkip := 0
521 for i := len(list) - 1; i >= totalSkip; i-- {
522 skip := 0
523 for j := i - 1; j >= totalSkip; j-- {
524 if list[i] == list[j] {
525 skip++
526 } else {
527 list[j+skip] = list[j]
528 }
529 }
530 totalSkip += skip
531 }
532 return list[totalSkip:]
533}
534
Colin Crossa140bb02018-04-17 10:52:26 -0700535// ReversePaths returns a copy of a Paths in reverse order.
536func ReversePaths(list Paths) Paths {
537 if list == nil {
538 return nil
539 }
540 ret := make(Paths, len(list))
541 for i := range list {
542 ret[i] = list[len(list)-1-i]
543 }
544 return ret
545}
546
Jeff Gaston294356f2017-09-27 17:05:30 -0700547func indexPathList(s Path, list []Path) int {
548 for i, l := range list {
549 if l == s {
550 return i
551 }
552 }
553
554 return -1
555}
556
557func inPathList(p Path, list []Path) bool {
558 return indexPathList(p, list) != -1
559}
560
561func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000562 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
563}
564
565func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700566 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000567 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700568 filtered = append(filtered, l)
569 } else {
570 remainder = append(remainder, l)
571 }
572 }
573
574 return
575}
576
Colin Cross93e85952017-08-15 13:34:18 -0700577// HasExt returns true of any of the paths have extension ext, otherwise false
578func (p Paths) HasExt(ext string) bool {
579 for _, path := range p {
580 if path.Ext() == ext {
581 return true
582 }
583 }
584
585 return false
586}
587
588// FilterByExt returns the subset of the paths that have extension ext
589func (p Paths) FilterByExt(ext string) Paths {
590 ret := make(Paths, 0, len(p))
591 for _, path := range p {
592 if path.Ext() == ext {
593 ret = append(ret, path)
594 }
595 }
596 return ret
597}
598
599// FilterOutByExt returns the subset of the paths that do not have extension ext
600func (p Paths) FilterOutByExt(ext string) Paths {
601 ret := make(Paths, 0, len(p))
602 for _, path := range p {
603 if path.Ext() != ext {
604 ret = append(ret, path)
605 }
606 }
607 return ret
608}
609
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700610// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
611// (including subdirectories) are in a contiguous subslice of the list, and can be found in
612// O(log(N)) time using a binary search on the directory prefix.
613type DirectorySortedPaths Paths
614
615func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
616 ret := append(DirectorySortedPaths(nil), paths...)
617 sort.Slice(ret, func(i, j int) bool {
618 return ret[i].String() < ret[j].String()
619 })
620 return ret
621}
622
623// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
624// that are in the specified directory and its subdirectories.
625func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
626 prefix := filepath.Clean(dir) + "/"
627 start := sort.Search(len(p), func(i int) bool {
628 return prefix < p[i].String()
629 })
630
631 ret := p[start:]
632
633 end := sort.Search(len(ret), func(i int) bool {
634 return !strings.HasPrefix(ret[i].String(), prefix)
635 })
636
637 ret = ret[:end]
638
639 return Paths(ret)
640}
641
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700642// WritablePaths is a slice of WritablePaths, used for multiple outputs.
643type WritablePaths []WritablePath
644
645// Strings returns the string forms of the writable paths.
646func (p WritablePaths) Strings() []string {
647 if p == nil {
648 return nil
649 }
650 ret := make([]string, len(p))
651 for i, path := range p {
652 ret[i] = path.String()
653 }
654 return ret
655}
656
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800657// Paths returns the WritablePaths as a Paths
658func (p WritablePaths) Paths() Paths {
659 if p == nil {
660 return nil
661 }
662 ret := make(Paths, len(p))
663 for i, path := range p {
664 ret[i] = path
665 }
666 return ret
667}
668
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700669type basePath struct {
670 path string
671 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800672 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700673}
674
675func (p basePath) Ext() string {
676 return filepath.Ext(p.path)
677}
678
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700679func (p basePath) Base() string {
680 return filepath.Base(p.path)
681}
682
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800683func (p basePath) Rel() string {
684 if p.rel != "" {
685 return p.rel
686 }
687 return p.path
688}
689
Colin Cross0875c522017-11-28 17:34:01 -0800690func (p basePath) String() string {
691 return p.path
692}
693
Colin Cross0db55682017-12-05 15:36:55 -0800694func (p basePath) withRel(rel string) basePath {
695 p.path = filepath.Join(p.path, rel)
696 p.rel = rel
697 return p
698}
699
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700700// SourcePath is a Path representing a file path rooted from SrcDir
701type SourcePath struct {
702 basePath
703}
704
705var _ Path = SourcePath{}
706
Colin Cross0db55682017-12-05 15:36:55 -0800707func (p SourcePath) withRel(rel string) SourcePath {
708 p.basePath = p.basePath.withRel(rel)
709 return p
710}
711
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700712// safePathForSource is for paths that we expect are safe -- only for use by go
713// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700714func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
715 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800716 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700717 if err != nil {
718 return ret, err
719 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700720
Colin Cross7b3dcc32019-01-24 13:14:39 -0800721 // absolute path already checked by validateSafePath
722 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800723 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700724 }
725
Colin Crossfe4bc362018-09-12 10:02:13 -0700726 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700727}
728
Colin Cross192e97a2018-02-22 14:21:02 -0800729// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
730func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000731 p, err := validatePath(pathComponents...)
732 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800733 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800734 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800735 }
736
Colin Cross7b3dcc32019-01-24 13:14:39 -0800737 // absolute path already checked by validatePath
738 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800739 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000740 }
741
Colin Cross192e97a2018-02-22 14:21:02 -0800742 return ret, nil
743}
744
745// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
746// path does not exist.
747func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
748 var files []string
749
750 if gctx, ok := ctx.(PathGlobContext); ok {
751 // Use glob to produce proper dependencies, even though we only want
752 // a single file.
753 files, err = gctx.GlobWithDeps(path.String(), nil)
754 } else {
755 var deps []string
756 // We cannot add build statements in this context, so we fall back to
757 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +0000758 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800759 ctx.AddNinjaFileDeps(deps...)
760 }
761
762 if err != nil {
763 return false, fmt.Errorf("glob: %s", err.Error())
764 }
765
766 return len(files) > 0, nil
767}
768
769// PathForSource joins the provided path components and validates that the result
770// neither escapes the source dir nor is in the out dir.
771// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
772func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
773 path, err := pathForSource(ctx, pathComponents...)
774 if err != nil {
775 reportPathError(ctx, err)
776 }
777
Colin Crosse3924e12018-08-15 20:18:53 -0700778 if pathtools.IsGlob(path.String()) {
779 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
780 }
781
Colin Cross192e97a2018-02-22 14:21:02 -0800782 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
783 exists, err := existsWithDependencies(ctx, path)
784 if err != nil {
785 reportPathError(ctx, err)
786 }
787 if !exists {
788 modCtx.AddMissingDependencies([]string{path.String()})
789 }
Colin Cross988414c2020-01-11 01:11:46 +0000790 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800791 reportPathErrorf(ctx, "%s: %s", path, err.Error())
792 } else if !exists {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800793 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800794 }
795 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700796}
797
Jeff Gaston734e3802017-04-10 15:47:24 -0700798// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700799// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
800// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800801func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800802 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800803 if err != nil {
804 reportPathError(ctx, err)
805 return OptionalPath{}
806 }
Colin Crossc48c1432018-02-23 07:09:01 +0000807
Colin Crosse3924e12018-08-15 20:18:53 -0700808 if pathtools.IsGlob(path.String()) {
809 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
810 return OptionalPath{}
811 }
812
Colin Cross192e97a2018-02-22 14:21:02 -0800813 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000814 if err != nil {
815 reportPathError(ctx, err)
816 return OptionalPath{}
817 }
Colin Cross192e97a2018-02-22 14:21:02 -0800818 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000819 return OptionalPath{}
820 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700821 return OptionalPathForPath(path)
822}
823
824func (p SourcePath) String() string {
825 return filepath.Join(p.config.srcDir, p.path)
826}
827
828// Join creates a new SourcePath with paths... joined with the current path. The
829// provided paths... may not use '..' to escape from the current path.
830func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800831 path, err := validatePath(paths...)
832 if err != nil {
833 reportPathError(ctx, err)
834 }
Colin Cross0db55682017-12-05 15:36:55 -0800835 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700836}
837
Colin Cross2fafa3e2019-03-05 12:39:51 -0800838// join is like Join but does less path validation.
839func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
840 path, err := validateSafePath(paths...)
841 if err != nil {
842 reportPathError(ctx, err)
843 }
844 return p.withRel(path)
845}
846
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700847// OverlayPath returns the overlay for `path' if it exists. This assumes that the
848// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700849func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700850 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800851 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700852 relDir = srcPath.path
853 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800854 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700855 return OptionalPath{}
856 }
857 dir := filepath.Join(p.config.srcDir, p.path, relDir)
858 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700859 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800860 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800861 }
Colin Cross461b4452018-02-23 09:22:42 -0800862 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700863 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800864 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700865 return OptionalPath{}
866 }
867 if len(paths) == 0 {
868 return OptionalPath{}
869 }
Colin Cross43f08db2018-11-12 10:13:39 -0800870 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700871 return OptionalPathForPath(PathForSource(ctx, relPath))
872}
873
Colin Cross70dda7e2019-10-01 22:05:35 -0700874// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700875type OutputPath struct {
876 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -0800877 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700878}
879
Colin Cross702e0f82017-10-18 17:27:54 -0700880func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800881 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -0800882 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700883 return p
884}
885
Colin Cross3063b782018-08-15 11:19:12 -0700886func (p OutputPath) WithoutRel() OutputPath {
887 p.basePath.rel = filepath.Base(p.basePath.path)
888 return p
889}
890
Paul Duffin9b478b02019-12-10 13:41:51 +0000891func (p OutputPath) buildDir() string {
892 return p.config.buildDir
893}
894
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700895var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +0000896var _ WritablePath = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700897
Jeff Gaston734e3802017-04-10 15:47:24 -0700898// PathForOutput joins the provided paths and returns an OutputPath that is
899// validated to not escape the build dir.
900// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
901func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800902 path, err := validatePath(pathComponents...)
903 if err != nil {
904 reportPathError(ctx, err)
905 }
Colin Crossd63c9a72020-01-29 16:52:50 -0800906 fullPath := filepath.Join(ctx.Config().buildDir, path)
907 path = fullPath[len(fullPath)-len(path):]
908 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700909}
910
Colin Cross40e33732019-02-15 11:08:35 -0800911// PathsForOutput returns Paths rooted from buildDir
912func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
913 ret := make(WritablePaths, len(paths))
914 for i, path := range paths {
915 ret[i] = PathForOutput(ctx, path)
916 }
917 return ret
918}
919
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700920func (p OutputPath) writablePath() {}
921
922func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -0800923 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700924}
925
926// Join creates a new OutputPath with paths... joined with the current path. The
927// provided paths... may not use '..' to escape from the current path.
928func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800929 path, err := validatePath(paths...)
930 if err != nil {
931 reportPathError(ctx, err)
932 }
Colin Cross0db55682017-12-05 15:36:55 -0800933 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700934}
935
Colin Cross8854a5a2019-02-11 14:14:16 -0800936// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
937func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
938 if strings.Contains(ext, "/") {
939 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
940 }
941 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800942 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800943 return ret
944}
945
Colin Cross40e33732019-02-15 11:08:35 -0800946// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
947func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
948 path, err := validatePath(paths...)
949 if err != nil {
950 reportPathError(ctx, err)
951 }
952
953 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800954 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800955 return ret
956}
957
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700958// PathForIntermediates returns an OutputPath representing the top-level
959// intermediates directory.
960func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800961 path, err := validatePath(paths...)
962 if err != nil {
963 reportPathError(ctx, err)
964 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700965 return PathForOutput(ctx, ".intermediates", path)
966}
967
Colin Cross07e51612019-03-05 12:46:40 -0800968var _ genPathProvider = SourcePath{}
969var _ objPathProvider = SourcePath{}
970var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700971
Colin Cross07e51612019-03-05 12:46:40 -0800972// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700973// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800974func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
975 p, err := validatePath(pathComponents...)
976 if err != nil {
977 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800978 }
Colin Cross8a497952019-03-05 22:25:09 -0800979 paths, err := expandOneSrcPath(ctx, p, nil)
980 if err != nil {
981 if depErr, ok := err.(missingDependencyError); ok {
982 if ctx.Config().AllowMissingDependencies() {
983 ctx.AddMissingDependencies(depErr.missingDeps)
984 } else {
985 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
986 }
987 } else {
988 reportPathError(ctx, err)
989 }
990 return nil
991 } else if len(paths) == 0 {
992 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
993 return nil
994 } else if len(paths) > 1 {
995 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
996 }
997 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700998}
999
Colin Cross07e51612019-03-05 12:46:40 -08001000func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
1001 p, err := validatePath(paths...)
1002 if err != nil {
1003 reportPathError(ctx, err)
1004 }
1005
1006 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1007 if err != nil {
1008 reportPathError(ctx, err)
1009 }
1010
1011 path.basePath.rel = p
1012
1013 return path
1014}
1015
Colin Cross2fafa3e2019-03-05 12:39:51 -08001016// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1017// will return the path relative to subDir in the module's source directory. If any input paths are not located
1018// inside subDir then a path error will be reported.
1019func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
1020 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001021 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001022 for i, path := range paths {
1023 rel := Rel(ctx, subDirFullPath.String(), path.String())
1024 paths[i] = subDirFullPath.join(ctx, rel)
1025 }
1026 return paths
1027}
1028
1029// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1030// module's source directory. If the input path is not located inside subDir then a path error will be reported.
1031func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001032 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001033 rel := Rel(ctx, subDirFullPath.String(), path.String())
1034 return subDirFullPath.Join(ctx, rel)
1035}
1036
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001037// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1038// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -07001039func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001040 if p == nil {
1041 return OptionalPath{}
1042 }
1043 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1044}
1045
Colin Cross07e51612019-03-05 12:46:40 -08001046func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001047 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001048}
1049
Colin Cross07e51612019-03-05 12:46:40 -08001050func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001051 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001052}
1053
Colin Cross07e51612019-03-05 12:46:40 -08001054func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001055 // TODO: Use full directory if the new ctx is not the current ctx?
1056 return PathForModuleRes(ctx, p.path, name)
1057}
1058
1059// ModuleOutPath is a Path representing a module's output directory.
1060type ModuleOutPath struct {
1061 OutputPath
1062}
1063
1064var _ Path = ModuleOutPath{}
1065
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001066func (p ModuleOutPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
1067 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1068}
1069
Colin Cross702e0f82017-10-18 17:27:54 -07001070func pathForModule(ctx ModuleContext) OutputPath {
1071 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1072}
1073
Logan Chien7eefdc42018-07-11 18:10:41 +08001074// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1075// reference abi dump for the given module. This is not guaranteed to be valid.
1076func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001077 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001078
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001079 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001080 if len(arches) == 0 {
1081 panic("device build with no primary arch")
1082 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001083 currentArch := ctx.Arch()
1084 archNameAndVariant := currentArch.ArchType.String()
1085 if currentArch.ArchVariant != "" {
1086 archNameAndVariant += "_" + currentArch.ArchVariant
1087 }
Logan Chien5237bed2018-07-11 17:15:57 +08001088
1089 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001090 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001091 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001092 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001093 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001094 } else {
1095 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001096 }
Logan Chien5237bed2018-07-11 17:15:57 +08001097
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001098 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001099
1100 var ext string
1101 if isGzip {
1102 ext = ".lsdump.gz"
1103 } else {
1104 ext = ".lsdump"
1105 }
1106
1107 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1108 version, binderBitness, archNameAndVariant, "source-based",
1109 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001110}
1111
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001112// PathForModuleOut returns a Path representing the paths... under the module's
1113// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001114func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001115 p, err := validatePath(paths...)
1116 if err != nil {
1117 reportPathError(ctx, err)
1118 }
Colin Cross702e0f82017-10-18 17:27:54 -07001119 return ModuleOutPath{
1120 OutputPath: pathForModule(ctx).withRel(p),
1121 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001122}
1123
1124// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1125// directory. Mainly used for generated sources.
1126type ModuleGenPath struct {
1127 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001128}
1129
1130var _ Path = ModuleGenPath{}
1131var _ genPathProvider = ModuleGenPath{}
1132var _ objPathProvider = ModuleGenPath{}
1133
1134// PathForModuleGen returns a Path representing the paths... under the module's
1135// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001136func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001137 p, err := validatePath(paths...)
1138 if err != nil {
1139 reportPathError(ctx, err)
1140 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001141 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001142 ModuleOutPath: ModuleOutPath{
1143 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1144 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001145 }
1146}
1147
Dan Willemsen21ec4902016-11-02 20:43:13 -07001148func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001149 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001150 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001151}
1152
Colin Cross635c3b02016-05-18 15:37:25 -07001153func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001154 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1155}
1156
1157// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1158// directory. Used for compiled objects.
1159type ModuleObjPath struct {
1160 ModuleOutPath
1161}
1162
1163var _ Path = ModuleObjPath{}
1164
1165// PathForModuleObj returns a Path representing the paths... under the module's
1166// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001167func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001168 p, err := validatePath(pathComponents...)
1169 if err != nil {
1170 reportPathError(ctx, err)
1171 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001172 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1173}
1174
1175// ModuleResPath is a a Path representing the 'res' directory in a module's
1176// output directory.
1177type ModuleResPath struct {
1178 ModuleOutPath
1179}
1180
1181var _ Path = ModuleResPath{}
1182
1183// PathForModuleRes returns a Path representing the paths... under the module's
1184// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001185func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001186 p, err := validatePath(pathComponents...)
1187 if err != nil {
1188 reportPathError(ctx, err)
1189 }
1190
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001191 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1192}
1193
Colin Cross70dda7e2019-10-01 22:05:35 -07001194// InstallPath is a Path representing a installed file path rooted from the build directory
1195type InstallPath struct {
1196 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001197
1198 baseDir string // "../" for Make paths to convert "out/soong" to "out", "" for Soong paths
Colin Cross70dda7e2019-10-01 22:05:35 -07001199}
1200
Paul Duffin9b478b02019-12-10 13:41:51 +00001201func (p InstallPath) buildDir() string {
1202 return p.config.buildDir
1203}
1204
1205var _ Path = InstallPath{}
1206var _ WritablePath = InstallPath{}
1207
Colin Cross70dda7e2019-10-01 22:05:35 -07001208func (p InstallPath) writablePath() {}
1209
1210func (p InstallPath) String() string {
Colin Crossff6c33d2019-10-02 16:01:35 -07001211 return filepath.Join(p.config.buildDir, p.baseDir, p.path)
Colin Cross70dda7e2019-10-01 22:05:35 -07001212}
1213
1214// Join creates a new InstallPath with paths... joined with the current path. The
1215// provided paths... may not use '..' to escape from the current path.
1216func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1217 path, err := validatePath(paths...)
1218 if err != nil {
1219 reportPathError(ctx, err)
1220 }
1221 return p.withRel(path)
1222}
1223
1224func (p InstallPath) withRel(rel string) InstallPath {
1225 p.basePath = p.basePath.withRel(rel)
1226 return p
1227}
1228
Colin Crossff6c33d2019-10-02 16:01:35 -07001229// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1230// i.e. out/ instead of out/soong/.
1231func (p InstallPath) ToMakePath() InstallPath {
1232 p.baseDir = "../"
1233 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001234}
1235
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001236// PathForModuleInstall returns a Path representing the install path for the
1237// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001238func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001239 os := ctx.Os()
1240 if forceOS := ctx.InstallForceOS(); forceOS != nil {
1241 os = *forceOS
1242 }
1243 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001244
1245 ret := pathForInstall(ctx, os, partition, ctx.Debug(), pathComponents...)
1246
1247 if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
1248 ret = ret.ToMakePath()
1249 }
1250
1251 return ret
1252}
1253
1254func pathForInstall(ctx PathContext, os OsType, partition string, debug bool,
1255 pathComponents ...string) InstallPath {
1256
1257 var outPaths []string
1258
Colin Cross6e359402020-02-10 15:29:54 -08001259 if os.Class == Device {
Colin Cross6510f912017-11-29 00:27:14 -08001260 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001261 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001262 switch os {
Dan Willemsen866b5632017-09-22 12:28:24 -07001263 case Linux:
Colin Cross6e359402020-02-10 15:29:54 -08001264 outPaths = []string{"host", "linux-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001265 case LinuxBionic:
1266 // TODO: should this be a separate top level, or shared with linux-x86?
Colin Cross6e359402020-02-10 15:29:54 -08001267 outPaths = []string{"host", "linux_bionic-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001268 default:
Colin Cross6e359402020-02-10 15:29:54 -08001269 outPaths = []string{"host", os.String() + "-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001270 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001271 }
Colin Cross609c49a2020-02-13 13:20:11 -08001272 if debug {
Dan Willemsen782a2d12015-12-21 14:55:28 -08001273 outPaths = append([]string{"debug"}, outPaths...)
1274 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001275 outPaths = append(outPaths, pathComponents...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001276
1277 path, err := validatePath(outPaths...)
1278 if err != nil {
1279 reportPathError(ctx, err)
1280 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001281
1282 ret := InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Crossff6c33d2019-10-02 16:01:35 -07001283
1284 return ret
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001285}
1286
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001287func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
1288 paths = append([]string{prefix}, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001289 path, err := validatePath(paths...)
1290 if err != nil {
1291 reportPathError(ctx, err)
1292 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001293 return InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Cross70dda7e2019-10-01 22:05:35 -07001294}
1295
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001296func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1297 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1298}
1299
1300func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1301 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1302}
1303
Colin Cross70dda7e2019-10-01 22:05:35 -07001304func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001305 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1306
1307 return "/" + rel
1308}
1309
Colin Cross6e359402020-02-10 15:29:54 -08001310func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001311 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001312 if ctx.InstallInTestcases() {
1313 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001314 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001315 } else if os.Class == Device {
1316 if ctx.InstallInData() {
1317 partition = "data"
1318 } else if ctx.InstallInRamdisk() {
1319 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1320 partition = "recovery/root/first_stage_ramdisk"
1321 } else {
1322 partition = "ramdisk"
1323 }
1324 if !ctx.InstallInRoot() {
1325 partition += "/system"
1326 }
1327 } else if ctx.InstallInRecovery() {
1328 if ctx.InstallInRoot() {
1329 partition = "recovery/root"
1330 } else {
1331 // the layout of recovery partion is the same as that of system partition
1332 partition = "recovery/root/system"
1333 }
1334 } else if ctx.SocSpecific() {
1335 partition = ctx.DeviceConfig().VendorPath()
1336 } else if ctx.DeviceSpecific() {
1337 partition = ctx.DeviceConfig().OdmPath()
1338 } else if ctx.ProductSpecific() {
1339 partition = ctx.DeviceConfig().ProductPath()
1340 } else if ctx.SystemExtSpecific() {
1341 partition = ctx.DeviceConfig().SystemExtPath()
1342 } else if ctx.InstallInRoot() {
1343 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001344 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001345 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001346 }
Colin Cross6e359402020-02-10 15:29:54 -08001347 if ctx.InstallInSanitizerDir() {
1348 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001349 }
Colin Cross43f08db2018-11-12 10:13:39 -08001350 }
1351 return partition
1352}
1353
Colin Cross609c49a2020-02-13 13:20:11 -08001354type InstallPaths []InstallPath
1355
1356// Paths returns the InstallPaths as a Paths
1357func (p InstallPaths) Paths() Paths {
1358 if p == nil {
1359 return nil
1360 }
1361 ret := make(Paths, len(p))
1362 for i, path := range p {
1363 ret[i] = path
1364 }
1365 return ret
1366}
1367
1368// Strings returns the string forms of the install paths.
1369func (p InstallPaths) Strings() []string {
1370 if p == nil {
1371 return nil
1372 }
1373 ret := make([]string, len(p))
1374 for i, path := range p {
1375 ret[i] = path.String()
1376 }
1377 return ret
1378}
1379
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001380// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001381// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001382func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001383 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001384 path := filepath.Clean(path)
1385 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001386 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001387 }
1388 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001389 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1390 // variables. '..' may remove the entire ninja variable, even if it
1391 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001392 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001393}
1394
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001395// validatePath validates that a path does not include ninja variables, and that
1396// each path component does not attempt to leave its component. Returns a joined
1397// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001398func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001399 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001400 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001401 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001402 }
1403 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001404 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001405}
Colin Cross5b529592017-05-09 13:34:34 -07001406
Colin Cross0875c522017-11-28 17:34:01 -08001407func PathForPhony(ctx PathContext, phony string) WritablePath {
1408 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001409 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001410 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001411 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001412}
1413
Colin Cross74e3fe42017-12-11 15:51:44 -08001414type PhonyPath struct {
1415 basePath
1416}
1417
1418func (p PhonyPath) writablePath() {}
1419
Paul Duffin9b478b02019-12-10 13:41:51 +00001420func (p PhonyPath) buildDir() string {
1421 return p.config.buildDir
1422}
1423
Colin Cross74e3fe42017-12-11 15:51:44 -08001424var _ Path = PhonyPath{}
1425var _ WritablePath = PhonyPath{}
1426
Colin Cross5b529592017-05-09 13:34:34 -07001427type testPath struct {
1428 basePath
1429}
1430
1431func (p testPath) String() string {
1432 return p.path
1433}
1434
Colin Cross40e33732019-02-15 11:08:35 -08001435// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1436// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001437func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001438 p, err := validateSafePath(paths...)
1439 if err != nil {
1440 panic(err)
1441 }
Colin Cross5b529592017-05-09 13:34:34 -07001442 return testPath{basePath{path: p, rel: p}}
1443}
1444
Colin Cross40e33732019-02-15 11:08:35 -08001445// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1446func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001447 p := make(Paths, len(strs))
1448 for i, s := range strs {
1449 p[i] = PathForTesting(s)
1450 }
1451
1452 return p
1453}
Colin Cross43f08db2018-11-12 10:13:39 -08001454
Colin Cross40e33732019-02-15 11:08:35 -08001455type testPathContext struct {
1456 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001457}
1458
Colin Cross40e33732019-02-15 11:08:35 -08001459func (x *testPathContext) Config() Config { return x.config }
1460func (x *testPathContext) AddNinjaFileDeps(...string) {}
1461
1462// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1463// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001464func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001465 return &testPathContext{
1466 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001467 }
1468}
1469
Colin Cross43f08db2018-11-12 10:13:39 -08001470// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1471// targetPath is not inside basePath.
1472func Rel(ctx PathContext, basePath string, targetPath string) string {
1473 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1474 if !isRel {
1475 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1476 return ""
1477 }
1478 return rel
1479}
1480
1481// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1482// targetPath is not inside basePath.
1483func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001484 rel, isRel, err := maybeRelErr(basePath, targetPath)
1485 if err != nil {
1486 reportPathError(ctx, err)
1487 }
1488 return rel, isRel
1489}
1490
1491func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001492 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1493 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001494 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001495 }
1496 rel, err := filepath.Rel(basePath, targetPath)
1497 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001498 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001499 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001500 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001501 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001502 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001503}
Colin Cross988414c2020-01-11 01:11:46 +00001504
1505// Writes a file to the output directory. Attempting to write directly to the output directory
1506// will fail due to the sandbox of the soong_build process.
1507func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1508 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1509}
1510
1511func absolutePath(path string) string {
1512 if filepath.IsAbs(path) {
1513 return path
1514 }
1515 return filepath.Join(absSrcDir, path)
1516}