blob: 70dcf40b18713a91c1244abcd64adcb871140d89 [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
58 sdkAttributes
Jingwen Chen53681ef2021-04-29 08:15:13 +000059}
60
Sam Delmericoc7681022022-02-04 21:01:20 +000061// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +000062func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -040063 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
64 // macro.
65 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Liz Kammer12615db2021-09-28 09:19:17 -040066 return func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
67 m, exists := ctx.ModuleFromName(label.OriginalModuleName)
68 labelStr := label.Label
Sam Delmericoc7681022022-02-04 21:01:20 +000069 if !exists || !android.IsFilegroup(ctx, m) {
Liz Kammer12615db2021-09-28 09:19:17 -040070 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +000071 }
Liz Kammer12615db2021-09-28 09:19:17 -040072 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -040073 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000074 }
75
Liz Kammer57e2e7a2021-09-20 12:55:02 -040076 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +000077 labels := bazel.LabelPartitions{
78 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -050079 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
80 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Trevor Radcliffeef9c9002022-05-13 20:55:35 +000081 // TODO(http://b/231968910): If there is ever a filegroup target that
82 // contains .l or .ll files we will need to find a way to add a
83 // LabelMapper for these that identifies these filegroups and
84 // converts them appropriately
85 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
86 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
Liz Kammer57e2e7a2021-09-20 12:55:02 -040087 // C++ is the "catch-all" group, and comprises generated sources because we don't
88 // know the language of these sources until the genrule is executed.
Liz Kammeraabfb5d2021-12-08 15:25:06 -050089 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
Sam Delmericoc7681022022-02-04 21:01:20 +000090 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000091
Sam Delmericoc7681022022-02-04 21:01:20 +000092 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +000093}
94
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +000095// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +000096func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +000097 lib, ok := module.compiler.(*libraryDecorator)
98 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -040099 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000100 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000101 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
102}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000103
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000104// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000105func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000106 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000107}
108
109// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000110func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000111 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400112}
113
Liz Kammer7a210ac2021-09-22 15:52:58 -0400114type depsPartition struct {
115 export bazel.LabelList
116 implementation bazel.LabelList
117}
118
Jingwen Chen55bc8202021-11-02 06:40:51 +0000119type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400120
Jingwen Chen55bc8202021-11-02 06:40:51 +0000121func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400122 if !exportsDeps {
123 return depsPartition{
124 implementation: fn(ctx, allDeps),
125 }
126 }
127
Liz Kammer7a210ac2021-09-22 15:52:58 -0400128 implementation, export := android.FilterList(allDeps, exportedDeps)
129
130 return depsPartition{
131 export: fn(ctx, export),
132 implementation: fn(ctx, implementation),
133 }
134}
135
Jingwen Chen55bc8202021-11-02 06:40:51 +0000136type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400137
Jingwen Chen55bc8202021-11-02 06:40:51 +0000138func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400139 if !exportsDeps {
140 return depsPartition{
141 implementation: fn(ctx, allDeps, excludes),
142 }
143 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400144 implementation, export := android.FilterList(allDeps, exportedDeps)
145
146 return depsPartition{
147 export: fn(ctx, export, excludes),
148 implementation: fn(ctx, implementation, excludes),
149 }
150}
151
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000152// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000153func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400154 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000155
Liz Kammer9abd62d2021-05-21 08:37:59 -0400156 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Liz Kammercac7f692021-12-16 14:19:32 -0500157 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000158 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400159 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400160
Liz Kammer2b8004b2021-10-04 13:55:44 -0400161 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400162 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
163 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
164
Liz Kammer2b8004b2021-10-04 13:55:44 -0400165 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400166 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
167 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
168
169 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500170 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000171 }
Liz Kammer135bf552021-08-11 10:46:06 -0400172 // system_dynamic_deps distinguishes between nil/empty list behavior:
173 // nil -> use default values
174 // empty list -> no values specified
175 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000176
177 if isStatic {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000178 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
179 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
180 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000181 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000182 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000183 } else {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000184 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
185 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
186 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000187 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000188 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000189 }
190
Liz Kammerae3994e2021-10-19 09:45:48 -0400191 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
192 attrs.Srcs = partitionedSrcs[cppSrcPartition]
193 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
194 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000195
Liz Kammer12615db2021-09-28 09:19:17 -0400196 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
197 // TODO(b/208815215): determine whether this is used and add support if necessary
198 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
199 }
200
Jingwen Chenbcf53042021-05-26 04:42:42 +0000201 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000202}
203
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400204// Convenience struct to hold all attributes parsed from prebuilt properties.
205type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000206 Src bazel.LabelAttribute
207 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400208}
209
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000210// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000211func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) prebuiltAttributes {
212 manySourceFileError := func(axis bazel.ConfigurationAxis, config string) {
213 ctx.ModuleErrorf("Bp2BuildParsePrebuiltLibraryProps: Expected at most one source file for %s %s\n", axis, config)
214 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400215 var srcLabelAttribute bazel.LabelAttribute
216
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000217 parseSrcs := func(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, srcs []string) {
218 if len(srcs) > 1 {
219 manySourceFileError(axis, config)
220 return
221 } else if len(srcs) == 0 {
222 return
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400223 }
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000224 if srcLabelAttribute.SelectValue(axis, config) != nil {
225 manySourceFileError(axis, config)
226 return
227 }
228
229 src := android.BazelLabelForModuleSrcSingle(ctx, srcs[0])
230 srcLabelAttribute.SetSelectValue(axis, config, src)
231 }
232
233 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
234 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
235 parseSrcs(ctx, axis, config, prebuiltLinkerProperties.Srcs)
236 }
237 })
238
239 var enabledLabelAttribute bazel.BoolAttribute
240 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
241 if props.Enabled != nil {
242 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
243 }
244 parseSrcs(ctx, axis, config, props.Srcs)
245 }
246
247 if isStatic {
248 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
249 if staticProperties, ok := props.(*StaticProperties); ok {
250 parseAttrs(axis, config, staticProperties.Static)
251 }
252 })
253 } else {
254 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
255 if sharedProperties, ok := props.(*SharedProperties); ok {
256 parseAttrs(axis, config, sharedProperties.Shared)
257 }
258 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400259 }
260
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400261 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000262 Src: srcLabelAttribute,
263 Enabled: enabledLabelAttribute,
264 }
265}
266
267func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
268 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
269 for config, props := range configToProps {
270 parseFunc(axis, config, props)
271 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400272 }
273}
274
Liz Kammere6583482021-10-19 13:56:10 -0400275type baseAttributes struct {
276 compilerAttributes
277 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400278
279 protoDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400280}
281
Jingwen Chen107c0de2021-04-09 10:43:12 +0000282// Convenience struct to hold all attributes parsed from compiler properties.
283type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400284 // Options for all languages
285 copts bazel.StringListAttribute
286 // Assembly options and sources
287 asFlags bazel.StringListAttribute
288 asSrcs bazel.LabelListAttribute
289 // C options and sources
290 conlyFlags bazel.StringListAttribute
291 cSrcs bazel.LabelListAttribute
292 // C++ options and sources
293 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000294 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400295
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000296 // Lex sources and options
297 lSrcs bazel.LabelListAttribute
298 llSrcs bazel.LabelListAttribute
299 lexopts bazel.StringListAttribute
300
Liz Kammere6583482021-10-19 13:56:10 -0400301 hdrs bazel.LabelListAttribute
302
Chris Parsons2c788392021-08-10 11:58:07 -0400303 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000304
305 // Not affected by arch variants
306 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500307 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000308 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400309
310 localIncludes bazel.StringListAttribute
311 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400312
Liz Kammer1263d9b2021-12-10 14:28:20 -0500313 includes BazelIncludes
314
Liz Kammer12615db2021-09-28 09:19:17 -0400315 protoSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000316
317 stubsSymbolFile *string
318 stubsVersions bazel.StringListAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000319}
320
Liz Kammercac7f692021-12-16 14:19:32 -0500321type filterOutFn func(string) bool
322
323func filterOutStdFlag(flag string) bool {
324 return strings.HasPrefix(flag, "-std=")
325}
326
327func parseCommandLineFlags(soongFlags []string, filterOut filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400328 var result []string
329 for _, flag := range soongFlags {
Liz Kammercac7f692021-12-16 14:19:32 -0500330 if filterOut != nil && filterOut(flag) {
331 continue
332 }
Liz Kammere6583482021-10-19 13:56:10 -0400333 // Soong's cflags can contain spaces, like `-include header.h`. For
334 // Bazel's copts, split them up to be compatible with the
335 // no_copts_tokenization feature.
336 result = append(result, strings.Split(flag, " ")...)
337 }
338 return result
339}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000340
Jingwen Chen55bc8202021-11-02 06:40:51 +0000341func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400342 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
343 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
344 if srcsList, ok := parseSrcs(ctx, props); ok {
345 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400346 }
347
Liz Kammere6583482021-10-19 13:56:10 -0400348 localIncludeDirs := props.Local_include_dirs
349 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500350 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400351 if includeBuildDirectory(props.Include_build_directory) {
352 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400353 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000354 }
355
Liz Kammere6583482021-10-19 13:56:10 -0400356 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
357 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
358
Liz Kammercac7f692021-12-16 14:19:32 -0500359 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
360 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
361 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
362 // cases.
363 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
364 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
365 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, nil))
366 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, nil))
Liz Kammere6583482021-10-19 13:56:10 -0400367 ca.rtti.SetSelectValue(axis, config, props.Rtti)
368}
369
Jingwen Chen55bc8202021-11-02 06:40:51 +0000370func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000371 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
372 if stlProps, ok := props.(*StlProperties); ok {
373 if stlProps.Stl == nil {
374 return
375 }
376 if ca.stl == nil {
377 ca.stl = stlProps.Stl
378 } else if ca.stl != stlProps.Stl {
379 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 -0400380 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000381 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000382 })
Liz Kammere6583482021-10-19 13:56:10 -0400383}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000384
Jingwen Chen55bc8202021-11-02 06:40:51 +0000385func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400386 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400387 "Cflags": &ca.copts,
388 "Asflags": &ca.asFlags,
389 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400390 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400391 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000392 if productConfigProps, exists := productVariableProps[propName]; exists {
393 for productConfigProp, prop := range productConfigProps {
394 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400395 if !ok {
396 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
397 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000398 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
399 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400400 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400401 }
402 }
Liz Kammere6583482021-10-19 13:56:10 -0400403}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400404
Jingwen Chen55bc8202021-11-02 06:40:51 +0000405func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400406 ca.srcs.ResolveExcludes()
407 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
408
Liz Kammer12615db2021-09-28 09:19:17 -0400409 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
410
Liz Kammere6583482021-10-19 13:56:10 -0400411 for p, lla := range partitionedSrcs {
412 // if there are no sources, there is no need for headers
413 if lla.IsEmpty() {
414 continue
415 }
416 lla.Append(implementationHdrs)
417 partitionedSrcs[p] = lla
418 }
419
420 ca.srcs = partitionedSrcs[cppSrcPartition]
421 ca.cSrcs = partitionedSrcs[cSrcPartition]
422 ca.asSrcs = partitionedSrcs[asSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000423 ca.lSrcs = partitionedSrcs[lSrcPartition]
424 ca.llSrcs = partitionedSrcs[llSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400425
426 ca.absoluteIncludes.DeduplicateAxesFromBase()
427 ca.localIncludes.DeduplicateAxesFromBase()
428}
429
430// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000431func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400432 anySrcs := false
433 // Add srcs-like dependencies such as generated files.
434 // First create a LabelList containing these dependencies, then merge the values with srcs.
435 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
436 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
437 anySrcs = true
438 }
439
440 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
441 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
442 anySrcs = true
443 }
444 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
445}
446
Liz Kammera5a29de2022-05-25 23:19:37 -0400447func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
448 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500449 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
450 // Defaults are handled by the toolchain definition.
451 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400452 stdVal := proptools.StringDefault(std, defaultVal)
453 if stdVal == "experimental" || stdVal == defaultVal {
454 if stdVal == "experimental" {
455 stdVal = prefix + "_std_experimental"
456 }
457 if !useGnu {
458 stdVal += "_no_gnu"
459 }
460 } else if !useGnu {
461 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500462 }
463
Liz Kammera5a29de2022-05-25 23:19:37 -0400464 if stdVal == defaultVal {
465 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500466 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400467 return &stdVal
468}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500469
Liz Kammera5a29de2022-05-25 23:19:37 -0400470func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
471 useGnu := useGnuExtensions(gnu_extensions)
472
473 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400474}
475
Liz Kammer1263d9b2021-12-10 14:28:20 -0500476// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
477// is fully-qualified.
478// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
479func packageFromLabel(label string) (string, bool) {
480 split := strings.Split(label, ":")
481 if len(split) != 2 {
482 return "", false
483 }
484 if split[0] == "" {
485 return ".", false
486 }
487 // remove leading "//"
488 return split[0][2:], true
489}
490
491// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
492func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
493 for _, hdr := range labelList.Includes {
494 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
495 absolute = append(absolute, pkg)
496 } else if pkg != "" {
497 relative = append(relative, pkg)
498 }
499 }
500 return relative, absolute
501}
502
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000503// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400504func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400505 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
506 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000507 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400508
509 var implementationHdrs bazel.LabelListAttribute
510
511 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
512 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
513 for axis, configMap := range cp {
514 if _, ok := axisToConfigs[axis]; !ok {
515 axisToConfigs[axis] = map[string]bool{}
516 }
517 for config, _ := range configMap {
518 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400519 }
520 }
521 }
Liz Kammere6583482021-10-19 13:56:10 -0400522 allAxesAndConfigs(archVariantCompilerProps)
523 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000524 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400525
Liz Kammere6583482021-10-19 13:56:10 -0400526 compilerAttrs := compilerAttributes{}
527 linkerAttrs := linkerAttributes{}
528
529 for axis, configs := range axisToConfigs {
530 for config, _ := range configs {
531 var allHdrs []string
532 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
533 allHdrs = baseCompilerProps.Generated_headers
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000534 if baseCompilerProps.Lex != nil {
535 compilerAttrs.lexopts.SetSelectValue(axis, config, baseCompilerProps.Lex.Flags)
536 }
Liz Kammere6583482021-10-19 13:56:10 -0400537 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
538 }
539
540 var exportHdrs []string
541
542 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
543 exportHdrs = baseLinkerProps.Export_generated_headers
544
545 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
546 }
547 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
548 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
549 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500550
551 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
552 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
553 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
554
555 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
556 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
557 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
558 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
559 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
560 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
561 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000562
563 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
564 if axis == bazel.NoConfigAxis {
565 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
566 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
567 }
568 }
Liz Kammere6583482021-10-19 13:56:10 -0400569 }
570 }
571
572 compilerAttrs.convertStlProps(ctx, module)
573 (&linkerAttrs).convertStripProps(ctx, module)
574
575 productVariableProps := android.ProductVariableProperties(ctx)
576
577 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
578 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
579
580 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500581 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400582
Liz Kammer12615db2021-09-28 09:19:17 -0400583 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
584
585 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
586 // which. This will add the newly generated proto library to the appropriate attribute and nothing
587 // to the other
588 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
589 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
590
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000591 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
592 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
593 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
594
Liz Kammere6583482021-10-19 13:56:10 -0400595 return baseAttributes{
596 compilerAttrs,
597 linkerAttrs,
Liz Kammer12615db2021-09-28 09:19:17 -0400598 protoDep.protoDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000599 }
600}
601
Yu Liufc603162022-03-01 15:44:08 -0800602func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000603 return sdkAttributes{
604 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800605 Min_sdk_version: module.Properties.Min_sdk_version,
606 }
607}
608
609type sdkAttributes struct {
610 Sdk_version *string
611 Min_sdk_version *string
612}
613
Jingwen Chen107c0de2021-04-09 10:43:12 +0000614// Convenience struct to hold all attributes parsed from linker properties.
615type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500616 deps bazel.LabelListAttribute
617 implementationDeps bazel.LabelListAttribute
618 dynamicDeps bazel.LabelListAttribute
619 implementationDynamicDeps bazel.LabelListAttribute
620 wholeArchiveDeps bazel.LabelListAttribute
621 implementationWholeArchiveDeps bazel.LabelListAttribute
622 systemDynamicDeps bazel.LabelListAttribute
623 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400624
Jingwen Chen6ada5892021-09-17 11:38:09 +0000625 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000626 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500627 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000628 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400629 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000630 stripKeepSymbols bazel.BoolAttribute
631 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
632 stripKeepSymbolsList bazel.StringListAttribute
633 stripAll bazel.BoolAttribute
634 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400635 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400636}
637
Liz Kammer54309532021-12-14 12:21:22 -0500638var (
639 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
640)
641
Jingwen Chen55bc8202021-11-02 06:40:51 +0000642func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400643 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
644 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400645
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400646 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
647 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammere6583482021-10-19 13:56:10 -0400648 // Excludes to parallel Soong:
649 // 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 -0400650 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
651
Liz Kammere6583482021-10-19 13:56:10 -0400652 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, staticLibs, props.Exclude_static_libs, props.Export_static_lib_headers, bazelLabelForStaticDepsExcludes)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400653
Liz Kammere6583482021-10-19 13:56:10 -0400654 headerLibs := android.FirstUniqueStrings(props.Header_libs)
655 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400656
Liz Kammere6583482021-10-19 13:56:10 -0400657 (&hDeps.export).Append(staticDeps.export)
658 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000659
Liz Kammere6583482021-10-19 13:56:10 -0400660 (&hDeps.implementation).Append(staticDeps.implementation)
661 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400662
Liz Kammere6583482021-10-19 13:56:10 -0400663 systemSharedLibs := props.System_shared_libs
664 // systemSharedLibs distinguishes between nil/empty list behavior:
665 // nil -> use default values
666 // empty list -> no values specified
667 if len(systemSharedLibs) > 0 {
668 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
669 }
670 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
671
672 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500673 excludeSharedLibs := props.Exclude_shared_libs
674 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
675 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
676 })
677 for _, el := range usedSystem {
678 if la.usedSystemDynamicDepAsDynamicDep == nil {
679 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
680 }
681 la.usedSystemDynamicDepAsDynamicDep[el] = true
682 }
683
Liz Kammere6583482021-10-19 13:56:10 -0400684 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, sharedLibs, props.Exclude_shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDepsExcludes)
685 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
686 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
687
688 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
689 axisFeatures = append(axisFeatures, "disable_pack_relocations")
690 }
691
692 if Bool(props.Allow_undefined_symbols) {
693 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
694 }
695
696 var linkerFlags []string
697 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -0500698 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -0400699 // binaries remove static flag if -shared is in the linker flags
700 if isBinary && android.InList("-shared", linkerFlags) {
701 axisFeatures = append(axisFeatures, "-static_flag")
702 }
703 }
704 if props.Version_script != nil {
705 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
706 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
707 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
708 }
Alix773adaa2022-04-27 17:49:34 +0000709
710 if props.Dynamic_list != nil {
711 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
712 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
713 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
714 }
715
Liz Kammere6583482021-10-19 13:56:10 -0400716 la.linkopts.SetSelectValue(axis, config, linkerFlags)
717 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
718
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500719 if axis == bazel.NoConfigAxis {
720 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
721 }
722
Liz Kammere6583482021-10-19 13:56:10 -0400723 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
724 if props.crt() != nil {
725 if axis == bazel.NoConfigAxis {
726 la.linkCrt.SetSelectValue(axis, config, props.crt())
727 } else if axis == bazel.ArchConfigurationAxis {
728 ctx.ModuleErrorf("nocrt is not supported for arch variants")
729 }
730 }
731
732 if axisFeatures != nil {
733 la.features.SetSelectValue(axis, config, axisFeatures)
734 }
735}
736
Jingwen Chen55bc8202021-11-02 06:40:51 +0000737func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000738 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
739 if stripProperties, ok := props.(*StripProperties); ok {
740 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
741 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
742 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
743 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
744 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000745 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000746 })
Liz Kammere6583482021-10-19 13:56:10 -0400747}
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000748
Jingwen Chen55bc8202021-11-02 06:40:51 +0000749func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +0000750
Liz Kammer47535c52021-06-02 16:02:22 -0400751 type productVarDep struct {
752 // the name of the corresponding excludes field, if one exists
753 excludesField string
754 // reference to the bazel attribute that should be set for the given product variable config
755 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400756
Jingwen Chen55bc8202021-11-02 06:40:51 +0000757 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -0400758 }
759
760 productVarToDepFields := map[string]productVarDep{
761 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +0000762 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
763 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
764 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -0400765 }
766
Liz Kammer47535c52021-06-02 16:02:22 -0400767 for name, dep := range productVarToDepFields {
768 props, exists := productVariableProps[name]
769 excludeProps, excludesExists := productVariableProps[dep.excludesField]
770 // if neither an include or excludes property exists, then skip it
771 if !exists && !excludesExists {
772 continue
773 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000774 // Collect all the configurations that an include or exclude property exists for.
775 // We want to iterate all configurations rather than either the include or exclude because, for a
776 // particular configuration, we may have either only an include or an exclude to handle.
777 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
778 for p := range props {
779 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400780 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000781 for p := range excludeProps {
782 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400783 }
784
Jingwen Chen25825ca2021-11-15 12:28:43 +0000785 for productConfigProp := range productConfigProps {
786 prop, includesExists := props[productConfigProp]
787 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -0400788 var includes, excludes []string
789 var ok bool
790 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +0000791 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400792 ctx.ModuleErrorf("Could not convert product variable %s property", name)
793 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000794 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400795 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
796 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400797
Jingwen Chen58ff6802021-11-17 12:14:41 +0000798 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +0000799 dep.attribute.SetSelectValue(
800 productConfigProp.ConfigurationAxis(),
801 productConfigProp.SelectKey(),
802 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
803 )
Liz Kammer47535c52021-06-02 16:02:22 -0400804 }
805 }
Liz Kammere6583482021-10-19 13:56:10 -0400806}
Liz Kammer47535c52021-06-02 16:02:22 -0400807
Liz Kammer54309532021-12-14 12:21:22 -0500808func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
809 // if system dynamic deps have the default value, any use of a system dynamic library used will
810 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
811 // from bionic OSes.
812 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
813 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
814 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
815 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
816 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
817 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
818 }
819
Liz Kammere6583482021-10-19 13:56:10 -0400820 la.deps.ResolveExcludes()
821 la.implementationDeps.ResolveExcludes()
822 la.dynamicDeps.ResolveExcludes()
823 la.implementationDynamicDeps.ResolveExcludes()
824 la.wholeArchiveDeps.ResolveExcludes()
825 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -0500826
Jingwen Chen91220d72021-03-24 02:18:33 -0400827}
828
Jingwen Chened9c17d2021-04-13 07:14:55 +0000829// Relativize a list of root-relative paths with respect to the module's
830// directory.
831//
832// include_dirs Soong prop are root-relative (b/183742505), but
833// local_include_dirs, export_include_dirs and export_system_include_dirs are
834// module dir relative. This function makes a list of paths entirely module dir
835// relative.
836//
837// For the `include` attribute, Bazel wants the paths to be relative to the
838// module.
839func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000840 var relativePaths []string
841 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +0000842 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
843 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
844 if err != nil {
845 panic(err)
846 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000847 relativePaths = append(relativePaths, relativePath)
848 }
849 return relativePaths
850}
851
Liz Kammer5fad5012021-09-09 14:08:21 -0400852// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
853// attributes.
854type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500855 AbsoluteIncludes bazel.StringListAttribute
856 Includes bazel.StringListAttribute
857 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -0400858}
859
Liz Kammer54549442022-05-11 13:55:06 -0400860func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500861 var exported BazelIncludes
862 if includes != nil {
863 exported = *includes
864 } else {
865 exported = BazelIncludes{}
866 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000867 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
868 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
869 if len(flagExporterProperties.Export_include_dirs) > 0 {
870 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
871 }
872 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
873 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 -0400874 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400875 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000876 })
Liz Kammer1263d9b2021-12-10 14:28:20 -0500877 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -0400878 exported.Includes.DeduplicateAxesFromBase()
879 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400880
Liz Kammer5fad5012021-09-09 14:08:21 -0400881 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -0400882}
Chris Parsons953b3562021-09-20 15:14:39 -0400883
Jingwen Chen55bc8202021-11-02 06:40:51 +0000884func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400885 label := android.BazelModuleLabel(ctx, m)
Liz Kammer35ca77e2021-12-22 15:31:40 -0500886 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GenerateCcLibraryStaticOnly(m.Name()) {
887 label += "_bp2build_cc_library_static"
Chris Parsons953b3562021-09-20 15:14:39 -0400888 }
889 return label
890}
891
Jingwen Chen55bc8202021-11-02 06:40:51 +0000892func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400893 // cc_library, at it's root name, propagates the shared library, which depends on the static
894 // library.
895 return android.BazelModuleLabel(ctx, m)
896}
897
Jingwen Chen55bc8202021-11-02 06:40:51 +0000898func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400899 label := bazelLabelForStaticModule(ctx, m)
900 if aModule, ok := m.(android.Module); ok {
901 if android.IsModulePrebuilt(aModule) {
902 label += "_alwayslink"
903 }
904 }
905 return label
906}
907
Jingwen Chen55bc8202021-11-02 06:40:51 +0000908func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400909 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
910}
911
Jingwen Chen55bc8202021-11-02 06:40:51 +0000912func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400913 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
914}
915
Jingwen Chen55bc8202021-11-02 06:40:51 +0000916func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400917 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
918}
919
Jingwen Chen55bc8202021-11-02 06:40:51 +0000920func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400921 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
922}
923
Jingwen Chen55bc8202021-11-02 06:40:51 +0000924func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400925 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
926}
927
Jingwen Chen55bc8202021-11-02 06:40:51 +0000928func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400929 // This is not elegant, but bp2build's shared library targets only propagate
930 // their header information as part of the normal C++ provider.
931 return bazelLabelForSharedDeps(ctx, modules)
932}
933
Jingwen Chen55bc8202021-11-02 06:40:51 +0000934func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400935 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
936}
Liz Kammer2b8004b2021-10-04 13:55:44 -0400937
938type binaryLinkerAttrs struct {
939 Linkshared *bool
940}
941
Jingwen Chen55bc8202021-11-02 06:40:51 +0000942func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400943 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000944 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
945 linkerProps := props.(*BinaryLinkerProperties)
946 staticExecutable := linkerProps.Static_executable
947 if axis == bazel.NoConfigAxis {
948 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
949 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -0400950 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000951 } else if staticExecutable != nil {
952 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
953 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
954 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -0400955 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000956 })
Liz Kammer2b8004b2021-10-04 13:55:44 -0400957
958 return attrs
959}