blob: 8b373da064b3fb0d7b3f013deea3f40a4a31dfe1 [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 {
473 k := 0
474outer:
475 for i := 0; i < len(list); i++ {
476 for j := 0; j < k; j++ {
477 if list[i] == list[j] {
478 continue outer
479 }
480 }
481 list[k] = list[i]
482 k++
483 }
484 return list[:k]
485}
486
Colin Crossb6715442017-10-24 11:13:31 -0700487// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
488// modifies the Paths slice contents in place, and returns a subslice of the original slice.
489func LastUniquePaths(list Paths) Paths {
490 totalSkip := 0
491 for i := len(list) - 1; i >= totalSkip; i-- {
492 skip := 0
493 for j := i - 1; j >= totalSkip; j-- {
494 if list[i] == list[j] {
495 skip++
496 } else {
497 list[j+skip] = list[j]
498 }
499 }
500 totalSkip += skip
501 }
502 return list[totalSkip:]
503}
504
Colin Crossa140bb02018-04-17 10:52:26 -0700505// ReversePaths returns a copy of a Paths in reverse order.
506func ReversePaths(list Paths) Paths {
507 if list == nil {
508 return nil
509 }
510 ret := make(Paths, len(list))
511 for i := range list {
512 ret[i] = list[len(list)-1-i]
513 }
514 return ret
515}
516
Jeff Gaston294356f2017-09-27 17:05:30 -0700517func indexPathList(s Path, list []Path) int {
518 for i, l := range list {
519 if l == s {
520 return i
521 }
522 }
523
524 return -1
525}
526
527func inPathList(p Path, list []Path) bool {
528 return indexPathList(p, list) != -1
529}
530
531func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000532 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
533}
534
535func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700536 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000537 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700538 filtered = append(filtered, l)
539 } else {
540 remainder = append(remainder, l)
541 }
542 }
543
544 return
545}
546
Colin Cross93e85952017-08-15 13:34:18 -0700547// HasExt returns true of any of the paths have extension ext, otherwise false
548func (p Paths) HasExt(ext string) bool {
549 for _, path := range p {
550 if path.Ext() == ext {
551 return true
552 }
553 }
554
555 return false
556}
557
558// FilterByExt returns the subset of the paths that have extension ext
559func (p Paths) FilterByExt(ext string) Paths {
560 ret := make(Paths, 0, len(p))
561 for _, path := range p {
562 if path.Ext() == ext {
563 ret = append(ret, path)
564 }
565 }
566 return ret
567}
568
569// FilterOutByExt returns the subset of the paths that do not have extension ext
570func (p Paths) FilterOutByExt(ext string) Paths {
571 ret := make(Paths, 0, len(p))
572 for _, path := range p {
573 if path.Ext() != ext {
574 ret = append(ret, path)
575 }
576 }
577 return ret
578}
579
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700580// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
581// (including subdirectories) are in a contiguous subslice of the list, and can be found in
582// O(log(N)) time using a binary search on the directory prefix.
583type DirectorySortedPaths Paths
584
585func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
586 ret := append(DirectorySortedPaths(nil), paths...)
587 sort.Slice(ret, func(i, j int) bool {
588 return ret[i].String() < ret[j].String()
589 })
590 return ret
591}
592
593// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
594// that are in the specified directory and its subdirectories.
595func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
596 prefix := filepath.Clean(dir) + "/"
597 start := sort.Search(len(p), func(i int) bool {
598 return prefix < p[i].String()
599 })
600
601 ret := p[start:]
602
603 end := sort.Search(len(ret), func(i int) bool {
604 return !strings.HasPrefix(ret[i].String(), prefix)
605 })
606
607 ret = ret[:end]
608
609 return Paths(ret)
610}
611
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700612// WritablePaths is a slice of WritablePaths, used for multiple outputs.
613type WritablePaths []WritablePath
614
615// Strings returns the string forms of the writable paths.
616func (p WritablePaths) Strings() []string {
617 if p == nil {
618 return nil
619 }
620 ret := make([]string, len(p))
621 for i, path := range p {
622 ret[i] = path.String()
623 }
624 return ret
625}
626
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800627// Paths returns the WritablePaths as a Paths
628func (p WritablePaths) Paths() Paths {
629 if p == nil {
630 return nil
631 }
632 ret := make(Paths, len(p))
633 for i, path := range p {
634 ret[i] = path
635 }
636 return ret
637}
638
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700639type basePath struct {
640 path string
641 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800642 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700643}
644
645func (p basePath) Ext() string {
646 return filepath.Ext(p.path)
647}
648
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700649func (p basePath) Base() string {
650 return filepath.Base(p.path)
651}
652
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800653func (p basePath) Rel() string {
654 if p.rel != "" {
655 return p.rel
656 }
657 return p.path
658}
659
Colin Cross0875c522017-11-28 17:34:01 -0800660func (p basePath) String() string {
661 return p.path
662}
663
Colin Cross0db55682017-12-05 15:36:55 -0800664func (p basePath) withRel(rel string) basePath {
665 p.path = filepath.Join(p.path, rel)
666 p.rel = rel
667 return p
668}
669
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700670// SourcePath is a Path representing a file path rooted from SrcDir
671type SourcePath struct {
672 basePath
673}
674
675var _ Path = SourcePath{}
676
Colin Cross0db55682017-12-05 15:36:55 -0800677func (p SourcePath) withRel(rel string) SourcePath {
678 p.basePath = p.basePath.withRel(rel)
679 return p
680}
681
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700682// safePathForSource is for paths that we expect are safe -- only for use by go
683// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700684func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
685 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800686 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700687 if err != nil {
688 return ret, err
689 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700690
Colin Cross7b3dcc32019-01-24 13:14:39 -0800691 // absolute path already checked by validateSafePath
692 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800693 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700694 }
695
Colin Crossfe4bc362018-09-12 10:02:13 -0700696 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700697}
698
Colin Cross192e97a2018-02-22 14:21:02 -0800699// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
700func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000701 p, err := validatePath(pathComponents...)
702 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800703 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800704 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800705 }
706
Colin Cross7b3dcc32019-01-24 13:14:39 -0800707 // absolute path already checked by validatePath
708 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800709 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000710 }
711
Colin Cross192e97a2018-02-22 14:21:02 -0800712 return ret, nil
713}
714
715// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
716// path does not exist.
717func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
718 var files []string
719
720 if gctx, ok := ctx.(PathGlobContext); ok {
721 // Use glob to produce proper dependencies, even though we only want
722 // a single file.
723 files, err = gctx.GlobWithDeps(path.String(), nil)
724 } else {
725 var deps []string
726 // We cannot add build statements in this context, so we fall back to
727 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +0000728 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800729 ctx.AddNinjaFileDeps(deps...)
730 }
731
732 if err != nil {
733 return false, fmt.Errorf("glob: %s", err.Error())
734 }
735
736 return len(files) > 0, nil
737}
738
739// PathForSource joins the provided path components and validates that the result
740// neither escapes the source dir nor is in the out dir.
741// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
742func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
743 path, err := pathForSource(ctx, pathComponents...)
744 if err != nil {
745 reportPathError(ctx, err)
746 }
747
Colin Crosse3924e12018-08-15 20:18:53 -0700748 if pathtools.IsGlob(path.String()) {
749 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
750 }
751
Colin Cross192e97a2018-02-22 14:21:02 -0800752 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
753 exists, err := existsWithDependencies(ctx, path)
754 if err != nil {
755 reportPathError(ctx, err)
756 }
757 if !exists {
758 modCtx.AddMissingDependencies([]string{path.String()})
759 }
Colin Cross988414c2020-01-11 01:11:46 +0000760 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800761 reportPathErrorf(ctx, "%s: %s", path, err.Error())
762 } else if !exists {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800763 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800764 }
765 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700766}
767
Jeff Gaston734e3802017-04-10 15:47:24 -0700768// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700769// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
770// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800771func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800772 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800773 if err != nil {
774 reportPathError(ctx, err)
775 return OptionalPath{}
776 }
Colin Crossc48c1432018-02-23 07:09:01 +0000777
Colin Crosse3924e12018-08-15 20:18:53 -0700778 if pathtools.IsGlob(path.String()) {
779 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
780 return OptionalPath{}
781 }
782
Colin Cross192e97a2018-02-22 14:21:02 -0800783 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000784 if err != nil {
785 reportPathError(ctx, err)
786 return OptionalPath{}
787 }
Colin Cross192e97a2018-02-22 14:21:02 -0800788 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000789 return OptionalPath{}
790 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700791 return OptionalPathForPath(path)
792}
793
794func (p SourcePath) String() string {
795 return filepath.Join(p.config.srcDir, p.path)
796}
797
798// Join creates a new SourcePath with paths... joined with the current path. The
799// provided paths... may not use '..' to escape from the current path.
800func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800801 path, err := validatePath(paths...)
802 if err != nil {
803 reportPathError(ctx, err)
804 }
Colin Cross0db55682017-12-05 15:36:55 -0800805 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700806}
807
Colin Cross2fafa3e2019-03-05 12:39:51 -0800808// join is like Join but does less path validation.
809func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
810 path, err := validateSafePath(paths...)
811 if err != nil {
812 reportPathError(ctx, err)
813 }
814 return p.withRel(path)
815}
816
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700817// OverlayPath returns the overlay for `path' if it exists. This assumes that the
818// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700819func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700820 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800821 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700822 relDir = srcPath.path
823 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800824 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700825 return OptionalPath{}
826 }
827 dir := filepath.Join(p.config.srcDir, p.path, relDir)
828 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700829 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800830 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800831 }
Colin Cross461b4452018-02-23 09:22:42 -0800832 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700833 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800834 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700835 return OptionalPath{}
836 }
837 if len(paths) == 0 {
838 return OptionalPath{}
839 }
Colin Cross43f08db2018-11-12 10:13:39 -0800840 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700841 return OptionalPathForPath(PathForSource(ctx, relPath))
842}
843
Colin Cross70dda7e2019-10-01 22:05:35 -0700844// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700845type OutputPath struct {
846 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -0800847 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700848}
849
Colin Cross702e0f82017-10-18 17:27:54 -0700850func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800851 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -0800852 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700853 return p
854}
855
Colin Cross3063b782018-08-15 11:19:12 -0700856func (p OutputPath) WithoutRel() OutputPath {
857 p.basePath.rel = filepath.Base(p.basePath.path)
858 return p
859}
860
Paul Duffin9b478b02019-12-10 13:41:51 +0000861func (p OutputPath) buildDir() string {
862 return p.config.buildDir
863}
864
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700865var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +0000866var _ WritablePath = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700867
Jeff Gaston734e3802017-04-10 15:47:24 -0700868// PathForOutput joins the provided paths and returns an OutputPath that is
869// validated to not escape the build dir.
870// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
871func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800872 path, err := validatePath(pathComponents...)
873 if err != nil {
874 reportPathError(ctx, err)
875 }
Colin Crossd63c9a72020-01-29 16:52:50 -0800876 fullPath := filepath.Join(ctx.Config().buildDir, path)
877 path = fullPath[len(fullPath)-len(path):]
878 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700879}
880
Colin Cross40e33732019-02-15 11:08:35 -0800881// PathsForOutput returns Paths rooted from buildDir
882func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
883 ret := make(WritablePaths, len(paths))
884 for i, path := range paths {
885 ret[i] = PathForOutput(ctx, path)
886 }
887 return ret
888}
889
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700890func (p OutputPath) writablePath() {}
891
892func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -0800893 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700894}
895
896// Join creates a new OutputPath with paths... joined with the current path. The
897// provided paths... may not use '..' to escape from the current path.
898func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800899 path, err := validatePath(paths...)
900 if err != nil {
901 reportPathError(ctx, err)
902 }
Colin Cross0db55682017-12-05 15:36:55 -0800903 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700904}
905
Colin Cross8854a5a2019-02-11 14:14:16 -0800906// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
907func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
908 if strings.Contains(ext, "/") {
909 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
910 }
911 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800912 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800913 return ret
914}
915
Colin Cross40e33732019-02-15 11:08:35 -0800916// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
917func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
918 path, err := validatePath(paths...)
919 if err != nil {
920 reportPathError(ctx, err)
921 }
922
923 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800924 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800925 return ret
926}
927
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700928// PathForIntermediates returns an OutputPath representing the top-level
929// intermediates directory.
930func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800931 path, err := validatePath(paths...)
932 if err != nil {
933 reportPathError(ctx, err)
934 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700935 return PathForOutput(ctx, ".intermediates", path)
936}
937
Colin Cross07e51612019-03-05 12:46:40 -0800938var _ genPathProvider = SourcePath{}
939var _ objPathProvider = SourcePath{}
940var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700941
Colin Cross07e51612019-03-05 12:46:40 -0800942// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700943// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800944func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
945 p, err := validatePath(pathComponents...)
946 if err != nil {
947 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800948 }
Colin Cross8a497952019-03-05 22:25:09 -0800949 paths, err := expandOneSrcPath(ctx, p, nil)
950 if err != nil {
951 if depErr, ok := err.(missingDependencyError); ok {
952 if ctx.Config().AllowMissingDependencies() {
953 ctx.AddMissingDependencies(depErr.missingDeps)
954 } else {
955 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
956 }
957 } else {
958 reportPathError(ctx, err)
959 }
960 return nil
961 } else if len(paths) == 0 {
962 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
963 return nil
964 } else if len(paths) > 1 {
965 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
966 }
967 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700968}
969
Colin Cross07e51612019-03-05 12:46:40 -0800970func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
971 p, err := validatePath(paths...)
972 if err != nil {
973 reportPathError(ctx, err)
974 }
975
976 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
977 if err != nil {
978 reportPathError(ctx, err)
979 }
980
981 path.basePath.rel = p
982
983 return path
984}
985
Colin Cross2fafa3e2019-03-05 12:39:51 -0800986// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
987// will return the path relative to subDir in the module's source directory. If any input paths are not located
988// inside subDir then a path error will be reported.
989func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
990 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -0800991 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800992 for i, path := range paths {
993 rel := Rel(ctx, subDirFullPath.String(), path.String())
994 paths[i] = subDirFullPath.join(ctx, rel)
995 }
996 return paths
997}
998
999// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1000// module's source directory. If the input path is not located inside subDir then a path error will be reported.
1001func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001002 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001003 rel := Rel(ctx, subDirFullPath.String(), path.String())
1004 return subDirFullPath.Join(ctx, rel)
1005}
1006
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001007// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1008// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -07001009func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001010 if p == nil {
1011 return OptionalPath{}
1012 }
1013 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1014}
1015
Colin Cross07e51612019-03-05 12:46:40 -08001016func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001017 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001018}
1019
Colin Cross07e51612019-03-05 12:46:40 -08001020func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001021 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001022}
1023
Colin Cross07e51612019-03-05 12:46:40 -08001024func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001025 // TODO: Use full directory if the new ctx is not the current ctx?
1026 return PathForModuleRes(ctx, p.path, name)
1027}
1028
1029// ModuleOutPath is a Path representing a module's output directory.
1030type ModuleOutPath struct {
1031 OutputPath
1032}
1033
1034var _ Path = ModuleOutPath{}
1035
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001036func (p ModuleOutPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
1037 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1038}
1039
Colin Cross702e0f82017-10-18 17:27:54 -07001040func pathForModule(ctx ModuleContext) OutputPath {
1041 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1042}
1043
Logan Chien7eefdc42018-07-11 18:10:41 +08001044// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1045// reference abi dump for the given module. This is not guaranteed to be valid.
1046func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001047 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001048
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001049 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001050 if len(arches) == 0 {
1051 panic("device build with no primary arch")
1052 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001053 currentArch := ctx.Arch()
1054 archNameAndVariant := currentArch.ArchType.String()
1055 if currentArch.ArchVariant != "" {
1056 archNameAndVariant += "_" + currentArch.ArchVariant
1057 }
Logan Chien5237bed2018-07-11 17:15:57 +08001058
1059 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001060 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001061 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001062 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001063 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001064 } else {
1065 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001066 }
Logan Chien5237bed2018-07-11 17:15:57 +08001067
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001068 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001069
1070 var ext string
1071 if isGzip {
1072 ext = ".lsdump.gz"
1073 } else {
1074 ext = ".lsdump"
1075 }
1076
1077 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1078 version, binderBitness, archNameAndVariant, "source-based",
1079 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001080}
1081
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001082// PathForModuleOut returns a Path representing the paths... under the module's
1083// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001084func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001085 p, err := validatePath(paths...)
1086 if err != nil {
1087 reportPathError(ctx, err)
1088 }
Colin Cross702e0f82017-10-18 17:27:54 -07001089 return ModuleOutPath{
1090 OutputPath: pathForModule(ctx).withRel(p),
1091 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001092}
1093
1094// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1095// directory. Mainly used for generated sources.
1096type ModuleGenPath struct {
1097 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001098}
1099
1100var _ Path = ModuleGenPath{}
1101var _ genPathProvider = ModuleGenPath{}
1102var _ objPathProvider = ModuleGenPath{}
1103
1104// PathForModuleGen returns a Path representing the paths... under the module's
1105// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001106func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001107 p, err := validatePath(paths...)
1108 if err != nil {
1109 reportPathError(ctx, err)
1110 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001111 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001112 ModuleOutPath: ModuleOutPath{
1113 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1114 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001115 }
1116}
1117
Dan Willemsen21ec4902016-11-02 20:43:13 -07001118func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001119 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001120 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001121}
1122
Colin Cross635c3b02016-05-18 15:37:25 -07001123func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001124 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1125}
1126
1127// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1128// directory. Used for compiled objects.
1129type ModuleObjPath struct {
1130 ModuleOutPath
1131}
1132
1133var _ Path = ModuleObjPath{}
1134
1135// PathForModuleObj returns a Path representing the paths... under the module's
1136// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001137func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001138 p, err := validatePath(pathComponents...)
1139 if err != nil {
1140 reportPathError(ctx, err)
1141 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001142 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1143}
1144
1145// ModuleResPath is a a Path representing the 'res' directory in a module's
1146// output directory.
1147type ModuleResPath struct {
1148 ModuleOutPath
1149}
1150
1151var _ Path = ModuleResPath{}
1152
1153// PathForModuleRes returns a Path representing the paths... under the module's
1154// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001155func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001156 p, err := validatePath(pathComponents...)
1157 if err != nil {
1158 reportPathError(ctx, err)
1159 }
1160
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001161 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1162}
1163
Colin Cross70dda7e2019-10-01 22:05:35 -07001164// InstallPath is a Path representing a installed file path rooted from the build directory
1165type InstallPath struct {
1166 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001167
1168 baseDir string // "../" for Make paths to convert "out/soong" to "out", "" for Soong paths
Colin Cross70dda7e2019-10-01 22:05:35 -07001169}
1170
Paul Duffin9b478b02019-12-10 13:41:51 +00001171func (p InstallPath) buildDir() string {
1172 return p.config.buildDir
1173}
1174
1175var _ Path = InstallPath{}
1176var _ WritablePath = InstallPath{}
1177
Colin Cross70dda7e2019-10-01 22:05:35 -07001178func (p InstallPath) writablePath() {}
1179
1180func (p InstallPath) String() string {
Colin Crossff6c33d2019-10-02 16:01:35 -07001181 return filepath.Join(p.config.buildDir, p.baseDir, p.path)
Colin Cross70dda7e2019-10-01 22:05:35 -07001182}
1183
1184// Join creates a new InstallPath with paths... joined with the current path. The
1185// provided paths... may not use '..' to escape from the current path.
1186func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1187 path, err := validatePath(paths...)
1188 if err != nil {
1189 reportPathError(ctx, err)
1190 }
1191 return p.withRel(path)
1192}
1193
1194func (p InstallPath) withRel(rel string) InstallPath {
1195 p.basePath = p.basePath.withRel(rel)
1196 return p
1197}
1198
Colin Crossff6c33d2019-10-02 16:01:35 -07001199// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1200// i.e. out/ instead of out/soong/.
1201func (p InstallPath) ToMakePath() InstallPath {
1202 p.baseDir = "../"
1203 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001204}
1205
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001206// PathForModuleInstall returns a Path representing the install path for the
1207// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001208func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001209 os := ctx.Os()
1210 if forceOS := ctx.InstallForceOS(); forceOS != nil {
1211 os = *forceOS
1212 }
1213 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001214
1215 ret := pathForInstall(ctx, os, partition, ctx.Debug(), pathComponents...)
1216
1217 if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
1218 ret = ret.ToMakePath()
1219 }
1220
1221 return ret
1222}
1223
1224func pathForInstall(ctx PathContext, os OsType, partition string, debug bool,
1225 pathComponents ...string) InstallPath {
1226
1227 var outPaths []string
1228
Colin Cross6e359402020-02-10 15:29:54 -08001229 if os.Class == Device {
Colin Cross6510f912017-11-29 00:27:14 -08001230 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001231 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001232 switch os {
Dan Willemsen866b5632017-09-22 12:28:24 -07001233 case Linux:
Colin Cross6e359402020-02-10 15:29:54 -08001234 outPaths = []string{"host", "linux-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001235 case LinuxBionic:
1236 // TODO: should this be a separate top level, or shared with linux-x86?
Colin Cross6e359402020-02-10 15:29:54 -08001237 outPaths = []string{"host", "linux_bionic-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001238 default:
Colin Cross6e359402020-02-10 15:29:54 -08001239 outPaths = []string{"host", os.String() + "-x86", partition}
Dan Willemsen866b5632017-09-22 12:28:24 -07001240 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001241 }
Colin Cross609c49a2020-02-13 13:20:11 -08001242 if debug {
Dan Willemsen782a2d12015-12-21 14:55:28 -08001243 outPaths = append([]string{"debug"}, outPaths...)
1244 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001245 outPaths = append(outPaths, pathComponents...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001246
1247 path, err := validatePath(outPaths...)
1248 if err != nil {
1249 reportPathError(ctx, err)
1250 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001251
1252 ret := InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Crossff6c33d2019-10-02 16:01:35 -07001253
1254 return ret
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001255}
1256
Colin Cross70dda7e2019-10-01 22:05:35 -07001257func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1258 paths = append([]string{"ndk"}, paths...)
1259 path, err := validatePath(paths...)
1260 if err != nil {
1261 reportPathError(ctx, err)
1262 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001263 return InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Cross70dda7e2019-10-01 22:05:35 -07001264}
1265
1266func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001267 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1268
1269 return "/" + rel
1270}
1271
Colin Cross6e359402020-02-10 15:29:54 -08001272func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001273 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001274 if ctx.InstallInTestcases() {
1275 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001276 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001277 } else if os.Class == Device {
1278 if ctx.InstallInData() {
1279 partition = "data"
1280 } else if ctx.InstallInRamdisk() {
1281 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1282 partition = "recovery/root/first_stage_ramdisk"
1283 } else {
1284 partition = "ramdisk"
1285 }
1286 if !ctx.InstallInRoot() {
1287 partition += "/system"
1288 }
1289 } else if ctx.InstallInRecovery() {
1290 if ctx.InstallInRoot() {
1291 partition = "recovery/root"
1292 } else {
1293 // the layout of recovery partion is the same as that of system partition
1294 partition = "recovery/root/system"
1295 }
1296 } else if ctx.SocSpecific() {
1297 partition = ctx.DeviceConfig().VendorPath()
1298 } else if ctx.DeviceSpecific() {
1299 partition = ctx.DeviceConfig().OdmPath()
1300 } else if ctx.ProductSpecific() {
1301 partition = ctx.DeviceConfig().ProductPath()
1302 } else if ctx.SystemExtSpecific() {
1303 partition = ctx.DeviceConfig().SystemExtPath()
1304 } else if ctx.InstallInRoot() {
1305 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001306 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001307 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001308 }
Colin Cross6e359402020-02-10 15:29:54 -08001309 if ctx.InstallInSanitizerDir() {
1310 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001311 }
Colin Cross43f08db2018-11-12 10:13:39 -08001312 }
1313 return partition
1314}
1315
Colin Cross609c49a2020-02-13 13:20:11 -08001316type InstallPaths []InstallPath
1317
1318// Paths returns the InstallPaths as a Paths
1319func (p InstallPaths) Paths() Paths {
1320 if p == nil {
1321 return nil
1322 }
1323 ret := make(Paths, len(p))
1324 for i, path := range p {
1325 ret[i] = path
1326 }
1327 return ret
1328}
1329
1330// Strings returns the string forms of the install paths.
1331func (p InstallPaths) Strings() []string {
1332 if p == nil {
1333 return nil
1334 }
1335 ret := make([]string, len(p))
1336 for i, path := range p {
1337 ret[i] = path.String()
1338 }
1339 return ret
1340}
1341
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001342// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001343// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001344func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001345 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001346 path := filepath.Clean(path)
1347 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001348 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001349 }
1350 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001351 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1352 // variables. '..' may remove the entire ninja variable, even if it
1353 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001354 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001355}
1356
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001357// validatePath validates that a path does not include ninja variables, and that
1358// each path component does not attempt to leave its component. Returns a joined
1359// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001360func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001361 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001362 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001363 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001364 }
1365 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001366 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001367}
Colin Cross5b529592017-05-09 13:34:34 -07001368
Colin Cross0875c522017-11-28 17:34:01 -08001369func PathForPhony(ctx PathContext, phony string) WritablePath {
1370 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001371 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001372 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001373 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001374}
1375
Colin Cross74e3fe42017-12-11 15:51:44 -08001376type PhonyPath struct {
1377 basePath
1378}
1379
1380func (p PhonyPath) writablePath() {}
1381
Paul Duffin9b478b02019-12-10 13:41:51 +00001382func (p PhonyPath) buildDir() string {
1383 return p.config.buildDir
1384}
1385
Colin Cross74e3fe42017-12-11 15:51:44 -08001386var _ Path = PhonyPath{}
1387var _ WritablePath = PhonyPath{}
1388
Colin Cross5b529592017-05-09 13:34:34 -07001389type testPath struct {
1390 basePath
1391}
1392
1393func (p testPath) String() string {
1394 return p.path
1395}
1396
Colin Cross40e33732019-02-15 11:08:35 -08001397// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1398// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001399func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001400 p, err := validateSafePath(paths...)
1401 if err != nil {
1402 panic(err)
1403 }
Colin Cross5b529592017-05-09 13:34:34 -07001404 return testPath{basePath{path: p, rel: p}}
1405}
1406
Colin Cross40e33732019-02-15 11:08:35 -08001407// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1408func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001409 p := make(Paths, len(strs))
1410 for i, s := range strs {
1411 p[i] = PathForTesting(s)
1412 }
1413
1414 return p
1415}
Colin Cross43f08db2018-11-12 10:13:39 -08001416
Colin Cross40e33732019-02-15 11:08:35 -08001417type testPathContext struct {
1418 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001419}
1420
Colin Cross40e33732019-02-15 11:08:35 -08001421func (x *testPathContext) Config() Config { return x.config }
1422func (x *testPathContext) AddNinjaFileDeps(...string) {}
1423
1424// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1425// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001426func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001427 return &testPathContext{
1428 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001429 }
1430}
1431
Colin Cross43f08db2018-11-12 10:13:39 -08001432// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1433// targetPath is not inside basePath.
1434func Rel(ctx PathContext, basePath string, targetPath string) string {
1435 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1436 if !isRel {
1437 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1438 return ""
1439 }
1440 return rel
1441}
1442
1443// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1444// targetPath is not inside basePath.
1445func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001446 rel, isRel, err := maybeRelErr(basePath, targetPath)
1447 if err != nil {
1448 reportPathError(ctx, err)
1449 }
1450 return rel, isRel
1451}
1452
1453func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001454 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1455 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001456 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001457 }
1458 rel, err := filepath.Rel(basePath, targetPath)
1459 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001460 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001461 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001462 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001463 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001464 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001465}
Colin Cross988414c2020-01-11 01:11:46 +00001466
1467// Writes a file to the output directory. Attempting to write directly to the output directory
1468// will fail due to the sandbox of the soong_build process.
1469func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1470 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1471}
1472
1473func absolutePath(path string) string {
1474 if filepath.IsAbs(path) {
1475 return path
1476 }
1477 return filepath.Join(absSrcDir, path)
1478}