blob: f74fed13f01fc2db06ce758092e5ae64c4316fdc [file] [log] [blame]
Liz Kammer620dea62021-04-14 17:36:10 -04001// 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
15package android
16
17import (
18 "android/soong/bazel"
19 "fmt"
20 "path/filepath"
21 "strings"
22
23 "github.com/google/blueprint"
24 "github.com/google/blueprint/pathtools"
25)
26
27// bazel_paths contains methods to:
28// * resolve Soong path and module references into bazel.LabelList
29// * resolve Bazel path references into Soong-compatible paths
30//
31// There is often a similar method for Bazel as there is for Soong path handling and should be used
32// in similar circumstances
33//
34// Bazel Soong
35//
36// BazelLabelForModuleSrc PathForModuleSrc
37// BazelLabelForModuleSrcExcludes PathForModuleSrcExcludes
38// BazelLabelForModuleDeps n/a
39// tbd PathForSource
40// tbd ExistentPathsForSources
41// PathForBazelOut PathForModuleOut
42//
43// Use cases:
44// * Module contains a property (often tagged `android:"path"`) that expects paths *relative to the
45// module directory*:
46// * BazelLabelForModuleSrcExcludes, if the module also contains an excludes_<propname> property
47// * BazelLabelForModuleSrc, otherwise
48// * Converting references to other modules to Bazel Labels:
49// BazelLabelForModuleDeps
50// * Converting a path obtained from bazel_handler cquery results:
51// PathForBazelOut
52//
53// NOTE: all Soong globs are expanded within Soong rather than being converted to a Bazel glob
54// syntax. This occurs because Soong does not have a concept of crossing package boundaries,
55// so the glob as computed by Soong may contain paths that cross package-boundaries. These
56// would be unknowingly omitted if the glob were handled by Bazel. By expanding globs within
57// Soong, we support identification and detection (within Bazel) use of paths that cross
58// package boundaries.
59//
60// Path resolution:
61// * filepath/globs: resolves as itself or is converted to an absolute Bazel label (e.g.
62// //path/to/dir:<filepath>) if path exists in a separate package or subpackage.
63// * references to other modules (using the ":name{.tag}" syntax). These resolve as a Bazel label
64// for a target. If the Bazel target is in the local module directory, it will be returned
65// relative to the current package (e.g. ":<target>"). Otherwise, it will be returned as an
66// absolute Bazel label (e.g. "//path/to/dir:<target>"). If the reference to another module
67// cannot be resolved,the function will panic. This is often due to the dependency not being added
68// via an AddDependency* method.
69
70// A subset of the ModuleContext methods which are sufficient to resolve references to paths/deps in
71// order to form a Bazel-compatible label for conversion.
72type BazelConversionPathContext interface {
73 EarlyModulePathContext
74
75 GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
76 Module() Module
77 ModuleType() string
78 OtherModuleName(m blueprint.Module) string
79 OtherModuleDir(m blueprint.Module) string
80}
81
82// BazelLabelForModuleDeps expects a list of reference to other modules, ("<module>"
83// or ":<module>") and returns a Bazel-compatible label which corresponds to dependencies on the
84// module within the given ctx.
85func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
Liz Kammer2d7bbe32021-06-10 18:20:06 -040086 return bazelLabelForModuleDeps(ctx, modules, false)
87}
88
89// BazelLabelForModuleWholeDeps expects a list of references to other modules, ("<module>"
90// or ":<module>") and returns a Bazel-compatible label which corresponds to dependencies on the
91// module within the given ctx, where prebuilt dependencies will be appended with _alwayslink so
92// they can be handled as whole static libraries.
93func BazelLabelForModuleWholeDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
94 return bazelLabelForModuleDeps(ctx, modules, true)
95}
96
97// BazelLabelForModuleDepsExcludes expects two lists: modules (containing modules to include in the
98// list), and excludes (modules to exclude from the list). Both of these should contain references
99// to other modules, ("<module>" or ":<module>"). It returns a Bazel-compatible label list which
100// corresponds to dependencies on the module within the given ctx, and the excluded dependencies.
101func BazelLabelForModuleDepsExcludes(ctx BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
102 return bazelLabelForModuleDepsExcludes(ctx, modules, excludes, false)
103}
104
105// BazelLabelForModuleWholeDepsExcludes expects two lists: modules (containing modules to include in
106// the list), and excludes (modules to exclude from the list). Both of these should contain
107// references to other modules, ("<module>" or ":<module>"). It returns a Bazel-compatible label
108// list which corresponds to dependencies on the module within the given ctx, and the excluded
109// dependencies. Prebuilt dependencies will be appended with _alwayslink so they can be handled as
110// whole static libraries.
111func BazelLabelForModuleWholeDepsExcludes(ctx BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
112 return bazelLabelForModuleDepsExcludes(ctx, modules, excludes, true)
113}
114
115func bazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string, isWholeLibs bool) bazel.LabelList {
Liz Kammer620dea62021-04-14 17:36:10 -0400116 var labels bazel.LabelList
117 for _, module := range modules {
118 bpText := module
119 if m := SrcIsModule(module); m == "" {
120 module = ":" + module
121 }
122 if m, t := SrcIsModuleWithTag(module); m != "" {
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400123 l := getOtherModuleLabel(ctx, m, t, isWholeLibs)
Jingwen Chen38e62642021-04-19 05:00:15 +0000124 l.OriginalModuleName = bpText
Liz Kammer620dea62021-04-14 17:36:10 -0400125 labels.Includes = append(labels.Includes, l)
126 } else {
127 ctx.ModuleErrorf("%q, is not a module reference", module)
128 }
129 }
130 return labels
131}
132
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400133func bazelLabelForModuleDepsExcludes(ctx BazelConversionPathContext, modules, excludes []string, isWholeLibs bool) bazel.LabelList {
134 moduleLabels := bazelLabelForModuleDeps(ctx, RemoveListFromList(modules, excludes), isWholeLibs)
Liz Kammer47535c52021-06-02 16:02:22 -0400135 if len(excludes) == 0 {
136 return moduleLabels
137 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400138 excludeLabels := bazelLabelForModuleDeps(ctx, excludes, isWholeLibs)
Liz Kammer47535c52021-06-02 16:02:22 -0400139 return bazel.LabelList{
140 Includes: moduleLabels.Includes,
141 Excludes: excludeLabels.Includes,
142 }
143}
144
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200145func BazelLabelForModuleSrcSingle(ctx BazelConversionPathContext, path string) bazel.Label {
146 return BazelLabelForModuleSrcExcludes(ctx, []string{path}, []string(nil)).Includes[0]
147}
148
Liz Kammer620dea62021-04-14 17:36:10 -0400149// BazelLabelForModuleSrc expects a list of path (relative to local module directory) and module
150// references (":<module>") and returns a bazel.LabelList{} containing the resolved references in
151// paths, relative to the local module, or Bazel-labels (absolute if in a different package or
152// relative if within the same package).
153// Properties must have been annotated with struct tag `android:"path"` so that dependencies modules
154// will have already been handled by the path_deps mutator.
155func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
156 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
157}
158
159// BazelLabelForModuleSrc expects lists of path and excludes (relative to local module directory)
160// and module references (":<module>") and returns a bazel.LabelList{} containing the resolved
161// references in paths, minus those in excludes, relative to the local module, or Bazel-labels
162// (absolute if in a different package or relative if within the same package).
163// Properties must have been annotated with struct tag `android:"path"` so that dependencies modules
164// will have already been handled by the path_deps mutator.
165func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
166 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
167 excluded := make([]string, 0, len(excludeLabels.Includes))
168 for _, e := range excludeLabels.Includes {
169 excluded = append(excluded, e.Label)
170 }
171 labels := expandSrcsForBazel(ctx, paths, excluded)
172 labels.Excludes = excludeLabels.Includes
173 labels = transformSubpackagePaths(ctx, labels)
174 return labels
175}
176
177// Returns true if a prefix + components[:i] + /Android.bp exists
178// TODO(b/185358476) Could check for BUILD file instead of checking for Android.bp file, or ensure BUILD is always generated?
179func directoryHasBlueprint(fs pathtools.FileSystem, prefix string, components []string, componentIndex int) bool {
180 blueprintPath := prefix
181 if blueprintPath != "" {
182 blueprintPath = blueprintPath + "/"
183 }
184 blueprintPath = blueprintPath + strings.Join(components[:componentIndex+1], "/")
185 blueprintPath = blueprintPath + "/Android.bp"
186 if exists, _, _ := fs.Exists(blueprintPath); exists {
187 return true
188 } else {
189 return false
190 }
191}
192
193// Transform a path (if necessary) to acknowledge package boundaries
194//
195// e.g. something like
196// async_safe/include/async_safe/CHECK.h
197// might become
198// //bionic/libc/async_safe:include/async_safe/CHECK.h
199// if the "async_safe" directory is actually a package and not just a directory.
200//
201// In particular, paths that extend into packages are transformed into absolute labels beginning with //.
202func transformSubpackagePath(ctx BazelConversionPathContext, path bazel.Label) bazel.Label {
203 var newPath bazel.Label
204
Jingwen Chen38e62642021-04-19 05:00:15 +0000205 // Don't transform OriginalModuleName
206 newPath.OriginalModuleName = path.OriginalModuleName
Liz Kammer620dea62021-04-14 17:36:10 -0400207
208 if strings.HasPrefix(path.Label, "//") {
209 // Assume absolute labels are already correct (e.g. //path/to/some/package:foo.h)
210 newPath.Label = path.Label
211 return newPath
212 }
213
214 newLabel := ""
215 pathComponents := strings.Split(path.Label, "/")
216 foundBlueprint := false
217 // Check the deepest subdirectory first and work upwards
218 for i := len(pathComponents) - 1; i >= 0; i-- {
219 pathComponent := pathComponents[i]
220 var sep string
221 if !foundBlueprint && directoryHasBlueprint(ctx.Config().fs, ctx.ModuleDir(), pathComponents, i) {
222 sep = ":"
223 foundBlueprint = true
224 } else {
225 sep = "/"
226 }
227 if newLabel == "" {
228 newLabel = pathComponent
229 } else {
230 newLabel = pathComponent + sep + newLabel
231 }
232 }
233 if foundBlueprint {
234 // Ensure paths end up looking like //bionic/... instead of //./bionic/...
235 moduleDir := ctx.ModuleDir()
236 if strings.HasPrefix(moduleDir, ".") {
237 moduleDir = moduleDir[1:]
238 }
239 // Make the path into an absolute label (e.g. //bionic/libc/foo:bar.h instead of just foo:bar.h)
240 if moduleDir == "" {
241 newLabel = "//" + newLabel
242 } else {
243 newLabel = "//" + moduleDir + "/" + newLabel
244 }
245 }
246 newPath.Label = newLabel
247
248 return newPath
249}
250
251// Transform paths to acknowledge package boundaries
252// See transformSubpackagePath() for more information
253func transformSubpackagePaths(ctx BazelConversionPathContext, paths bazel.LabelList) bazel.LabelList {
254 var newPaths bazel.LabelList
255 for _, include := range paths.Includes {
256 newPaths.Includes = append(newPaths.Includes, transformSubpackagePath(ctx, include))
257 }
258 for _, exclude := range paths.Excludes {
259 newPaths.Excludes = append(newPaths.Excludes, transformSubpackagePath(ctx, exclude))
260 }
261 return newPaths
262}
263
264// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local source
265// directory and Bazel target labels, excluding those included in the excludes argument (which
266// should already be expanded to resolve references to Soong-modules). Valid elements of paths
267// include:
268// * filepath, relative to local module directory, resolves as a filepath relative to the local
269// source directory
270// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
271// module directory. Because Soong does not have a concept of crossing package boundaries, the
272// glob as computed by Soong may contain paths that cross package-boundaries that would be
273// unknowingly omitted if the glob were handled by Bazel. To allow identification and detect
274// (within Bazel) use of paths that cross package boundaries, we expand globs within Soong rather
275// than converting Soong glob syntax to Bazel glob syntax. **Invalid for excludes.**
276// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
277// or OutputFileProducer. These resolve as a Bazel label for a target. If the Bazel target is in
278// the local module directory, it will be returned relative to the current package (e.g.
279// ":<target>"). Otherwise, it will be returned as an absolute Bazel label (e.g.
280// "//path/to/dir:<target>"). If the reference to another module cannot be resolved,the function
281// will panic.
282// Properties passed as the paths or excludes argument must have been annotated with struct tag
283// `android:"path"` so that dependencies on other modules will have already been handled by the
284// path_deps mutator.
285func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
286 if paths == nil {
287 return bazel.LabelList{}
288 }
289 labels := bazel.LabelList{
290 Includes: []bazel.Label{},
291 }
Jingwen Chen4ecc67d2021-04-27 09:47:02 +0000292
293 // expandedExcludes contain module-dir relative paths, but root-relative paths
294 // are needed for GlobFiles later.
295 var rootRelativeExpandedExcludes []string
296 for _, e := range expandedExcludes {
297 rootRelativeExpandedExcludes = append(rootRelativeExpandedExcludes, filepath.Join(ctx.ModuleDir(), e))
298 }
299
Liz Kammer620dea62021-04-14 17:36:10 -0400300 for _, p := range paths {
301 if m, tag := SrcIsModuleWithTag(p); m != "" {
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400302 l := getOtherModuleLabel(ctx, m, tag, false)
Liz Kammer620dea62021-04-14 17:36:10 -0400303 if !InList(l.Label, expandedExcludes) {
Jingwen Chen38e62642021-04-19 05:00:15 +0000304 l.OriginalModuleName = fmt.Sprintf(":%s", m)
Liz Kammer620dea62021-04-14 17:36:10 -0400305 labels.Includes = append(labels.Includes, l)
306 }
307 } else {
308 var expandedPaths []bazel.Label
309 if pathtools.IsGlob(p) {
Jingwen Chen4ecc67d2021-04-27 09:47:02 +0000310 // e.g. turn "math/*.c" in
311 // external/arm-optimized-routines to external/arm-optimized-routines/math/*.c
312 rootRelativeGlobPath := pathForModuleSrc(ctx, p).String()
313 globbedPaths := GlobFiles(ctx, rootRelativeGlobPath, rootRelativeExpandedExcludes)
Liz Kammer620dea62021-04-14 17:36:10 -0400314 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
315 for _, path := range globbedPaths {
316 s := path.Rel()
317 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
318 }
319 } else {
320 if !InList(p, expandedExcludes) {
321 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
322 }
323 }
324 labels.Includes = append(labels.Includes, expandedPaths...)
325 }
326 }
327 return labels
328}
329
330// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
331// module. The label will be relative to the current directory if appropriate. The dependency must
332// already be resolved by either deps mutator or path deps mutator.
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400333func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string, isWholeLibs bool) bazel.Label {
Liz Kammer620dea62021-04-14 17:36:10 -0400334 m, _ := ctx.GetDirectDep(dep)
335 if m == nil {
336 panic(fmt.Errorf(`Cannot get direct dep %q of %q.
337 This is likely because it was not added via AddDependency().
338 This may be due a mutator skipped during bp2build.`, dep, ctx.Module().Name()))
339 }
340 otherLabel := bazelModuleLabel(ctx, m, tag)
341 label := bazelModuleLabel(ctx, ctx.Module(), "")
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400342 if isWholeLibs {
343 if m, ok := m.(Module); ok && IsModulePrebuilt(m) {
344 otherLabel += "_alwayslink"
345 }
346 }
Liz Kammer620dea62021-04-14 17:36:10 -0400347 if samePackage(label, otherLabel) {
348 otherLabel = bazelShortLabel(otherLabel)
349 }
350
351 return bazel.Label{
352 Label: otherLabel,
353 }
354}
355
356func bazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module, tag string) string {
357 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
358 b, ok := module.(Bazelable)
359 // TODO(b/181155349): perhaps return an error here if the module can't be/isn't being converted
360 if !ok || !b.ConvertedToBazel(ctx) {
361 return bp2buildModuleLabel(ctx, module)
362 }
363 return b.GetBazelLabel(ctx, module)
364}
365
366func bazelShortLabel(label string) string {
367 i := strings.Index(label, ":")
368 return label[i:]
369}
370
371func bazelPackage(label string) string {
372 i := strings.Index(label, ":")
373 return label[0:i]
374}
375
376func samePackage(label1, label2 string) bool {
377 return bazelPackage(label1) == bazelPackage(label2)
378}
379
380func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
381 moduleName := ctx.OtherModuleName(module)
382 moduleDir := ctx.OtherModuleDir(module)
383 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
384}
385
386// BazelOutPath is a Bazel output path compatible to be used for mixed builds within Soong/Ninja.
387type BazelOutPath struct {
388 OutputPath
389}
390
391var _ Path = BazelOutPath{}
392var _ objPathProvider = BazelOutPath{}
393
394func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
395 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
396}
397
398// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
399// bazel-owned outputs.
400func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
401 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
402 execRootPath := filepath.Join(execRootPathComponents...)
403 validatedExecRootPath, err := validatePath(execRootPath)
404 if err != nil {
405 reportPathError(ctx, err)
406 }
407
408 outputPath := OutputPath{basePath{"", ""},
409 ctx.Config().buildDir,
410 ctx.Config().BazelContext.OutputBase()}
411
412 return BazelOutPath{
413 OutputPath: outputPath.withRel(validatedExecRootPath),
414 }
415}
Liz Kammerb6a55bf2021-04-12 15:42:51 -0400416
417// PathsForBazelOut returns a list of paths representing the paths under an output directory
418// dedicated to Bazel-owned outputs.
419func PathsForBazelOut(ctx PathContext, paths []string) Paths {
420 outs := make(Paths, 0, len(paths))
421 for _, p := range paths {
422 outs = append(outs, PathForBazelOut(ctx, p))
423 }
424 return outs
425}