blob: 379d6f246fb6752aff697323c0ba1691e17a9390 [file] [log] [blame]
Jingwen Chen91220d72021-03-24 02:18:33 -04001// Copyright 2021 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.
14package cc
15
16import (
Liz Kammerd2871182021-10-04 13:54:37 -040017 "fmt"
Jingwen Chened9c17d2021-04-13 07:14:55 +000018 "path/filepath"
Jingwen Chen3950cd62021-05-12 04:33:00 +000019 "strings"
Chris Parsons484e50a2021-05-13 15:13:04 -040020
21 "android/soong/android"
22 "android/soong/bazel"
Liz Kammer7a210ac2021-09-22 15:52:58 -040023
Chris Parsons953b3562021-09-20 15:14:39 -040024 "github.com/google/blueprint"
Liz Kammerba7a9c52021-05-26 08:45:30 -040025
26 "github.com/google/blueprint/proptools"
Jingwen Chen91220d72021-03-24 02:18:33 -040027)
28
Liz Kammerae3994e2021-10-19 09:45:48 -040029const (
Liz Kammer12615db2021-09-28 09:19:17 -040030 cSrcPartition = "c"
31 asSrcPartition = "as"
32 cppSrcPartition = "cpp"
33 protoSrcPartition = "proto"
Liz Kammerae3994e2021-10-19 09:45:48 -040034)
35
Liz Kammer2222c6b2021-05-24 15:41:47 -040036// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000037// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040038type staticOrSharedAttributes struct {
Jingwen Chenc4dc9b42021-06-11 12:51:48 +000039 Srcs bazel.LabelListAttribute
40 Srcs_c bazel.LabelListAttribute
41 Srcs_as bazel.LabelListAttribute
Liz Kammere6583482021-10-19 13:56:10 -040042 Hdrs bazel.LabelListAttribute
Jingwen Chenc4dc9b42021-06-11 12:51:48 +000043 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000044
Liz Kammer12615db2021-09-28 09:19:17 -040045 Deps bazel.LabelListAttribute
46 Implementation_deps bazel.LabelListAttribute
47 Dynamic_deps bazel.LabelListAttribute
48 Implementation_dynamic_deps bazel.LabelListAttribute
49 Whole_archive_deps bazel.LabelListAttribute
50 Implementation_whole_archive_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040051
52 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050053
54 Enabled bazel.BoolAttribute
Jingwen Chen53681ef2021-04-29 08:15:13 +000055}
56
Sam Delmericoc7681022022-02-04 21:01:20 +000057// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +000058func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -040059 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
60 // macro.
61 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Liz Kammer12615db2021-09-28 09:19:17 -040062 return func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
63 m, exists := ctx.ModuleFromName(label.OriginalModuleName)
64 labelStr := label.Label
Sam Delmericoc7681022022-02-04 21:01:20 +000065 if !exists || !android.IsFilegroup(ctx, m) {
Liz Kammer12615db2021-09-28 09:19:17 -040066 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +000067 }
Liz Kammer12615db2021-09-28 09:19:17 -040068 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -040069 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000070 }
71
Liz Kammer57e2e7a2021-09-20 12:55:02 -040072 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +000073 labels := bazel.LabelPartitions{
74 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -050075 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
76 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Liz Kammer57e2e7a2021-09-20 12:55:02 -040077 // C++ is the "catch-all" group, and comprises generated sources because we don't
78 // know the language of these sources until the genrule is executed.
Liz Kammeraabfb5d2021-12-08 15:25:06 -050079 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
Sam Delmericoc7681022022-02-04 21:01:20 +000080 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000081
Sam Delmericoc7681022022-02-04 21:01:20 +000082 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +000083}
84
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +000085// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +000086func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +000087 lib, ok := module.compiler.(*libraryDecorator)
88 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -040089 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +000090 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +000091 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
92}
Jingwen Chen53681ef2021-04-29 08:15:13 +000093
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +000094// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +000095func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +000096 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +000097}
98
99// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000100func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000101 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400102}
103
Liz Kammer7a210ac2021-09-22 15:52:58 -0400104type depsPartition struct {
105 export bazel.LabelList
106 implementation bazel.LabelList
107}
108
Jingwen Chen55bc8202021-11-02 06:40:51 +0000109type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400110
Jingwen Chen55bc8202021-11-02 06:40:51 +0000111func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400112 if !exportsDeps {
113 return depsPartition{
114 implementation: fn(ctx, allDeps),
115 }
116 }
117
Liz Kammer7a210ac2021-09-22 15:52:58 -0400118 implementation, export := android.FilterList(allDeps, exportedDeps)
119
120 return depsPartition{
121 export: fn(ctx, export),
122 implementation: fn(ctx, implementation),
123 }
124}
125
Jingwen Chen55bc8202021-11-02 06:40:51 +0000126type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400127
Jingwen Chen55bc8202021-11-02 06:40:51 +0000128func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400129 if !exportsDeps {
130 return depsPartition{
131 implementation: fn(ctx, allDeps, excludes),
132 }
133 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400134 implementation, export := android.FilterList(allDeps, exportedDeps)
135
136 return depsPartition{
137 export: fn(ctx, export, excludes),
138 implementation: fn(ctx, implementation, excludes),
139 }
140}
141
Jingwen Chen55bc8202021-11-02 06:40:51 +0000142func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400143 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000144
Liz Kammer9abd62d2021-05-21 08:37:59 -0400145 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Liz Kammercac7f692021-12-16 14:19:32 -0500146 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000147 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400148 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400149
Liz Kammer2b8004b2021-10-04 13:55:44 -0400150 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400151 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
152 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
153
Liz Kammer2b8004b2021-10-04 13:55:44 -0400154 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400155 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
156 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
157
158 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500159 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000160 }
Liz Kammer135bf552021-08-11 10:46:06 -0400161 // system_dynamic_deps distinguishes between nil/empty list behavior:
162 // nil -> use default values
163 // empty list -> no values specified
164 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000165
166 if isStatic {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400167 for axis, configToProps := range module.GetArchVariantProperties(ctx, &StaticProperties{}) {
168 for config, props := range configToProps {
169 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
170 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000171 }
172 }
173 }
174 } else {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400175 for axis, configToProps := range module.GetArchVariantProperties(ctx, &SharedProperties{}) {
176 for config, props := range configToProps {
177 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
178 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000179 }
180 }
181 }
182 }
183
Liz Kammerae3994e2021-10-19 09:45:48 -0400184 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
185 attrs.Srcs = partitionedSrcs[cppSrcPartition]
186 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
187 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000188
Liz Kammer12615db2021-09-28 09:19:17 -0400189 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
190 // TODO(b/208815215): determine whether this is used and add support if necessary
191 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
192 }
193
Jingwen Chenbcf53042021-05-26 04:42:42 +0000194 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000195}
196
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400197// Convenience struct to hold all attributes parsed from prebuilt properties.
198type prebuiltAttributes struct {
199 Src bazel.LabelAttribute
200}
201
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000202// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Jingwen Chen55bc8202021-11-02 06:40:51 +0000203func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400204 var srcLabelAttribute bazel.LabelAttribute
205
Liz Kammer9abd62d2021-05-21 08:37:59 -0400206 for axis, configToProps := range module.GetArchVariantProperties(ctx, &prebuiltLinkerProperties{}) {
207 for config, props := range configToProps {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400208 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
209 if len(prebuiltLinkerProperties.Srcs) > 1 {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400210 ctx.ModuleErrorf("Bp2BuildParsePrebuiltLibraryProps: Expected at most once source file for %s %s\n", axis, config)
211 continue
212 } else if len(prebuiltLinkerProperties.Srcs) == 0 {
213 continue
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400214 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400215 src := android.BazelLabelForModuleSrcSingle(ctx, prebuiltLinkerProperties.Srcs[0])
216 srcLabelAttribute.SetSelectValue(axis, config, src)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400217 }
218 }
219 }
220
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400221 return prebuiltAttributes{
222 Src: srcLabelAttribute,
223 }
224}
225
Liz Kammere6583482021-10-19 13:56:10 -0400226type baseAttributes struct {
227 compilerAttributes
228 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400229
230 protoDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400231}
232
Jingwen Chen107c0de2021-04-09 10:43:12 +0000233// Convenience struct to hold all attributes parsed from compiler properties.
234type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400235 // Options for all languages
236 copts bazel.StringListAttribute
237 // Assembly options and sources
238 asFlags bazel.StringListAttribute
239 asSrcs bazel.LabelListAttribute
240 // C options and sources
241 conlyFlags bazel.StringListAttribute
242 cSrcs bazel.LabelListAttribute
243 // C++ options and sources
244 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000245 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400246
Liz Kammere6583482021-10-19 13:56:10 -0400247 hdrs bazel.LabelListAttribute
248
Chris Parsons2c788392021-08-10 11:58:07 -0400249 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000250
251 // Not affected by arch variants
252 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500253 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000254 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400255
256 localIncludes bazel.StringListAttribute
257 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400258
Liz Kammer1263d9b2021-12-10 14:28:20 -0500259 includes BazelIncludes
260
Liz Kammer12615db2021-09-28 09:19:17 -0400261 protoSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000262
263 stubsSymbolFile *string
264 stubsVersions bazel.StringListAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000265}
266
Liz Kammercac7f692021-12-16 14:19:32 -0500267type filterOutFn func(string) bool
268
269func filterOutStdFlag(flag string) bool {
270 return strings.HasPrefix(flag, "-std=")
271}
272
273func parseCommandLineFlags(soongFlags []string, filterOut filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400274 var result []string
275 for _, flag := range soongFlags {
Liz Kammercac7f692021-12-16 14:19:32 -0500276 if filterOut != nil && filterOut(flag) {
277 continue
278 }
Liz Kammere6583482021-10-19 13:56:10 -0400279 // Soong's cflags can contain spaces, like `-include header.h`. For
280 // Bazel's copts, split them up to be compatible with the
281 // no_copts_tokenization feature.
282 result = append(result, strings.Split(flag, " ")...)
283 }
284 return result
285}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000286
Jingwen Chen55bc8202021-11-02 06:40:51 +0000287func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400288 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
289 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
290 if srcsList, ok := parseSrcs(ctx, props); ok {
291 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400292 }
293
Liz Kammere6583482021-10-19 13:56:10 -0400294 localIncludeDirs := props.Local_include_dirs
295 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500296 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400297 if includeBuildDirectory(props.Include_build_directory) {
298 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400299 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000300 }
301
Liz Kammere6583482021-10-19 13:56:10 -0400302 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
303 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
304
Liz Kammercac7f692021-12-16 14:19:32 -0500305 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
306 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
307 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
308 // cases.
309 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
310 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
311 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, nil))
312 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, nil))
Liz Kammere6583482021-10-19 13:56:10 -0400313 ca.rtti.SetSelectValue(axis, config, props.Rtti)
314}
315
Jingwen Chen55bc8202021-11-02 06:40:51 +0000316func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Liz Kammere6583482021-10-19 13:56:10 -0400317 stlPropsByArch := module.GetArchVariantProperties(ctx, &StlProperties{})
318 for _, configToProps := range stlPropsByArch {
319 for _, props := range configToProps {
320 if stlProps, ok := props.(*StlProperties); ok {
321 if stlProps.Stl == nil {
322 continue
Liz Kammer9abd62d2021-05-21 08:37:59 -0400323 }
Liz Kammere6583482021-10-19 13:56:10 -0400324 if ca.stl == nil {
325 ca.stl = stlProps.Stl
326 } else if ca.stl != stlProps.Stl {
327 ctx.ModuleErrorf("Unsupported conversion: module with different stl for different variants: %s and %s", *ca.stl, stlProps.Stl)
Liz Kammerae3994e2021-10-19 09:45:48 -0400328 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400329 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000330 }
331 }
Liz Kammere6583482021-10-19 13:56:10 -0400332}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000333
Jingwen Chen55bc8202021-11-02 06:40:51 +0000334func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400335 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400336 "Cflags": &ca.copts,
337 "Asflags": &ca.asFlags,
338 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400339 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400340 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000341 if productConfigProps, exists := productVariableProps[propName]; exists {
342 for productConfigProp, prop := range productConfigProps {
343 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400344 if !ok {
345 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
346 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000347 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
348 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400349 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400350 }
351 }
Liz Kammere6583482021-10-19 13:56:10 -0400352}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400353
Jingwen Chen55bc8202021-11-02 06:40:51 +0000354func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400355 ca.srcs.ResolveExcludes()
356 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
357
Liz Kammer12615db2021-09-28 09:19:17 -0400358 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
359
Liz Kammere6583482021-10-19 13:56:10 -0400360 for p, lla := range partitionedSrcs {
361 // if there are no sources, there is no need for headers
362 if lla.IsEmpty() {
363 continue
364 }
365 lla.Append(implementationHdrs)
366 partitionedSrcs[p] = lla
367 }
368
369 ca.srcs = partitionedSrcs[cppSrcPartition]
370 ca.cSrcs = partitionedSrcs[cSrcPartition]
371 ca.asSrcs = partitionedSrcs[asSrcPartition]
372
373 ca.absoluteIncludes.DeduplicateAxesFromBase()
374 ca.localIncludes.DeduplicateAxesFromBase()
375}
376
377// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000378func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400379 anySrcs := false
380 // Add srcs-like dependencies such as generated files.
381 // First create a LabelList containing these dependencies, then merge the values with srcs.
382 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
383 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
384 anySrcs = true
385 }
386
387 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
388 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
389 anySrcs = true
390 }
391 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
392}
393
Chris Parsons79bd2b72021-11-29 17:52:41 -0500394func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
395 var cStdVal, cppStdVal string
396 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
397 // Defaults are handled by the toolchain definition.
398 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammere6583482021-10-19 13:56:10 -0400399 if cpp_std != nil {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500400 cppStdVal = parseCppStd(cpp_std)
Liz Kammere6583482021-10-19 13:56:10 -0400401 } else if gnu_extensions != nil && !*gnu_extensions {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500402 cppStdVal = "c++17"
Liz Kammere6583482021-10-19 13:56:10 -0400403 }
Chris Parsons79bd2b72021-11-29 17:52:41 -0500404 if c_std != nil {
405 cStdVal = parseCStd(c_std)
406 } else if gnu_extensions != nil && !*gnu_extensions {
407 cStdVal = "c99"
408 }
409
410 cStdVal, cppStdVal = maybeReplaceGnuToC(gnu_extensions, cStdVal, cppStdVal)
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500411 var c_std_prop, cpp_std_prop *string
412 if cStdVal != "" {
413 c_std_prop = &cStdVal
414 }
415 if cppStdVal != "" {
416 cpp_std_prop = &cppStdVal
417 }
418
419 return c_std_prop, cpp_std_prop
Liz Kammere6583482021-10-19 13:56:10 -0400420}
421
Liz Kammer1263d9b2021-12-10 14:28:20 -0500422// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
423// is fully-qualified.
424// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
425func packageFromLabel(label string) (string, bool) {
426 split := strings.Split(label, ":")
427 if len(split) != 2 {
428 return "", false
429 }
430 if split[0] == "" {
431 return ".", false
432 }
433 // remove leading "//"
434 return split[0][2:], true
435}
436
437// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
438func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
439 for _, hdr := range labelList.Includes {
440 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
441 absolute = append(absolute, pkg)
442 } else if pkg != "" {
443 relative = append(relative, pkg)
444 }
445 }
446 return relative, absolute
447}
448
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000449// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400450func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400451 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
452 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000453 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400454
455 var implementationHdrs bazel.LabelListAttribute
456
457 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
458 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
459 for axis, configMap := range cp {
460 if _, ok := axisToConfigs[axis]; !ok {
461 axisToConfigs[axis] = map[string]bool{}
462 }
463 for config, _ := range configMap {
464 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400465 }
466 }
467 }
Liz Kammere6583482021-10-19 13:56:10 -0400468 allAxesAndConfigs(archVariantCompilerProps)
469 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000470 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400471
Liz Kammere6583482021-10-19 13:56:10 -0400472 compilerAttrs := compilerAttributes{}
473 linkerAttrs := linkerAttributes{}
474
475 for axis, configs := range axisToConfigs {
476 for config, _ := range configs {
477 var allHdrs []string
478 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
479 allHdrs = baseCompilerProps.Generated_headers
480
481 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
482 }
483
484 var exportHdrs []string
485
486 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
487 exportHdrs = baseLinkerProps.Export_generated_headers
488
489 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
490 }
491 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
492 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
493 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500494
495 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
496 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
497 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
498
499 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
500 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
501 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
502 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
503 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
504 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
505 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000506
507 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
508 if axis == bazel.NoConfigAxis {
509 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
510 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
511 }
512 }
Liz Kammere6583482021-10-19 13:56:10 -0400513 }
514 }
515
516 compilerAttrs.convertStlProps(ctx, module)
517 (&linkerAttrs).convertStripProps(ctx, module)
518
519 productVariableProps := android.ProductVariableProperties(ctx)
520
521 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
522 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
523
524 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500525 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400526
Liz Kammer12615db2021-09-28 09:19:17 -0400527 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
528
529 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
530 // which. This will add the newly generated proto library to the appropriate attribute and nothing
531 // to the other
532 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
533 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
534
Liz Kammere6583482021-10-19 13:56:10 -0400535 return baseAttributes{
536 compilerAttrs,
537 linkerAttrs,
Liz Kammer12615db2021-09-28 09:19:17 -0400538 protoDep.protoDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000539 }
540}
541
542// Convenience struct to hold all attributes parsed from linker properties.
543type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500544 deps bazel.LabelListAttribute
545 implementationDeps bazel.LabelListAttribute
546 dynamicDeps bazel.LabelListAttribute
547 implementationDynamicDeps bazel.LabelListAttribute
548 wholeArchiveDeps bazel.LabelListAttribute
549 implementationWholeArchiveDeps bazel.LabelListAttribute
550 systemDynamicDeps bazel.LabelListAttribute
551 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400552
Jingwen Chen6ada5892021-09-17 11:38:09 +0000553 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000554 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500555 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000556 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400557 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000558 stripKeepSymbols bazel.BoolAttribute
559 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
560 stripKeepSymbolsList bazel.StringListAttribute
561 stripAll bazel.BoolAttribute
562 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400563 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400564}
565
Liz Kammer54309532021-12-14 12:21:22 -0500566var (
567 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
568)
569
Jingwen Chen55bc8202021-11-02 06:40:51 +0000570func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400571 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
572 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400573
Liz Kammere6583482021-10-19 13:56:10 -0400574 // Excludes to parallel Soong:
575 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=247-249;drc=088b53577dde6e40085ffd737a1ae96ad82fc4b0
576 staticLibs := android.FirstUniqueStrings(props.Static_libs)
577 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, staticLibs, props.Exclude_static_libs, props.Export_static_lib_headers, bazelLabelForStaticDepsExcludes)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400578
Liz Kammere6583482021-10-19 13:56:10 -0400579 headerLibs := android.FirstUniqueStrings(props.Header_libs)
580 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400581
Liz Kammere6583482021-10-19 13:56:10 -0400582 (&hDeps.export).Append(staticDeps.export)
583 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000584
Liz Kammere6583482021-10-19 13:56:10 -0400585 (&hDeps.implementation).Append(staticDeps.implementation)
586 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400587
Liz Kammere6583482021-10-19 13:56:10 -0400588 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
589 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
590
591 systemSharedLibs := props.System_shared_libs
592 // systemSharedLibs distinguishes between nil/empty list behavior:
593 // nil -> use default values
594 // empty list -> no values specified
595 if len(systemSharedLibs) > 0 {
596 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
597 }
598 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
599
600 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500601 excludeSharedLibs := props.Exclude_shared_libs
602 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
603 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
604 })
605 for _, el := range usedSystem {
606 if la.usedSystemDynamicDepAsDynamicDep == nil {
607 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
608 }
609 la.usedSystemDynamicDepAsDynamicDep[el] = true
610 }
611
Liz Kammere6583482021-10-19 13:56:10 -0400612 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, sharedLibs, props.Exclude_shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDepsExcludes)
613 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
614 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
615
616 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
617 axisFeatures = append(axisFeatures, "disable_pack_relocations")
618 }
619
620 if Bool(props.Allow_undefined_symbols) {
621 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
622 }
623
624 var linkerFlags []string
625 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -0500626 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -0400627 // binaries remove static flag if -shared is in the linker flags
628 if isBinary && android.InList("-shared", linkerFlags) {
629 axisFeatures = append(axisFeatures, "-static_flag")
630 }
631 }
632 if props.Version_script != nil {
633 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
634 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
635 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
636 }
637 la.linkopts.SetSelectValue(axis, config, linkerFlags)
638 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
639
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500640 if axis == bazel.NoConfigAxis {
641 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
642 }
643
Liz Kammere6583482021-10-19 13:56:10 -0400644 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
645 if props.crt() != nil {
646 if axis == bazel.NoConfigAxis {
647 la.linkCrt.SetSelectValue(axis, config, props.crt())
648 } else if axis == bazel.ArchConfigurationAxis {
649 ctx.ModuleErrorf("nocrt is not supported for arch variants")
650 }
651 }
652
653 if axisFeatures != nil {
654 la.features.SetSelectValue(axis, config, axisFeatures)
655 }
656}
657
Jingwen Chen55bc8202021-11-02 06:40:51 +0000658func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000659 for axis, configToProps := range module.GetArchVariantProperties(ctx, &StripProperties{}) {
660 for config, props := range configToProps {
661 if stripProperties, ok := props.(*StripProperties); ok {
Liz Kammere6583482021-10-19 13:56:10 -0400662 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
663 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
664 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
665 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
666 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000667 }
668 }
669 }
Liz Kammere6583482021-10-19 13:56:10 -0400670}
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000671
Jingwen Chen55bc8202021-11-02 06:40:51 +0000672func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +0000673
Liz Kammer47535c52021-06-02 16:02:22 -0400674 type productVarDep struct {
675 // the name of the corresponding excludes field, if one exists
676 excludesField string
677 // reference to the bazel attribute that should be set for the given product variable config
678 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400679
Jingwen Chen55bc8202021-11-02 06:40:51 +0000680 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -0400681 }
682
683 productVarToDepFields := map[string]productVarDep{
684 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +0000685 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
686 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
687 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -0400688 }
689
Liz Kammer47535c52021-06-02 16:02:22 -0400690 for name, dep := range productVarToDepFields {
691 props, exists := productVariableProps[name]
692 excludeProps, excludesExists := productVariableProps[dep.excludesField]
693 // if neither an include or excludes property exists, then skip it
694 if !exists && !excludesExists {
695 continue
696 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000697 // Collect all the configurations that an include or exclude property exists for.
698 // We want to iterate all configurations rather than either the include or exclude because, for a
699 // particular configuration, we may have either only an include or an exclude to handle.
700 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
701 for p := range props {
702 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400703 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000704 for p := range excludeProps {
705 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400706 }
707
Jingwen Chen25825ca2021-11-15 12:28:43 +0000708 for productConfigProp := range productConfigProps {
709 prop, includesExists := props[productConfigProp]
710 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -0400711 var includes, excludes []string
712 var ok bool
713 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +0000714 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400715 ctx.ModuleErrorf("Could not convert product variable %s property", name)
716 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000717 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400718 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
719 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400720
Jingwen Chen58ff6802021-11-17 12:14:41 +0000721 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +0000722 dep.attribute.SetSelectValue(
723 productConfigProp.ConfigurationAxis(),
724 productConfigProp.SelectKey(),
725 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
726 )
Liz Kammer47535c52021-06-02 16:02:22 -0400727 }
728 }
Liz Kammere6583482021-10-19 13:56:10 -0400729}
Liz Kammer47535c52021-06-02 16:02:22 -0400730
Liz Kammer54309532021-12-14 12:21:22 -0500731func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
732 // if system dynamic deps have the default value, any use of a system dynamic library used will
733 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
734 // from bionic OSes.
735 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
736 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
737 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
738 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
739 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
740 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
741 }
742
Liz Kammere6583482021-10-19 13:56:10 -0400743 la.deps.ResolveExcludes()
744 la.implementationDeps.ResolveExcludes()
745 la.dynamicDeps.ResolveExcludes()
746 la.implementationDynamicDeps.ResolveExcludes()
747 la.wholeArchiveDeps.ResolveExcludes()
748 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -0500749
Jingwen Chen91220d72021-03-24 02:18:33 -0400750}
751
Jingwen Chened9c17d2021-04-13 07:14:55 +0000752// Relativize a list of root-relative paths with respect to the module's
753// directory.
754//
755// include_dirs Soong prop are root-relative (b/183742505), but
756// local_include_dirs, export_include_dirs and export_system_include_dirs are
757// module dir relative. This function makes a list of paths entirely module dir
758// relative.
759//
760// For the `include` attribute, Bazel wants the paths to be relative to the
761// module.
762func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000763 var relativePaths []string
764 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +0000765 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
766 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
767 if err != nil {
768 panic(err)
769 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000770 relativePaths = append(relativePaths, relativePath)
771 }
772 return relativePaths
773}
774
Liz Kammer5fad5012021-09-09 14:08:21 -0400775// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
776// attributes.
777type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500778 AbsoluteIncludes bazel.StringListAttribute
779 Includes bazel.StringListAttribute
780 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -0400781}
782
Liz Kammer1263d9b2021-12-10 14:28:20 -0500783func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, existingIncludes BazelIncludes) BazelIncludes {
Jingwen Chen91220d72021-03-24 02:18:33 -0400784 libraryDecorator := module.linker.(*libraryDecorator)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500785 return bp2BuildParseExportedIncludesHelper(ctx, module, libraryDecorator, &existingIncludes)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400786}
Jingwen Chen91220d72021-03-24 02:18:33 -0400787
Liz Kammer5fad5012021-09-09 14:08:21 -0400788// Bp2buildParseExportedIncludesForPrebuiltLibrary returns a BazelIncludes with Bazel-ified values
789// to export includes from the underlying module's properties.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000790func Bp2BuildParseExportedIncludesForPrebuiltLibrary(ctx android.BazelConversionPathContext, module *Module) BazelIncludes {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400791 prebuiltLibraryLinker := module.linker.(*prebuiltLibraryLinker)
792 libraryDecorator := prebuiltLibraryLinker.libraryDecorator
Liz Kammer1263d9b2021-12-10 14:28:20 -0500793 return bp2BuildParseExportedIncludesHelper(ctx, module, libraryDecorator, nil)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400794}
795
796// bp2BuildParseExportedIncludes creates a string list attribute contains the
797// exported included directories of a module.
Liz Kammer1263d9b2021-12-10 14:28:20 -0500798func bp2BuildParseExportedIncludesHelper(ctx android.BazelConversionPathContext, module *Module, libraryDecorator *libraryDecorator, includes *BazelIncludes) BazelIncludes {
799 var exported BazelIncludes
800 if includes != nil {
801 exported = *includes
802 } else {
803 exported = BazelIncludes{}
804 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400805 for axis, configToProps := range module.GetArchVariantProperties(ctx, &FlagExporterProperties{}) {
806 for config, props := range configToProps {
807 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
Liz Kammer5fad5012021-09-09 14:08:21 -0400808 if len(flagExporterProperties.Export_include_dirs) > 0 {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500809 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
Liz Kammer5fad5012021-09-09 14:08:21 -0400810 }
811 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500812 exported.SystemIncludes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.SystemIncludes.SelectValue(axis, config), flagExporterProperties.Export_system_include_dirs...)))
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400813 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400814 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400815 }
816 }
Liz Kammer1263d9b2021-12-10 14:28:20 -0500817 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -0400818 exported.Includes.DeduplicateAxesFromBase()
819 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400820
Liz Kammer5fad5012021-09-09 14:08:21 -0400821 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -0400822}
Chris Parsons953b3562021-09-20 15:14:39 -0400823
Jingwen Chen55bc8202021-11-02 06:40:51 +0000824func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400825 label := android.BazelModuleLabel(ctx, m)
Liz Kammer35ca77e2021-12-22 15:31:40 -0500826 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GenerateCcLibraryStaticOnly(m.Name()) {
827 label += "_bp2build_cc_library_static"
Chris Parsons953b3562021-09-20 15:14:39 -0400828 }
829 return label
830}
831
Jingwen Chen55bc8202021-11-02 06:40:51 +0000832func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400833 // cc_library, at it's root name, propagates the shared library, which depends on the static
834 // library.
835 return android.BazelModuleLabel(ctx, m)
836}
837
Jingwen Chen55bc8202021-11-02 06:40:51 +0000838func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400839 label := bazelLabelForStaticModule(ctx, m)
840 if aModule, ok := m.(android.Module); ok {
841 if android.IsModulePrebuilt(aModule) {
842 label += "_alwayslink"
843 }
844 }
845 return label
846}
847
Jingwen Chen55bc8202021-11-02 06:40:51 +0000848func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400849 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
850}
851
Jingwen Chen55bc8202021-11-02 06:40:51 +0000852func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400853 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
854}
855
Jingwen Chen55bc8202021-11-02 06:40:51 +0000856func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400857 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
858}
859
Jingwen Chen55bc8202021-11-02 06:40:51 +0000860func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400861 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
862}
863
Jingwen Chen55bc8202021-11-02 06:40:51 +0000864func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400865 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
866}
867
Jingwen Chen55bc8202021-11-02 06:40:51 +0000868func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400869 // This is not elegant, but bp2build's shared library targets only propagate
870 // their header information as part of the normal C++ provider.
871 return bazelLabelForSharedDeps(ctx, modules)
872}
873
Jingwen Chen55bc8202021-11-02 06:40:51 +0000874func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400875 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
876}
Liz Kammer2b8004b2021-10-04 13:55:44 -0400877
878type binaryLinkerAttrs struct {
879 Linkshared *bool
880}
881
Jingwen Chen55bc8202021-11-02 06:40:51 +0000882func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400883 attrs := binaryLinkerAttrs{}
884 archVariantProps := m.GetArchVariantProperties(ctx, &BinaryLinkerProperties{})
885 for axis, configToProps := range archVariantProps {
886 for _, p := range configToProps {
887 props := p.(*BinaryLinkerProperties)
888 staticExecutable := props.Static_executable
889 if axis == bazel.NoConfigAxis {
890 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
891 attrs.Linkshared = &linkBinaryShared
892 }
893 } else if staticExecutable != nil {
894 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
895 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
896 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
897 }
898 }
899 }
900
901 return attrs
902}