blob: c4b1073685914df5e2495d360eaac1139a79a046 [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
Dan Willemsen00269f22017-07-06 16:59:48 -070046type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -070047 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -070048
49 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -070050 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -070051 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -080052 InstallInRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +090053 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -070054 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -070055 InstallBypassMake() bool
Colin Cross6e359402020-02-10 15:29:54 -080056 InstallForceOS() *OsType
Dan Willemsen00269f22017-07-06 16:59:48 -070057}
58
59var _ ModuleInstallPathContext = ModuleContext(nil)
60
Dan Willemsen34cc69e2015-09-23 15:26:20 -070061// errorfContext is the interface containing the Errorf method matching the
62// Errorf method in blueprint.SingletonContext.
63type errorfContext interface {
64 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080065}
66
Dan Willemsen34cc69e2015-09-23 15:26:20 -070067var _ errorfContext = blueprint.SingletonContext(nil)
68
69// moduleErrorf is the interface containing the ModuleErrorf method matching
70// the ModuleErrorf method in blueprint.ModuleContext.
71type moduleErrorf interface {
72 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080073}
74
Dan Willemsen34cc69e2015-09-23 15:26:20 -070075var _ moduleErrorf = blueprint.ModuleContext(nil)
76
Dan Willemsen34cc69e2015-09-23 15:26:20 -070077// reportPathError will register an error with the attached context. It
78// attempts ctx.ModuleErrorf for a better error message first, then falls
79// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -080080func reportPathError(ctx PathContext, err error) {
81 reportPathErrorf(ctx, "%s", err.Error())
82}
83
84// reportPathErrorf will register an error with the attached context. It
85// attempts ctx.ModuleErrorf for a better error message first, then falls
86// back to ctx.Errorf.
87func reportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -070088 if mctx, ok := ctx.(moduleErrorf); ok {
89 mctx.ModuleErrorf(format, args...)
90 } else if ectx, ok := ctx.(errorfContext); ok {
91 ectx.Errorf(format, args...)
92 } else {
93 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -070094 }
95}
96
Colin Cross5e708052019-08-06 13:59:50 -070097func pathContextName(ctx PathContext, module blueprint.Module) string {
98 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
99 return x.ModuleName(module)
100 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
101 return x.OtherModuleName(module)
102 }
103 return "unknown"
104}
105
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700106type Path interface {
107 // Returns the path in string form
108 String() string
109
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700110 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700111 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700112
113 // Base returns the last element of the path
114 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800115
116 // Rel returns the portion of the path relative to the directory it was created from. For
117 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800118 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800119 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700120}
121
122// WritablePath is a type of path that can be used as an output for build rules.
123type WritablePath interface {
124 Path
125
Paul Duffin9b478b02019-12-10 13:41:51 +0000126 // return the path to the build directory.
127 buildDir() string
128
Jeff Gaston734e3802017-04-10 15:47:24 -0700129 // the writablePath method doesn't directly do anything,
130 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700131 writablePath()
132}
133
134type genPathProvider interface {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700135 genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700136}
137type objPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700138 objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700139}
140type resPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700141 resPathWithName(ctx ModuleContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700142}
143
144// GenPathWithExt derives a new file path in ctx's generated sources directory
145// from the current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700146func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700147 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700148 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700149 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800150 reportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700151 return PathForModuleGen(ctx)
152}
153
154// ObjPathWithExt derives a new file path in ctx's object directory from the
155// current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700156func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700157 if path, ok := p.(objPathProvider); ok {
158 return path.objPathWithExt(ctx, subdir, ext)
159 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800160 reportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700161 return PathForModuleObj(ctx)
162}
163
164// ResPathWithName derives a new path in ctx's output resource directory, using
165// the current path to create the directory name, and the `name` argument for
166// the filename.
Colin Cross635c3b02016-05-18 15:37:25 -0700167func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700168 if path, ok := p.(resPathProvider); ok {
169 return path.resPathWithName(ctx, name)
170 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800171 reportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700172 return PathForModuleRes(ctx)
173}
174
175// OptionalPath is a container that may or may not contain a valid Path.
176type OptionalPath struct {
177 valid bool
178 path Path
179}
180
181// OptionalPathForPath returns an OptionalPath containing the path.
182func OptionalPathForPath(path Path) OptionalPath {
183 if path == nil {
184 return OptionalPath{}
185 }
186 return OptionalPath{valid: true, path: path}
187}
188
189// Valid returns whether there is a valid path
190func (p OptionalPath) Valid() bool {
191 return p.valid
192}
193
194// Path returns the Path embedded in this OptionalPath. You must be sure that
195// there is a valid path, since this method will panic if there is not.
196func (p OptionalPath) Path() Path {
197 if !p.valid {
198 panic("Requesting an invalid path")
199 }
200 return p.path
201}
202
203// String returns the string version of the Path, or "" if it isn't valid.
204func (p OptionalPath) String() string {
205 if p.valid {
206 return p.path.String()
207 } else {
208 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700209 }
210}
Colin Cross6e18ca42015-07-14 18:55:36 -0700211
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700212// Paths is a slice of Path objects, with helpers to operate on the collection.
213type Paths []Path
214
215// PathsForSource returns Paths rooted from SrcDir
216func PathsForSource(ctx PathContext, paths []string) Paths {
217 ret := make(Paths, len(paths))
218 for i, path := range paths {
219 ret[i] = PathForSource(ctx, path)
220 }
221 return ret
222}
223
Jeff Gaston734e3802017-04-10 15:47:24 -0700224// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800225// found in the tree. If any are not found, they are omitted from the list,
226// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800227func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800228 ret := make(Paths, 0, len(paths))
229 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800230 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800231 if p.Valid() {
232 ret = append(ret, p.Path())
233 }
234 }
235 return ret
236}
237
Colin Cross41955e82019-05-29 14:40:35 -0700238// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
239// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
240// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
241// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
242// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
243// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Colin Cross635c3b02016-05-18 15:37:25 -0700244func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800245 return PathsForModuleSrcExcludes(ctx, paths, nil)
246}
247
Colin Crossba71a3f2019-03-18 12:12:48 -0700248// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700249// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
250// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
251// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
252// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100253// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700254// having missing dependencies.
Colin Cross8a497952019-03-05 22:25:09 -0800255func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700256 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
257 if ctx.Config().AllowMissingDependencies() {
258 ctx.AddMissingDependencies(missingDeps)
259 } else {
260 for _, m := range missingDeps {
261 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
262 }
263 }
264 return ret
265}
266
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000267// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
268type OutputPaths []OutputPath
269
270// Paths returns the OutputPaths as a Paths
271func (p OutputPaths) Paths() Paths {
272 if p == nil {
273 return nil
274 }
275 ret := make(Paths, len(p))
276 for i, path := range p {
277 ret[i] = path
278 }
279 return ret
280}
281
282// Strings returns the string forms of the writable paths.
283func (p OutputPaths) Strings() []string {
284 if p == nil {
285 return nil
286 }
287 ret := make([]string, len(p))
288 for i, path := range p {
289 ret[i] = path.String()
290 }
291 return ret
292}
293
Colin Crossba71a3f2019-03-18 12:12:48 -0700294// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700295// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
296// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
297// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
298// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
299// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
300// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
301// dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700302func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800303 prefix := pathForModuleSrc(ctx).String()
304
305 var expandedExcludes []string
306 if excludes != nil {
307 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700308 }
Colin Cross8a497952019-03-05 22:25:09 -0800309
Colin Crossba71a3f2019-03-18 12:12:48 -0700310 var missingExcludeDeps []string
311
Colin Cross8a497952019-03-05 22:25:09 -0800312 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700313 if m, t := SrcIsModuleWithTag(e); m != "" {
314 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800315 if module == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700316 missingExcludeDeps = append(missingExcludeDeps, m)
Colin Cross8a497952019-03-05 22:25:09 -0800317 continue
318 }
Colin Cross41955e82019-05-29 14:40:35 -0700319 if outProducer, ok := module.(OutputFileProducer); ok {
320 outputFiles, err := outProducer.OutputFiles(t)
321 if err != nil {
322 ctx.ModuleErrorf("path dependency %q: %s", e, err)
323 }
324 expandedExcludes = append(expandedExcludes, outputFiles.Strings()...)
325 } else if t != "" {
326 ctx.ModuleErrorf("path dependency %q is not an output file producing module", e)
327 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800328 expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
329 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700330 ctx.ModuleErrorf("path dependency %q is not a source file producing module", e)
Colin Cross8a497952019-03-05 22:25:09 -0800331 }
332 } else {
333 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
334 }
335 }
336
337 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700338 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800339 }
340
Colin Crossba71a3f2019-03-18 12:12:48 -0700341 var missingDeps []string
342
Colin Cross8a497952019-03-05 22:25:09 -0800343 expandedSrcFiles := make(Paths, 0, len(paths))
344 for _, s := range paths {
345 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
346 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700347 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800348 } else if err != nil {
349 reportPathError(ctx, err)
350 }
351 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
352 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700353
354 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800355}
356
357type missingDependencyError struct {
358 missingDeps []string
359}
360
361func (e missingDependencyError) Error() string {
362 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
363}
364
365func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
Colin Cross41955e82019-05-29 14:40:35 -0700366 if m, t := SrcIsModuleWithTag(s); m != "" {
367 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800368 if module == nil {
369 return nil, missingDependencyError{[]string{m}}
370 }
Colin Cross41955e82019-05-29 14:40:35 -0700371 if outProducer, ok := module.(OutputFileProducer); ok {
372 outputFiles, err := outProducer.OutputFiles(t)
373 if err != nil {
374 return nil, fmt.Errorf("path dependency %q: %s", s, err)
375 }
376 return outputFiles, nil
377 } else if t != "" {
378 return nil, fmt.Errorf("path dependency %q is not an output file producing module", s)
379 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800380 moduleSrcs := srcProducer.Srcs()
381 for _, e := range expandedExcludes {
382 for j := 0; j < len(moduleSrcs); j++ {
383 if moduleSrcs[j].String() == e {
384 moduleSrcs = append(moduleSrcs[:j], moduleSrcs[j+1:]...)
385 j--
386 }
387 }
388 }
389 return moduleSrcs, nil
390 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700391 return nil, fmt.Errorf("path dependency %q is not a source file producing module", s)
Colin Cross8a497952019-03-05 22:25:09 -0800392 }
393 } else if pathtools.IsGlob(s) {
394 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
395 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
396 } else {
397 p := pathForModuleSrc(ctx, s)
Colin Cross988414c2020-01-11 01:11:46 +0000398 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Colin Cross8a497952019-03-05 22:25:09 -0800399 reportPathErrorf(ctx, "%s: %s", p, err.Error())
400 } else if !exists {
401 reportPathErrorf(ctx, "module source path %q does not exist", p)
402 }
403
404 j := findStringInSlice(p.String(), expandedExcludes)
405 if j >= 0 {
406 return nil, nil
407 }
408 return Paths{p}, nil
409 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700410}
411
412// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
413// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800414// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700415// It intended for use in globs that only list files that exist, so it allows '$' in
416// filenames.
Colin Cross1184b642019-12-30 18:43:07 -0800417func pathsForModuleSrcFromFullPath(ctx EarlyModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800418 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700419 if prefix == "./" {
420 prefix = ""
421 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700422 ret := make(Paths, 0, len(paths))
423 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800424 if !incDirs && strings.HasSuffix(p, "/") {
425 continue
426 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700427 path := filepath.Clean(p)
428 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800429 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700430 continue
431 }
Colin Crosse3924e12018-08-15 20:18:53 -0700432
Colin Crossfe4bc362018-09-12 10:02:13 -0700433 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700434 if err != nil {
435 reportPathError(ctx, err)
436 continue
437 }
438
Colin Cross07e51612019-03-05 12:46:40 -0800439 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700440
Colin Cross07e51612019-03-05 12:46:40 -0800441 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700442 }
443 return ret
444}
445
446// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800447// 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 -0700448func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800449 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700450 return PathsForModuleSrc(ctx, input)
451 }
452 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
453 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800454 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800455 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700456}
457
458// Strings returns the Paths in string form
459func (p Paths) Strings() []string {
460 if p == nil {
461 return nil
462 }
463 ret := make([]string, len(p))
464 for i, path := range p {
465 ret[i] = path.String()
466 }
467 return ret
468}
469
Colin Crossb6715442017-10-24 11:13:31 -0700470// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
471// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700472func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800473 // 128 was chosen based on BenchmarkFirstUniquePaths results.
474 if len(list) > 128 {
475 return firstUniquePathsMap(list)
476 }
477 return firstUniquePathsList(list)
478}
479
480func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700481 k := 0
482outer:
483 for i := 0; i < len(list); i++ {
484 for j := 0; j < k; j++ {
485 if list[i] == list[j] {
486 continue outer
487 }
488 }
489 list[k] = list[i]
490 k++
491 }
492 return list[:k]
493}
494
Colin Cross27027c72020-02-28 15:34:17 -0800495func firstUniquePathsMap(list Paths) Paths {
496 k := 0
497 seen := make(map[Path]bool, len(list))
498 for i := 0; i < len(list); i++ {
499 if seen[list[i]] {
500 continue
501 }
502 seen[list[i]] = true
503 list[k] = list[i]
504 k++
505 }
506 return list[:k]
507}
508
Colin Crossb6715442017-10-24 11:13:31 -0700509// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
510// modifies the Paths slice contents in place, and returns a subslice of the original slice.
511func LastUniquePaths(list Paths) Paths {
512 totalSkip := 0
513 for i := len(list) - 1; i >= totalSkip; i-- {
514 skip := 0
515 for j := i - 1; j >= totalSkip; j-- {
516 if list[i] == list[j] {
517 skip++
518 } else {
519 list[j+skip] = list[j]
520 }
521 }
522 totalSkip += skip
523 }
524 return list[totalSkip:]
525}
526
Colin Crossa140bb02018-04-17 10:52:26 -0700527// ReversePaths returns a copy of a Paths in reverse order.
528func ReversePaths(list Paths) Paths {
529 if list == nil {
530 return nil
531 }
532 ret := make(Paths, len(list))
533 for i := range list {
534 ret[i] = list[len(list)-1-i]
535 }
536 return ret
537}
538
Jeff Gaston294356f2017-09-27 17:05:30 -0700539func indexPathList(s Path, list []Path) int {
540 for i, l := range list {
541 if l == s {
542 return i
543 }
544 }
545
546 return -1
547}
548
549func inPathList(p Path, list []Path) bool {
550 return indexPathList(p, list) != -1
551}
552
553func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000554 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
555}
556
557func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700558 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000559 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700560 filtered = append(filtered, l)
561 } else {
562 remainder = append(remainder, l)
563 }
564 }
565
566 return
567}
568
Colin Cross93e85952017-08-15 13:34:18 -0700569// HasExt returns true of any of the paths have extension ext, otherwise false
570func (p Paths) HasExt(ext string) bool {
571 for _, path := range p {
572 if path.Ext() == ext {
573 return true
574 }
575 }
576
577 return false
578}
579
580// FilterByExt returns the subset of the paths that have extension ext
581func (p Paths) FilterByExt(ext string) Paths {
582 ret := make(Paths, 0, len(p))
583 for _, path := range p {
584 if path.Ext() == ext {
585 ret = append(ret, path)
586 }
587 }
588 return ret
589}
590
591// FilterOutByExt returns the subset of the paths that do not have extension ext
592func (p Paths) FilterOutByExt(ext string) Paths {
593 ret := make(Paths, 0, len(p))
594 for _, path := range p {
595 if path.Ext() != ext {
596 ret = append(ret, path)
597 }
598 }
599 return ret
600}
601
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700602// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
603// (including subdirectories) are in a contiguous subslice of the list, and can be found in
604// O(log(N)) time using a binary search on the directory prefix.
605type DirectorySortedPaths Paths
606
607func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
608 ret := append(DirectorySortedPaths(nil), paths...)
609 sort.Slice(ret, func(i, j int) bool {
610 return ret[i].String() < ret[j].String()
611 })
612 return ret
613}
614
615// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
616// that are in the specified directory and its subdirectories.
617func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
618 prefix := filepath.Clean(dir) + "/"
619 start := sort.Search(len(p), func(i int) bool {
620 return prefix < p[i].String()
621 })
622
623 ret := p[start:]
624
625 end := sort.Search(len(ret), func(i int) bool {
626 return !strings.HasPrefix(ret[i].String(), prefix)
627 })
628
629 ret = ret[:end]
630
631 return Paths(ret)
632}
633
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700634// WritablePaths is a slice of WritablePaths, used for multiple outputs.
635type WritablePaths []WritablePath
636
637// Strings returns the string forms of the writable paths.
638func (p WritablePaths) Strings() []string {
639 if p == nil {
640 return nil
641 }
642 ret := make([]string, len(p))
643 for i, path := range p {
644 ret[i] = path.String()
645 }
646 return ret
647}
648
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800649// Paths returns the WritablePaths as a Paths
650func (p WritablePaths) Paths() Paths {
651 if p == nil {
652 return nil
653 }
654 ret := make(Paths, len(p))
655 for i, path := range p {
656 ret[i] = path
657 }
658 return ret
659}
660
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700661type basePath struct {
662 path string
663 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800664 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700665}
666
667func (p basePath) Ext() string {
668 return filepath.Ext(p.path)
669}
670
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700671func (p basePath) Base() string {
672 return filepath.Base(p.path)
673}
674
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800675func (p basePath) Rel() string {
676 if p.rel != "" {
677 return p.rel
678 }
679 return p.path
680}
681
Colin Cross0875c522017-11-28 17:34:01 -0800682func (p basePath) String() string {
683 return p.path
684}
685
Colin Cross0db55682017-12-05 15:36:55 -0800686func (p basePath) withRel(rel string) basePath {
687 p.path = filepath.Join(p.path, rel)
688 p.rel = rel
689 return p
690}
691
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700692// SourcePath is a Path representing a file path rooted from SrcDir
693type SourcePath struct {
694 basePath
695}
696
697var _ Path = SourcePath{}
698
Colin Cross0db55682017-12-05 15:36:55 -0800699func (p SourcePath) withRel(rel string) SourcePath {
700 p.basePath = p.basePath.withRel(rel)
701 return p
702}
703
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700704// safePathForSource is for paths that we expect are safe -- only for use by go
705// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700706func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
707 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800708 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700709 if err != nil {
710 return ret, err
711 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700712
Colin Cross7b3dcc32019-01-24 13:14:39 -0800713 // absolute path already checked by validateSafePath
714 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800715 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700716 }
717
Colin Crossfe4bc362018-09-12 10:02:13 -0700718 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700719}
720
Colin Cross192e97a2018-02-22 14:21:02 -0800721// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
722func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000723 p, err := validatePath(pathComponents...)
724 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800725 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800726 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800727 }
728
Colin Cross7b3dcc32019-01-24 13:14:39 -0800729 // absolute path already checked by validatePath
730 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800731 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000732 }
733
Colin Cross192e97a2018-02-22 14:21:02 -0800734 return ret, nil
735}
736
737// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
738// path does not exist.
739func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
740 var files []string
741
742 if gctx, ok := ctx.(PathGlobContext); ok {
743 // Use glob to produce proper dependencies, even though we only want
744 // a single file.
745 files, err = gctx.GlobWithDeps(path.String(), nil)
746 } else {
747 var deps []string
748 // We cannot add build statements in this context, so we fall back to
749 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +0000750 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800751 ctx.AddNinjaFileDeps(deps...)
752 }
753
754 if err != nil {
755 return false, fmt.Errorf("glob: %s", err.Error())
756 }
757
758 return len(files) > 0, nil
759}
760
761// PathForSource joins the provided path components and validates that the result
762// neither escapes the source dir nor is in the out dir.
763// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
764func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
765 path, err := pathForSource(ctx, pathComponents...)
766 if err != nil {
767 reportPathError(ctx, err)
768 }
769
Colin Crosse3924e12018-08-15 20:18:53 -0700770 if pathtools.IsGlob(path.String()) {
771 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
772 }
773
Colin Cross192e97a2018-02-22 14:21:02 -0800774 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
775 exists, err := existsWithDependencies(ctx, path)
776 if err != nil {
777 reportPathError(ctx, err)
778 }
779 if !exists {
780 modCtx.AddMissingDependencies([]string{path.String()})
781 }
Colin Cross988414c2020-01-11 01:11:46 +0000782 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800783 reportPathErrorf(ctx, "%s: %s", path, err.Error())
784 } else if !exists {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800785 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800786 }
787 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700788}
789
Jeff Gaston734e3802017-04-10 15:47:24 -0700790// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700791// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
792// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800793func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800794 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800795 if err != nil {
796 reportPathError(ctx, err)
797 return OptionalPath{}
798 }
Colin Crossc48c1432018-02-23 07:09:01 +0000799
Colin Crosse3924e12018-08-15 20:18:53 -0700800 if pathtools.IsGlob(path.String()) {
801 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
802 return OptionalPath{}
803 }
804
Colin Cross192e97a2018-02-22 14:21:02 -0800805 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000806 if err != nil {
807 reportPathError(ctx, err)
808 return OptionalPath{}
809 }
Colin Cross192e97a2018-02-22 14:21:02 -0800810 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000811 return OptionalPath{}
812 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700813 return OptionalPathForPath(path)
814}
815
816func (p SourcePath) String() string {
817 return filepath.Join(p.config.srcDir, p.path)
818}
819
820// Join creates a new SourcePath with paths... joined with the current path. The
821// provided paths... may not use '..' to escape from the current path.
822func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800823 path, err := validatePath(paths...)
824 if err != nil {
825 reportPathError(ctx, err)
826 }
Colin Cross0db55682017-12-05 15:36:55 -0800827 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700828}
829
Colin Cross2fafa3e2019-03-05 12:39:51 -0800830// join is like Join but does less path validation.
831func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
832 path, err := validateSafePath(paths...)
833 if err != nil {
834 reportPathError(ctx, err)
835 }
836 return p.withRel(path)
837}
838
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700839// OverlayPath returns the overlay for `path' if it exists. This assumes that the
840// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700841func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700842 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800843 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700844 relDir = srcPath.path
845 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800846 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700847 return OptionalPath{}
848 }
849 dir := filepath.Join(p.config.srcDir, p.path, relDir)
850 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700851 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800852 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800853 }
Colin Cross461b4452018-02-23 09:22:42 -0800854 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700855 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800856 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700857 return OptionalPath{}
858 }
859 if len(paths) == 0 {
860 return OptionalPath{}
861 }
Colin Cross43f08db2018-11-12 10:13:39 -0800862 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700863 return OptionalPathForPath(PathForSource(ctx, relPath))
864}
865
Colin Cross70dda7e2019-10-01 22:05:35 -0700866// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700867type OutputPath struct {
868 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -0800869 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700870}
871
Colin Cross702e0f82017-10-18 17:27:54 -0700872func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800873 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -0800874 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700875 return p
876}
877
Colin Cross3063b782018-08-15 11:19:12 -0700878func (p OutputPath) WithoutRel() OutputPath {
879 p.basePath.rel = filepath.Base(p.basePath.path)
880 return p
881}
882
Paul Duffin9b478b02019-12-10 13:41:51 +0000883func (p OutputPath) buildDir() string {
884 return p.config.buildDir
885}
886
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700887var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +0000888var _ WritablePath = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700889
Jeff Gaston734e3802017-04-10 15:47:24 -0700890// PathForOutput joins the provided paths and returns an OutputPath that is
891// validated to not escape the build dir.
892// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
893func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800894 path, err := validatePath(pathComponents...)
895 if err != nil {
896 reportPathError(ctx, err)
897 }
Colin Crossd63c9a72020-01-29 16:52:50 -0800898 fullPath := filepath.Join(ctx.Config().buildDir, path)
899 path = fullPath[len(fullPath)-len(path):]
900 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700901}
902
Colin Cross40e33732019-02-15 11:08:35 -0800903// PathsForOutput returns Paths rooted from buildDir
904func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
905 ret := make(WritablePaths, len(paths))
906 for i, path := range paths {
907 ret[i] = PathForOutput(ctx, path)
908 }
909 return ret
910}
911
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700912func (p OutputPath) writablePath() {}
913
914func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -0800915 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700916}
917
918// Join creates a new OutputPath with paths... joined with the current path. The
919// provided paths... may not use '..' to escape from the current path.
920func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800921 path, err := validatePath(paths...)
922 if err != nil {
923 reportPathError(ctx, err)
924 }
Colin Cross0db55682017-12-05 15:36:55 -0800925 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700926}
927
Colin Cross8854a5a2019-02-11 14:14:16 -0800928// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
929func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
930 if strings.Contains(ext, "/") {
931 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
932 }
933 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800934 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800935 return ret
936}
937
Colin Cross40e33732019-02-15 11:08:35 -0800938// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
939func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
940 path, err := validatePath(paths...)
941 if err != nil {
942 reportPathError(ctx, err)
943 }
944
945 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800946 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800947 return ret
948}
949
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700950// PathForIntermediates returns an OutputPath representing the top-level
951// intermediates directory.
952func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800953 path, err := validatePath(paths...)
954 if err != nil {
955 reportPathError(ctx, err)
956 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700957 return PathForOutput(ctx, ".intermediates", path)
958}
959
Colin Cross07e51612019-03-05 12:46:40 -0800960var _ genPathProvider = SourcePath{}
961var _ objPathProvider = SourcePath{}
962var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700963
Colin Cross07e51612019-03-05 12:46:40 -0800964// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700965// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800966func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
967 p, err := validatePath(pathComponents...)
968 if err != nil {
969 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800970 }
Colin Cross8a497952019-03-05 22:25:09 -0800971 paths, err := expandOneSrcPath(ctx, p, nil)
972 if err != nil {
973 if depErr, ok := err.(missingDependencyError); ok {
974 if ctx.Config().AllowMissingDependencies() {
975 ctx.AddMissingDependencies(depErr.missingDeps)
976 } else {
977 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
978 }
979 } else {
980 reportPathError(ctx, err)
981 }
982 return nil
983 } else if len(paths) == 0 {
984 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
985 return nil
986 } else if len(paths) > 1 {
987 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
988 }
989 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700990}
991
Colin Cross07e51612019-03-05 12:46:40 -0800992func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
993 p, err := validatePath(paths...)
994 if err != nil {
995 reportPathError(ctx, err)
996 }
997
998 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
999 if err != nil {
1000 reportPathError(ctx, err)
1001 }
1002
1003 path.basePath.rel = p
1004
1005 return path
1006}
1007
Colin Cross2fafa3e2019-03-05 12:39:51 -08001008// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1009// will return the path relative to subDir in the module's source directory. If any input paths are not located
1010// inside subDir then a path error will be reported.
1011func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
1012 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001013 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001014 for i, path := range paths {
1015 rel := Rel(ctx, subDirFullPath.String(), path.String())
1016 paths[i] = subDirFullPath.join(ctx, rel)
1017 }
1018 return paths
1019}
1020
1021// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1022// module's source directory. If the input path is not located inside subDir then a path error will be reported.
1023func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001024 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001025 rel := Rel(ctx, subDirFullPath.String(), path.String())
1026 return subDirFullPath.Join(ctx, rel)
1027}
1028
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001029// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1030// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -07001031func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001032 if p == nil {
1033 return OptionalPath{}
1034 }
1035 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1036}
1037
Colin Cross07e51612019-03-05 12:46:40 -08001038func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001039 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001040}
1041
Colin Cross07e51612019-03-05 12:46:40 -08001042func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001043 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001044}
1045
Colin Cross07e51612019-03-05 12:46:40 -08001046func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001047 // TODO: Use full directory if the new ctx is not the current ctx?
1048 return PathForModuleRes(ctx, p.path, name)
1049}
1050
1051// ModuleOutPath is a Path representing a module's output directory.
1052type ModuleOutPath struct {
1053 OutputPath
1054}
1055
1056var _ Path = ModuleOutPath{}
1057
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001058func (p ModuleOutPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
1059 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1060}
1061
Colin Cross702e0f82017-10-18 17:27:54 -07001062func pathForModule(ctx ModuleContext) OutputPath {
1063 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1064}
1065
Logan Chien7eefdc42018-07-11 18:10:41 +08001066// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1067// reference abi dump for the given module. This is not guaranteed to be valid.
1068func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001069 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001070
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001071 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001072 if len(arches) == 0 {
1073 panic("device build with no primary arch")
1074 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001075 currentArch := ctx.Arch()
1076 archNameAndVariant := currentArch.ArchType.String()
1077 if currentArch.ArchVariant != "" {
1078 archNameAndVariant += "_" + currentArch.ArchVariant
1079 }
Logan Chien5237bed2018-07-11 17:15:57 +08001080
1081 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001082 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001083 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001084 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001085 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001086 } else {
1087 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001088 }
Logan Chien5237bed2018-07-11 17:15:57 +08001089
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001090 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001091
1092 var ext string
1093 if isGzip {
1094 ext = ".lsdump.gz"
1095 } else {
1096 ext = ".lsdump"
1097 }
1098
1099 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1100 version, binderBitness, archNameAndVariant, "source-based",
1101 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001102}
1103
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001104// PathForModuleOut returns a Path representing the paths... under the module's
1105// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001106func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001107 p, err := validatePath(paths...)
1108 if err != nil {
1109 reportPathError(ctx, err)
1110 }
Colin Cross702e0f82017-10-18 17:27:54 -07001111 return ModuleOutPath{
1112 OutputPath: pathForModule(ctx).withRel(p),
1113 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001114}
1115
1116// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1117// directory. Mainly used for generated sources.
1118type ModuleGenPath struct {
1119 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001120}
1121
1122var _ Path = ModuleGenPath{}
1123var _ genPathProvider = ModuleGenPath{}
1124var _ objPathProvider = ModuleGenPath{}
1125
1126// PathForModuleGen returns a Path representing the paths... under the module's
1127// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001128func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001129 p, err := validatePath(paths...)
1130 if err != nil {
1131 reportPathError(ctx, err)
1132 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001133 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001134 ModuleOutPath: ModuleOutPath{
1135 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1136 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001137 }
1138}
1139
Dan Willemsen21ec4902016-11-02 20:43:13 -07001140func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001141 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001142 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001143}
1144
Colin Cross635c3b02016-05-18 15:37:25 -07001145func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001146 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1147}
1148
1149// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1150// directory. Used for compiled objects.
1151type ModuleObjPath struct {
1152 ModuleOutPath
1153}
1154
1155var _ Path = ModuleObjPath{}
1156
1157// PathForModuleObj returns a Path representing the paths... under the module's
1158// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001159func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001160 p, err := validatePath(pathComponents...)
1161 if err != nil {
1162 reportPathError(ctx, err)
1163 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001164 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1165}
1166
1167// ModuleResPath is a a Path representing the 'res' directory in a module's
1168// output directory.
1169type ModuleResPath struct {
1170 ModuleOutPath
1171}
1172
1173var _ Path = ModuleResPath{}
1174
1175// PathForModuleRes returns a Path representing the paths... under the module's
1176// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001177func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001178 p, err := validatePath(pathComponents...)
1179 if err != nil {
1180 reportPathError(ctx, err)
1181 }
1182
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001183 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1184}
1185
Colin Cross70dda7e2019-10-01 22:05:35 -07001186// InstallPath is a Path representing a installed file path rooted from the build directory
1187type InstallPath struct {
1188 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001189
1190 baseDir string // "../" for Make paths to convert "out/soong" to "out", "" for Soong paths
Colin Cross70dda7e2019-10-01 22:05:35 -07001191}
1192
Paul Duffin9b478b02019-12-10 13:41:51 +00001193func (p InstallPath) buildDir() string {
1194 return p.config.buildDir
1195}
1196
1197var _ Path = InstallPath{}
1198var _ WritablePath = InstallPath{}
1199
Colin Cross70dda7e2019-10-01 22:05:35 -07001200func (p InstallPath) writablePath() {}
1201
1202func (p InstallPath) String() string {
Colin Crossff6c33d2019-10-02 16:01:35 -07001203 return filepath.Join(p.config.buildDir, p.baseDir, p.path)
Colin Cross70dda7e2019-10-01 22:05:35 -07001204}
1205
1206// Join creates a new InstallPath with paths... joined with the current path. The
1207// provided paths... may not use '..' to escape from the current path.
1208func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1209 path, err := validatePath(paths...)
1210 if err != nil {
1211 reportPathError(ctx, err)
1212 }
1213 return p.withRel(path)
1214}
1215
1216func (p InstallPath) withRel(rel string) InstallPath {
1217 p.basePath = p.basePath.withRel(rel)
1218 return p
1219}
1220
Colin Crossff6c33d2019-10-02 16:01:35 -07001221// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1222// i.e. out/ instead of out/soong/.
1223func (p InstallPath) ToMakePath() InstallPath {
1224 p.baseDir = "../"
1225 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001226}
1227
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001228// PathForModuleInstall returns a Path representing the install path for the
1229// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001230func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001231 os := ctx.Os()
1232 if forceOS := ctx.InstallForceOS(); forceOS != nil {
1233 os = *forceOS
1234 }
1235 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001236
1237 ret := pathForInstall(ctx, os, partition, ctx.Debug(), pathComponents...)
1238
1239 if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
1240 ret = ret.ToMakePath()
1241 }
1242
1243 return ret
1244}
1245
1246func pathForInstall(ctx PathContext, os OsType, partition string, debug bool,
1247 pathComponents ...string) InstallPath {
1248
1249 var outPaths []string
1250
Colin Cross6e359402020-02-10 15:29:54 -08001251 if os.Class == Device {
Colin Cross6510f912017-11-29 00:27:14 -08001252 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001253 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001254 switch os {
Dan Willemsen866b5632017-09-22 12:28:24 -07001255 case Linux:
Colin Cross6e359402020-02-10 15:29:54 -08001256 outPaths = []string{"host", "linux-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001257 case LinuxBionic:
1258 // TODO: should this be a separate top level, or shared with linux-x86?
Colin Cross6e359402020-02-10 15:29:54 -08001259 outPaths = []string{"host", "linux_bionic-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001260 default:
Colin Cross6e359402020-02-10 15:29:54 -08001261 outPaths = []string{"host", os.String() + "-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001262 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001263 }
Colin Cross609c49a2020-02-13 13:20:11 -08001264 if debug {
Dan Willemsen782a2d12015-12-21 14:55:28 -08001265 outPaths = append([]string{"debug"}, outPaths...)
1266 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001267 outPaths = append(outPaths, pathComponents...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001268
1269 path, err := validatePath(outPaths...)
1270 if err != nil {
1271 reportPathError(ctx, err)
1272 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001273
1274 ret := InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Crossff6c33d2019-10-02 16:01:35 -07001275
1276 return ret
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001277}
1278
Colin Cross70dda7e2019-10-01 22:05:35 -07001279func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1280 paths = append([]string{"ndk"}, paths...)
1281 path, err := validatePath(paths...)
1282 if err != nil {
1283 reportPathError(ctx, err)
1284 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001285 return InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Cross70dda7e2019-10-01 22:05:35 -07001286}
1287
1288func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001289 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1290
1291 return "/" + rel
1292}
1293
Colin Cross6e359402020-02-10 15:29:54 -08001294func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001295 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001296 if ctx.InstallInTestcases() {
1297 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001298 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001299 } else if os.Class == Device {
1300 if ctx.InstallInData() {
1301 partition = "data"
1302 } else if ctx.InstallInRamdisk() {
1303 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1304 partition = "recovery/root/first_stage_ramdisk"
1305 } else {
1306 partition = "ramdisk"
1307 }
1308 if !ctx.InstallInRoot() {
1309 partition += "/system"
1310 }
1311 } else if ctx.InstallInRecovery() {
1312 if ctx.InstallInRoot() {
1313 partition = "recovery/root"
1314 } else {
1315 // the layout of recovery partion is the same as that of system partition
1316 partition = "recovery/root/system"
1317 }
1318 } else if ctx.SocSpecific() {
1319 partition = ctx.DeviceConfig().VendorPath()
1320 } else if ctx.DeviceSpecific() {
1321 partition = ctx.DeviceConfig().OdmPath()
1322 } else if ctx.ProductSpecific() {
1323 partition = ctx.DeviceConfig().ProductPath()
1324 } else if ctx.SystemExtSpecific() {
1325 partition = ctx.DeviceConfig().SystemExtPath()
1326 } else if ctx.InstallInRoot() {
1327 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001328 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001329 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001330 }
Colin Cross6e359402020-02-10 15:29:54 -08001331 if ctx.InstallInSanitizerDir() {
1332 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001333 }
Colin Cross43f08db2018-11-12 10:13:39 -08001334 }
1335 return partition
1336}
1337
Colin Cross609c49a2020-02-13 13:20:11 -08001338type InstallPaths []InstallPath
1339
1340// Paths returns the InstallPaths as a Paths
1341func (p InstallPaths) Paths() Paths {
1342 if p == nil {
1343 return nil
1344 }
1345 ret := make(Paths, len(p))
1346 for i, path := range p {
1347 ret[i] = path
1348 }
1349 return ret
1350}
1351
1352// Strings returns the string forms of the install paths.
1353func (p InstallPaths) Strings() []string {
1354 if p == nil {
1355 return nil
1356 }
1357 ret := make([]string, len(p))
1358 for i, path := range p {
1359 ret[i] = path.String()
1360 }
1361 return ret
1362}
1363
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001364// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001365// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001366func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001367 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001368 path := filepath.Clean(path)
1369 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001370 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001371 }
1372 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001373 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1374 // variables. '..' may remove the entire ninja variable, even if it
1375 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001376 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001377}
1378
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001379// validatePath validates that a path does not include ninja variables, and that
1380// each path component does not attempt to leave its component. Returns a joined
1381// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001382func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001383 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001384 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001385 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001386 }
1387 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001388 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001389}
Colin Cross5b529592017-05-09 13:34:34 -07001390
Colin Cross0875c522017-11-28 17:34:01 -08001391func PathForPhony(ctx PathContext, phony string) WritablePath {
1392 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001393 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001394 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001395 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001396}
1397
Colin Cross74e3fe42017-12-11 15:51:44 -08001398type PhonyPath struct {
1399 basePath
1400}
1401
1402func (p PhonyPath) writablePath() {}
1403
Paul Duffin9b478b02019-12-10 13:41:51 +00001404func (p PhonyPath) buildDir() string {
1405 return p.config.buildDir
1406}
1407
Colin Cross74e3fe42017-12-11 15:51:44 -08001408var _ Path = PhonyPath{}
1409var _ WritablePath = PhonyPath{}
1410
Colin Cross5b529592017-05-09 13:34:34 -07001411type testPath struct {
1412 basePath
1413}
1414
1415func (p testPath) String() string {
1416 return p.path
1417}
1418
Colin Cross40e33732019-02-15 11:08:35 -08001419// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1420// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001421func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001422 p, err := validateSafePath(paths...)
1423 if err != nil {
1424 panic(err)
1425 }
Colin Cross5b529592017-05-09 13:34:34 -07001426 return testPath{basePath{path: p, rel: p}}
1427}
1428
Colin Cross40e33732019-02-15 11:08:35 -08001429// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1430func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001431 p := make(Paths, len(strs))
1432 for i, s := range strs {
1433 p[i] = PathForTesting(s)
1434 }
1435
1436 return p
1437}
Colin Cross43f08db2018-11-12 10:13:39 -08001438
Colin Cross40e33732019-02-15 11:08:35 -08001439type testPathContext struct {
1440 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001441}
1442
Colin Cross40e33732019-02-15 11:08:35 -08001443func (x *testPathContext) Config() Config { return x.config }
1444func (x *testPathContext) AddNinjaFileDeps(...string) {}
1445
1446// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1447// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001448func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001449 return &testPathContext{
1450 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001451 }
1452}
1453
Colin Cross43f08db2018-11-12 10:13:39 -08001454// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1455// targetPath is not inside basePath.
1456func Rel(ctx PathContext, basePath string, targetPath string) string {
1457 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1458 if !isRel {
1459 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1460 return ""
1461 }
1462 return rel
1463}
1464
1465// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1466// targetPath is not inside basePath.
1467func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001468 rel, isRel, err := maybeRelErr(basePath, targetPath)
1469 if err != nil {
1470 reportPathError(ctx, err)
1471 }
1472 return rel, isRel
1473}
1474
1475func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001476 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1477 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001478 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001479 }
1480 rel, err := filepath.Rel(basePath, targetPath)
1481 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001482 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001483 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001484 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001485 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001486 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001487}
Colin Cross988414c2020-01-11 01:11:46 +00001488
1489// Writes a file to the output directory. Attempting to write directly to the output directory
1490// will fail due to the sandbox of the soong_build process.
1491func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1492 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1493}
1494
1495func absolutePath(path string) string {
1496 if filepath.IsAbs(path) {
1497 return path
1498 }
1499 return filepath.Join(absSrcDir, path)
1500}