blob: bed6f3f582ba74890b48029d6c43822c7f3a1347 [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())
Colin Cross5e6a7972020-06-07 16:56:32 -0700408 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Colin Cross8a497952019-03-05 22:25:09 -0800409 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
Jiyong Park33c77362020-05-29 22:00:16 +0900488// SortedUniquePaths returns what its name says
489func SortedUniquePaths(list Paths) Paths {
490 unique := FirstUniquePaths(list)
491 sort.Slice(unique, func(i, j int) bool {
492 return unique[i].String() < unique[j].String()
493 })
494 return unique
495}
496
Colin Cross27027c72020-02-28 15:34:17 -0800497func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700498 k := 0
499outer:
500 for i := 0; i < len(list); i++ {
501 for j := 0; j < k; j++ {
502 if list[i] == list[j] {
503 continue outer
504 }
505 }
506 list[k] = list[i]
507 k++
508 }
509 return list[:k]
510}
511
Colin Cross27027c72020-02-28 15:34:17 -0800512func firstUniquePathsMap(list Paths) Paths {
513 k := 0
514 seen := make(map[Path]bool, len(list))
515 for i := 0; i < len(list); i++ {
516 if seen[list[i]] {
517 continue
518 }
519 seen[list[i]] = true
520 list[k] = list[i]
521 k++
522 }
523 return list[:k]
524}
525
Colin Crossb6715442017-10-24 11:13:31 -0700526// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
527// modifies the Paths slice contents in place, and returns a subslice of the original slice.
528func LastUniquePaths(list Paths) Paths {
529 totalSkip := 0
530 for i := len(list) - 1; i >= totalSkip; i-- {
531 skip := 0
532 for j := i - 1; j >= totalSkip; j-- {
533 if list[i] == list[j] {
534 skip++
535 } else {
536 list[j+skip] = list[j]
537 }
538 }
539 totalSkip += skip
540 }
541 return list[totalSkip:]
542}
543
Colin Crossa140bb02018-04-17 10:52:26 -0700544// ReversePaths returns a copy of a Paths in reverse order.
545func ReversePaths(list Paths) Paths {
546 if list == nil {
547 return nil
548 }
549 ret := make(Paths, len(list))
550 for i := range list {
551 ret[i] = list[len(list)-1-i]
552 }
553 return ret
554}
555
Jeff Gaston294356f2017-09-27 17:05:30 -0700556func indexPathList(s Path, list []Path) int {
557 for i, l := range list {
558 if l == s {
559 return i
560 }
561 }
562
563 return -1
564}
565
566func inPathList(p Path, list []Path) bool {
567 return indexPathList(p, list) != -1
568}
569
570func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000571 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
572}
573
574func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700575 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000576 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700577 filtered = append(filtered, l)
578 } else {
579 remainder = append(remainder, l)
580 }
581 }
582
583 return
584}
585
Colin Cross93e85952017-08-15 13:34:18 -0700586// HasExt returns true of any of the paths have extension ext, otherwise false
587func (p Paths) HasExt(ext string) bool {
588 for _, path := range p {
589 if path.Ext() == ext {
590 return true
591 }
592 }
593
594 return false
595}
596
597// FilterByExt returns the subset of the paths that have extension ext
598func (p Paths) FilterByExt(ext string) Paths {
599 ret := make(Paths, 0, len(p))
600 for _, path := range p {
601 if path.Ext() == ext {
602 ret = append(ret, path)
603 }
604 }
605 return ret
606}
607
608// FilterOutByExt returns the subset of the paths that do not have extension ext
609func (p Paths) FilterOutByExt(ext string) Paths {
610 ret := make(Paths, 0, len(p))
611 for _, path := range p {
612 if path.Ext() != ext {
613 ret = append(ret, path)
614 }
615 }
616 return ret
617}
618
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700619// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
620// (including subdirectories) are in a contiguous subslice of the list, and can be found in
621// O(log(N)) time using a binary search on the directory prefix.
622type DirectorySortedPaths Paths
623
624func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
625 ret := append(DirectorySortedPaths(nil), paths...)
626 sort.Slice(ret, func(i, j int) bool {
627 return ret[i].String() < ret[j].String()
628 })
629 return ret
630}
631
632// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
633// that are in the specified directory and its subdirectories.
634func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
635 prefix := filepath.Clean(dir) + "/"
636 start := sort.Search(len(p), func(i int) bool {
637 return prefix < p[i].String()
638 })
639
640 ret := p[start:]
641
642 end := sort.Search(len(ret), func(i int) bool {
643 return !strings.HasPrefix(ret[i].String(), prefix)
644 })
645
646 ret = ret[:end]
647
648 return Paths(ret)
649}
650
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700651// WritablePaths is a slice of WritablePaths, used for multiple outputs.
652type WritablePaths []WritablePath
653
654// Strings returns the string forms of the writable paths.
655func (p WritablePaths) Strings() []string {
656 if p == nil {
657 return nil
658 }
659 ret := make([]string, len(p))
660 for i, path := range p {
661 ret[i] = path.String()
662 }
663 return ret
664}
665
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800666// Paths returns the WritablePaths as a Paths
667func (p WritablePaths) Paths() Paths {
668 if p == nil {
669 return nil
670 }
671 ret := make(Paths, len(p))
672 for i, path := range p {
673 ret[i] = path
674 }
675 return ret
676}
677
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700678type basePath struct {
679 path string
680 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800681 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700682}
683
684func (p basePath) Ext() string {
685 return filepath.Ext(p.path)
686}
687
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700688func (p basePath) Base() string {
689 return filepath.Base(p.path)
690}
691
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800692func (p basePath) Rel() string {
693 if p.rel != "" {
694 return p.rel
695 }
696 return p.path
697}
698
Colin Cross0875c522017-11-28 17:34:01 -0800699func (p basePath) String() string {
700 return p.path
701}
702
Colin Cross0db55682017-12-05 15:36:55 -0800703func (p basePath) withRel(rel string) basePath {
704 p.path = filepath.Join(p.path, rel)
705 p.rel = rel
706 return p
707}
708
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700709// SourcePath is a Path representing a file path rooted from SrcDir
710type SourcePath struct {
711 basePath
712}
713
714var _ Path = SourcePath{}
715
Colin Cross0db55682017-12-05 15:36:55 -0800716func (p SourcePath) withRel(rel string) SourcePath {
717 p.basePath = p.basePath.withRel(rel)
718 return p
719}
720
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700721// safePathForSource is for paths that we expect are safe -- only for use by go
722// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700723func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
724 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800725 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700726 if err != nil {
727 return ret, err
728 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700729
Colin Cross7b3dcc32019-01-24 13:14:39 -0800730 // absolute path already checked by validateSafePath
731 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800732 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700733 }
734
Colin Crossfe4bc362018-09-12 10:02:13 -0700735 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700736}
737
Colin Cross192e97a2018-02-22 14:21:02 -0800738// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
739func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000740 p, err := validatePath(pathComponents...)
741 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800742 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800743 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800744 }
745
Colin Cross7b3dcc32019-01-24 13:14:39 -0800746 // absolute path already checked by validatePath
747 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800748 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000749 }
750
Colin Cross192e97a2018-02-22 14:21:02 -0800751 return ret, nil
752}
753
754// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
755// path does not exist.
756func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
757 var files []string
758
759 if gctx, ok := ctx.(PathGlobContext); ok {
760 // Use glob to produce proper dependencies, even though we only want
761 // a single file.
762 files, err = gctx.GlobWithDeps(path.String(), nil)
763 } else {
764 var deps []string
765 // We cannot add build statements in this context, so we fall back to
766 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +0000767 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800768 ctx.AddNinjaFileDeps(deps...)
769 }
770
771 if err != nil {
772 return false, fmt.Errorf("glob: %s", err.Error())
773 }
774
775 return len(files) > 0, nil
776}
777
778// PathForSource joins the provided path components and validates that the result
779// neither escapes the source dir nor is in the out dir.
780// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
781func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
782 path, err := pathForSource(ctx, pathComponents...)
783 if err != nil {
784 reportPathError(ctx, err)
785 }
786
Colin Crosse3924e12018-08-15 20:18:53 -0700787 if pathtools.IsGlob(path.String()) {
788 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
789 }
790
Colin Cross192e97a2018-02-22 14:21:02 -0800791 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
792 exists, err := existsWithDependencies(ctx, path)
793 if err != nil {
794 reportPathError(ctx, err)
795 }
796 if !exists {
797 modCtx.AddMissingDependencies([]string{path.String()})
798 }
Colin Cross988414c2020-01-11 01:11:46 +0000799 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800800 reportPathErrorf(ctx, "%s: %s", path, err.Error())
Colin Cross5e6a7972020-06-07 16:56:32 -0700801 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800802 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800803 }
804 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700805}
806
Jeff Gaston734e3802017-04-10 15:47:24 -0700807// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700808// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
809// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800810func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800811 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800812 if err != nil {
813 reportPathError(ctx, err)
814 return OptionalPath{}
815 }
Colin Crossc48c1432018-02-23 07:09:01 +0000816
Colin Crosse3924e12018-08-15 20:18:53 -0700817 if pathtools.IsGlob(path.String()) {
818 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
819 return OptionalPath{}
820 }
821
Colin Cross192e97a2018-02-22 14:21:02 -0800822 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000823 if err != nil {
824 reportPathError(ctx, err)
825 return OptionalPath{}
826 }
Colin Cross192e97a2018-02-22 14:21:02 -0800827 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000828 return OptionalPath{}
829 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700830 return OptionalPathForPath(path)
831}
832
833func (p SourcePath) String() string {
834 return filepath.Join(p.config.srcDir, p.path)
835}
836
837// Join creates a new SourcePath with paths... joined with the current path. The
838// provided paths... may not use '..' to escape from the current path.
839func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800840 path, err := validatePath(paths...)
841 if err != nil {
842 reportPathError(ctx, err)
843 }
Colin Cross0db55682017-12-05 15:36:55 -0800844 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700845}
846
Colin Cross2fafa3e2019-03-05 12:39:51 -0800847// join is like Join but does less path validation.
848func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
849 path, err := validateSafePath(paths...)
850 if err != nil {
851 reportPathError(ctx, err)
852 }
853 return p.withRel(path)
854}
855
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700856// OverlayPath returns the overlay for `path' if it exists. This assumes that the
857// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700858func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700859 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800860 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700861 relDir = srcPath.path
862 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800863 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700864 return OptionalPath{}
865 }
866 dir := filepath.Join(p.config.srcDir, p.path, relDir)
867 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700868 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800869 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800870 }
Colin Cross461b4452018-02-23 09:22:42 -0800871 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700872 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800873 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700874 return OptionalPath{}
875 }
876 if len(paths) == 0 {
877 return OptionalPath{}
878 }
Colin Cross43f08db2018-11-12 10:13:39 -0800879 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700880 return OptionalPathForPath(PathForSource(ctx, relPath))
881}
882
Colin Cross70dda7e2019-10-01 22:05:35 -0700883// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700884type OutputPath struct {
885 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -0800886 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700887}
888
Colin Cross702e0f82017-10-18 17:27:54 -0700889func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800890 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -0800891 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700892 return p
893}
894
Colin Cross3063b782018-08-15 11:19:12 -0700895func (p OutputPath) WithoutRel() OutputPath {
896 p.basePath.rel = filepath.Base(p.basePath.path)
897 return p
898}
899
Paul Duffin9b478b02019-12-10 13:41:51 +0000900func (p OutputPath) buildDir() string {
901 return p.config.buildDir
902}
903
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700904var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +0000905var _ WritablePath = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700906
Jeff Gaston734e3802017-04-10 15:47:24 -0700907// PathForOutput joins the provided paths and returns an OutputPath that is
908// validated to not escape the build dir.
909// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
910func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800911 path, err := validatePath(pathComponents...)
912 if err != nil {
913 reportPathError(ctx, err)
914 }
Colin Crossd63c9a72020-01-29 16:52:50 -0800915 fullPath := filepath.Join(ctx.Config().buildDir, path)
916 path = fullPath[len(fullPath)-len(path):]
917 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700918}
919
Colin Cross40e33732019-02-15 11:08:35 -0800920// PathsForOutput returns Paths rooted from buildDir
921func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
922 ret := make(WritablePaths, len(paths))
923 for i, path := range paths {
924 ret[i] = PathForOutput(ctx, path)
925 }
926 return ret
927}
928
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700929func (p OutputPath) writablePath() {}
930
931func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -0800932 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700933}
934
935// Join creates a new OutputPath with paths... joined with the current path. The
936// provided paths... may not use '..' to escape from the current path.
937func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800938 path, err := validatePath(paths...)
939 if err != nil {
940 reportPathError(ctx, err)
941 }
Colin Cross0db55682017-12-05 15:36:55 -0800942 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700943}
944
Colin Cross8854a5a2019-02-11 14:14:16 -0800945// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
946func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
947 if strings.Contains(ext, "/") {
948 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
949 }
950 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800951 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800952 return ret
953}
954
Colin Cross40e33732019-02-15 11:08:35 -0800955// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
956func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
957 path, err := validatePath(paths...)
958 if err != nil {
959 reportPathError(ctx, err)
960 }
961
962 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800963 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800964 return ret
965}
966
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700967// PathForIntermediates returns an OutputPath representing the top-level
968// intermediates directory.
969func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800970 path, err := validatePath(paths...)
971 if err != nil {
972 reportPathError(ctx, err)
973 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700974 return PathForOutput(ctx, ".intermediates", path)
975}
976
Colin Cross07e51612019-03-05 12:46:40 -0800977var _ genPathProvider = SourcePath{}
978var _ objPathProvider = SourcePath{}
979var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700980
Colin Cross07e51612019-03-05 12:46:40 -0800981// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700982// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800983func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
984 p, err := validatePath(pathComponents...)
985 if err != nil {
986 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800987 }
Colin Cross8a497952019-03-05 22:25:09 -0800988 paths, err := expandOneSrcPath(ctx, p, nil)
989 if err != nil {
990 if depErr, ok := err.(missingDependencyError); ok {
991 if ctx.Config().AllowMissingDependencies() {
992 ctx.AddMissingDependencies(depErr.missingDeps)
993 } else {
994 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
995 }
996 } else {
997 reportPathError(ctx, err)
998 }
999 return nil
1000 } else if len(paths) == 0 {
1001 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
1002 return nil
1003 } else if len(paths) > 1 {
1004 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
1005 }
1006 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001007}
1008
Colin Cross07e51612019-03-05 12:46:40 -08001009func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
1010 p, err := validatePath(paths...)
1011 if err != nil {
1012 reportPathError(ctx, err)
1013 }
1014
1015 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1016 if err != nil {
1017 reportPathError(ctx, err)
1018 }
1019
1020 path.basePath.rel = p
1021
1022 return path
1023}
1024
Colin Cross2fafa3e2019-03-05 12:39:51 -08001025// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1026// will return the path relative to subDir in the module's source directory. If any input paths are not located
1027// inside subDir then a path error will be reported.
1028func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
1029 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001030 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001031 for i, path := range paths {
1032 rel := Rel(ctx, subDirFullPath.String(), path.String())
1033 paths[i] = subDirFullPath.join(ctx, rel)
1034 }
1035 return paths
1036}
1037
1038// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1039// module's source directory. If the input path is not located inside subDir then a path error will be reported.
1040func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001041 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001042 rel := Rel(ctx, subDirFullPath.String(), path.String())
1043 return subDirFullPath.Join(ctx, rel)
1044}
1045
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001046// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1047// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -07001048func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001049 if p == nil {
1050 return OptionalPath{}
1051 }
1052 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1053}
1054
Colin Cross07e51612019-03-05 12:46:40 -08001055func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001056 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001057}
1058
Colin Cross07e51612019-03-05 12:46:40 -08001059func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001060 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001061}
1062
Colin Cross07e51612019-03-05 12:46:40 -08001063func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001064 // TODO: Use full directory if the new ctx is not the current ctx?
1065 return PathForModuleRes(ctx, p.path, name)
1066}
1067
1068// ModuleOutPath is a Path representing a module's output directory.
1069type ModuleOutPath struct {
1070 OutputPath
1071}
1072
1073var _ Path = ModuleOutPath{}
1074
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001075func (p ModuleOutPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
1076 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1077}
1078
Colin Cross702e0f82017-10-18 17:27:54 -07001079func pathForModule(ctx ModuleContext) OutputPath {
1080 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1081}
1082
Logan Chien7eefdc42018-07-11 18:10:41 +08001083// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1084// reference abi dump for the given module. This is not guaranteed to be valid.
1085func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001086 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001087
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001088 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001089 if len(arches) == 0 {
1090 panic("device build with no primary arch")
1091 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001092 currentArch := ctx.Arch()
1093 archNameAndVariant := currentArch.ArchType.String()
1094 if currentArch.ArchVariant != "" {
1095 archNameAndVariant += "_" + currentArch.ArchVariant
1096 }
Logan Chien5237bed2018-07-11 17:15:57 +08001097
1098 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001099 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001100 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001101 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001102 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001103 } else {
1104 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001105 }
Logan Chien5237bed2018-07-11 17:15:57 +08001106
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001107 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001108
1109 var ext string
1110 if isGzip {
1111 ext = ".lsdump.gz"
1112 } else {
1113 ext = ".lsdump"
1114 }
1115
1116 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1117 version, binderBitness, archNameAndVariant, "source-based",
1118 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001119}
1120
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001121// PathForModuleOut returns a Path representing the paths... under the module's
1122// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001123func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001124 p, err := validatePath(paths...)
1125 if err != nil {
1126 reportPathError(ctx, err)
1127 }
Colin Cross702e0f82017-10-18 17:27:54 -07001128 return ModuleOutPath{
1129 OutputPath: pathForModule(ctx).withRel(p),
1130 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001131}
1132
1133// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1134// directory. Mainly used for generated sources.
1135type ModuleGenPath struct {
1136 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001137}
1138
1139var _ Path = ModuleGenPath{}
1140var _ genPathProvider = ModuleGenPath{}
1141var _ objPathProvider = ModuleGenPath{}
1142
1143// PathForModuleGen returns a Path representing the paths... under the module's
1144// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001145func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001146 p, err := validatePath(paths...)
1147 if err != nil {
1148 reportPathError(ctx, err)
1149 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001150 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001151 ModuleOutPath: ModuleOutPath{
1152 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1153 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001154 }
1155}
1156
Dan Willemsen21ec4902016-11-02 20:43:13 -07001157func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001158 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001159 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001160}
1161
Colin Cross635c3b02016-05-18 15:37:25 -07001162func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001163 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1164}
1165
1166// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1167// directory. Used for compiled objects.
1168type ModuleObjPath struct {
1169 ModuleOutPath
1170}
1171
1172var _ Path = ModuleObjPath{}
1173
1174// PathForModuleObj returns a Path representing the paths... under the module's
1175// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001176func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001177 p, err := validatePath(pathComponents...)
1178 if err != nil {
1179 reportPathError(ctx, err)
1180 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001181 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1182}
1183
1184// ModuleResPath is a a Path representing the 'res' directory in a module's
1185// output directory.
1186type ModuleResPath struct {
1187 ModuleOutPath
1188}
1189
1190var _ Path = ModuleResPath{}
1191
1192// PathForModuleRes returns a Path representing the paths... under the module's
1193// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001194func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001195 p, err := validatePath(pathComponents...)
1196 if err != nil {
1197 reportPathError(ctx, err)
1198 }
1199
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001200 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1201}
1202
Colin Cross70dda7e2019-10-01 22:05:35 -07001203// InstallPath is a Path representing a installed file path rooted from the build directory
1204type InstallPath struct {
1205 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001206
1207 baseDir string // "../" for Make paths to convert "out/soong" to "out", "" for Soong paths
Colin Cross70dda7e2019-10-01 22:05:35 -07001208}
1209
Paul Duffin9b478b02019-12-10 13:41:51 +00001210func (p InstallPath) buildDir() string {
1211 return p.config.buildDir
1212}
1213
1214var _ Path = InstallPath{}
1215var _ WritablePath = InstallPath{}
1216
Colin Cross70dda7e2019-10-01 22:05:35 -07001217func (p InstallPath) writablePath() {}
1218
1219func (p InstallPath) String() string {
Colin Crossff6c33d2019-10-02 16:01:35 -07001220 return filepath.Join(p.config.buildDir, p.baseDir, p.path)
Colin Cross70dda7e2019-10-01 22:05:35 -07001221}
1222
1223// Join creates a new InstallPath with paths... joined with the current path. The
1224// provided paths... may not use '..' to escape from the current path.
1225func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1226 path, err := validatePath(paths...)
1227 if err != nil {
1228 reportPathError(ctx, err)
1229 }
1230 return p.withRel(path)
1231}
1232
1233func (p InstallPath) withRel(rel string) InstallPath {
1234 p.basePath = p.basePath.withRel(rel)
1235 return p
1236}
1237
Colin Crossff6c33d2019-10-02 16:01:35 -07001238// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1239// i.e. out/ instead of out/soong/.
1240func (p InstallPath) ToMakePath() InstallPath {
1241 p.baseDir = "../"
1242 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001243}
1244
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001245// PathForModuleInstall returns a Path representing the install path for the
1246// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001247func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001248 os := ctx.Os()
1249 if forceOS := ctx.InstallForceOS(); forceOS != nil {
1250 os = *forceOS
1251 }
1252 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001253
1254 ret := pathForInstall(ctx, os, partition, ctx.Debug(), pathComponents...)
1255
1256 if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
1257 ret = ret.ToMakePath()
1258 }
1259
1260 return ret
1261}
1262
1263func pathForInstall(ctx PathContext, os OsType, partition string, debug bool,
1264 pathComponents ...string) InstallPath {
1265
1266 var outPaths []string
1267
Colin Cross6e359402020-02-10 15:29:54 -08001268 if os.Class == Device {
Colin Cross6510f912017-11-29 00:27:14 -08001269 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001270 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001271 switch os {
Dan Willemsen866b5632017-09-22 12:28:24 -07001272 case Linux:
Colin Cross6e359402020-02-10 15:29:54 -08001273 outPaths = []string{"host", "linux-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001274 case LinuxBionic:
1275 // TODO: should this be a separate top level, or shared with linux-x86?
Colin Cross6e359402020-02-10 15:29:54 -08001276 outPaths = []string{"host", "linux_bionic-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001277 default:
Colin Cross6e359402020-02-10 15:29:54 -08001278 outPaths = []string{"host", os.String() + "-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001279 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001280 }
Colin Cross609c49a2020-02-13 13:20:11 -08001281 if debug {
Dan Willemsen782a2d12015-12-21 14:55:28 -08001282 outPaths = append([]string{"debug"}, outPaths...)
1283 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001284 outPaths = append(outPaths, pathComponents...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001285
1286 path, err := validatePath(outPaths...)
1287 if err != nil {
1288 reportPathError(ctx, err)
1289 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001290
1291 ret := InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Crossff6c33d2019-10-02 16:01:35 -07001292
1293 return ret
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001294}
1295
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001296func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
1297 paths = append([]string{prefix}, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001298 path, err := validatePath(paths...)
1299 if err != nil {
1300 reportPathError(ctx, err)
1301 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001302 return InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Cross70dda7e2019-10-01 22:05:35 -07001303}
1304
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001305func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1306 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1307}
1308
1309func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1310 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1311}
1312
Colin Cross70dda7e2019-10-01 22:05:35 -07001313func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001314 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1315
1316 return "/" + rel
1317}
1318
Colin Cross6e359402020-02-10 15:29:54 -08001319func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001320 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001321 if ctx.InstallInTestcases() {
1322 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001323 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001324 } else if os.Class == Device {
1325 if ctx.InstallInData() {
1326 partition = "data"
1327 } else if ctx.InstallInRamdisk() {
1328 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1329 partition = "recovery/root/first_stage_ramdisk"
1330 } else {
1331 partition = "ramdisk"
1332 }
1333 if !ctx.InstallInRoot() {
1334 partition += "/system"
1335 }
1336 } else if ctx.InstallInRecovery() {
1337 if ctx.InstallInRoot() {
1338 partition = "recovery/root"
1339 } else {
1340 // the layout of recovery partion is the same as that of system partition
1341 partition = "recovery/root/system"
1342 }
1343 } else if ctx.SocSpecific() {
1344 partition = ctx.DeviceConfig().VendorPath()
1345 } else if ctx.DeviceSpecific() {
1346 partition = ctx.DeviceConfig().OdmPath()
1347 } else if ctx.ProductSpecific() {
1348 partition = ctx.DeviceConfig().ProductPath()
1349 } else if ctx.SystemExtSpecific() {
1350 partition = ctx.DeviceConfig().SystemExtPath()
1351 } else if ctx.InstallInRoot() {
1352 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001353 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001354 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001355 }
Colin Cross6e359402020-02-10 15:29:54 -08001356 if ctx.InstallInSanitizerDir() {
1357 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001358 }
Colin Cross43f08db2018-11-12 10:13:39 -08001359 }
1360 return partition
1361}
1362
Colin Cross609c49a2020-02-13 13:20:11 -08001363type InstallPaths []InstallPath
1364
1365// Paths returns the InstallPaths as a Paths
1366func (p InstallPaths) Paths() Paths {
1367 if p == nil {
1368 return nil
1369 }
1370 ret := make(Paths, len(p))
1371 for i, path := range p {
1372 ret[i] = path
1373 }
1374 return ret
1375}
1376
1377// Strings returns the string forms of the install paths.
1378func (p InstallPaths) Strings() []string {
1379 if p == nil {
1380 return nil
1381 }
1382 ret := make([]string, len(p))
1383 for i, path := range p {
1384 ret[i] = path.String()
1385 }
1386 return ret
1387}
1388
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001389// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001390// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001391func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001392 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001393 path := filepath.Clean(path)
1394 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001395 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001396 }
1397 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001398 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1399 // variables. '..' may remove the entire ninja variable, even if it
1400 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001401 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001402}
1403
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001404// validatePath validates that a path does not include ninja variables, and that
1405// each path component does not attempt to leave its component. Returns a joined
1406// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001407func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001408 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001409 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001410 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001411 }
1412 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001413 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001414}
Colin Cross5b529592017-05-09 13:34:34 -07001415
Colin Cross0875c522017-11-28 17:34:01 -08001416func PathForPhony(ctx PathContext, phony string) WritablePath {
1417 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001418 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001419 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001420 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001421}
1422
Colin Cross74e3fe42017-12-11 15:51:44 -08001423type PhonyPath struct {
1424 basePath
1425}
1426
1427func (p PhonyPath) writablePath() {}
1428
Paul Duffin9b478b02019-12-10 13:41:51 +00001429func (p PhonyPath) buildDir() string {
1430 return p.config.buildDir
1431}
1432
Colin Cross74e3fe42017-12-11 15:51:44 -08001433var _ Path = PhonyPath{}
1434var _ WritablePath = PhonyPath{}
1435
Colin Cross5b529592017-05-09 13:34:34 -07001436type testPath struct {
1437 basePath
1438}
1439
1440func (p testPath) String() string {
1441 return p.path
1442}
1443
Colin Cross40e33732019-02-15 11:08:35 -08001444// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1445// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001446func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001447 p, err := validateSafePath(paths...)
1448 if err != nil {
1449 panic(err)
1450 }
Colin Cross5b529592017-05-09 13:34:34 -07001451 return testPath{basePath{path: p, rel: p}}
1452}
1453
Colin Cross40e33732019-02-15 11:08:35 -08001454// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1455func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001456 p := make(Paths, len(strs))
1457 for i, s := range strs {
1458 p[i] = PathForTesting(s)
1459 }
1460
1461 return p
1462}
Colin Cross43f08db2018-11-12 10:13:39 -08001463
Colin Cross40e33732019-02-15 11:08:35 -08001464type testPathContext struct {
1465 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001466}
1467
Colin Cross40e33732019-02-15 11:08:35 -08001468func (x *testPathContext) Config() Config { return x.config }
1469func (x *testPathContext) AddNinjaFileDeps(...string) {}
1470
1471// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1472// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001473func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001474 return &testPathContext{
1475 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001476 }
1477}
1478
Colin Cross43f08db2018-11-12 10:13:39 -08001479// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1480// targetPath is not inside basePath.
1481func Rel(ctx PathContext, basePath string, targetPath string) string {
1482 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1483 if !isRel {
1484 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1485 return ""
1486 }
1487 return rel
1488}
1489
1490// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1491// targetPath is not inside basePath.
1492func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001493 rel, isRel, err := maybeRelErr(basePath, targetPath)
1494 if err != nil {
1495 reportPathError(ctx, err)
1496 }
1497 return rel, isRel
1498}
1499
1500func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001501 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1502 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001503 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001504 }
1505 rel, err := filepath.Rel(basePath, targetPath)
1506 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001507 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001508 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001509 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001510 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001511 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001512}
Colin Cross988414c2020-01-11 01:11:46 +00001513
1514// Writes a file to the output directory. Attempting to write directly to the output directory
1515// will fail due to the sandbox of the soong_build process.
1516func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1517 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1518}
1519
1520func absolutePath(path string) string {
1521 if filepath.IsAbs(path) {
1522 return path
1523 }
1524 return filepath.Join(absSrcDir, path)
1525}