blob: d13b6d86ec81ae8e410034612a829b89452314ac [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) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900383 excludePaths := func(paths Paths) Paths {
384 if len(expandedExcludes) == 0 {
385 return paths
386 }
387 remainder := make(Paths, 0, len(paths))
388 for _, p := range paths {
389 if !InList(p.String(), expandedExcludes) {
390 remainder = append(remainder, p)
391 }
392 }
393 return remainder
394 }
Colin Cross41955e82019-05-29 14:40:35 -0700395 if m, t := SrcIsModuleWithTag(s); m != "" {
396 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800397 if module == nil {
398 return nil, missingDependencyError{[]string{m}}
399 }
Colin Cross41955e82019-05-29 14:40:35 -0700400 if outProducer, ok := module.(OutputFileProducer); ok {
401 outputFiles, err := outProducer.OutputFiles(t)
402 if err != nil {
403 return nil, fmt.Errorf("path dependency %q: %s", s, err)
404 }
Jooyung Han7607dd32020-07-05 10:23:14 +0900405 return excludePaths(outputFiles), nil
Colin Cross41955e82019-05-29 14:40:35 -0700406 } else if t != "" {
407 return nil, fmt.Errorf("path dependency %q is not an output file producing module", s)
408 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Jooyung Han7607dd32020-07-05 10:23:14 +0900409 return excludePaths(srcProducer.Srcs()), nil
Colin Cross8a497952019-03-05 22:25:09 -0800410 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700411 return nil, fmt.Errorf("path dependency %q is not a source file producing module", s)
Colin Cross8a497952019-03-05 22:25:09 -0800412 }
413 } else if pathtools.IsGlob(s) {
414 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
415 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
416 } else {
417 p := pathForModuleSrc(ctx, s)
Colin Cross988414c2020-01-11 01:11:46 +0000418 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Colin Cross8a497952019-03-05 22:25:09 -0800419 reportPathErrorf(ctx, "%s: %s", p, err.Error())
Colin Cross5e6a7972020-06-07 16:56:32 -0700420 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Colin Cross8a497952019-03-05 22:25:09 -0800421 reportPathErrorf(ctx, "module source path %q does not exist", p)
422 }
423
Jooyung Han7607dd32020-07-05 10:23:14 +0900424 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800425 return nil, nil
426 }
427 return Paths{p}, nil
428 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700429}
430
431// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
432// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800433// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700434// It intended for use in globs that only list files that exist, so it allows '$' in
435// filenames.
Colin Cross1184b642019-12-30 18:43:07 -0800436func pathsForModuleSrcFromFullPath(ctx EarlyModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800437 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700438 if prefix == "./" {
439 prefix = ""
440 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700441 ret := make(Paths, 0, len(paths))
442 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800443 if !incDirs && strings.HasSuffix(p, "/") {
444 continue
445 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700446 path := filepath.Clean(p)
447 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800448 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700449 continue
450 }
Colin Crosse3924e12018-08-15 20:18:53 -0700451
Colin Crossfe4bc362018-09-12 10:02:13 -0700452 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700453 if err != nil {
454 reportPathError(ctx, err)
455 continue
456 }
457
Colin Cross07e51612019-03-05 12:46:40 -0800458 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700459
Colin Cross07e51612019-03-05 12:46:40 -0800460 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700461 }
462 return ret
463}
464
465// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800466// 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 -0700467func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800468 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700469 return PathsForModuleSrc(ctx, input)
470 }
471 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
472 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800473 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800474 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700475}
476
477// Strings returns the Paths in string form
478func (p Paths) Strings() []string {
479 if p == nil {
480 return nil
481 }
482 ret := make([]string, len(p))
483 for i, path := range p {
484 ret[i] = path.String()
485 }
486 return ret
487}
488
Colin Crossb6715442017-10-24 11:13:31 -0700489// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
490// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700491func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800492 // 128 was chosen based on BenchmarkFirstUniquePaths results.
493 if len(list) > 128 {
494 return firstUniquePathsMap(list)
495 }
496 return firstUniquePathsList(list)
497}
498
Jiyong Park33c77362020-05-29 22:00:16 +0900499// SortedUniquePaths returns what its name says
500func SortedUniquePaths(list Paths) Paths {
501 unique := FirstUniquePaths(list)
502 sort.Slice(unique, func(i, j int) bool {
503 return unique[i].String() < unique[j].String()
504 })
505 return unique
506}
507
Colin Cross27027c72020-02-28 15:34:17 -0800508func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700509 k := 0
510outer:
511 for i := 0; i < len(list); i++ {
512 for j := 0; j < k; j++ {
513 if list[i] == list[j] {
514 continue outer
515 }
516 }
517 list[k] = list[i]
518 k++
519 }
520 return list[:k]
521}
522
Colin Cross27027c72020-02-28 15:34:17 -0800523func firstUniquePathsMap(list Paths) Paths {
524 k := 0
525 seen := make(map[Path]bool, len(list))
526 for i := 0; i < len(list); i++ {
527 if seen[list[i]] {
528 continue
529 }
530 seen[list[i]] = true
531 list[k] = list[i]
532 k++
533 }
534 return list[:k]
535}
536
Colin Crossb6715442017-10-24 11:13:31 -0700537// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
538// modifies the Paths slice contents in place, and returns a subslice of the original slice.
539func LastUniquePaths(list Paths) Paths {
540 totalSkip := 0
541 for i := len(list) - 1; i >= totalSkip; i-- {
542 skip := 0
543 for j := i - 1; j >= totalSkip; j-- {
544 if list[i] == list[j] {
545 skip++
546 } else {
547 list[j+skip] = list[j]
548 }
549 }
550 totalSkip += skip
551 }
552 return list[totalSkip:]
553}
554
Colin Crossa140bb02018-04-17 10:52:26 -0700555// ReversePaths returns a copy of a Paths in reverse order.
556func ReversePaths(list Paths) Paths {
557 if list == nil {
558 return nil
559 }
560 ret := make(Paths, len(list))
561 for i := range list {
562 ret[i] = list[len(list)-1-i]
563 }
564 return ret
565}
566
Jeff Gaston294356f2017-09-27 17:05:30 -0700567func indexPathList(s Path, list []Path) int {
568 for i, l := range list {
569 if l == s {
570 return i
571 }
572 }
573
574 return -1
575}
576
577func inPathList(p Path, list []Path) bool {
578 return indexPathList(p, list) != -1
579}
580
581func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000582 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
583}
584
585func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700586 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000587 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700588 filtered = append(filtered, l)
589 } else {
590 remainder = append(remainder, l)
591 }
592 }
593
594 return
595}
596
Colin Cross93e85952017-08-15 13:34:18 -0700597// HasExt returns true of any of the paths have extension ext, otherwise false
598func (p Paths) HasExt(ext string) bool {
599 for _, path := range p {
600 if path.Ext() == ext {
601 return true
602 }
603 }
604
605 return false
606}
607
608// FilterByExt returns the subset of the paths that have extension ext
609func (p Paths) FilterByExt(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
619// FilterOutByExt returns the subset of the paths that do not have extension ext
620func (p Paths) FilterOutByExt(ext string) Paths {
621 ret := make(Paths, 0, len(p))
622 for _, path := range p {
623 if path.Ext() != ext {
624 ret = append(ret, path)
625 }
626 }
627 return ret
628}
629
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700630// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
631// (including subdirectories) are in a contiguous subslice of the list, and can be found in
632// O(log(N)) time using a binary search on the directory prefix.
633type DirectorySortedPaths Paths
634
635func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
636 ret := append(DirectorySortedPaths(nil), paths...)
637 sort.Slice(ret, func(i, j int) bool {
638 return ret[i].String() < ret[j].String()
639 })
640 return ret
641}
642
643// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
644// that are in the specified directory and its subdirectories.
645func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
646 prefix := filepath.Clean(dir) + "/"
647 start := sort.Search(len(p), func(i int) bool {
648 return prefix < p[i].String()
649 })
650
651 ret := p[start:]
652
653 end := sort.Search(len(ret), func(i int) bool {
654 return !strings.HasPrefix(ret[i].String(), prefix)
655 })
656
657 ret = ret[:end]
658
659 return Paths(ret)
660}
661
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700662// WritablePaths is a slice of WritablePaths, used for multiple outputs.
663type WritablePaths []WritablePath
664
665// Strings returns the string forms of the writable paths.
666func (p WritablePaths) Strings() []string {
667 if p == nil {
668 return nil
669 }
670 ret := make([]string, len(p))
671 for i, path := range p {
672 ret[i] = path.String()
673 }
674 return ret
675}
676
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800677// Paths returns the WritablePaths as a Paths
678func (p WritablePaths) Paths() Paths {
679 if p == nil {
680 return nil
681 }
682 ret := make(Paths, len(p))
683 for i, path := range p {
684 ret[i] = path
685 }
686 return ret
687}
688
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700689type basePath struct {
690 path string
691 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800692 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700693}
694
695func (p basePath) Ext() string {
696 return filepath.Ext(p.path)
697}
698
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700699func (p basePath) Base() string {
700 return filepath.Base(p.path)
701}
702
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800703func (p basePath) Rel() string {
704 if p.rel != "" {
705 return p.rel
706 }
707 return p.path
708}
709
Colin Cross0875c522017-11-28 17:34:01 -0800710func (p basePath) String() string {
711 return p.path
712}
713
Colin Cross0db55682017-12-05 15:36:55 -0800714func (p basePath) withRel(rel string) basePath {
715 p.path = filepath.Join(p.path, rel)
716 p.rel = rel
717 return p
718}
719
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700720// SourcePath is a Path representing a file path rooted from SrcDir
721type SourcePath struct {
722 basePath
723}
724
725var _ Path = SourcePath{}
726
Colin Cross0db55682017-12-05 15:36:55 -0800727func (p SourcePath) withRel(rel string) SourcePath {
728 p.basePath = p.basePath.withRel(rel)
729 return p
730}
731
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700732// safePathForSource is for paths that we expect are safe -- only for use by go
733// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700734func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
735 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800736 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700737 if err != nil {
738 return ret, err
739 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700740
Colin Cross7b3dcc32019-01-24 13:14:39 -0800741 // absolute path already checked by validateSafePath
742 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800743 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700744 }
745
Colin Crossfe4bc362018-09-12 10:02:13 -0700746 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700747}
748
Colin Cross192e97a2018-02-22 14:21:02 -0800749// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
750func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000751 p, err := validatePath(pathComponents...)
752 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800753 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800754 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800755 }
756
Colin Cross7b3dcc32019-01-24 13:14:39 -0800757 // absolute path already checked by validatePath
758 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800759 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000760 }
761
Colin Cross192e97a2018-02-22 14:21:02 -0800762 return ret, nil
763}
764
765// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
766// path does not exist.
767func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
768 var files []string
769
770 if gctx, ok := ctx.(PathGlobContext); ok {
771 // Use glob to produce proper dependencies, even though we only want
772 // a single file.
773 files, err = gctx.GlobWithDeps(path.String(), nil)
774 } else {
775 var deps []string
776 // We cannot add build statements in this context, so we fall back to
777 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +0000778 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800779 ctx.AddNinjaFileDeps(deps...)
780 }
781
782 if err != nil {
783 return false, fmt.Errorf("glob: %s", err.Error())
784 }
785
786 return len(files) > 0, nil
787}
788
789// PathForSource joins the provided path components and validates that the result
790// neither escapes the source dir nor is in the out dir.
791// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
792func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
793 path, err := pathForSource(ctx, pathComponents...)
794 if err != nil {
795 reportPathError(ctx, err)
796 }
797
Colin Crosse3924e12018-08-15 20:18:53 -0700798 if pathtools.IsGlob(path.String()) {
799 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
800 }
801
Colin Cross192e97a2018-02-22 14:21:02 -0800802 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
803 exists, err := existsWithDependencies(ctx, path)
804 if err != nil {
805 reportPathError(ctx, err)
806 }
807 if !exists {
808 modCtx.AddMissingDependencies([]string{path.String()})
809 }
Colin Cross988414c2020-01-11 01:11:46 +0000810 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800811 reportPathErrorf(ctx, "%s: %s", path, err.Error())
Colin Cross5e6a7972020-06-07 16:56:32 -0700812 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800813 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800814 }
815 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700816}
817
Jeff Gaston734e3802017-04-10 15:47:24 -0700818// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700819// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
820// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800821func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800822 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800823 if err != nil {
824 reportPathError(ctx, err)
825 return OptionalPath{}
826 }
Colin Crossc48c1432018-02-23 07:09:01 +0000827
Colin Crosse3924e12018-08-15 20:18:53 -0700828 if pathtools.IsGlob(path.String()) {
829 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
830 return OptionalPath{}
831 }
832
Colin Cross192e97a2018-02-22 14:21:02 -0800833 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000834 if err != nil {
835 reportPathError(ctx, err)
836 return OptionalPath{}
837 }
Colin Cross192e97a2018-02-22 14:21:02 -0800838 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000839 return OptionalPath{}
840 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700841 return OptionalPathForPath(path)
842}
843
844func (p SourcePath) String() string {
845 return filepath.Join(p.config.srcDir, p.path)
846}
847
848// Join creates a new SourcePath with paths... joined with the current path. The
849// provided paths... may not use '..' to escape from the current path.
850func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800851 path, err := validatePath(paths...)
852 if err != nil {
853 reportPathError(ctx, err)
854 }
Colin Cross0db55682017-12-05 15:36:55 -0800855 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700856}
857
Colin Cross2fafa3e2019-03-05 12:39:51 -0800858// join is like Join but does less path validation.
859func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
860 path, err := validateSafePath(paths...)
861 if err != nil {
862 reportPathError(ctx, err)
863 }
864 return p.withRel(path)
865}
866
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700867// OverlayPath returns the overlay for `path' if it exists. This assumes that the
868// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700869func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700870 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800871 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700872 relDir = srcPath.path
873 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800874 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700875 return OptionalPath{}
876 }
877 dir := filepath.Join(p.config.srcDir, p.path, relDir)
878 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700879 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800880 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800881 }
Colin Cross461b4452018-02-23 09:22:42 -0800882 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700883 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800884 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700885 return OptionalPath{}
886 }
887 if len(paths) == 0 {
888 return OptionalPath{}
889 }
Colin Cross43f08db2018-11-12 10:13:39 -0800890 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700891 return OptionalPathForPath(PathForSource(ctx, relPath))
892}
893
Colin Cross70dda7e2019-10-01 22:05:35 -0700894// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700895type OutputPath struct {
896 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -0800897 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700898}
899
Colin Cross702e0f82017-10-18 17:27:54 -0700900func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800901 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -0800902 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700903 return p
904}
905
Colin Cross3063b782018-08-15 11:19:12 -0700906func (p OutputPath) WithoutRel() OutputPath {
907 p.basePath.rel = filepath.Base(p.basePath.path)
908 return p
909}
910
Paul Duffin9b478b02019-12-10 13:41:51 +0000911func (p OutputPath) buildDir() string {
912 return p.config.buildDir
913}
914
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700915var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +0000916var _ WritablePath = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700917
Chris Parsons8f232a22020-06-23 17:37:05 -0400918// toolDepPath is a Path representing a dependency of the build tool.
919type toolDepPath struct {
920 basePath
921}
922
923var _ Path = toolDepPath{}
924
925// pathForBuildToolDep returns a toolDepPath representing the given path string.
926// There is no validation for the path, as it is "trusted": It may fail
927// normal validation checks. For example, it may be an absolute path.
928// Only use this function to construct paths for dependencies of the build
929// tool invocation.
930func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
931 return toolDepPath{basePath{path, ctx.Config(), ""}}
932}
933
Jeff Gaston734e3802017-04-10 15:47:24 -0700934// PathForOutput joins the provided paths and returns an OutputPath that is
935// validated to not escape the build dir.
936// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
937func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800938 path, err := validatePath(pathComponents...)
939 if err != nil {
940 reportPathError(ctx, err)
941 }
Colin Crossd63c9a72020-01-29 16:52:50 -0800942 fullPath := filepath.Join(ctx.Config().buildDir, path)
943 path = fullPath[len(fullPath)-len(path):]
944 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700945}
946
Colin Cross40e33732019-02-15 11:08:35 -0800947// PathsForOutput returns Paths rooted from buildDir
948func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
949 ret := make(WritablePaths, len(paths))
950 for i, path := range paths {
951 ret[i] = PathForOutput(ctx, path)
952 }
953 return ret
954}
955
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700956func (p OutputPath) writablePath() {}
957
958func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -0800959 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700960}
961
962// Join creates a new OutputPath with paths... joined with the current path. The
963// provided paths... may not use '..' to escape from the current path.
964func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800965 path, err := validatePath(paths...)
966 if err != nil {
967 reportPathError(ctx, err)
968 }
Colin Cross0db55682017-12-05 15:36:55 -0800969 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700970}
971
Colin Cross8854a5a2019-02-11 14:14:16 -0800972// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
973func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
974 if strings.Contains(ext, "/") {
975 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
976 }
977 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800978 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800979 return ret
980}
981
Colin Cross40e33732019-02-15 11:08:35 -0800982// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
983func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
984 path, err := validatePath(paths...)
985 if err != nil {
986 reportPathError(ctx, err)
987 }
988
989 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800990 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800991 return ret
992}
993
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700994// PathForIntermediates returns an OutputPath representing the top-level
995// intermediates directory.
996func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800997 path, err := validatePath(paths...)
998 if err != nil {
999 reportPathError(ctx, err)
1000 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001001 return PathForOutput(ctx, ".intermediates", path)
1002}
1003
Colin Cross07e51612019-03-05 12:46:40 -08001004var _ genPathProvider = SourcePath{}
1005var _ objPathProvider = SourcePath{}
1006var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001007
Colin Cross07e51612019-03-05 12:46:40 -08001008// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001009// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -08001010func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
1011 p, err := validatePath(pathComponents...)
1012 if err != nil {
1013 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001014 }
Colin Cross8a497952019-03-05 22:25:09 -08001015 paths, err := expandOneSrcPath(ctx, p, nil)
1016 if err != nil {
1017 if depErr, ok := err.(missingDependencyError); ok {
1018 if ctx.Config().AllowMissingDependencies() {
1019 ctx.AddMissingDependencies(depErr.missingDeps)
1020 } else {
1021 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1022 }
1023 } else {
1024 reportPathError(ctx, err)
1025 }
1026 return nil
1027 } else if len(paths) == 0 {
1028 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
1029 return nil
1030 } else if len(paths) > 1 {
1031 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
1032 }
1033 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001034}
1035
Colin Cross07e51612019-03-05 12:46:40 -08001036func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
1037 p, err := validatePath(paths...)
1038 if err != nil {
1039 reportPathError(ctx, err)
1040 }
1041
1042 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1043 if err != nil {
1044 reportPathError(ctx, err)
1045 }
1046
1047 path.basePath.rel = p
1048
1049 return path
1050}
1051
Colin Cross2fafa3e2019-03-05 12:39:51 -08001052// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1053// will return the path relative to subDir in the module's source directory. If any input paths are not located
1054// inside subDir then a path error will be reported.
1055func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
1056 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001057 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001058 for i, path := range paths {
1059 rel := Rel(ctx, subDirFullPath.String(), path.String())
1060 paths[i] = subDirFullPath.join(ctx, rel)
1061 }
1062 return paths
1063}
1064
1065// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1066// module's source directory. If the input path is not located inside subDir then a path error will be reported.
1067func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001068 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001069 rel := Rel(ctx, subDirFullPath.String(), path.String())
1070 return subDirFullPath.Join(ctx, rel)
1071}
1072
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001073// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1074// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -07001075func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001076 if p == nil {
1077 return OptionalPath{}
1078 }
1079 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1080}
1081
Colin Cross07e51612019-03-05 12:46:40 -08001082func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001083 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001084}
1085
Colin Cross07e51612019-03-05 12:46:40 -08001086func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001087 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001088}
1089
Colin Cross07e51612019-03-05 12:46:40 -08001090func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001091 // TODO: Use full directory if the new ctx is not the current ctx?
1092 return PathForModuleRes(ctx, p.path, name)
1093}
1094
1095// ModuleOutPath is a Path representing a module's output directory.
1096type ModuleOutPath struct {
1097 OutputPath
1098}
1099
1100var _ Path = ModuleOutPath{}
1101
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001102func (p ModuleOutPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
1103 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1104}
1105
Colin Cross702e0f82017-10-18 17:27:54 -07001106func pathForModule(ctx ModuleContext) OutputPath {
1107 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1108}
1109
Logan Chien7eefdc42018-07-11 18:10:41 +08001110// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1111// reference abi dump for the given module. This is not guaranteed to be valid.
1112func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001113 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001114
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001115 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001116 if len(arches) == 0 {
1117 panic("device build with no primary arch")
1118 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001119 currentArch := ctx.Arch()
1120 archNameAndVariant := currentArch.ArchType.String()
1121 if currentArch.ArchVariant != "" {
1122 archNameAndVariant += "_" + currentArch.ArchVariant
1123 }
Logan Chien5237bed2018-07-11 17:15:57 +08001124
1125 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001126 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001127 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001128 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001129 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001130 } else {
1131 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001132 }
Logan Chien5237bed2018-07-11 17:15:57 +08001133
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001134 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001135
1136 var ext string
1137 if isGzip {
1138 ext = ".lsdump.gz"
1139 } else {
1140 ext = ".lsdump"
1141 }
1142
1143 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1144 version, binderBitness, archNameAndVariant, "source-based",
1145 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001146}
1147
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001148// PathForModuleOut returns a Path representing the paths... under the module's
1149// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001150func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001151 p, err := validatePath(paths...)
1152 if err != nil {
1153 reportPathError(ctx, err)
1154 }
Colin Cross702e0f82017-10-18 17:27:54 -07001155 return ModuleOutPath{
1156 OutputPath: pathForModule(ctx).withRel(p),
1157 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001158}
1159
1160// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1161// directory. Mainly used for generated sources.
1162type ModuleGenPath struct {
1163 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001164}
1165
1166var _ Path = ModuleGenPath{}
1167var _ genPathProvider = ModuleGenPath{}
1168var _ objPathProvider = ModuleGenPath{}
1169
1170// PathForModuleGen returns a Path representing the paths... under the module's
1171// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001172func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001173 p, err := validatePath(paths...)
1174 if err != nil {
1175 reportPathError(ctx, err)
1176 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001177 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001178 ModuleOutPath: ModuleOutPath{
1179 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1180 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001181 }
1182}
1183
Dan Willemsen21ec4902016-11-02 20:43:13 -07001184func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001185 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001186 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001187}
1188
Colin Cross635c3b02016-05-18 15:37:25 -07001189func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001190 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1191}
1192
1193// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1194// directory. Used for compiled objects.
1195type ModuleObjPath struct {
1196 ModuleOutPath
1197}
1198
1199var _ Path = ModuleObjPath{}
1200
1201// PathForModuleObj returns a Path representing the paths... under the module's
1202// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001203func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001204 p, err := validatePath(pathComponents...)
1205 if err != nil {
1206 reportPathError(ctx, err)
1207 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001208 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1209}
1210
1211// ModuleResPath is a a Path representing the 'res' directory in a module's
1212// output directory.
1213type ModuleResPath struct {
1214 ModuleOutPath
1215}
1216
1217var _ Path = ModuleResPath{}
1218
1219// PathForModuleRes returns a Path representing the paths... under the module's
1220// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001221func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001222 p, err := validatePath(pathComponents...)
1223 if err != nil {
1224 reportPathError(ctx, err)
1225 }
1226
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001227 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1228}
1229
Colin Cross70dda7e2019-10-01 22:05:35 -07001230// InstallPath is a Path representing a installed file path rooted from the build directory
1231type InstallPath struct {
1232 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001233
1234 baseDir string // "../" for Make paths to convert "out/soong" to "out", "" for Soong paths
Colin Cross70dda7e2019-10-01 22:05:35 -07001235}
1236
Paul Duffin9b478b02019-12-10 13:41:51 +00001237func (p InstallPath) buildDir() string {
1238 return p.config.buildDir
1239}
1240
1241var _ Path = InstallPath{}
1242var _ WritablePath = InstallPath{}
1243
Colin Cross70dda7e2019-10-01 22:05:35 -07001244func (p InstallPath) writablePath() {}
1245
1246func (p InstallPath) String() string {
Colin Crossff6c33d2019-10-02 16:01:35 -07001247 return filepath.Join(p.config.buildDir, p.baseDir, p.path)
Colin Cross70dda7e2019-10-01 22:05:35 -07001248}
1249
1250// Join creates a new InstallPath with paths... joined with the current path. The
1251// provided paths... may not use '..' to escape from the current path.
1252func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1253 path, err := validatePath(paths...)
1254 if err != nil {
1255 reportPathError(ctx, err)
1256 }
1257 return p.withRel(path)
1258}
1259
1260func (p InstallPath) withRel(rel string) InstallPath {
1261 p.basePath = p.basePath.withRel(rel)
1262 return p
1263}
1264
Colin Crossff6c33d2019-10-02 16:01:35 -07001265// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1266// i.e. out/ instead of out/soong/.
1267func (p InstallPath) ToMakePath() InstallPath {
1268 p.baseDir = "../"
1269 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001270}
1271
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001272// PathForModuleInstall returns a Path representing the install path for the
1273// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001274func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001275 os := ctx.Os()
1276 if forceOS := ctx.InstallForceOS(); forceOS != nil {
1277 os = *forceOS
1278 }
1279 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001280
1281 ret := pathForInstall(ctx, os, partition, ctx.Debug(), pathComponents...)
1282
1283 if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
1284 ret = ret.ToMakePath()
1285 }
1286
1287 return ret
1288}
1289
1290func pathForInstall(ctx PathContext, os OsType, partition string, debug bool,
1291 pathComponents ...string) InstallPath {
1292
1293 var outPaths []string
1294
Colin Cross6e359402020-02-10 15:29:54 -08001295 if os.Class == Device {
Colin Cross6510f912017-11-29 00:27:14 -08001296 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001297 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001298 switch os {
Dan Willemsen866b5632017-09-22 12:28:24 -07001299 case Linux:
Colin Cross6e359402020-02-10 15:29:54 -08001300 outPaths = []string{"host", "linux-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001301 case LinuxBionic:
1302 // TODO: should this be a separate top level, or shared with linux-x86?
Colin Cross6e359402020-02-10 15:29:54 -08001303 outPaths = []string{"host", "linux_bionic-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001304 default:
Colin Cross6e359402020-02-10 15:29:54 -08001305 outPaths = []string{"host", os.String() + "-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001306 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001307 }
Colin Cross609c49a2020-02-13 13:20:11 -08001308 if debug {
Dan Willemsen782a2d12015-12-21 14:55:28 -08001309 outPaths = append([]string{"debug"}, outPaths...)
1310 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001311 outPaths = append(outPaths, pathComponents...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001312
1313 path, err := validatePath(outPaths...)
1314 if err != nil {
1315 reportPathError(ctx, err)
1316 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001317
1318 ret := InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Crossff6c33d2019-10-02 16:01:35 -07001319
1320 return ret
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001321}
1322
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001323func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
1324 paths = append([]string{prefix}, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001325 path, err := validatePath(paths...)
1326 if err != nil {
1327 reportPathError(ctx, err)
1328 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001329 return InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Cross70dda7e2019-10-01 22:05:35 -07001330}
1331
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001332func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1333 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1334}
1335
1336func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1337 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1338}
1339
Colin Cross70dda7e2019-10-01 22:05:35 -07001340func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001341 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1342
1343 return "/" + rel
1344}
1345
Colin Cross6e359402020-02-10 15:29:54 -08001346func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001347 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001348 if ctx.InstallInTestcases() {
1349 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001350 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001351 } else if os.Class == Device {
1352 if ctx.InstallInData() {
1353 partition = "data"
1354 } else if ctx.InstallInRamdisk() {
1355 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1356 partition = "recovery/root/first_stage_ramdisk"
1357 } else {
1358 partition = "ramdisk"
1359 }
1360 if !ctx.InstallInRoot() {
1361 partition += "/system"
1362 }
1363 } else if ctx.InstallInRecovery() {
1364 if ctx.InstallInRoot() {
1365 partition = "recovery/root"
1366 } else {
1367 // the layout of recovery partion is the same as that of system partition
1368 partition = "recovery/root/system"
1369 }
1370 } else if ctx.SocSpecific() {
1371 partition = ctx.DeviceConfig().VendorPath()
1372 } else if ctx.DeviceSpecific() {
1373 partition = ctx.DeviceConfig().OdmPath()
1374 } else if ctx.ProductSpecific() {
1375 partition = ctx.DeviceConfig().ProductPath()
1376 } else if ctx.SystemExtSpecific() {
1377 partition = ctx.DeviceConfig().SystemExtPath()
1378 } else if ctx.InstallInRoot() {
1379 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001380 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001381 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001382 }
Colin Cross6e359402020-02-10 15:29:54 -08001383 if ctx.InstallInSanitizerDir() {
1384 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001385 }
Colin Cross43f08db2018-11-12 10:13:39 -08001386 }
1387 return partition
1388}
1389
Colin Cross609c49a2020-02-13 13:20:11 -08001390type InstallPaths []InstallPath
1391
1392// Paths returns the InstallPaths as a Paths
1393func (p InstallPaths) Paths() Paths {
1394 if p == nil {
1395 return nil
1396 }
1397 ret := make(Paths, len(p))
1398 for i, path := range p {
1399 ret[i] = path
1400 }
1401 return ret
1402}
1403
1404// Strings returns the string forms of the install paths.
1405func (p InstallPaths) Strings() []string {
1406 if p == nil {
1407 return nil
1408 }
1409 ret := make([]string, len(p))
1410 for i, path := range p {
1411 ret[i] = path.String()
1412 }
1413 return ret
1414}
1415
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001416// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001417// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001418func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001419 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001420 path := filepath.Clean(path)
1421 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001422 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001423 }
1424 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001425 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1426 // variables. '..' may remove the entire ninja variable, even if it
1427 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001428 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001429}
1430
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001431// validatePath validates that a path does not include ninja variables, and that
1432// each path component does not attempt to leave its component. Returns a joined
1433// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001434func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001435 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001436 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001437 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001438 }
1439 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001440 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001441}
Colin Cross5b529592017-05-09 13:34:34 -07001442
Colin Cross0875c522017-11-28 17:34:01 -08001443func PathForPhony(ctx PathContext, phony string) WritablePath {
1444 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001445 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001446 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001447 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001448}
1449
Colin Cross74e3fe42017-12-11 15:51:44 -08001450type PhonyPath struct {
1451 basePath
1452}
1453
1454func (p PhonyPath) writablePath() {}
1455
Paul Duffin9b478b02019-12-10 13:41:51 +00001456func (p PhonyPath) buildDir() string {
1457 return p.config.buildDir
1458}
1459
Colin Cross74e3fe42017-12-11 15:51:44 -08001460var _ Path = PhonyPath{}
1461var _ WritablePath = PhonyPath{}
1462
Colin Cross5b529592017-05-09 13:34:34 -07001463type testPath struct {
1464 basePath
1465}
1466
1467func (p testPath) String() string {
1468 return p.path
1469}
1470
Colin Cross40e33732019-02-15 11:08:35 -08001471// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1472// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001473func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001474 p, err := validateSafePath(paths...)
1475 if err != nil {
1476 panic(err)
1477 }
Colin Cross5b529592017-05-09 13:34:34 -07001478 return testPath{basePath{path: p, rel: p}}
1479}
1480
Colin Cross40e33732019-02-15 11:08:35 -08001481// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1482func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001483 p := make(Paths, len(strs))
1484 for i, s := range strs {
1485 p[i] = PathForTesting(s)
1486 }
1487
1488 return p
1489}
Colin Cross43f08db2018-11-12 10:13:39 -08001490
Colin Cross40e33732019-02-15 11:08:35 -08001491type testPathContext struct {
1492 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001493}
1494
Colin Cross40e33732019-02-15 11:08:35 -08001495func (x *testPathContext) Config() Config { return x.config }
1496func (x *testPathContext) AddNinjaFileDeps(...string) {}
1497
1498// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1499// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001500func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001501 return &testPathContext{
1502 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001503 }
1504}
1505
Colin Cross43f08db2018-11-12 10:13:39 -08001506// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1507// targetPath is not inside basePath.
1508func Rel(ctx PathContext, basePath string, targetPath string) string {
1509 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1510 if !isRel {
1511 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1512 return ""
1513 }
1514 return rel
1515}
1516
1517// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1518// targetPath is not inside basePath.
1519func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001520 rel, isRel, err := maybeRelErr(basePath, targetPath)
1521 if err != nil {
1522 reportPathError(ctx, err)
1523 }
1524 return rel, isRel
1525}
1526
1527func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001528 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1529 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001530 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001531 }
1532 rel, err := filepath.Rel(basePath, targetPath)
1533 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001534 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001535 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001536 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001537 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001538 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001539}
Colin Cross988414c2020-01-11 01:11:46 +00001540
1541// Writes a file to the output directory. Attempting to write directly to the output directory
1542// will fail due to the sandbox of the soong_build process.
1543func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1544 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1545}
1546
1547func absolutePath(path string) string {
1548 if filepath.IsAbs(path) {
1549 return path
1550 }
1551 return filepath.Join(absSrcDir, path)
1552}