blob: 8d2725b9afe54e57c16f915b0dcf9e9ed2e5af3d [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Colin Cross6e18ca42015-07-14 18:55:36 -070018 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000019 "io/ioutil"
20 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070021 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070022 "reflect"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070023 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070024 "strings"
25
26 "github.com/google/blueprint"
27 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080028)
29
Colin Cross988414c2020-01-11 01:11:46 +000030var absSrcDir string
31
Dan Willemsen34cc69e2015-09-23 15:26:20 -070032// PathContext is the subset of a (Module|Singleton)Context required by the
33// Path methods.
34type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080035 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080036 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080037}
38
Colin Cross7f19f372016-11-01 11:10:25 -070039type PathGlobContext interface {
40 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
41}
42
Colin Crossaabf6792017-11-29 00:27:14 -080043var _ PathContext = SingletonContext(nil)
44var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070045
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010046// "Null" path context is a minimal path context for a given config.
47type NullPathContext struct {
48 config Config
49}
50
51func (NullPathContext) AddNinjaFileDeps(...string) {}
52func (ctx NullPathContext) Config() Config { return ctx.config }
53
Dan Willemsen00269f22017-07-06 16:59:48 -070054type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -070055 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -070056
57 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -070058 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -070059 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -080060 InstallInRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +090061 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -070062 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -070063 InstallBypassMake() bool
Colin Cross6e359402020-02-10 15:29:54 -080064 InstallForceOS() *OsType
Dan Willemsen00269f22017-07-06 16:59:48 -070065}
66
67var _ ModuleInstallPathContext = ModuleContext(nil)
68
Dan Willemsen34cc69e2015-09-23 15:26:20 -070069// errorfContext is the interface containing the Errorf method matching the
70// Errorf method in blueprint.SingletonContext.
71type errorfContext interface {
72 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080073}
74
Dan Willemsen34cc69e2015-09-23 15:26:20 -070075var _ errorfContext = blueprint.SingletonContext(nil)
76
77// moduleErrorf is the interface containing the ModuleErrorf method matching
78// the ModuleErrorf method in blueprint.ModuleContext.
79type moduleErrorf interface {
80 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080081}
82
Dan Willemsen34cc69e2015-09-23 15:26:20 -070083var _ moduleErrorf = blueprint.ModuleContext(nil)
84
Dan Willemsen34cc69e2015-09-23 15:26:20 -070085// reportPathError will register an error with the attached context. It
86// attempts ctx.ModuleErrorf for a better error message first, then falls
87// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -080088func reportPathError(ctx PathContext, err error) {
89 reportPathErrorf(ctx, "%s", err.Error())
90}
91
92// reportPathErrorf will register an error with the attached context. It
93// attempts ctx.ModuleErrorf for a better error message first, then falls
94// back to ctx.Errorf.
95func reportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -070096 if mctx, ok := ctx.(moduleErrorf); ok {
97 mctx.ModuleErrorf(format, args...)
98 } else if ectx, ok := ctx.(errorfContext); ok {
99 ectx.Errorf(format, args...)
100 } else {
101 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700102 }
103}
104
Colin Cross5e708052019-08-06 13:59:50 -0700105func pathContextName(ctx PathContext, module blueprint.Module) string {
106 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
107 return x.ModuleName(module)
108 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
109 return x.OtherModuleName(module)
110 }
111 return "unknown"
112}
113
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700114type Path interface {
115 // Returns the path in string form
116 String() string
117
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700118 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700119 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700120
121 // Base returns the last element of the path
122 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800123
124 // Rel returns the portion of the path relative to the directory it was created from. For
125 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800126 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800127 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700128}
129
130// WritablePath is a type of path that can be used as an output for build rules.
131type WritablePath interface {
132 Path
133
Paul Duffin9b478b02019-12-10 13:41:51 +0000134 // return the path to the build directory.
135 buildDir() string
136
Jeff Gaston734e3802017-04-10 15:47:24 -0700137 // the writablePath method doesn't directly do anything,
138 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700139 writablePath()
140}
141
142type genPathProvider interface {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700143 genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700144}
145type objPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700146 objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700147}
148type resPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700149 resPathWithName(ctx ModuleContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700150}
151
152// GenPathWithExt derives a new file path in ctx's generated sources directory
153// from the current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700154func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700155 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700156 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700157 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800158 reportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700159 return PathForModuleGen(ctx)
160}
161
162// ObjPathWithExt derives a new file path in ctx's object directory from the
163// current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700164func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700165 if path, ok := p.(objPathProvider); ok {
166 return path.objPathWithExt(ctx, subdir, ext)
167 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800168 reportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700169 return PathForModuleObj(ctx)
170}
171
172// ResPathWithName derives a new path in ctx's output resource directory, using
173// the current path to create the directory name, and the `name` argument for
174// the filename.
Colin Cross635c3b02016-05-18 15:37:25 -0700175func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700176 if path, ok := p.(resPathProvider); ok {
177 return path.resPathWithName(ctx, name)
178 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800179 reportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700180 return PathForModuleRes(ctx)
181}
182
183// OptionalPath is a container that may or may not contain a valid Path.
184type OptionalPath struct {
185 valid bool
186 path Path
187}
188
189// OptionalPathForPath returns an OptionalPath containing the path.
190func OptionalPathForPath(path Path) OptionalPath {
191 if path == nil {
192 return OptionalPath{}
193 }
194 return OptionalPath{valid: true, path: path}
195}
196
197// Valid returns whether there is a valid path
198func (p OptionalPath) Valid() bool {
199 return p.valid
200}
201
202// Path returns the Path embedded in this OptionalPath. You must be sure that
203// there is a valid path, since this method will panic if there is not.
204func (p OptionalPath) Path() Path {
205 if !p.valid {
206 panic("Requesting an invalid path")
207 }
208 return p.path
209}
210
211// String returns the string version of the Path, or "" if it isn't valid.
212func (p OptionalPath) String() string {
213 if p.valid {
214 return p.path.String()
215 } else {
216 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700217 }
218}
Colin Cross6e18ca42015-07-14 18:55:36 -0700219
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700220// Paths is a slice of Path objects, with helpers to operate on the collection.
221type Paths []Path
222
223// PathsForSource returns Paths rooted from SrcDir
224func PathsForSource(ctx PathContext, paths []string) Paths {
225 ret := make(Paths, len(paths))
226 for i, path := range paths {
227 ret[i] = PathForSource(ctx, path)
228 }
229 return ret
230}
231
Jeff Gaston734e3802017-04-10 15:47:24 -0700232// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800233// found in the tree. If any are not found, they are omitted from the list,
234// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800235func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800236 ret := make(Paths, 0, len(paths))
237 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800238 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800239 if p.Valid() {
240 ret = append(ret, p.Path())
241 }
242 }
243 return ret
244}
245
Colin Cross41955e82019-05-29 14:40:35 -0700246// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
247// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
248// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
249// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
250// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
251// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Colin Cross635c3b02016-05-18 15:37:25 -0700252func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800253 return PathsForModuleSrcExcludes(ctx, paths, nil)
254}
255
Colin Crossba71a3f2019-03-18 12:12:48 -0700256// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700257// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
258// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
259// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
260// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100261// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700262// having missing dependencies.
Colin Cross8a497952019-03-05 22:25:09 -0800263func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700264 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
265 if ctx.Config().AllowMissingDependencies() {
266 ctx.AddMissingDependencies(missingDeps)
267 } else {
268 for _, m := range missingDeps {
269 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
270 }
271 }
272 return ret
273}
274
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000275// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
276type OutputPaths []OutputPath
277
278// Paths returns the OutputPaths as a Paths
279func (p OutputPaths) Paths() Paths {
280 if p == nil {
281 return nil
282 }
283 ret := make(Paths, len(p))
284 for i, path := range p {
285 ret[i] = path
286 }
287 return ret
288}
289
290// Strings returns the string forms of the writable paths.
291func (p OutputPaths) Strings() []string {
292 if p == nil {
293 return nil
294 }
295 ret := make([]string, len(p))
296 for i, path := range p {
297 ret[i] = path.String()
298 }
299 return ret
300}
301
Colin Crossba71a3f2019-03-18 12:12:48 -0700302// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700303// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
304// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
305// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
306// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
307// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
308// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
309// dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700310func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800311 prefix := pathForModuleSrc(ctx).String()
312
313 var expandedExcludes []string
314 if excludes != nil {
315 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700316 }
Colin Cross8a497952019-03-05 22:25:09 -0800317
Colin Crossba71a3f2019-03-18 12:12:48 -0700318 var missingExcludeDeps []string
319
Colin Cross8a497952019-03-05 22:25:09 -0800320 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700321 if m, t := SrcIsModuleWithTag(e); m != "" {
322 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800323 if module == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700324 missingExcludeDeps = append(missingExcludeDeps, m)
Colin Cross8a497952019-03-05 22:25:09 -0800325 continue
326 }
Colin Cross41955e82019-05-29 14:40:35 -0700327 if outProducer, ok := module.(OutputFileProducer); ok {
328 outputFiles, err := outProducer.OutputFiles(t)
329 if err != nil {
330 ctx.ModuleErrorf("path dependency %q: %s", e, err)
331 }
332 expandedExcludes = append(expandedExcludes, outputFiles.Strings()...)
333 } else if t != "" {
334 ctx.ModuleErrorf("path dependency %q is not an output file producing module", e)
335 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800336 expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
337 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700338 ctx.ModuleErrorf("path dependency %q is not a source file producing module", e)
Colin Cross8a497952019-03-05 22:25:09 -0800339 }
340 } else {
341 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
342 }
343 }
344
345 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700346 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800347 }
348
Colin Crossba71a3f2019-03-18 12:12:48 -0700349 var missingDeps []string
350
Colin Cross8a497952019-03-05 22:25:09 -0800351 expandedSrcFiles := make(Paths, 0, len(paths))
352 for _, s := range paths {
353 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
354 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700355 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800356 } else if err != nil {
357 reportPathError(ctx, err)
358 }
359 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
360 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700361
362 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800363}
364
365type missingDependencyError struct {
366 missingDeps []string
367}
368
369func (e missingDependencyError) Error() string {
370 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
371}
372
373func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
Colin Cross41955e82019-05-29 14:40:35 -0700374 if m, t := SrcIsModuleWithTag(s); m != "" {
375 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800376 if module == nil {
377 return nil, missingDependencyError{[]string{m}}
378 }
Colin Cross41955e82019-05-29 14:40:35 -0700379 if outProducer, ok := module.(OutputFileProducer); ok {
380 outputFiles, err := outProducer.OutputFiles(t)
381 if err != nil {
382 return nil, fmt.Errorf("path dependency %q: %s", s, err)
383 }
384 return outputFiles, nil
385 } else if t != "" {
386 return nil, fmt.Errorf("path dependency %q is not an output file producing module", s)
387 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800388 moduleSrcs := srcProducer.Srcs()
389 for _, e := range expandedExcludes {
390 for j := 0; j < len(moduleSrcs); j++ {
391 if moduleSrcs[j].String() == e {
392 moduleSrcs = append(moduleSrcs[:j], moduleSrcs[j+1:]...)
393 j--
394 }
395 }
396 }
397 return moduleSrcs, nil
398 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700399 return nil, fmt.Errorf("path dependency %q is not a source file producing module", s)
Colin Cross8a497952019-03-05 22:25:09 -0800400 }
401 } else if pathtools.IsGlob(s) {
402 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
403 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
404 } else {
405 p := pathForModuleSrc(ctx, s)
Colin Cross988414c2020-01-11 01:11:46 +0000406 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Colin Cross8a497952019-03-05 22:25:09 -0800407 reportPathErrorf(ctx, "%s: %s", p, err.Error())
Colin Cross5e6a7972020-06-07 16:56:32 -0700408 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Colin Cross8a497952019-03-05 22:25:09 -0800409 reportPathErrorf(ctx, "module source path %q does not exist", p)
410 }
411
412 j := findStringInSlice(p.String(), expandedExcludes)
413 if j >= 0 {
414 return nil, nil
415 }
416 return Paths{p}, nil
417 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700418}
419
420// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
421// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800422// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700423// It intended for use in globs that only list files that exist, so it allows '$' in
424// filenames.
Colin Cross1184b642019-12-30 18:43:07 -0800425func pathsForModuleSrcFromFullPath(ctx EarlyModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800426 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700427 if prefix == "./" {
428 prefix = ""
429 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700430 ret := make(Paths, 0, len(paths))
431 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800432 if !incDirs && strings.HasSuffix(p, "/") {
433 continue
434 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700435 path := filepath.Clean(p)
436 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800437 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700438 continue
439 }
Colin Crosse3924e12018-08-15 20:18:53 -0700440
Colin Crossfe4bc362018-09-12 10:02:13 -0700441 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700442 if err != nil {
443 reportPathError(ctx, err)
444 continue
445 }
446
Colin Cross07e51612019-03-05 12:46:40 -0800447 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700448
Colin Cross07e51612019-03-05 12:46:40 -0800449 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700450 }
451 return ret
452}
453
454// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800455// local source directory. If input is nil, use the default if it exists. If input is empty, returns nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700456func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800457 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700458 return PathsForModuleSrc(ctx, input)
459 }
460 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
461 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800462 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800463 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700464}
465
466// Strings returns the Paths in string form
467func (p Paths) Strings() []string {
468 if p == nil {
469 return nil
470 }
471 ret := make([]string, len(p))
472 for i, path := range p {
473 ret[i] = path.String()
474 }
475 return ret
476}
477
Colin Crossb6715442017-10-24 11:13:31 -0700478// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
479// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700480func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800481 // 128 was chosen based on BenchmarkFirstUniquePaths results.
482 if len(list) > 128 {
483 return firstUniquePathsMap(list)
484 }
485 return firstUniquePathsList(list)
486}
487
Jiyong Park33c77362020-05-29 22:00:16 +0900488// SortedUniquePaths returns what its name says
489func SortedUniquePaths(list Paths) Paths {
490 unique := FirstUniquePaths(list)
491 sort.Slice(unique, func(i, j int) bool {
492 return unique[i].String() < unique[j].String()
493 })
494 return unique
495}
496
Colin Cross27027c72020-02-28 15:34:17 -0800497func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700498 k := 0
499outer:
500 for i := 0; i < len(list); i++ {
501 for j := 0; j < k; j++ {
502 if list[i] == list[j] {
503 continue outer
504 }
505 }
506 list[k] = list[i]
507 k++
508 }
509 return list[:k]
510}
511
Colin Cross27027c72020-02-28 15:34:17 -0800512func firstUniquePathsMap(list Paths) Paths {
513 k := 0
514 seen := make(map[Path]bool, len(list))
515 for i := 0; i < len(list); i++ {
516 if seen[list[i]] {
517 continue
518 }
519 seen[list[i]] = true
520 list[k] = list[i]
521 k++
522 }
523 return list[:k]
524}
525
Colin Crossb6715442017-10-24 11:13:31 -0700526// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
527// modifies the Paths slice contents in place, and returns a subslice of the original slice.
528func LastUniquePaths(list Paths) Paths {
529 totalSkip := 0
530 for i := len(list) - 1; i >= totalSkip; i-- {
531 skip := 0
532 for j := i - 1; j >= totalSkip; j-- {
533 if list[i] == list[j] {
534 skip++
535 } else {
536 list[j+skip] = list[j]
537 }
538 }
539 totalSkip += skip
540 }
541 return list[totalSkip:]
542}
543
Colin Crossa140bb02018-04-17 10:52:26 -0700544// ReversePaths returns a copy of a Paths in reverse order.
545func ReversePaths(list Paths) Paths {
546 if list == nil {
547 return nil
548 }
549 ret := make(Paths, len(list))
550 for i := range list {
551 ret[i] = list[len(list)-1-i]
552 }
553 return ret
554}
555
Jeff Gaston294356f2017-09-27 17:05:30 -0700556func indexPathList(s Path, list []Path) int {
557 for i, l := range list {
558 if l == s {
559 return i
560 }
561 }
562
563 return -1
564}
565
566func inPathList(p Path, list []Path) bool {
567 return indexPathList(p, list) != -1
568}
569
570func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000571 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
572}
573
574func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700575 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000576 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700577 filtered = append(filtered, l)
578 } else {
579 remainder = append(remainder, l)
580 }
581 }
582
583 return
584}
585
Colin Cross93e85952017-08-15 13:34:18 -0700586// HasExt returns true of any of the paths have extension ext, otherwise false
587func (p Paths) HasExt(ext string) bool {
588 for _, path := range p {
589 if path.Ext() == ext {
590 return true
591 }
592 }
593
594 return false
595}
596
597// FilterByExt returns the subset of the paths that have extension ext
598func (p Paths) FilterByExt(ext string) Paths {
599 ret := make(Paths, 0, len(p))
600 for _, path := range p {
601 if path.Ext() == ext {
602 ret = append(ret, path)
603 }
604 }
605 return ret
606}
607
608// FilterOutByExt returns the subset of the paths that do not have extension ext
609func (p Paths) FilterOutByExt(ext string) Paths {
610 ret := make(Paths, 0, len(p))
611 for _, path := range p {
612 if path.Ext() != ext {
613 ret = append(ret, path)
614 }
615 }
616 return ret
617}
618
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700619// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
620// (including subdirectories) are in a contiguous subslice of the list, and can be found in
621// O(log(N)) time using a binary search on the directory prefix.
622type DirectorySortedPaths Paths
623
624func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
625 ret := append(DirectorySortedPaths(nil), paths...)
626 sort.Slice(ret, func(i, j int) bool {
627 return ret[i].String() < ret[j].String()
628 })
629 return ret
630}
631
632// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
633// that are in the specified directory and its subdirectories.
634func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
635 prefix := filepath.Clean(dir) + "/"
636 start := sort.Search(len(p), func(i int) bool {
637 return prefix < p[i].String()
638 })
639
640 ret := p[start:]
641
642 end := sort.Search(len(ret), func(i int) bool {
643 return !strings.HasPrefix(ret[i].String(), prefix)
644 })
645
646 ret = ret[:end]
647
648 return Paths(ret)
649}
650
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700651// WritablePaths is a slice of WritablePaths, used for multiple outputs.
652type WritablePaths []WritablePath
653
654// Strings returns the string forms of the writable paths.
655func (p WritablePaths) Strings() []string {
656 if p == nil {
657 return nil
658 }
659 ret := make([]string, len(p))
660 for i, path := range p {
661 ret[i] = path.String()
662 }
663 return ret
664}
665
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800666// Paths returns the WritablePaths as a Paths
667func (p WritablePaths) Paths() Paths {
668 if p == nil {
669 return nil
670 }
671 ret := make(Paths, len(p))
672 for i, path := range p {
673 ret[i] = path
674 }
675 return ret
676}
677
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700678type basePath struct {
679 path string
680 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800681 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700682}
683
684func (p basePath) Ext() string {
685 return filepath.Ext(p.path)
686}
687
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700688func (p basePath) Base() string {
689 return filepath.Base(p.path)
690}
691
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800692func (p basePath) Rel() string {
693 if p.rel != "" {
694 return p.rel
695 }
696 return p.path
697}
698
Colin Cross0875c522017-11-28 17:34:01 -0800699func (p basePath) String() string {
700 return p.path
701}
702
Colin Cross0db55682017-12-05 15:36:55 -0800703func (p basePath) withRel(rel string) basePath {
704 p.path = filepath.Join(p.path, rel)
705 p.rel = rel
706 return p
707}
708
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700709// SourcePath is a Path representing a file path rooted from SrcDir
710type SourcePath struct {
711 basePath
712}
713
714var _ Path = SourcePath{}
715
Colin Cross0db55682017-12-05 15:36:55 -0800716func (p SourcePath) withRel(rel string) SourcePath {
717 p.basePath = p.basePath.withRel(rel)
718 return p
719}
720
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700721// safePathForSource is for paths that we expect are safe -- only for use by go
722// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700723func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
724 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800725 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700726 if err != nil {
727 return ret, err
728 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700729
Colin Cross7b3dcc32019-01-24 13:14:39 -0800730 // absolute path already checked by validateSafePath
731 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800732 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700733 }
734
Colin Crossfe4bc362018-09-12 10:02:13 -0700735 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700736}
737
Colin Cross192e97a2018-02-22 14:21:02 -0800738// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
739func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000740 p, err := validatePath(pathComponents...)
741 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800742 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800743 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800744 }
745
Colin Cross7b3dcc32019-01-24 13:14:39 -0800746 // absolute path already checked by validatePath
747 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800748 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000749 }
750
Colin Cross192e97a2018-02-22 14:21:02 -0800751 return ret, nil
752}
753
754// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
755// path does not exist.
756func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
757 var files []string
758
759 if gctx, ok := ctx.(PathGlobContext); ok {
760 // Use glob to produce proper dependencies, even though we only want
761 // a single file.
762 files, err = gctx.GlobWithDeps(path.String(), nil)
763 } else {
764 var deps []string
765 // We cannot add build statements in this context, so we fall back to
766 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +0000767 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800768 ctx.AddNinjaFileDeps(deps...)
769 }
770
771 if err != nil {
772 return false, fmt.Errorf("glob: %s", err.Error())
773 }
774
775 return len(files) > 0, nil
776}
777
778// PathForSource joins the provided path components and validates that the result
779// neither escapes the source dir nor is in the out dir.
780// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
781func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
782 path, err := pathForSource(ctx, pathComponents...)
783 if err != nil {
784 reportPathError(ctx, err)
785 }
786
Colin Crosse3924e12018-08-15 20:18:53 -0700787 if pathtools.IsGlob(path.String()) {
788 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
789 }
790
Colin Cross192e97a2018-02-22 14:21:02 -0800791 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
792 exists, err := existsWithDependencies(ctx, path)
793 if err != nil {
794 reportPathError(ctx, err)
795 }
796 if !exists {
797 modCtx.AddMissingDependencies([]string{path.String()})
798 }
Colin Cross988414c2020-01-11 01:11:46 +0000799 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800800 reportPathErrorf(ctx, "%s: %s", path, err.Error())
Colin Cross5e6a7972020-06-07 16:56:32 -0700801 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800802 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800803 }
804 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700805}
806
Jeff Gaston734e3802017-04-10 15:47:24 -0700807// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700808// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
809// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800810func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800811 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800812 if err != nil {
813 reportPathError(ctx, err)
814 return OptionalPath{}
815 }
Colin Crossc48c1432018-02-23 07:09:01 +0000816
Colin Crosse3924e12018-08-15 20:18:53 -0700817 if pathtools.IsGlob(path.String()) {
818 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
819 return OptionalPath{}
820 }
821
Colin Cross192e97a2018-02-22 14:21:02 -0800822 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000823 if err != nil {
824 reportPathError(ctx, err)
825 return OptionalPath{}
826 }
Colin Cross192e97a2018-02-22 14:21:02 -0800827 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000828 return OptionalPath{}
829 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700830 return OptionalPathForPath(path)
831}
832
833func (p SourcePath) String() string {
834 return filepath.Join(p.config.srcDir, p.path)
835}
836
837// Join creates a new SourcePath with paths... joined with the current path. The
838// provided paths... may not use '..' to escape from the current path.
839func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800840 path, err := validatePath(paths...)
841 if err != nil {
842 reportPathError(ctx, err)
843 }
Colin Cross0db55682017-12-05 15:36:55 -0800844 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700845}
846
Colin Cross2fafa3e2019-03-05 12:39:51 -0800847// join is like Join but does less path validation.
848func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
849 path, err := validateSafePath(paths...)
850 if err != nil {
851 reportPathError(ctx, err)
852 }
853 return p.withRel(path)
854}
855
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700856// OverlayPath returns the overlay for `path' if it exists. This assumes that the
857// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700858func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700859 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800860 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700861 relDir = srcPath.path
862 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800863 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700864 return OptionalPath{}
865 }
866 dir := filepath.Join(p.config.srcDir, p.path, relDir)
867 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700868 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800869 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800870 }
Colin Cross461b4452018-02-23 09:22:42 -0800871 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700872 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800873 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700874 return OptionalPath{}
875 }
876 if len(paths) == 0 {
877 return OptionalPath{}
878 }
Colin Cross43f08db2018-11-12 10:13:39 -0800879 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700880 return OptionalPathForPath(PathForSource(ctx, relPath))
881}
882
Colin Cross70dda7e2019-10-01 22:05:35 -0700883// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700884type OutputPath struct {
885 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -0800886 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700887}
888
Colin Cross702e0f82017-10-18 17:27:54 -0700889func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800890 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -0800891 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700892 return p
893}
894
Colin Cross3063b782018-08-15 11:19:12 -0700895func (p OutputPath) WithoutRel() OutputPath {
896 p.basePath.rel = filepath.Base(p.basePath.path)
897 return p
898}
899
Paul Duffin9b478b02019-12-10 13:41:51 +0000900func (p OutputPath) buildDir() string {
901 return p.config.buildDir
902}
903
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700904var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +0000905var _ WritablePath = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700906
Chris Parsons8f232a22020-06-23 17:37:05 -0400907// toolDepPath is a Path representing a dependency of the build tool.
908type toolDepPath struct {
909 basePath
910}
911
912var _ Path = toolDepPath{}
913
914// pathForBuildToolDep returns a toolDepPath representing the given path string.
915// There is no validation for the path, as it is "trusted": It may fail
916// normal validation checks. For example, it may be an absolute path.
917// Only use this function to construct paths for dependencies of the build
918// tool invocation.
919func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
920 return toolDepPath{basePath{path, ctx.Config(), ""}}
921}
922
Jeff Gaston734e3802017-04-10 15:47:24 -0700923// PathForOutput joins the provided paths and returns an OutputPath that is
924// validated to not escape the build dir.
925// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
926func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800927 path, err := validatePath(pathComponents...)
928 if err != nil {
929 reportPathError(ctx, err)
930 }
Colin Crossd63c9a72020-01-29 16:52:50 -0800931 fullPath := filepath.Join(ctx.Config().buildDir, path)
932 path = fullPath[len(fullPath)-len(path):]
933 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700934}
935
Colin Cross40e33732019-02-15 11:08:35 -0800936// PathsForOutput returns Paths rooted from buildDir
937func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
938 ret := make(WritablePaths, len(paths))
939 for i, path := range paths {
940 ret[i] = PathForOutput(ctx, path)
941 }
942 return ret
943}
944
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700945func (p OutputPath) writablePath() {}
946
947func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -0800948 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700949}
950
951// Join creates a new OutputPath with paths... joined with the current path. The
952// provided paths... may not use '..' to escape from the current path.
953func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800954 path, err := validatePath(paths...)
955 if err != nil {
956 reportPathError(ctx, err)
957 }
Colin Cross0db55682017-12-05 15:36:55 -0800958 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700959}
960
Colin Cross8854a5a2019-02-11 14:14:16 -0800961// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
962func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
963 if strings.Contains(ext, "/") {
964 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
965 }
966 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800967 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800968 return ret
969}
970
Colin Cross40e33732019-02-15 11:08:35 -0800971// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
972func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
973 path, err := validatePath(paths...)
974 if err != nil {
975 reportPathError(ctx, err)
976 }
977
978 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800979 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800980 return ret
981}
982
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700983// PathForIntermediates returns an OutputPath representing the top-level
984// intermediates directory.
985func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800986 path, err := validatePath(paths...)
987 if err != nil {
988 reportPathError(ctx, err)
989 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700990 return PathForOutput(ctx, ".intermediates", path)
991}
992
Colin Cross07e51612019-03-05 12:46:40 -0800993var _ genPathProvider = SourcePath{}
994var _ objPathProvider = SourcePath{}
995var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700996
Colin Cross07e51612019-03-05 12:46:40 -0800997// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700998// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800999func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
1000 p, err := validatePath(pathComponents...)
1001 if err != nil {
1002 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001003 }
Colin Cross8a497952019-03-05 22:25:09 -08001004 paths, err := expandOneSrcPath(ctx, p, nil)
1005 if err != nil {
1006 if depErr, ok := err.(missingDependencyError); ok {
1007 if ctx.Config().AllowMissingDependencies() {
1008 ctx.AddMissingDependencies(depErr.missingDeps)
1009 } else {
1010 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1011 }
1012 } else {
1013 reportPathError(ctx, err)
1014 }
1015 return nil
1016 } else if len(paths) == 0 {
1017 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
1018 return nil
1019 } else if len(paths) > 1 {
1020 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
1021 }
1022 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001023}
1024
Colin Cross07e51612019-03-05 12:46:40 -08001025func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
1026 p, err := validatePath(paths...)
1027 if err != nil {
1028 reportPathError(ctx, err)
1029 }
1030
1031 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1032 if err != nil {
1033 reportPathError(ctx, err)
1034 }
1035
1036 path.basePath.rel = p
1037
1038 return path
1039}
1040
Colin Cross2fafa3e2019-03-05 12:39:51 -08001041// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1042// will return the path relative to subDir in the module's source directory. If any input paths are not located
1043// inside subDir then a path error will be reported.
1044func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
1045 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001046 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001047 for i, path := range paths {
1048 rel := Rel(ctx, subDirFullPath.String(), path.String())
1049 paths[i] = subDirFullPath.join(ctx, rel)
1050 }
1051 return paths
1052}
1053
1054// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1055// module's source directory. If the input path is not located inside subDir then a path error will be reported.
1056func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001057 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001058 rel := Rel(ctx, subDirFullPath.String(), path.String())
1059 return subDirFullPath.Join(ctx, rel)
1060}
1061
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001062// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1063// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -07001064func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001065 if p == nil {
1066 return OptionalPath{}
1067 }
1068 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1069}
1070
Colin Cross07e51612019-03-05 12:46:40 -08001071func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001072 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001073}
1074
Colin Cross07e51612019-03-05 12:46:40 -08001075func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001076 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001077}
1078
Colin Cross07e51612019-03-05 12:46:40 -08001079func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001080 // TODO: Use full directory if the new ctx is not the current ctx?
1081 return PathForModuleRes(ctx, p.path, name)
1082}
1083
1084// ModuleOutPath is a Path representing a module's output directory.
1085type ModuleOutPath struct {
1086 OutputPath
1087}
1088
1089var _ Path = ModuleOutPath{}
1090
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001091func (p ModuleOutPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
1092 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1093}
1094
Colin Cross702e0f82017-10-18 17:27:54 -07001095func pathForModule(ctx ModuleContext) OutputPath {
1096 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1097}
1098
Logan Chien7eefdc42018-07-11 18:10:41 +08001099// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1100// reference abi dump for the given module. This is not guaranteed to be valid.
1101func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001102 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001103
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001104 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001105 if len(arches) == 0 {
1106 panic("device build with no primary arch")
1107 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001108 currentArch := ctx.Arch()
1109 archNameAndVariant := currentArch.ArchType.String()
1110 if currentArch.ArchVariant != "" {
1111 archNameAndVariant += "_" + currentArch.ArchVariant
1112 }
Logan Chien5237bed2018-07-11 17:15:57 +08001113
1114 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001115 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001116 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001117 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001118 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001119 } else {
1120 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001121 }
Logan Chien5237bed2018-07-11 17:15:57 +08001122
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001123 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001124
1125 var ext string
1126 if isGzip {
1127 ext = ".lsdump.gz"
1128 } else {
1129 ext = ".lsdump"
1130 }
1131
1132 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1133 version, binderBitness, archNameAndVariant, "source-based",
1134 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001135}
1136
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001137// PathForModuleOut returns a Path representing the paths... under the module's
1138// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001139func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001140 p, err := validatePath(paths...)
1141 if err != nil {
1142 reportPathError(ctx, err)
1143 }
Colin Cross702e0f82017-10-18 17:27:54 -07001144 return ModuleOutPath{
1145 OutputPath: pathForModule(ctx).withRel(p),
1146 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001147}
1148
1149// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1150// directory. Mainly used for generated sources.
1151type ModuleGenPath struct {
1152 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001153}
1154
1155var _ Path = ModuleGenPath{}
1156var _ genPathProvider = ModuleGenPath{}
1157var _ objPathProvider = ModuleGenPath{}
1158
1159// PathForModuleGen returns a Path representing the paths... under the module's
1160// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001161func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001162 p, err := validatePath(paths...)
1163 if err != nil {
1164 reportPathError(ctx, err)
1165 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001166 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001167 ModuleOutPath: ModuleOutPath{
1168 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1169 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001170 }
1171}
1172
Dan Willemsen21ec4902016-11-02 20:43:13 -07001173func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001174 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001175 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001176}
1177
Colin Cross635c3b02016-05-18 15:37:25 -07001178func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001179 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1180}
1181
1182// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1183// directory. Used for compiled objects.
1184type ModuleObjPath struct {
1185 ModuleOutPath
1186}
1187
1188var _ Path = ModuleObjPath{}
1189
1190// PathForModuleObj returns a Path representing the paths... under the module's
1191// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001192func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001193 p, err := validatePath(pathComponents...)
1194 if err != nil {
1195 reportPathError(ctx, err)
1196 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001197 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1198}
1199
1200// ModuleResPath is a a Path representing the 'res' directory in a module's
1201// output directory.
1202type ModuleResPath struct {
1203 ModuleOutPath
1204}
1205
1206var _ Path = ModuleResPath{}
1207
1208// PathForModuleRes returns a Path representing the paths... under the module's
1209// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001210func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001211 p, err := validatePath(pathComponents...)
1212 if err != nil {
1213 reportPathError(ctx, err)
1214 }
1215
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001216 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1217}
1218
Colin Cross70dda7e2019-10-01 22:05:35 -07001219// InstallPath is a Path representing a installed file path rooted from the build directory
1220type InstallPath struct {
1221 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001222
1223 baseDir string // "../" for Make paths to convert "out/soong" to "out", "" for Soong paths
Colin Cross70dda7e2019-10-01 22:05:35 -07001224}
1225
Paul Duffin9b478b02019-12-10 13:41:51 +00001226func (p InstallPath) buildDir() string {
1227 return p.config.buildDir
1228}
1229
1230var _ Path = InstallPath{}
1231var _ WritablePath = InstallPath{}
1232
Colin Cross70dda7e2019-10-01 22:05:35 -07001233func (p InstallPath) writablePath() {}
1234
1235func (p InstallPath) String() string {
Colin Crossff6c33d2019-10-02 16:01:35 -07001236 return filepath.Join(p.config.buildDir, p.baseDir, p.path)
Colin Cross70dda7e2019-10-01 22:05:35 -07001237}
1238
1239// Join creates a new InstallPath with paths... joined with the current path. The
1240// provided paths... may not use '..' to escape from the current path.
1241func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1242 path, err := validatePath(paths...)
1243 if err != nil {
1244 reportPathError(ctx, err)
1245 }
1246 return p.withRel(path)
1247}
1248
1249func (p InstallPath) withRel(rel string) InstallPath {
1250 p.basePath = p.basePath.withRel(rel)
1251 return p
1252}
1253
Colin Crossff6c33d2019-10-02 16:01:35 -07001254// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1255// i.e. out/ instead of out/soong/.
1256func (p InstallPath) ToMakePath() InstallPath {
1257 p.baseDir = "../"
1258 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001259}
1260
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001261// PathForModuleInstall returns a Path representing the install path for the
1262// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001263func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001264 os := ctx.Os()
1265 if forceOS := ctx.InstallForceOS(); forceOS != nil {
1266 os = *forceOS
1267 }
1268 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001269
1270 ret := pathForInstall(ctx, os, partition, ctx.Debug(), pathComponents...)
1271
1272 if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
1273 ret = ret.ToMakePath()
1274 }
1275
1276 return ret
1277}
1278
1279func pathForInstall(ctx PathContext, os OsType, partition string, debug bool,
1280 pathComponents ...string) InstallPath {
1281
1282 var outPaths []string
1283
Colin Cross6e359402020-02-10 15:29:54 -08001284 if os.Class == Device {
Colin Cross6510f912017-11-29 00:27:14 -08001285 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001286 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001287 switch os {
Dan Willemsen866b5632017-09-22 12:28:24 -07001288 case Linux:
Colin Cross6e359402020-02-10 15:29:54 -08001289 outPaths = []string{"host", "linux-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001290 case LinuxBionic:
1291 // TODO: should this be a separate top level, or shared with linux-x86?
Colin Cross6e359402020-02-10 15:29:54 -08001292 outPaths = []string{"host", "linux_bionic-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001293 default:
Colin Cross6e359402020-02-10 15:29:54 -08001294 outPaths = []string{"host", os.String() + "-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001295 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001296 }
Colin Cross609c49a2020-02-13 13:20:11 -08001297 if debug {
Dan Willemsen782a2d12015-12-21 14:55:28 -08001298 outPaths = append([]string{"debug"}, outPaths...)
1299 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001300 outPaths = append(outPaths, pathComponents...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001301
1302 path, err := validatePath(outPaths...)
1303 if err != nil {
1304 reportPathError(ctx, err)
1305 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001306
1307 ret := InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Crossff6c33d2019-10-02 16:01:35 -07001308
1309 return ret
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001310}
1311
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001312func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
1313 paths = append([]string{prefix}, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001314 path, err := validatePath(paths...)
1315 if err != nil {
1316 reportPathError(ctx, err)
1317 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001318 return InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Cross70dda7e2019-10-01 22:05:35 -07001319}
1320
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001321func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1322 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1323}
1324
1325func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1326 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1327}
1328
Colin Cross70dda7e2019-10-01 22:05:35 -07001329func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001330 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1331
1332 return "/" + rel
1333}
1334
Colin Cross6e359402020-02-10 15:29:54 -08001335func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001336 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001337 if ctx.InstallInTestcases() {
1338 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001339 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001340 } else if os.Class == Device {
1341 if ctx.InstallInData() {
1342 partition = "data"
1343 } else if ctx.InstallInRamdisk() {
1344 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1345 partition = "recovery/root/first_stage_ramdisk"
1346 } else {
1347 partition = "ramdisk"
1348 }
1349 if !ctx.InstallInRoot() {
1350 partition += "/system"
1351 }
1352 } else if ctx.InstallInRecovery() {
1353 if ctx.InstallInRoot() {
1354 partition = "recovery/root"
1355 } else {
1356 // the layout of recovery partion is the same as that of system partition
1357 partition = "recovery/root/system"
1358 }
1359 } else if ctx.SocSpecific() {
1360 partition = ctx.DeviceConfig().VendorPath()
1361 } else if ctx.DeviceSpecific() {
1362 partition = ctx.DeviceConfig().OdmPath()
1363 } else if ctx.ProductSpecific() {
1364 partition = ctx.DeviceConfig().ProductPath()
1365 } else if ctx.SystemExtSpecific() {
1366 partition = ctx.DeviceConfig().SystemExtPath()
1367 } else if ctx.InstallInRoot() {
1368 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001369 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001370 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001371 }
Colin Cross6e359402020-02-10 15:29:54 -08001372 if ctx.InstallInSanitizerDir() {
1373 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001374 }
Colin Cross43f08db2018-11-12 10:13:39 -08001375 }
1376 return partition
1377}
1378
Colin Cross609c49a2020-02-13 13:20:11 -08001379type InstallPaths []InstallPath
1380
1381// Paths returns the InstallPaths as a Paths
1382func (p InstallPaths) Paths() Paths {
1383 if p == nil {
1384 return nil
1385 }
1386 ret := make(Paths, len(p))
1387 for i, path := range p {
1388 ret[i] = path
1389 }
1390 return ret
1391}
1392
1393// Strings returns the string forms of the install paths.
1394func (p InstallPaths) Strings() []string {
1395 if p == nil {
1396 return nil
1397 }
1398 ret := make([]string, len(p))
1399 for i, path := range p {
1400 ret[i] = path.String()
1401 }
1402 return ret
1403}
1404
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001405// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001406// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001407func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001408 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001409 path := filepath.Clean(path)
1410 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001411 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001412 }
1413 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001414 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1415 // variables. '..' may remove the entire ninja variable, even if it
1416 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001417 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001418}
1419
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001420// validatePath validates that a path does not include ninja variables, and that
1421// each path component does not attempt to leave its component. Returns a joined
1422// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001423func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001424 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001425 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001426 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001427 }
1428 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001429 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001430}
Colin Cross5b529592017-05-09 13:34:34 -07001431
Colin Cross0875c522017-11-28 17:34:01 -08001432func PathForPhony(ctx PathContext, phony string) WritablePath {
1433 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001434 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001435 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001436 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001437}
1438
Colin Cross74e3fe42017-12-11 15:51:44 -08001439type PhonyPath struct {
1440 basePath
1441}
1442
1443func (p PhonyPath) writablePath() {}
1444
Paul Duffin9b478b02019-12-10 13:41:51 +00001445func (p PhonyPath) buildDir() string {
1446 return p.config.buildDir
1447}
1448
Colin Cross74e3fe42017-12-11 15:51:44 -08001449var _ Path = PhonyPath{}
1450var _ WritablePath = PhonyPath{}
1451
Colin Cross5b529592017-05-09 13:34:34 -07001452type testPath struct {
1453 basePath
1454}
1455
1456func (p testPath) String() string {
1457 return p.path
1458}
1459
Colin Cross40e33732019-02-15 11:08:35 -08001460// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1461// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001462func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001463 p, err := validateSafePath(paths...)
1464 if err != nil {
1465 panic(err)
1466 }
Colin Cross5b529592017-05-09 13:34:34 -07001467 return testPath{basePath{path: p, rel: p}}
1468}
1469
Colin Cross40e33732019-02-15 11:08:35 -08001470// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1471func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001472 p := make(Paths, len(strs))
1473 for i, s := range strs {
1474 p[i] = PathForTesting(s)
1475 }
1476
1477 return p
1478}
Colin Cross43f08db2018-11-12 10:13:39 -08001479
Colin Cross40e33732019-02-15 11:08:35 -08001480type testPathContext struct {
1481 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001482}
1483
Colin Cross40e33732019-02-15 11:08:35 -08001484func (x *testPathContext) Config() Config { return x.config }
1485func (x *testPathContext) AddNinjaFileDeps(...string) {}
1486
1487// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1488// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001489func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001490 return &testPathContext{
1491 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001492 }
1493}
1494
Colin Cross43f08db2018-11-12 10:13:39 -08001495// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1496// targetPath is not inside basePath.
1497func Rel(ctx PathContext, basePath string, targetPath string) string {
1498 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1499 if !isRel {
1500 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1501 return ""
1502 }
1503 return rel
1504}
1505
1506// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1507// targetPath is not inside basePath.
1508func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001509 rel, isRel, err := maybeRelErr(basePath, targetPath)
1510 if err != nil {
1511 reportPathError(ctx, err)
1512 }
1513 return rel, isRel
1514}
1515
1516func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001517 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1518 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001519 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001520 }
1521 rel, err := filepath.Rel(basePath, targetPath)
1522 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001523 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001524 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001525 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001526 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001527 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001528}
Colin Cross988414c2020-01-11 01:11:46 +00001529
1530// Writes a file to the output directory. Attempting to write directly to the output directory
1531// will fail due to the sandbox of the soong_build process.
1532func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1533 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1534}
1535
1536func absolutePath(path string) string {
1537 if filepath.IsAbs(path) {
1538 return path
1539 }
1540 return filepath.Join(absSrcDir, path)
1541}