blob: fa30d096ba26d6c3e9f4b115022dae0b3f6af58e [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"
Trevor Radcliffeef9c9002022-05-13 20:55:35 +000032 lSrcPartition = "l"
33 llSrcPartition = "ll"
Liz Kammer12615db2021-09-28 09:19:17 -040034 cppSrcPartition = "cpp"
35 protoSrcPartition = "proto"
Liz Kammerae3994e2021-10-19 09:45:48 -040036)
37
Liz Kammer2222c6b2021-05-24 15:41:47 -040038// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000039// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040040type staticOrSharedAttributes struct {
Jingwen Chenc4dc9b42021-06-11 12:51:48 +000041 Srcs bazel.LabelListAttribute
42 Srcs_c bazel.LabelListAttribute
43 Srcs_as bazel.LabelListAttribute
Liz Kammere6583482021-10-19 13:56:10 -040044 Hdrs bazel.LabelListAttribute
Jingwen Chenc4dc9b42021-06-11 12:51:48 +000045 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000046
Liz Kammer12615db2021-09-28 09:19:17 -040047 Deps bazel.LabelListAttribute
48 Implementation_deps bazel.LabelListAttribute
49 Dynamic_deps bazel.LabelListAttribute
50 Implementation_dynamic_deps bazel.LabelListAttribute
51 Whole_archive_deps bazel.LabelListAttribute
52 Implementation_whole_archive_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040053
54 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050055
56 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080057
Yu Liu8d82ac52022-05-17 15:13:28 -070058 Native_coverage bazel.BoolAttribute
59
Yu Liufc603162022-03-01 15:44:08 -080060 sdkAttributes
Jingwen Chen53681ef2021-04-29 08:15:13 +000061}
62
Sam Delmericoc7681022022-02-04 21:01:20 +000063// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +000064func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -040065 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
66 // macro.
67 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Liz Kammer12615db2021-09-28 09:19:17 -040068 return func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
69 m, exists := ctx.ModuleFromName(label.OriginalModuleName)
70 labelStr := label.Label
Sam Delmericoc7681022022-02-04 21:01:20 +000071 if !exists || !android.IsFilegroup(ctx, m) {
Liz Kammer12615db2021-09-28 09:19:17 -040072 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +000073 }
Liz Kammer12615db2021-09-28 09:19:17 -040074 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -040075 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000076 }
77
Liz Kammer57e2e7a2021-09-20 12:55:02 -040078 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +000079 labels := bazel.LabelPartitions{
80 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -050081 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
82 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Trevor Radcliffeef9c9002022-05-13 20:55:35 +000083 // TODO(http://b/231968910): If there is ever a filegroup target that
84 // contains .l or .ll files we will need to find a way to add a
85 // LabelMapper for these that identifies these filegroups and
86 // converts them appropriately
87 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
88 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
Liz Kammer57e2e7a2021-09-20 12:55:02 -040089 // C++ is the "catch-all" group, and comprises generated sources because we don't
90 // know the language of these sources until the genrule is executed.
Liz Kammeraabfb5d2021-12-08 15:25:06 -050091 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
Sam Delmericoc7681022022-02-04 21:01:20 +000092 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000093
Sam Delmericoc7681022022-02-04 21:01:20 +000094 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +000095}
96
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +000097// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +000098func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +000099 lib, ok := module.compiler.(*libraryDecorator)
100 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400101 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000102 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000103 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
104}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000105
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000106// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000107func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000108 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000109}
110
111// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000112func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000113 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400114}
115
Liz Kammer7a210ac2021-09-22 15:52:58 -0400116type depsPartition struct {
117 export bazel.LabelList
118 implementation bazel.LabelList
119}
120
Jingwen Chen55bc8202021-11-02 06:40:51 +0000121type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400122
Jingwen Chen55bc8202021-11-02 06:40:51 +0000123func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400124 if !exportsDeps {
125 return depsPartition{
126 implementation: fn(ctx, allDeps),
127 }
128 }
129
Liz Kammer7a210ac2021-09-22 15:52:58 -0400130 implementation, export := android.FilterList(allDeps, exportedDeps)
131
132 return depsPartition{
133 export: fn(ctx, export),
134 implementation: fn(ctx, implementation),
135 }
136}
137
Jingwen Chen55bc8202021-11-02 06:40:51 +0000138type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400139
Jingwen Chen55bc8202021-11-02 06:40:51 +0000140func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400141 if !exportsDeps {
142 return depsPartition{
143 implementation: fn(ctx, allDeps, excludes),
144 }
145 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400146 implementation, export := android.FilterList(allDeps, exportedDeps)
147
148 return depsPartition{
149 export: fn(ctx, export, excludes),
150 implementation: fn(ctx, implementation, excludes),
151 }
152}
153
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000154// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000155func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400156 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000157
Liz Kammer9abd62d2021-05-21 08:37:59 -0400158 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Liz Kammercac7f692021-12-16 14:19:32 -0500159 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000160 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400161 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400162
Liz Kammer2b8004b2021-10-04 13:55:44 -0400163 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400164 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
165 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
166
Liz Kammer2b8004b2021-10-04 13:55:44 -0400167 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400168 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
169 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
170
171 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500172 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000173 }
Liz Kammer135bf552021-08-11 10:46:06 -0400174 // system_dynamic_deps distinguishes between nil/empty list behavior:
175 // nil -> use default values
176 // empty list -> no values specified
177 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000178
179 if isStatic {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000180 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
181 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
182 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000183 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000184 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000185 } else {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000186 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
187 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
188 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000189 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000190 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000191 }
192
Liz Kammerae3994e2021-10-19 09:45:48 -0400193 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
194 attrs.Srcs = partitionedSrcs[cppSrcPartition]
195 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
196 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000197
Liz Kammer12615db2021-09-28 09:19:17 -0400198 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
199 // TODO(b/208815215): determine whether this is used and add support if necessary
200 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
201 }
202
Jingwen Chenbcf53042021-05-26 04:42:42 +0000203 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000204}
205
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400206// Convenience struct to hold all attributes parsed from prebuilt properties.
207type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000208 Src bazel.LabelAttribute
209 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400210}
211
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000212// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000213func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) prebuiltAttributes {
214 manySourceFileError := func(axis bazel.ConfigurationAxis, config string) {
215 ctx.ModuleErrorf("Bp2BuildParsePrebuiltLibraryProps: Expected at most one source file for %s %s\n", axis, config)
216 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400217 var srcLabelAttribute bazel.LabelAttribute
218
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000219 parseSrcs := func(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, srcs []string) {
220 if len(srcs) > 1 {
221 manySourceFileError(axis, config)
222 return
223 } else if len(srcs) == 0 {
224 return
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400225 }
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000226 if srcLabelAttribute.SelectValue(axis, config) != nil {
227 manySourceFileError(axis, config)
228 return
229 }
230
231 src := android.BazelLabelForModuleSrcSingle(ctx, srcs[0])
232 srcLabelAttribute.SetSelectValue(axis, config, src)
233 }
234
235 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
236 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
237 parseSrcs(ctx, axis, config, prebuiltLinkerProperties.Srcs)
238 }
239 })
240
241 var enabledLabelAttribute bazel.BoolAttribute
242 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
243 if props.Enabled != nil {
244 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
245 }
246 parseSrcs(ctx, axis, config, props.Srcs)
247 }
248
249 if isStatic {
250 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
251 if staticProperties, ok := props.(*StaticProperties); ok {
252 parseAttrs(axis, config, staticProperties.Static)
253 }
254 })
255 } else {
256 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
257 if sharedProperties, ok := props.(*SharedProperties); ok {
258 parseAttrs(axis, config, sharedProperties.Shared)
259 }
260 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400261 }
262
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400263 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000264 Src: srcLabelAttribute,
265 Enabled: enabledLabelAttribute,
266 }
267}
268
269func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
270 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
271 for config, props := range configToProps {
272 parseFunc(axis, config, props)
273 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400274 }
275}
276
Liz Kammere6583482021-10-19 13:56:10 -0400277type baseAttributes struct {
278 compilerAttributes
279 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400280
281 protoDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400282}
283
Jingwen Chen107c0de2021-04-09 10:43:12 +0000284// Convenience struct to hold all attributes parsed from compiler properties.
285type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400286 // Options for all languages
287 copts bazel.StringListAttribute
288 // Assembly options and sources
289 asFlags bazel.StringListAttribute
290 asSrcs bazel.LabelListAttribute
291 // C options and sources
292 conlyFlags bazel.StringListAttribute
293 cSrcs bazel.LabelListAttribute
294 // C++ options and sources
295 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000296 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400297
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000298 // Lex sources and options
299 lSrcs bazel.LabelListAttribute
300 llSrcs bazel.LabelListAttribute
301 lexopts bazel.StringListAttribute
302
Liz Kammere6583482021-10-19 13:56:10 -0400303 hdrs bazel.LabelListAttribute
304
Chris Parsons2c788392021-08-10 11:58:07 -0400305 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000306
307 // Not affected by arch variants
308 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500309 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000310 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400311
312 localIncludes bazel.StringListAttribute
313 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400314
Liz Kammer1263d9b2021-12-10 14:28:20 -0500315 includes BazelIncludes
316
Liz Kammer12615db2021-09-28 09:19:17 -0400317 protoSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000318
319 stubsSymbolFile *string
320 stubsVersions bazel.StringListAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000321}
322
Liz Kammercac7f692021-12-16 14:19:32 -0500323type filterOutFn func(string) bool
324
325func filterOutStdFlag(flag string) bool {
326 return strings.HasPrefix(flag, "-std=")
327}
328
329func parseCommandLineFlags(soongFlags []string, filterOut filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400330 var result []string
331 for _, flag := range soongFlags {
Liz Kammercac7f692021-12-16 14:19:32 -0500332 if filterOut != nil && filterOut(flag) {
333 continue
334 }
Liz Kammere6583482021-10-19 13:56:10 -0400335 // Soong's cflags can contain spaces, like `-include header.h`. For
336 // Bazel's copts, split them up to be compatible with the
337 // no_copts_tokenization feature.
338 result = append(result, strings.Split(flag, " ")...)
339 }
340 return result
341}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000342
Jingwen Chen55bc8202021-11-02 06:40:51 +0000343func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400344 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
345 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
346 if srcsList, ok := parseSrcs(ctx, props); ok {
347 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400348 }
349
Liz Kammere6583482021-10-19 13:56:10 -0400350 localIncludeDirs := props.Local_include_dirs
351 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500352 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400353 if includeBuildDirectory(props.Include_build_directory) {
354 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400355 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000356 }
357
Liz Kammere6583482021-10-19 13:56:10 -0400358 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
359 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
360
Liz Kammercac7f692021-12-16 14:19:32 -0500361 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
362 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
363 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
364 // cases.
365 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
366 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
367 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, nil))
368 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, nil))
Liz Kammere6583482021-10-19 13:56:10 -0400369 ca.rtti.SetSelectValue(axis, config, props.Rtti)
370}
371
Jingwen Chen55bc8202021-11-02 06:40:51 +0000372func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000373 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
374 if stlProps, ok := props.(*StlProperties); ok {
375 if stlProps.Stl == nil {
376 return
377 }
378 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400379 stl := deduplicateStlInput(*stlProps.Stl)
380 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000381 } else if ca.stl != stlProps.Stl {
382 ctx.ModuleErrorf("Unsupported conversion: module with different stl for different variants: %s and %s", *ca.stl, stlProps.Stl)
Liz Kammer9abd62d2021-05-21 08:37:59 -0400383 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000384 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000385 })
Liz Kammere6583482021-10-19 13:56:10 -0400386}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000387
Jingwen Chen55bc8202021-11-02 06:40:51 +0000388func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400389 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400390 "Cflags": &ca.copts,
391 "Asflags": &ca.asFlags,
392 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400393 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400394 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000395 if productConfigProps, exists := productVariableProps[propName]; exists {
396 for productConfigProp, prop := range productConfigProps {
397 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400398 if !ok {
399 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
400 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000401 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
402 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400403 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400404 }
405 }
Liz Kammere6583482021-10-19 13:56:10 -0400406}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400407
Jingwen Chen55bc8202021-11-02 06:40:51 +0000408func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400409 ca.srcs.ResolveExcludes()
410 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
411
Liz Kammer12615db2021-09-28 09:19:17 -0400412 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
413
Liz Kammere6583482021-10-19 13:56:10 -0400414 for p, lla := range partitionedSrcs {
415 // if there are no sources, there is no need for headers
416 if lla.IsEmpty() {
417 continue
418 }
419 lla.Append(implementationHdrs)
420 partitionedSrcs[p] = lla
421 }
422
423 ca.srcs = partitionedSrcs[cppSrcPartition]
424 ca.cSrcs = partitionedSrcs[cSrcPartition]
425 ca.asSrcs = partitionedSrcs[asSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000426 ca.lSrcs = partitionedSrcs[lSrcPartition]
427 ca.llSrcs = partitionedSrcs[llSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400428
429 ca.absoluteIncludes.DeduplicateAxesFromBase()
430 ca.localIncludes.DeduplicateAxesFromBase()
431}
432
433// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000434func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400435 anySrcs := false
436 // Add srcs-like dependencies such as generated files.
437 // First create a LabelList containing these dependencies, then merge the values with srcs.
438 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
439 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
440 anySrcs = true
441 }
442
443 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
444 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
445 anySrcs = true
446 }
447 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
448}
449
Liz Kammera5a29de2022-05-25 23:19:37 -0400450func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
451 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500452 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
453 // Defaults are handled by the toolchain definition.
454 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400455 stdVal := proptools.StringDefault(std, defaultVal)
456 if stdVal == "experimental" || stdVal == defaultVal {
457 if stdVal == "experimental" {
458 stdVal = prefix + "_std_experimental"
459 }
460 if !useGnu {
461 stdVal += "_no_gnu"
462 }
463 } else if !useGnu {
464 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500465 }
466
Liz Kammera5a29de2022-05-25 23:19:37 -0400467 if stdVal == defaultVal {
468 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500469 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400470 return &stdVal
471}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500472
Liz Kammera5a29de2022-05-25 23:19:37 -0400473func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
474 useGnu := useGnuExtensions(gnu_extensions)
475
476 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400477}
478
Liz Kammer1263d9b2021-12-10 14:28:20 -0500479// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
480// is fully-qualified.
481// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
482func packageFromLabel(label string) (string, bool) {
483 split := strings.Split(label, ":")
484 if len(split) != 2 {
485 return "", false
486 }
487 if split[0] == "" {
488 return ".", false
489 }
490 // remove leading "//"
491 return split[0][2:], true
492}
493
494// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
495func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
496 for _, hdr := range labelList.Includes {
497 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
498 absolute = append(absolute, pkg)
499 } else if pkg != "" {
500 relative = append(relative, pkg)
501 }
502 }
503 return relative, absolute
504}
505
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000506// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400507func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400508 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
509 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000510 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400511
512 var implementationHdrs bazel.LabelListAttribute
513
514 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
515 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
516 for axis, configMap := range cp {
517 if _, ok := axisToConfigs[axis]; !ok {
518 axisToConfigs[axis] = map[string]bool{}
519 }
520 for config, _ := range configMap {
521 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400522 }
523 }
524 }
Liz Kammere6583482021-10-19 13:56:10 -0400525 allAxesAndConfigs(archVariantCompilerProps)
526 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000527 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400528
Liz Kammere6583482021-10-19 13:56:10 -0400529 compilerAttrs := compilerAttributes{}
530 linkerAttrs := linkerAttributes{}
531
532 for axis, configs := range axisToConfigs {
533 for config, _ := range configs {
534 var allHdrs []string
535 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
536 allHdrs = baseCompilerProps.Generated_headers
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000537 if baseCompilerProps.Lex != nil {
538 compilerAttrs.lexopts.SetSelectValue(axis, config, baseCompilerProps.Lex.Flags)
539 }
Liz Kammere6583482021-10-19 13:56:10 -0400540 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
541 }
542
543 var exportHdrs []string
544
545 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
546 exportHdrs = baseLinkerProps.Export_generated_headers
547
548 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
549 }
550 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
551 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
552 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500553
554 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
555 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
556 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
557
558 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
559 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
560 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
561 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
562 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
563 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
564 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000565
566 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
567 if axis == bazel.NoConfigAxis {
568 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
569 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
570 }
571 }
Liz Kammere6583482021-10-19 13:56:10 -0400572 }
573 }
Liz Kammere6583482021-10-19 13:56:10 -0400574 compilerAttrs.convertStlProps(ctx, module)
575 (&linkerAttrs).convertStripProps(ctx, module)
576
Yu Liu8d82ac52022-05-17 15:13:28 -0700577 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
578 !Bool(module.coverage.Properties.Native_coverage) {
579 // Native_coverage is arch neutral
580 (&linkerAttrs).features.Append(bazel.MakeStringListAttribute([]string{"-coverage"}))
581 }
582
Liz Kammere6583482021-10-19 13:56:10 -0400583 productVariableProps := android.ProductVariableProperties(ctx)
584
585 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
586 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
587
588 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500589 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400590
Liz Kammer12615db2021-09-28 09:19:17 -0400591 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
592
593 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
594 // which. This will add the newly generated proto library to the appropriate attribute and nothing
595 // to the other
596 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
597 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
598
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000599 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
600 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
601 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
602
Liz Kammere6583482021-10-19 13:56:10 -0400603 return baseAttributes{
604 compilerAttrs,
605 linkerAttrs,
Liz Kammer12615db2021-09-28 09:19:17 -0400606 protoDep.protoDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000607 }
608}
609
Yu Liufc603162022-03-01 15:44:08 -0800610func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000611 return sdkAttributes{
612 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800613 Min_sdk_version: module.Properties.Min_sdk_version,
614 }
615}
616
617type sdkAttributes struct {
618 Sdk_version *string
619 Min_sdk_version *string
620}
621
Jingwen Chen107c0de2021-04-09 10:43:12 +0000622// Convenience struct to hold all attributes parsed from linker properties.
623type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500624 deps bazel.LabelListAttribute
625 implementationDeps bazel.LabelListAttribute
626 dynamicDeps bazel.LabelListAttribute
627 implementationDynamicDeps bazel.LabelListAttribute
628 wholeArchiveDeps bazel.LabelListAttribute
629 implementationWholeArchiveDeps bazel.LabelListAttribute
630 systemDynamicDeps bazel.LabelListAttribute
631 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400632
Jingwen Chen6ada5892021-09-17 11:38:09 +0000633 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000634 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500635 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000636 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400637 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000638 stripKeepSymbols bazel.BoolAttribute
639 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
640 stripKeepSymbolsList bazel.StringListAttribute
641 stripAll bazel.BoolAttribute
642 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400643 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400644}
645
Liz Kammer54309532021-12-14 12:21:22 -0500646var (
647 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
648)
649
Jingwen Chen55bc8202021-11-02 06:40:51 +0000650func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400651 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
652 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400653
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400654 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
655 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammere6583482021-10-19 13:56:10 -0400656 // Excludes to parallel Soong:
657 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=247-249;drc=088b53577dde6e40085ffd737a1ae96ad82fc4b0
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400658 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
659
Liz Kammere6583482021-10-19 13:56:10 -0400660 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, staticLibs, props.Exclude_static_libs, props.Export_static_lib_headers, bazelLabelForStaticDepsExcludes)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400661
Liz Kammere6583482021-10-19 13:56:10 -0400662 headerLibs := android.FirstUniqueStrings(props.Header_libs)
663 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400664
Liz Kammere6583482021-10-19 13:56:10 -0400665 (&hDeps.export).Append(staticDeps.export)
666 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000667
Liz Kammere6583482021-10-19 13:56:10 -0400668 (&hDeps.implementation).Append(staticDeps.implementation)
669 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400670
Liz Kammere6583482021-10-19 13:56:10 -0400671 systemSharedLibs := props.System_shared_libs
672 // systemSharedLibs distinguishes between nil/empty list behavior:
673 // nil -> use default values
674 // empty list -> no values specified
675 if len(systemSharedLibs) > 0 {
676 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
677 }
678 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
679
680 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500681 excludeSharedLibs := props.Exclude_shared_libs
682 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
683 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
684 })
685 for _, el := range usedSystem {
686 if la.usedSystemDynamicDepAsDynamicDep == nil {
687 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
688 }
689 la.usedSystemDynamicDepAsDynamicDep[el] = true
690 }
691
Liz Kammere6583482021-10-19 13:56:10 -0400692 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, sharedLibs, props.Exclude_shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDepsExcludes)
693 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
694 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
695
696 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
697 axisFeatures = append(axisFeatures, "disable_pack_relocations")
698 }
699
700 if Bool(props.Allow_undefined_symbols) {
701 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
702 }
703
704 var linkerFlags []string
705 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -0500706 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -0400707 // binaries remove static flag if -shared is in the linker flags
708 if isBinary && android.InList("-shared", linkerFlags) {
709 axisFeatures = append(axisFeatures, "-static_flag")
710 }
711 }
712 if props.Version_script != nil {
713 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
714 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
715 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
716 }
Alix773adaa2022-04-27 17:49:34 +0000717
718 if props.Dynamic_list != nil {
719 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
720 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
721 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
722 }
723
Liz Kammere6583482021-10-19 13:56:10 -0400724 la.linkopts.SetSelectValue(axis, config, linkerFlags)
725 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
726
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500727 if axis == bazel.NoConfigAxis {
728 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
729 }
730
Liz Kammere6583482021-10-19 13:56:10 -0400731 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
732 if props.crt() != nil {
733 if axis == bazel.NoConfigAxis {
734 la.linkCrt.SetSelectValue(axis, config, props.crt())
735 } else if axis == bazel.ArchConfigurationAxis {
736 ctx.ModuleErrorf("nocrt is not supported for arch variants")
737 }
738 }
739
740 if axisFeatures != nil {
741 la.features.SetSelectValue(axis, config, axisFeatures)
742 }
743}
744
Jingwen Chen55bc8202021-11-02 06:40:51 +0000745func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000746 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
747 if stripProperties, ok := props.(*StripProperties); ok {
748 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
749 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
750 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
751 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
752 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000753 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000754 })
Liz Kammere6583482021-10-19 13:56:10 -0400755}
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000756
Jingwen Chen55bc8202021-11-02 06:40:51 +0000757func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +0000758
Liz Kammer47535c52021-06-02 16:02:22 -0400759 type productVarDep struct {
760 // the name of the corresponding excludes field, if one exists
761 excludesField string
762 // reference to the bazel attribute that should be set for the given product variable config
763 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400764
Jingwen Chen55bc8202021-11-02 06:40:51 +0000765 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -0400766 }
767
768 productVarToDepFields := map[string]productVarDep{
769 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +0000770 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
771 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
772 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -0400773 }
774
Liz Kammer47535c52021-06-02 16:02:22 -0400775 for name, dep := range productVarToDepFields {
776 props, exists := productVariableProps[name]
777 excludeProps, excludesExists := productVariableProps[dep.excludesField]
778 // if neither an include or excludes property exists, then skip it
779 if !exists && !excludesExists {
780 continue
781 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000782 // Collect all the configurations that an include or exclude property exists for.
783 // We want to iterate all configurations rather than either the include or exclude because, for a
784 // particular configuration, we may have either only an include or an exclude to handle.
785 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
786 for p := range props {
787 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400788 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000789 for p := range excludeProps {
790 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400791 }
792
Jingwen Chen25825ca2021-11-15 12:28:43 +0000793 for productConfigProp := range productConfigProps {
794 prop, includesExists := props[productConfigProp]
795 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -0400796 var includes, excludes []string
797 var ok bool
798 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +0000799 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400800 ctx.ModuleErrorf("Could not convert product variable %s property", name)
801 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000802 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400803 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
804 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400805
Jingwen Chen58ff6802021-11-17 12:14:41 +0000806 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +0000807 dep.attribute.SetSelectValue(
808 productConfigProp.ConfigurationAxis(),
809 productConfigProp.SelectKey(),
810 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
811 )
Liz Kammer47535c52021-06-02 16:02:22 -0400812 }
813 }
Liz Kammere6583482021-10-19 13:56:10 -0400814}
Liz Kammer47535c52021-06-02 16:02:22 -0400815
Liz Kammer54309532021-12-14 12:21:22 -0500816func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
817 // if system dynamic deps have the default value, any use of a system dynamic library used will
818 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
819 // from bionic OSes.
820 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
821 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
822 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
823 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
824 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
825 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
826 }
827
Liz Kammere6583482021-10-19 13:56:10 -0400828 la.deps.ResolveExcludes()
829 la.implementationDeps.ResolveExcludes()
830 la.dynamicDeps.ResolveExcludes()
831 la.implementationDynamicDeps.ResolveExcludes()
832 la.wholeArchiveDeps.ResolveExcludes()
833 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -0500834
Jingwen Chen91220d72021-03-24 02:18:33 -0400835}
836
Jingwen Chened9c17d2021-04-13 07:14:55 +0000837// Relativize a list of root-relative paths with respect to the module's
838// directory.
839//
840// include_dirs Soong prop are root-relative (b/183742505), but
841// local_include_dirs, export_include_dirs and export_system_include_dirs are
842// module dir relative. This function makes a list of paths entirely module dir
843// relative.
844//
845// For the `include` attribute, Bazel wants the paths to be relative to the
846// module.
847func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000848 var relativePaths []string
849 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +0000850 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
851 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
852 if err != nil {
853 panic(err)
854 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000855 relativePaths = append(relativePaths, relativePath)
856 }
857 return relativePaths
858}
859
Liz Kammer5fad5012021-09-09 14:08:21 -0400860// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
861// attributes.
862type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500863 AbsoluteIncludes bazel.StringListAttribute
864 Includes bazel.StringListAttribute
865 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -0400866}
867
Liz Kammer54549442022-05-11 13:55:06 -0400868func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500869 var exported BazelIncludes
870 if includes != nil {
871 exported = *includes
872 } else {
873 exported = BazelIncludes{}
874 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000875 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
876 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
877 if len(flagExporterProperties.Export_include_dirs) > 0 {
878 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
879 }
880 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
881 exported.SystemIncludes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.SystemIncludes.SelectValue(axis, config), flagExporterProperties.Export_system_include_dirs...)))
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400882 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400883 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000884 })
Liz Kammer1263d9b2021-12-10 14:28:20 -0500885 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -0400886 exported.Includes.DeduplicateAxesFromBase()
887 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400888
Liz Kammer5fad5012021-09-09 14:08:21 -0400889 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -0400890}
Chris Parsons953b3562021-09-20 15:14:39 -0400891
Jingwen Chen55bc8202021-11-02 06:40:51 +0000892func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400893 label := android.BazelModuleLabel(ctx, m)
Liz Kammer35ca77e2021-12-22 15:31:40 -0500894 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GenerateCcLibraryStaticOnly(m.Name()) {
895 label += "_bp2build_cc_library_static"
Chris Parsons953b3562021-09-20 15:14:39 -0400896 }
897 return label
898}
899
Jingwen Chen55bc8202021-11-02 06:40:51 +0000900func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400901 // cc_library, at it's root name, propagates the shared library, which depends on the static
902 // library.
903 return android.BazelModuleLabel(ctx, m)
904}
905
Jingwen Chen55bc8202021-11-02 06:40:51 +0000906func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400907 label := bazelLabelForStaticModule(ctx, m)
908 if aModule, ok := m.(android.Module); ok {
909 if android.IsModulePrebuilt(aModule) {
910 label += "_alwayslink"
911 }
912 }
913 return label
914}
915
Jingwen Chen55bc8202021-11-02 06:40:51 +0000916func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400917 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
918}
919
Jingwen Chen55bc8202021-11-02 06:40:51 +0000920func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400921 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
922}
923
Jingwen Chen55bc8202021-11-02 06:40:51 +0000924func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400925 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
926}
927
Jingwen Chen55bc8202021-11-02 06:40:51 +0000928func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400929 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
930}
931
Jingwen Chen55bc8202021-11-02 06:40:51 +0000932func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400933 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
934}
935
Jingwen Chen55bc8202021-11-02 06:40:51 +0000936func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400937 // This is not elegant, but bp2build's shared library targets only propagate
938 // their header information as part of the normal C++ provider.
939 return bazelLabelForSharedDeps(ctx, modules)
940}
941
Jingwen Chen55bc8202021-11-02 06:40:51 +0000942func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400943 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
944}
Liz Kammer2b8004b2021-10-04 13:55:44 -0400945
946type binaryLinkerAttrs struct {
947 Linkshared *bool
948}
949
Jingwen Chen55bc8202021-11-02 06:40:51 +0000950func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400951 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000952 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
953 linkerProps := props.(*BinaryLinkerProperties)
954 staticExecutable := linkerProps.Static_executable
955 if axis == bazel.NoConfigAxis {
956 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
957 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -0400958 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000959 } else if staticExecutable != nil {
960 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
961 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
962 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -0400963 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000964 })
Liz Kammer2b8004b2021-10-04 13:55:44 -0400965
966 return attrs
967}