blob: d8d51a777250cb1001426501565adb7dcf0e55e8 [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
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000223func (paths Paths) containsPath(path Path) bool {
224 for _, p := range paths {
225 if p == path {
226 return true
227 }
228 }
229 return false
230}
231
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700232// PathsForSource returns Paths rooted from SrcDir
233func PathsForSource(ctx PathContext, paths []string) Paths {
234 ret := make(Paths, len(paths))
235 for i, path := range paths {
236 ret[i] = PathForSource(ctx, path)
237 }
238 return ret
239}
240
Jeff Gaston734e3802017-04-10 15:47:24 -0700241// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800242// found in the tree. If any are not found, they are omitted from the list,
243// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800244func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800245 ret := make(Paths, 0, len(paths))
246 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800247 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800248 if p.Valid() {
249 ret = append(ret, p.Path())
250 }
251 }
252 return ret
253}
254
Colin Cross41955e82019-05-29 14:40:35 -0700255// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
256// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
257// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
258// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
259// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
260// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Colin Cross635c3b02016-05-18 15:37:25 -0700261func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800262 return PathsForModuleSrcExcludes(ctx, paths, nil)
263}
264
Colin Crossba71a3f2019-03-18 12:12:48 -0700265// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700266// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
267// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
268// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
269// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100270// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700271// having missing dependencies.
Colin Cross8a497952019-03-05 22:25:09 -0800272func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700273 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
274 if ctx.Config().AllowMissingDependencies() {
275 ctx.AddMissingDependencies(missingDeps)
276 } else {
277 for _, m := range missingDeps {
278 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
279 }
280 }
281 return ret
282}
283
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000284// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
285type OutputPaths []OutputPath
286
287// Paths returns the OutputPaths as a Paths
288func (p OutputPaths) Paths() Paths {
289 if p == nil {
290 return nil
291 }
292 ret := make(Paths, len(p))
293 for i, path := range p {
294 ret[i] = path
295 }
296 return ret
297}
298
299// Strings returns the string forms of the writable paths.
300func (p OutputPaths) Strings() []string {
301 if p == nil {
302 return nil
303 }
304 ret := make([]string, len(p))
305 for i, path := range p {
306 ret[i] = path.String()
307 }
308 return ret
309}
310
Colin Crossba71a3f2019-03-18 12:12:48 -0700311// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700312// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
313// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
314// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
315// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
316// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
317// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
318// dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700319func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800320 prefix := pathForModuleSrc(ctx).String()
321
322 var expandedExcludes []string
323 if excludes != nil {
324 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700325 }
Colin Cross8a497952019-03-05 22:25:09 -0800326
Colin Crossba71a3f2019-03-18 12:12:48 -0700327 var missingExcludeDeps []string
328
Colin Cross8a497952019-03-05 22:25:09 -0800329 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700330 if m, t := SrcIsModuleWithTag(e); m != "" {
331 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800332 if module == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700333 missingExcludeDeps = append(missingExcludeDeps, m)
Colin Cross8a497952019-03-05 22:25:09 -0800334 continue
335 }
Colin Cross41955e82019-05-29 14:40:35 -0700336 if outProducer, ok := module.(OutputFileProducer); ok {
337 outputFiles, err := outProducer.OutputFiles(t)
338 if err != nil {
339 ctx.ModuleErrorf("path dependency %q: %s", e, err)
340 }
341 expandedExcludes = append(expandedExcludes, outputFiles.Strings()...)
342 } else if t != "" {
343 ctx.ModuleErrorf("path dependency %q is not an output file producing module", e)
344 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800345 expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
346 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700347 ctx.ModuleErrorf("path dependency %q is not a source file producing module", e)
Colin Cross8a497952019-03-05 22:25:09 -0800348 }
349 } else {
350 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
351 }
352 }
353
354 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700355 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800356 }
357
Colin Crossba71a3f2019-03-18 12:12:48 -0700358 var missingDeps []string
359
Colin Cross8a497952019-03-05 22:25:09 -0800360 expandedSrcFiles := make(Paths, 0, len(paths))
361 for _, s := range paths {
362 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
363 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700364 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800365 } else if err != nil {
366 reportPathError(ctx, err)
367 }
368 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
369 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700370
371 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800372}
373
374type missingDependencyError struct {
375 missingDeps []string
376}
377
378func (e missingDependencyError) Error() string {
379 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
380}
381
382func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
Colin Cross41955e82019-05-29 14:40:35 -0700383 if m, t := SrcIsModuleWithTag(s); m != "" {
384 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800385 if module == nil {
386 return nil, missingDependencyError{[]string{m}}
387 }
Colin Cross41955e82019-05-29 14:40:35 -0700388 if outProducer, ok := module.(OutputFileProducer); ok {
389 outputFiles, err := outProducer.OutputFiles(t)
390 if err != nil {
391 return nil, fmt.Errorf("path dependency %q: %s", s, err)
392 }
393 return outputFiles, nil
394 } else if t != "" {
395 return nil, fmt.Errorf("path dependency %q is not an output file producing module", s)
396 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800397 moduleSrcs := srcProducer.Srcs()
398 for _, e := range expandedExcludes {
399 for j := 0; j < len(moduleSrcs); j++ {
400 if moduleSrcs[j].String() == e {
401 moduleSrcs = append(moduleSrcs[:j], moduleSrcs[j+1:]...)
402 j--
403 }
404 }
405 }
406 return moduleSrcs, nil
407 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700408 return nil, fmt.Errorf("path dependency %q is not a source file producing module", s)
Colin Cross8a497952019-03-05 22:25:09 -0800409 }
410 } else if pathtools.IsGlob(s) {
411 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
412 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
413 } else {
414 p := pathForModuleSrc(ctx, s)
Colin Cross988414c2020-01-11 01:11:46 +0000415 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Colin Cross8a497952019-03-05 22:25:09 -0800416 reportPathErrorf(ctx, "%s: %s", p, err.Error())
Colin Cross5e6a7972020-06-07 16:56:32 -0700417 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Colin Cross8a497952019-03-05 22:25:09 -0800418 reportPathErrorf(ctx, "module source path %q does not exist", p)
419 }
420
421 j := findStringInSlice(p.String(), expandedExcludes)
422 if j >= 0 {
423 return nil, nil
424 }
425 return Paths{p}, nil
426 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700427}
428
429// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
430// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800431// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700432// It intended for use in globs that only list files that exist, so it allows '$' in
433// filenames.
Colin Cross1184b642019-12-30 18:43:07 -0800434func pathsForModuleSrcFromFullPath(ctx EarlyModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800435 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700436 if prefix == "./" {
437 prefix = ""
438 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700439 ret := make(Paths, 0, len(paths))
440 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800441 if !incDirs && strings.HasSuffix(p, "/") {
442 continue
443 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700444 path := filepath.Clean(p)
445 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800446 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700447 continue
448 }
Colin Crosse3924e12018-08-15 20:18:53 -0700449
Colin Crossfe4bc362018-09-12 10:02:13 -0700450 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700451 if err != nil {
452 reportPathError(ctx, err)
453 continue
454 }
455
Colin Cross07e51612019-03-05 12:46:40 -0800456 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700457
Colin Cross07e51612019-03-05 12:46:40 -0800458 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700459 }
460 return ret
461}
462
463// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800464// 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 -0700465func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800466 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700467 return PathsForModuleSrc(ctx, input)
468 }
469 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
470 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800471 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800472 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700473}
474
475// Strings returns the Paths in string form
476func (p Paths) Strings() []string {
477 if p == nil {
478 return nil
479 }
480 ret := make([]string, len(p))
481 for i, path := range p {
482 ret[i] = path.String()
483 }
484 return ret
485}
486
Colin Crossb6715442017-10-24 11:13:31 -0700487// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
488// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700489func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800490 // 128 was chosen based on BenchmarkFirstUniquePaths results.
491 if len(list) > 128 {
492 return firstUniquePathsMap(list)
493 }
494 return firstUniquePathsList(list)
495}
496
Jiyong Park33c77362020-05-29 22:00:16 +0900497// SortedUniquePaths returns what its name says
498func SortedUniquePaths(list Paths) Paths {
499 unique := FirstUniquePaths(list)
500 sort.Slice(unique, func(i, j int) bool {
501 return unique[i].String() < unique[j].String()
502 })
503 return unique
504}
505
Colin Cross27027c72020-02-28 15:34:17 -0800506func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700507 k := 0
508outer:
509 for i := 0; i < len(list); i++ {
510 for j := 0; j < k; j++ {
511 if list[i] == list[j] {
512 continue outer
513 }
514 }
515 list[k] = list[i]
516 k++
517 }
518 return list[:k]
519}
520
Colin Cross27027c72020-02-28 15:34:17 -0800521func firstUniquePathsMap(list Paths) Paths {
522 k := 0
523 seen := make(map[Path]bool, len(list))
524 for i := 0; i < len(list); i++ {
525 if seen[list[i]] {
526 continue
527 }
528 seen[list[i]] = true
529 list[k] = list[i]
530 k++
531 }
532 return list[:k]
533}
534
Colin Crossb6715442017-10-24 11:13:31 -0700535// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
536// modifies the Paths slice contents in place, and returns a subslice of the original slice.
537func LastUniquePaths(list Paths) Paths {
538 totalSkip := 0
539 for i := len(list) - 1; i >= totalSkip; i-- {
540 skip := 0
541 for j := i - 1; j >= totalSkip; j-- {
542 if list[i] == list[j] {
543 skip++
544 } else {
545 list[j+skip] = list[j]
546 }
547 }
548 totalSkip += skip
549 }
550 return list[totalSkip:]
551}
552
Colin Crossa140bb02018-04-17 10:52:26 -0700553// ReversePaths returns a copy of a Paths in reverse order.
554func ReversePaths(list Paths) Paths {
555 if list == nil {
556 return nil
557 }
558 ret := make(Paths, len(list))
559 for i := range list {
560 ret[i] = list[len(list)-1-i]
561 }
562 return ret
563}
564
Jeff Gaston294356f2017-09-27 17:05:30 -0700565func indexPathList(s Path, list []Path) int {
566 for i, l := range list {
567 if l == s {
568 return i
569 }
570 }
571
572 return -1
573}
574
575func inPathList(p Path, list []Path) bool {
576 return indexPathList(p, list) != -1
577}
578
579func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000580 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
581}
582
583func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700584 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000585 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700586 filtered = append(filtered, l)
587 } else {
588 remainder = append(remainder, l)
589 }
590 }
591
592 return
593}
594
Colin Cross93e85952017-08-15 13:34:18 -0700595// HasExt returns true of any of the paths have extension ext, otherwise false
596func (p Paths) HasExt(ext string) bool {
597 for _, path := range p {
598 if path.Ext() == ext {
599 return true
600 }
601 }
602
603 return false
604}
605
606// FilterByExt returns the subset of the paths that have extension ext
607func (p Paths) FilterByExt(ext string) Paths {
608 ret := make(Paths, 0, len(p))
609 for _, path := range p {
610 if path.Ext() == ext {
611 ret = append(ret, path)
612 }
613 }
614 return ret
615}
616
617// FilterOutByExt returns the subset of the paths that do not have extension ext
618func (p Paths) FilterOutByExt(ext string) Paths {
619 ret := make(Paths, 0, len(p))
620 for _, path := range p {
621 if path.Ext() != ext {
622 ret = append(ret, path)
623 }
624 }
625 return ret
626}
627
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700628// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
629// (including subdirectories) are in a contiguous subslice of the list, and can be found in
630// O(log(N)) time using a binary search on the directory prefix.
631type DirectorySortedPaths Paths
632
633func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
634 ret := append(DirectorySortedPaths(nil), paths...)
635 sort.Slice(ret, func(i, j int) bool {
636 return ret[i].String() < ret[j].String()
637 })
638 return ret
639}
640
641// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
642// that are in the specified directory and its subdirectories.
643func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
644 prefix := filepath.Clean(dir) + "/"
645 start := sort.Search(len(p), func(i int) bool {
646 return prefix < p[i].String()
647 })
648
649 ret := p[start:]
650
651 end := sort.Search(len(ret), func(i int) bool {
652 return !strings.HasPrefix(ret[i].String(), prefix)
653 })
654
655 ret = ret[:end]
656
657 return Paths(ret)
658}
659
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700660// WritablePaths is a slice of WritablePaths, used for multiple outputs.
661type WritablePaths []WritablePath
662
663// Strings returns the string forms of the writable paths.
664func (p WritablePaths) Strings() []string {
665 if p == nil {
666 return nil
667 }
668 ret := make([]string, len(p))
669 for i, path := range p {
670 ret[i] = path.String()
671 }
672 return ret
673}
674
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800675// Paths returns the WritablePaths as a Paths
676func (p WritablePaths) Paths() Paths {
677 if p == nil {
678 return nil
679 }
680 ret := make(Paths, len(p))
681 for i, path := range p {
682 ret[i] = path
683 }
684 return ret
685}
686
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700687type basePath struct {
688 path string
689 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800690 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700691}
692
693func (p basePath) Ext() string {
694 return filepath.Ext(p.path)
695}
696
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700697func (p basePath) Base() string {
698 return filepath.Base(p.path)
699}
700
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800701func (p basePath) Rel() string {
702 if p.rel != "" {
703 return p.rel
704 }
705 return p.path
706}
707
Colin Cross0875c522017-11-28 17:34:01 -0800708func (p basePath) String() string {
709 return p.path
710}
711
Colin Cross0db55682017-12-05 15:36:55 -0800712func (p basePath) withRel(rel string) basePath {
713 p.path = filepath.Join(p.path, rel)
714 p.rel = rel
715 return p
716}
717
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700718// SourcePath is a Path representing a file path rooted from SrcDir
719type SourcePath struct {
720 basePath
721}
722
723var _ Path = SourcePath{}
724
Colin Cross0db55682017-12-05 15:36:55 -0800725func (p SourcePath) withRel(rel string) SourcePath {
726 p.basePath = p.basePath.withRel(rel)
727 return p
728}
729
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700730// safePathForSource is for paths that we expect are safe -- only for use by go
731// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700732func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
733 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800734 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700735 if err != nil {
736 return ret, err
737 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700738
Colin Cross7b3dcc32019-01-24 13:14:39 -0800739 // absolute path already checked by validateSafePath
740 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800741 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700742 }
743
Colin Crossfe4bc362018-09-12 10:02:13 -0700744 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700745}
746
Colin Cross192e97a2018-02-22 14:21:02 -0800747// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
748func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000749 p, err := validatePath(pathComponents...)
750 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800751 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800752 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800753 }
754
Colin Cross7b3dcc32019-01-24 13:14:39 -0800755 // absolute path already checked by validatePath
756 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800757 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000758 }
759
Colin Cross192e97a2018-02-22 14:21:02 -0800760 return ret, nil
761}
762
763// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
764// path does not exist.
765func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
766 var files []string
767
768 if gctx, ok := ctx.(PathGlobContext); ok {
769 // Use glob to produce proper dependencies, even though we only want
770 // a single file.
771 files, err = gctx.GlobWithDeps(path.String(), nil)
772 } else {
773 var deps []string
774 // We cannot add build statements in this context, so we fall back to
775 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +0000776 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800777 ctx.AddNinjaFileDeps(deps...)
778 }
779
780 if err != nil {
781 return false, fmt.Errorf("glob: %s", err.Error())
782 }
783
784 return len(files) > 0, nil
785}
786
787// PathForSource joins the provided path components and validates that the result
788// neither escapes the source dir nor is in the out dir.
789// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
790func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
791 path, err := pathForSource(ctx, pathComponents...)
792 if err != nil {
793 reportPathError(ctx, err)
794 }
795
Colin Crosse3924e12018-08-15 20:18:53 -0700796 if pathtools.IsGlob(path.String()) {
797 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
798 }
799
Colin Cross192e97a2018-02-22 14:21:02 -0800800 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
801 exists, err := existsWithDependencies(ctx, path)
802 if err != nil {
803 reportPathError(ctx, err)
804 }
805 if !exists {
806 modCtx.AddMissingDependencies([]string{path.String()})
807 }
Colin Cross988414c2020-01-11 01:11:46 +0000808 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800809 reportPathErrorf(ctx, "%s: %s", path, err.Error())
Colin Cross5e6a7972020-06-07 16:56:32 -0700810 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800811 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800812 }
813 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700814}
815
Jeff Gaston734e3802017-04-10 15:47:24 -0700816// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700817// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
818// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800819func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800820 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800821 if err != nil {
822 reportPathError(ctx, err)
823 return OptionalPath{}
824 }
Colin Crossc48c1432018-02-23 07:09:01 +0000825
Colin Crosse3924e12018-08-15 20:18:53 -0700826 if pathtools.IsGlob(path.String()) {
827 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
828 return OptionalPath{}
829 }
830
Colin Cross192e97a2018-02-22 14:21:02 -0800831 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000832 if err != nil {
833 reportPathError(ctx, err)
834 return OptionalPath{}
835 }
Colin Cross192e97a2018-02-22 14:21:02 -0800836 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000837 return OptionalPath{}
838 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700839 return OptionalPathForPath(path)
840}
841
842func (p SourcePath) String() string {
843 return filepath.Join(p.config.srcDir, p.path)
844}
845
846// Join creates a new SourcePath with paths... joined with the current path. The
847// provided paths... may not use '..' to escape from the current path.
848func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800849 path, err := validatePath(paths...)
850 if err != nil {
851 reportPathError(ctx, err)
852 }
Colin Cross0db55682017-12-05 15:36:55 -0800853 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700854}
855
Colin Cross2fafa3e2019-03-05 12:39:51 -0800856// join is like Join but does less path validation.
857func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
858 path, err := validateSafePath(paths...)
859 if err != nil {
860 reportPathError(ctx, err)
861 }
862 return p.withRel(path)
863}
864
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700865// OverlayPath returns the overlay for `path' if it exists. This assumes that the
866// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700867func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700868 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800869 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700870 relDir = srcPath.path
871 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800872 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700873 return OptionalPath{}
874 }
875 dir := filepath.Join(p.config.srcDir, p.path, relDir)
876 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700877 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800878 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800879 }
Colin Cross461b4452018-02-23 09:22:42 -0800880 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700881 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800882 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700883 return OptionalPath{}
884 }
885 if len(paths) == 0 {
886 return OptionalPath{}
887 }
Colin Cross43f08db2018-11-12 10:13:39 -0800888 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700889 return OptionalPathForPath(PathForSource(ctx, relPath))
890}
891
Colin Cross70dda7e2019-10-01 22:05:35 -0700892// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700893type OutputPath struct {
894 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -0800895 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700896}
897
Colin Cross702e0f82017-10-18 17:27:54 -0700898func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800899 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -0800900 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700901 return p
902}
903
Colin Cross3063b782018-08-15 11:19:12 -0700904func (p OutputPath) WithoutRel() OutputPath {
905 p.basePath.rel = filepath.Base(p.basePath.path)
906 return p
907}
908
Paul Duffin9b478b02019-12-10 13:41:51 +0000909func (p OutputPath) buildDir() string {
910 return p.config.buildDir
911}
912
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700913var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +0000914var _ WritablePath = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700915
Jeff Gaston734e3802017-04-10 15:47:24 -0700916// PathForOutput joins the provided paths and returns an OutputPath that is
917// validated to not escape the build dir.
918// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
919func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800920 path, err := validatePath(pathComponents...)
921 if err != nil {
922 reportPathError(ctx, err)
923 }
Colin Crossd63c9a72020-01-29 16:52:50 -0800924 fullPath := filepath.Join(ctx.Config().buildDir, path)
925 path = fullPath[len(fullPath)-len(path):]
926 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700927}
928
Colin Cross40e33732019-02-15 11:08:35 -0800929// PathsForOutput returns Paths rooted from buildDir
930func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
931 ret := make(WritablePaths, len(paths))
932 for i, path := range paths {
933 ret[i] = PathForOutput(ctx, path)
934 }
935 return ret
936}
937
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700938func (p OutputPath) writablePath() {}
939
940func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -0800941 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700942}
943
944// Join creates a new OutputPath with paths... joined with the current path. The
945// provided paths... may not use '..' to escape from the current path.
946func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800947 path, err := validatePath(paths...)
948 if err != nil {
949 reportPathError(ctx, err)
950 }
Colin Cross0db55682017-12-05 15:36:55 -0800951 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700952}
953
Colin Cross8854a5a2019-02-11 14:14:16 -0800954// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
955func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
956 if strings.Contains(ext, "/") {
957 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
958 }
959 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800960 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800961 return ret
962}
963
Colin Cross40e33732019-02-15 11:08:35 -0800964// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
965func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
966 path, err := validatePath(paths...)
967 if err != nil {
968 reportPathError(ctx, err)
969 }
970
971 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800972 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800973 return ret
974}
975
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700976// PathForIntermediates returns an OutputPath representing the top-level
977// intermediates directory.
978func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800979 path, err := validatePath(paths...)
980 if err != nil {
981 reportPathError(ctx, err)
982 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700983 return PathForOutput(ctx, ".intermediates", path)
984}
985
Colin Cross07e51612019-03-05 12:46:40 -0800986var _ genPathProvider = SourcePath{}
987var _ objPathProvider = SourcePath{}
988var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700989
Colin Cross07e51612019-03-05 12:46:40 -0800990// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700991// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800992func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
993 p, err := validatePath(pathComponents...)
994 if err != nil {
995 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800996 }
Colin Cross8a497952019-03-05 22:25:09 -0800997 paths, err := expandOneSrcPath(ctx, p, nil)
998 if err != nil {
999 if depErr, ok := err.(missingDependencyError); ok {
1000 if ctx.Config().AllowMissingDependencies() {
1001 ctx.AddMissingDependencies(depErr.missingDeps)
1002 } else {
1003 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1004 }
1005 } else {
1006 reportPathError(ctx, err)
1007 }
1008 return nil
1009 } else if len(paths) == 0 {
1010 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
1011 return nil
1012 } else if len(paths) > 1 {
1013 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
1014 }
1015 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001016}
1017
Colin Cross07e51612019-03-05 12:46:40 -08001018func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
1019 p, err := validatePath(paths...)
1020 if err != nil {
1021 reportPathError(ctx, err)
1022 }
1023
1024 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1025 if err != nil {
1026 reportPathError(ctx, err)
1027 }
1028
1029 path.basePath.rel = p
1030
1031 return path
1032}
1033
Colin Cross2fafa3e2019-03-05 12:39:51 -08001034// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1035// will return the path relative to subDir in the module's source directory. If any input paths are not located
1036// inside subDir then a path error will be reported.
1037func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
1038 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001039 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001040 for i, path := range paths {
1041 rel := Rel(ctx, subDirFullPath.String(), path.String())
1042 paths[i] = subDirFullPath.join(ctx, rel)
1043 }
1044 return paths
1045}
1046
1047// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1048// module's source directory. If the input path is not located inside subDir then a path error will be reported.
1049func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001050 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001051 rel := Rel(ctx, subDirFullPath.String(), path.String())
1052 return subDirFullPath.Join(ctx, rel)
1053}
1054
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001055// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1056// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -07001057func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001058 if p == nil {
1059 return OptionalPath{}
1060 }
1061 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1062}
1063
Colin Cross07e51612019-03-05 12:46:40 -08001064func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001065 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001066}
1067
Colin Cross07e51612019-03-05 12:46:40 -08001068func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001069 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001070}
1071
Colin Cross07e51612019-03-05 12:46:40 -08001072func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001073 // TODO: Use full directory if the new ctx is not the current ctx?
1074 return PathForModuleRes(ctx, p.path, name)
1075}
1076
1077// ModuleOutPath is a Path representing a module's output directory.
1078type ModuleOutPath struct {
1079 OutputPath
1080}
1081
1082var _ Path = ModuleOutPath{}
1083
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001084func (p ModuleOutPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
1085 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1086}
1087
Colin Cross702e0f82017-10-18 17:27:54 -07001088func pathForModule(ctx ModuleContext) OutputPath {
1089 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1090}
1091
Logan Chien7eefdc42018-07-11 18:10:41 +08001092// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1093// reference abi dump for the given module. This is not guaranteed to be valid.
1094func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001095 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001096
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001097 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001098 if len(arches) == 0 {
1099 panic("device build with no primary arch")
1100 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001101 currentArch := ctx.Arch()
1102 archNameAndVariant := currentArch.ArchType.String()
1103 if currentArch.ArchVariant != "" {
1104 archNameAndVariant += "_" + currentArch.ArchVariant
1105 }
Logan Chien5237bed2018-07-11 17:15:57 +08001106
1107 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001108 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001109 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001110 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001111 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001112 } else {
1113 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001114 }
Logan Chien5237bed2018-07-11 17:15:57 +08001115
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001116 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001117
1118 var ext string
1119 if isGzip {
1120 ext = ".lsdump.gz"
1121 } else {
1122 ext = ".lsdump"
1123 }
1124
1125 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1126 version, binderBitness, archNameAndVariant, "source-based",
1127 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001128}
1129
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001130// PathForModuleOut returns a Path representing the paths... under the module's
1131// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001132func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001133 p, err := validatePath(paths...)
1134 if err != nil {
1135 reportPathError(ctx, err)
1136 }
Colin Cross702e0f82017-10-18 17:27:54 -07001137 return ModuleOutPath{
1138 OutputPath: pathForModule(ctx).withRel(p),
1139 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001140}
1141
1142// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1143// directory. Mainly used for generated sources.
1144type ModuleGenPath struct {
1145 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001146}
1147
1148var _ Path = ModuleGenPath{}
1149var _ genPathProvider = ModuleGenPath{}
1150var _ objPathProvider = ModuleGenPath{}
1151
1152// PathForModuleGen returns a Path representing the paths... under the module's
1153// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001154func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001155 p, err := validatePath(paths...)
1156 if err != nil {
1157 reportPathError(ctx, err)
1158 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001159 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001160 ModuleOutPath: ModuleOutPath{
1161 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1162 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001163 }
1164}
1165
Dan Willemsen21ec4902016-11-02 20:43:13 -07001166func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001167 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001168 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001169}
1170
Colin Cross635c3b02016-05-18 15:37:25 -07001171func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001172 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1173}
1174
1175// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1176// directory. Used for compiled objects.
1177type ModuleObjPath struct {
1178 ModuleOutPath
1179}
1180
1181var _ Path = ModuleObjPath{}
1182
1183// PathForModuleObj returns a Path representing the paths... under the module's
1184// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001185func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001186 p, err := validatePath(pathComponents...)
1187 if err != nil {
1188 reportPathError(ctx, err)
1189 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001190 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1191}
1192
1193// ModuleResPath is a a Path representing the 'res' directory in a module's
1194// output directory.
1195type ModuleResPath struct {
1196 ModuleOutPath
1197}
1198
1199var _ Path = ModuleResPath{}
1200
1201// PathForModuleRes returns a Path representing the paths... under the module's
1202// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001203func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001204 p, err := validatePath(pathComponents...)
1205 if err != nil {
1206 reportPathError(ctx, err)
1207 }
1208
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001209 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1210}
1211
Colin Cross70dda7e2019-10-01 22:05:35 -07001212// InstallPath is a Path representing a installed file path rooted from the build directory
1213type InstallPath struct {
1214 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001215
1216 baseDir string // "../" for Make paths to convert "out/soong" to "out", "" for Soong paths
Colin Cross70dda7e2019-10-01 22:05:35 -07001217}
1218
Paul Duffin9b478b02019-12-10 13:41:51 +00001219func (p InstallPath) buildDir() string {
1220 return p.config.buildDir
1221}
1222
1223var _ Path = InstallPath{}
1224var _ WritablePath = InstallPath{}
1225
Colin Cross70dda7e2019-10-01 22:05:35 -07001226func (p InstallPath) writablePath() {}
1227
1228func (p InstallPath) String() string {
Colin Crossff6c33d2019-10-02 16:01:35 -07001229 return filepath.Join(p.config.buildDir, p.baseDir, p.path)
Colin Cross70dda7e2019-10-01 22:05:35 -07001230}
1231
1232// Join creates a new InstallPath with paths... joined with the current path. The
1233// provided paths... may not use '..' to escape from the current path.
1234func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1235 path, err := validatePath(paths...)
1236 if err != nil {
1237 reportPathError(ctx, err)
1238 }
1239 return p.withRel(path)
1240}
1241
1242func (p InstallPath) withRel(rel string) InstallPath {
1243 p.basePath = p.basePath.withRel(rel)
1244 return p
1245}
1246
Colin Crossff6c33d2019-10-02 16:01:35 -07001247// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1248// i.e. out/ instead of out/soong/.
1249func (p InstallPath) ToMakePath() InstallPath {
1250 p.baseDir = "../"
1251 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001252}
1253
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001254// PathForModuleInstall returns a Path representing the install path for the
1255// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001256func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001257 os := ctx.Os()
1258 if forceOS := ctx.InstallForceOS(); forceOS != nil {
1259 os = *forceOS
1260 }
1261 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001262
1263 ret := pathForInstall(ctx, os, partition, ctx.Debug(), pathComponents...)
1264
1265 if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
1266 ret = ret.ToMakePath()
1267 }
1268
1269 return ret
1270}
1271
1272func pathForInstall(ctx PathContext, os OsType, partition string, debug bool,
1273 pathComponents ...string) InstallPath {
1274
1275 var outPaths []string
1276
Colin Cross6e359402020-02-10 15:29:54 -08001277 if os.Class == Device {
Colin Cross6510f912017-11-29 00:27:14 -08001278 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001279 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001280 switch os {
Dan Willemsen866b5632017-09-22 12:28:24 -07001281 case Linux:
Colin Cross6e359402020-02-10 15:29:54 -08001282 outPaths = []string{"host", "linux-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001283 case LinuxBionic:
1284 // TODO: should this be a separate top level, or shared with linux-x86?
Colin Cross6e359402020-02-10 15:29:54 -08001285 outPaths = []string{"host", "linux_bionic-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001286 default:
Colin Cross6e359402020-02-10 15:29:54 -08001287 outPaths = []string{"host", os.String() + "-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001288 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001289 }
Colin Cross609c49a2020-02-13 13:20:11 -08001290 if debug {
Dan Willemsen782a2d12015-12-21 14:55:28 -08001291 outPaths = append([]string{"debug"}, outPaths...)
1292 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001293 outPaths = append(outPaths, pathComponents...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001294
1295 path, err := validatePath(outPaths...)
1296 if err != nil {
1297 reportPathError(ctx, err)
1298 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001299
1300 ret := InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Crossff6c33d2019-10-02 16:01:35 -07001301
1302 return ret
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001303}
1304
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001305func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
1306 paths = append([]string{prefix}, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001307 path, err := validatePath(paths...)
1308 if err != nil {
1309 reportPathError(ctx, err)
1310 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001311 return InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Cross70dda7e2019-10-01 22:05:35 -07001312}
1313
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001314func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1315 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1316}
1317
1318func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1319 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1320}
1321
Colin Cross70dda7e2019-10-01 22:05:35 -07001322func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001323 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1324
1325 return "/" + rel
1326}
1327
Colin Cross6e359402020-02-10 15:29:54 -08001328func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001329 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001330 if ctx.InstallInTestcases() {
1331 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001332 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001333 } else if os.Class == Device {
1334 if ctx.InstallInData() {
1335 partition = "data"
1336 } else if ctx.InstallInRamdisk() {
1337 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1338 partition = "recovery/root/first_stage_ramdisk"
1339 } else {
1340 partition = "ramdisk"
1341 }
1342 if !ctx.InstallInRoot() {
1343 partition += "/system"
1344 }
1345 } else if ctx.InstallInRecovery() {
1346 if ctx.InstallInRoot() {
1347 partition = "recovery/root"
1348 } else {
1349 // the layout of recovery partion is the same as that of system partition
1350 partition = "recovery/root/system"
1351 }
1352 } else if ctx.SocSpecific() {
1353 partition = ctx.DeviceConfig().VendorPath()
1354 } else if ctx.DeviceSpecific() {
1355 partition = ctx.DeviceConfig().OdmPath()
1356 } else if ctx.ProductSpecific() {
1357 partition = ctx.DeviceConfig().ProductPath()
1358 } else if ctx.SystemExtSpecific() {
1359 partition = ctx.DeviceConfig().SystemExtPath()
1360 } else if ctx.InstallInRoot() {
1361 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001362 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001363 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001364 }
Colin Cross6e359402020-02-10 15:29:54 -08001365 if ctx.InstallInSanitizerDir() {
1366 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001367 }
Colin Cross43f08db2018-11-12 10:13:39 -08001368 }
1369 return partition
1370}
1371
Colin Cross609c49a2020-02-13 13:20:11 -08001372type InstallPaths []InstallPath
1373
1374// Paths returns the InstallPaths as a Paths
1375func (p InstallPaths) Paths() Paths {
1376 if p == nil {
1377 return nil
1378 }
1379 ret := make(Paths, len(p))
1380 for i, path := range p {
1381 ret[i] = path
1382 }
1383 return ret
1384}
1385
1386// Strings returns the string forms of the install paths.
1387func (p InstallPaths) Strings() []string {
1388 if p == nil {
1389 return nil
1390 }
1391 ret := make([]string, len(p))
1392 for i, path := range p {
1393 ret[i] = path.String()
1394 }
1395 return ret
1396}
1397
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001398// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001399// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001400func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001401 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001402 path := filepath.Clean(path)
1403 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001404 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001405 }
1406 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001407 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1408 // variables. '..' may remove the entire ninja variable, even if it
1409 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001410 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001411}
1412
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001413// validatePath validates that a path does not include ninja variables, and that
1414// each path component does not attempt to leave its component. Returns a joined
1415// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001416func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001417 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001418 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001419 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001420 }
1421 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001422 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001423}
Colin Cross5b529592017-05-09 13:34:34 -07001424
Colin Cross0875c522017-11-28 17:34:01 -08001425func PathForPhony(ctx PathContext, phony string) WritablePath {
1426 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001427 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001428 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001429 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001430}
1431
Colin Cross74e3fe42017-12-11 15:51:44 -08001432type PhonyPath struct {
1433 basePath
1434}
1435
1436func (p PhonyPath) writablePath() {}
1437
Paul Duffin9b478b02019-12-10 13:41:51 +00001438func (p PhonyPath) buildDir() string {
1439 return p.config.buildDir
1440}
1441
Colin Cross74e3fe42017-12-11 15:51:44 -08001442var _ Path = PhonyPath{}
1443var _ WritablePath = PhonyPath{}
1444
Colin Cross5b529592017-05-09 13:34:34 -07001445type testPath struct {
1446 basePath
1447}
1448
1449func (p testPath) String() string {
1450 return p.path
1451}
1452
Colin Cross40e33732019-02-15 11:08:35 -08001453// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1454// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001455func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001456 p, err := validateSafePath(paths...)
1457 if err != nil {
1458 panic(err)
1459 }
Colin Cross5b529592017-05-09 13:34:34 -07001460 return testPath{basePath{path: p, rel: p}}
1461}
1462
Colin Cross40e33732019-02-15 11:08:35 -08001463// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1464func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001465 p := make(Paths, len(strs))
1466 for i, s := range strs {
1467 p[i] = PathForTesting(s)
1468 }
1469
1470 return p
1471}
Colin Cross43f08db2018-11-12 10:13:39 -08001472
Colin Cross40e33732019-02-15 11:08:35 -08001473type testPathContext struct {
1474 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001475}
1476
Colin Cross40e33732019-02-15 11:08:35 -08001477func (x *testPathContext) Config() Config { return x.config }
1478func (x *testPathContext) AddNinjaFileDeps(...string) {}
1479
1480// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1481// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001482func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001483 return &testPathContext{
1484 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001485 }
1486}
1487
Colin Cross43f08db2018-11-12 10:13:39 -08001488// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1489// targetPath is not inside basePath.
1490func Rel(ctx PathContext, basePath string, targetPath string) string {
1491 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1492 if !isRel {
1493 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1494 return ""
1495 }
1496 return rel
1497}
1498
1499// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1500// targetPath is not inside basePath.
1501func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001502 rel, isRel, err := maybeRelErr(basePath, targetPath)
1503 if err != nil {
1504 reportPathError(ctx, err)
1505 }
1506 return rel, isRel
1507}
1508
1509func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001510 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1511 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001512 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001513 }
1514 rel, err := filepath.Rel(basePath, targetPath)
1515 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001516 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001517 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001518 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001519 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001520 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001521}
Colin Cross988414c2020-01-11 01:11:46 +00001522
1523// Writes a file to the output directory. Attempting to write directly to the output directory
1524// will fail due to the sandbox of the soong_build process.
1525func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1526 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1527}
1528
1529func absolutePath(path string) string {
1530 if filepath.IsAbs(path) {
1531 return path
1532 }
1533 return filepath.Join(absSrcDir, path)
1534}