blob: ae77336b724eba4870c133065a7aee7d32f7b300 [file] [log] [blame]
Jingwen Chen91220d72021-03-24 02:18:33 -04001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14package cc
15
16import (
Liz Kammerd2871182021-10-04 13:54:37 -040017 "fmt"
Jingwen Chened9c17d2021-04-13 07:14:55 +000018 "path/filepath"
Jingwen Chen3950cd62021-05-12 04:33:00 +000019 "strings"
Chris Parsons484e50a2021-05-13 15:13:04 -040020
21 "android/soong/android"
22 "android/soong/bazel"
Liz Kammer7a210ac2021-09-22 15:52:58 -040023
Chris Parsons953b3562021-09-20 15:14:39 -040024 "github.com/google/blueprint"
Liz Kammerba7a9c52021-05-26 08:45:30 -040025
26 "github.com/google/blueprint/proptools"
Jingwen Chen91220d72021-03-24 02:18:33 -040027)
28
Liz Kammerae3994e2021-10-19 09:45:48 -040029const (
Liz Kammer12615db2021-09-28 09:19:17 -040030 cSrcPartition = "c"
31 asSrcPartition = "as"
32 cppSrcPartition = "cpp"
33 protoSrcPartition = "proto"
Liz Kammerae3994e2021-10-19 09:45:48 -040034)
35
Liz Kammer2222c6b2021-05-24 15:41:47 -040036// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000037// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040038type staticOrSharedAttributes struct {
Jingwen Chenc4dc9b42021-06-11 12:51:48 +000039 Srcs bazel.LabelListAttribute
40 Srcs_c bazel.LabelListAttribute
41 Srcs_as bazel.LabelListAttribute
Liz Kammere6583482021-10-19 13:56:10 -040042 Hdrs bazel.LabelListAttribute
Jingwen Chenc4dc9b42021-06-11 12:51:48 +000043 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000044
Liz Kammer12615db2021-09-28 09:19:17 -040045 Deps bazel.LabelListAttribute
46 Implementation_deps bazel.LabelListAttribute
47 Dynamic_deps bazel.LabelListAttribute
48 Implementation_dynamic_deps bazel.LabelListAttribute
49 Whole_archive_deps bazel.LabelListAttribute
50 Implementation_whole_archive_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040051
52 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050053
54 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080055
56 sdkAttributes
Jingwen Chen53681ef2021-04-29 08:15:13 +000057}
58
Sam Delmericoc7681022022-02-04 21:01:20 +000059// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +000060func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -040061 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
62 // macro.
63 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Liz Kammer12615db2021-09-28 09:19:17 -040064 return func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
65 m, exists := ctx.ModuleFromName(label.OriginalModuleName)
66 labelStr := label.Label
Sam Delmericoc7681022022-02-04 21:01:20 +000067 if !exists || !android.IsFilegroup(ctx, m) {
Liz Kammer12615db2021-09-28 09:19:17 -040068 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +000069 }
Liz Kammer12615db2021-09-28 09:19:17 -040070 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -040071 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000072 }
73
Liz Kammer57e2e7a2021-09-20 12:55:02 -040074 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +000075 labels := bazel.LabelPartitions{
76 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -050077 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
78 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Liz Kammer57e2e7a2021-09-20 12:55:02 -040079 // C++ is the "catch-all" group, and comprises generated sources because we don't
80 // know the language of these sources until the genrule is executed.
Liz Kammeraabfb5d2021-12-08 15:25:06 -050081 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
Sam Delmericoc7681022022-02-04 21:01:20 +000082 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000083
Sam Delmericoc7681022022-02-04 21:01:20 +000084 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +000085}
86
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +000087// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +000088func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +000089 lib, ok := module.compiler.(*libraryDecorator)
90 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -040091 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +000092 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +000093 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
94}
Jingwen Chen53681ef2021-04-29 08:15:13 +000095
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +000096// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +000097func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +000098 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +000099}
100
101// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000102func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000103 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400104}
105
Liz Kammer7a210ac2021-09-22 15:52:58 -0400106type depsPartition struct {
107 export bazel.LabelList
108 implementation bazel.LabelList
109}
110
Jingwen Chen55bc8202021-11-02 06:40:51 +0000111type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400112
Jingwen Chen55bc8202021-11-02 06:40:51 +0000113func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400114 if !exportsDeps {
115 return depsPartition{
116 implementation: fn(ctx, allDeps),
117 }
118 }
119
Liz Kammer7a210ac2021-09-22 15:52:58 -0400120 implementation, export := android.FilterList(allDeps, exportedDeps)
121
122 return depsPartition{
123 export: fn(ctx, export),
124 implementation: fn(ctx, implementation),
125 }
126}
127
Jingwen Chen55bc8202021-11-02 06:40:51 +0000128type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400129
Jingwen Chen55bc8202021-11-02 06:40:51 +0000130func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400131 if !exportsDeps {
132 return depsPartition{
133 implementation: fn(ctx, allDeps, excludes),
134 }
135 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400136 implementation, export := android.FilterList(allDeps, exportedDeps)
137
138 return depsPartition{
139 export: fn(ctx, export, excludes),
140 implementation: fn(ctx, implementation, excludes),
141 }
142}
143
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000144// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000145func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400146 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000147
Liz Kammer9abd62d2021-05-21 08:37:59 -0400148 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Liz Kammercac7f692021-12-16 14:19:32 -0500149 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000150 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400151 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400152
Liz Kammer2b8004b2021-10-04 13:55:44 -0400153 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400154 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
155 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
156
Liz Kammer2b8004b2021-10-04 13:55:44 -0400157 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400158 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
159 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
160
161 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500162 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000163 }
Liz Kammer135bf552021-08-11 10:46:06 -0400164 // system_dynamic_deps distinguishes between nil/empty list behavior:
165 // nil -> use default values
166 // empty list -> no values specified
167 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000168
169 if isStatic {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000170 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
171 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
172 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000173 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000174 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000175 } else {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000176 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
177 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
178 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000179 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000180 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000181 }
182
Liz Kammerae3994e2021-10-19 09:45:48 -0400183 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
184 attrs.Srcs = partitionedSrcs[cppSrcPartition]
185 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
186 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000187
Liz Kammer12615db2021-09-28 09:19:17 -0400188 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
189 // TODO(b/208815215): determine whether this is used and add support if necessary
190 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
191 }
192
Jingwen Chenbcf53042021-05-26 04:42:42 +0000193 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000194}
195
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400196// Convenience struct to hold all attributes parsed from prebuilt properties.
197type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000198 Src bazel.LabelAttribute
199 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400200}
201
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000202// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000203func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) prebuiltAttributes {
204 manySourceFileError := func(axis bazel.ConfigurationAxis, config string) {
205 ctx.ModuleErrorf("Bp2BuildParsePrebuiltLibraryProps: Expected at most one source file for %s %s\n", axis, config)
206 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400207 var srcLabelAttribute bazel.LabelAttribute
208
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000209 parseSrcs := func(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, srcs []string) {
210 if len(srcs) > 1 {
211 manySourceFileError(axis, config)
212 return
213 } else if len(srcs) == 0 {
214 return
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400215 }
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000216 if srcLabelAttribute.SelectValue(axis, config) != nil {
217 manySourceFileError(axis, config)
218 return
219 }
220
221 src := android.BazelLabelForModuleSrcSingle(ctx, srcs[0])
222 srcLabelAttribute.SetSelectValue(axis, config, src)
223 }
224
225 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
226 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
227 parseSrcs(ctx, axis, config, prebuiltLinkerProperties.Srcs)
228 }
229 })
230
231 var enabledLabelAttribute bazel.BoolAttribute
232 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
233 if props.Enabled != nil {
234 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
235 }
236 parseSrcs(ctx, axis, config, props.Srcs)
237 }
238
239 if isStatic {
240 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
241 if staticProperties, ok := props.(*StaticProperties); ok {
242 parseAttrs(axis, config, staticProperties.Static)
243 }
244 })
245 } else {
246 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
247 if sharedProperties, ok := props.(*SharedProperties); ok {
248 parseAttrs(axis, config, sharedProperties.Shared)
249 }
250 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400251 }
252
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400253 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000254 Src: srcLabelAttribute,
255 Enabled: enabledLabelAttribute,
256 }
257}
258
259func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
260 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
261 for config, props := range configToProps {
262 parseFunc(axis, config, props)
263 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400264 }
265}
266
Liz Kammere6583482021-10-19 13:56:10 -0400267type baseAttributes struct {
268 compilerAttributes
269 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400270
271 protoDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400272}
273
Jingwen Chen107c0de2021-04-09 10:43:12 +0000274// Convenience struct to hold all attributes parsed from compiler properties.
275type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400276 // Options for all languages
277 copts bazel.StringListAttribute
278 // Assembly options and sources
279 asFlags bazel.StringListAttribute
280 asSrcs bazel.LabelListAttribute
281 // C options and sources
282 conlyFlags bazel.StringListAttribute
283 cSrcs bazel.LabelListAttribute
284 // C++ options and sources
285 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000286 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400287
Liz Kammere6583482021-10-19 13:56:10 -0400288 hdrs bazel.LabelListAttribute
289
Chris Parsons2c788392021-08-10 11:58:07 -0400290 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000291
292 // Not affected by arch variants
293 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500294 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000295 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400296
297 localIncludes bazel.StringListAttribute
298 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400299
Liz Kammer1263d9b2021-12-10 14:28:20 -0500300 includes BazelIncludes
301
Liz Kammer12615db2021-09-28 09:19:17 -0400302 protoSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000303
304 stubsSymbolFile *string
305 stubsVersions bazel.StringListAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000306}
307
Liz Kammercac7f692021-12-16 14:19:32 -0500308type filterOutFn func(string) bool
309
310func filterOutStdFlag(flag string) bool {
311 return strings.HasPrefix(flag, "-std=")
312}
313
314func parseCommandLineFlags(soongFlags []string, filterOut filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400315 var result []string
316 for _, flag := range soongFlags {
Liz Kammercac7f692021-12-16 14:19:32 -0500317 if filterOut != nil && filterOut(flag) {
318 continue
319 }
Liz Kammere6583482021-10-19 13:56:10 -0400320 // Soong's cflags can contain spaces, like `-include header.h`. For
321 // Bazel's copts, split them up to be compatible with the
322 // no_copts_tokenization feature.
323 result = append(result, strings.Split(flag, " ")...)
324 }
325 return result
326}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000327
Jingwen Chen55bc8202021-11-02 06:40:51 +0000328func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400329 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
330 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
331 if srcsList, ok := parseSrcs(ctx, props); ok {
332 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400333 }
334
Liz Kammere6583482021-10-19 13:56:10 -0400335 localIncludeDirs := props.Local_include_dirs
336 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500337 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400338 if includeBuildDirectory(props.Include_build_directory) {
339 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400340 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000341 }
342
Liz Kammere6583482021-10-19 13:56:10 -0400343 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
344 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
345
Liz Kammercac7f692021-12-16 14:19:32 -0500346 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
347 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
348 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
349 // cases.
350 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
351 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
352 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, nil))
353 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, nil))
Liz Kammere6583482021-10-19 13:56:10 -0400354 ca.rtti.SetSelectValue(axis, config, props.Rtti)
355}
356
Jingwen Chen55bc8202021-11-02 06:40:51 +0000357func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000358 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
359 if stlProps, ok := props.(*StlProperties); ok {
360 if stlProps.Stl == nil {
361 return
362 }
363 if ca.stl == nil {
364 ca.stl = stlProps.Stl
365 } else if ca.stl != stlProps.Stl {
366 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 -0400367 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000368 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000369 })
Liz Kammere6583482021-10-19 13:56:10 -0400370}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000371
Jingwen Chen55bc8202021-11-02 06:40:51 +0000372func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400373 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400374 "Cflags": &ca.copts,
375 "Asflags": &ca.asFlags,
376 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400377 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400378 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000379 if productConfigProps, exists := productVariableProps[propName]; exists {
380 for productConfigProp, prop := range productConfigProps {
381 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400382 if !ok {
383 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
384 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000385 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
386 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400387 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400388 }
389 }
Liz Kammere6583482021-10-19 13:56:10 -0400390}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400391
Jingwen Chen55bc8202021-11-02 06:40:51 +0000392func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400393 ca.srcs.ResolveExcludes()
394 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
395
Liz Kammer12615db2021-09-28 09:19:17 -0400396 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
397
Liz Kammere6583482021-10-19 13:56:10 -0400398 for p, lla := range partitionedSrcs {
399 // if there are no sources, there is no need for headers
400 if lla.IsEmpty() {
401 continue
402 }
403 lla.Append(implementationHdrs)
404 partitionedSrcs[p] = lla
405 }
406
407 ca.srcs = partitionedSrcs[cppSrcPartition]
408 ca.cSrcs = partitionedSrcs[cSrcPartition]
409 ca.asSrcs = partitionedSrcs[asSrcPartition]
410
411 ca.absoluteIncludes.DeduplicateAxesFromBase()
412 ca.localIncludes.DeduplicateAxesFromBase()
413}
414
415// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000416func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400417 anySrcs := false
418 // Add srcs-like dependencies such as generated files.
419 // First create a LabelList containing these dependencies, then merge the values with srcs.
420 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
421 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
422 anySrcs = true
423 }
424
425 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
426 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
427 anySrcs = true
428 }
429 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
430}
431
Liz Kammera5a29de2022-05-25 23:19:37 -0400432func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
433 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500434 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
435 // Defaults are handled by the toolchain definition.
436 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400437 stdVal := proptools.StringDefault(std, defaultVal)
438 if stdVal == "experimental" || stdVal == defaultVal {
439 if stdVal == "experimental" {
440 stdVal = prefix + "_std_experimental"
441 }
442 if !useGnu {
443 stdVal += "_no_gnu"
444 }
445 } else if !useGnu {
446 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500447 }
448
Liz Kammera5a29de2022-05-25 23:19:37 -0400449 if stdVal == defaultVal {
450 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500451 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400452 return &stdVal
453}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500454
Liz Kammera5a29de2022-05-25 23:19:37 -0400455func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
456 useGnu := useGnuExtensions(gnu_extensions)
457
458 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400459}
460
Liz Kammer1263d9b2021-12-10 14:28:20 -0500461// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
462// is fully-qualified.
463// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
464func packageFromLabel(label string) (string, bool) {
465 split := strings.Split(label, ":")
466 if len(split) != 2 {
467 return "", false
468 }
469 if split[0] == "" {
470 return ".", false
471 }
472 // remove leading "//"
473 return split[0][2:], true
474}
475
476// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
477func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
478 for _, hdr := range labelList.Includes {
479 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
480 absolute = append(absolute, pkg)
481 } else if pkg != "" {
482 relative = append(relative, pkg)
483 }
484 }
485 return relative, absolute
486}
487
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000488// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400489func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400490 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
491 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000492 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400493
494 var implementationHdrs bazel.LabelListAttribute
495
496 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
497 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
498 for axis, configMap := range cp {
499 if _, ok := axisToConfigs[axis]; !ok {
500 axisToConfigs[axis] = map[string]bool{}
501 }
502 for config, _ := range configMap {
503 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400504 }
505 }
506 }
Liz Kammere6583482021-10-19 13:56:10 -0400507 allAxesAndConfigs(archVariantCompilerProps)
508 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000509 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400510
Liz Kammere6583482021-10-19 13:56:10 -0400511 compilerAttrs := compilerAttributes{}
512 linkerAttrs := linkerAttributes{}
513
514 for axis, configs := range axisToConfigs {
515 for config, _ := range configs {
516 var allHdrs []string
517 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
518 allHdrs = baseCompilerProps.Generated_headers
519
520 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
521 }
522
523 var exportHdrs []string
524
525 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
526 exportHdrs = baseLinkerProps.Export_generated_headers
527
528 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
529 }
530 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
531 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
532 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500533
534 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
535 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
536 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
537
538 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
539 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
540 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
541 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
542 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
543 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
544 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000545
546 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
547 if axis == bazel.NoConfigAxis {
548 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
549 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
550 }
551 }
Liz Kammere6583482021-10-19 13:56:10 -0400552 }
553 }
554
555 compilerAttrs.convertStlProps(ctx, module)
556 (&linkerAttrs).convertStripProps(ctx, module)
557
558 productVariableProps := android.ProductVariableProperties(ctx)
559
560 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
561 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
562
563 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500564 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400565
Liz Kammer12615db2021-09-28 09:19:17 -0400566 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
567
568 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
569 // which. This will add the newly generated proto library to the appropriate attribute and nothing
570 // to the other
571 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
572 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
573
Liz Kammere6583482021-10-19 13:56:10 -0400574 return baseAttributes{
575 compilerAttrs,
576 linkerAttrs,
Liz Kammer12615db2021-09-28 09:19:17 -0400577 protoDep.protoDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000578 }
579}
580
Yu Liufc603162022-03-01 15:44:08 -0800581func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000582 return sdkAttributes{
583 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800584 Min_sdk_version: module.Properties.Min_sdk_version,
585 }
586}
587
588type sdkAttributes struct {
589 Sdk_version *string
590 Min_sdk_version *string
591}
592
Jingwen Chen107c0de2021-04-09 10:43:12 +0000593// Convenience struct to hold all attributes parsed from linker properties.
594type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500595 deps bazel.LabelListAttribute
596 implementationDeps bazel.LabelListAttribute
597 dynamicDeps bazel.LabelListAttribute
598 implementationDynamicDeps bazel.LabelListAttribute
599 wholeArchiveDeps bazel.LabelListAttribute
600 implementationWholeArchiveDeps bazel.LabelListAttribute
601 systemDynamicDeps bazel.LabelListAttribute
602 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400603
Jingwen Chen6ada5892021-09-17 11:38:09 +0000604 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000605 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500606 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000607 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400608 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000609 stripKeepSymbols bazel.BoolAttribute
610 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
611 stripKeepSymbolsList bazel.StringListAttribute
612 stripAll bazel.BoolAttribute
613 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400614 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400615}
616
Liz Kammer54309532021-12-14 12:21:22 -0500617var (
618 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
619)
620
Jingwen Chen55bc8202021-11-02 06:40:51 +0000621func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400622 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
623 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400624
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400625 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
626 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammere6583482021-10-19 13:56:10 -0400627 // Excludes to parallel Soong:
628 // 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 -0400629 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
630
Liz Kammere6583482021-10-19 13:56:10 -0400631 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, staticLibs, props.Exclude_static_libs, props.Export_static_lib_headers, bazelLabelForStaticDepsExcludes)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400632
Liz Kammere6583482021-10-19 13:56:10 -0400633 headerLibs := android.FirstUniqueStrings(props.Header_libs)
634 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400635
Liz Kammere6583482021-10-19 13:56:10 -0400636 (&hDeps.export).Append(staticDeps.export)
637 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000638
Liz Kammere6583482021-10-19 13:56:10 -0400639 (&hDeps.implementation).Append(staticDeps.implementation)
640 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400641
Liz Kammere6583482021-10-19 13:56:10 -0400642 systemSharedLibs := props.System_shared_libs
643 // systemSharedLibs distinguishes between nil/empty list behavior:
644 // nil -> use default values
645 // empty list -> no values specified
646 if len(systemSharedLibs) > 0 {
647 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
648 }
649 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
650
651 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500652 excludeSharedLibs := props.Exclude_shared_libs
653 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
654 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
655 })
656 for _, el := range usedSystem {
657 if la.usedSystemDynamicDepAsDynamicDep == nil {
658 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
659 }
660 la.usedSystemDynamicDepAsDynamicDep[el] = true
661 }
662
Liz Kammere6583482021-10-19 13:56:10 -0400663 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, sharedLibs, props.Exclude_shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDepsExcludes)
664 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
665 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
666
667 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
668 axisFeatures = append(axisFeatures, "disable_pack_relocations")
669 }
670
671 if Bool(props.Allow_undefined_symbols) {
672 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
673 }
674
675 var linkerFlags []string
676 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -0500677 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -0400678 // binaries remove static flag if -shared is in the linker flags
679 if isBinary && android.InList("-shared", linkerFlags) {
680 axisFeatures = append(axisFeatures, "-static_flag")
681 }
682 }
683 if props.Version_script != nil {
684 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
685 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
686 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
687 }
Alix773adaa2022-04-27 17:49:34 +0000688
689 if props.Dynamic_list != nil {
690 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
691 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
692 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
693 }
694
Liz Kammere6583482021-10-19 13:56:10 -0400695 la.linkopts.SetSelectValue(axis, config, linkerFlags)
696 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
697
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500698 if axis == bazel.NoConfigAxis {
699 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
700 }
701
Liz Kammere6583482021-10-19 13:56:10 -0400702 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
703 if props.crt() != nil {
704 if axis == bazel.NoConfigAxis {
705 la.linkCrt.SetSelectValue(axis, config, props.crt())
706 } else if axis == bazel.ArchConfigurationAxis {
707 ctx.ModuleErrorf("nocrt is not supported for arch variants")
708 }
709 }
710
711 if axisFeatures != nil {
712 la.features.SetSelectValue(axis, config, axisFeatures)
713 }
714}
715
Jingwen Chen55bc8202021-11-02 06:40:51 +0000716func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000717 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
718 if stripProperties, ok := props.(*StripProperties); ok {
719 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
720 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
721 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
722 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
723 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000724 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000725 })
Liz Kammere6583482021-10-19 13:56:10 -0400726}
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000727
Jingwen Chen55bc8202021-11-02 06:40:51 +0000728func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +0000729
Liz Kammer47535c52021-06-02 16:02:22 -0400730 type productVarDep struct {
731 // the name of the corresponding excludes field, if one exists
732 excludesField string
733 // reference to the bazel attribute that should be set for the given product variable config
734 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400735
Jingwen Chen55bc8202021-11-02 06:40:51 +0000736 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -0400737 }
738
739 productVarToDepFields := map[string]productVarDep{
740 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +0000741 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
742 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
743 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -0400744 }
745
Liz Kammer47535c52021-06-02 16:02:22 -0400746 for name, dep := range productVarToDepFields {
747 props, exists := productVariableProps[name]
748 excludeProps, excludesExists := productVariableProps[dep.excludesField]
749 // if neither an include or excludes property exists, then skip it
750 if !exists && !excludesExists {
751 continue
752 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000753 // Collect all the configurations that an include or exclude property exists for.
754 // We want to iterate all configurations rather than either the include or exclude because, for a
755 // particular configuration, we may have either only an include or an exclude to handle.
756 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
757 for p := range props {
758 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400759 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000760 for p := range excludeProps {
761 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400762 }
763
Jingwen Chen25825ca2021-11-15 12:28:43 +0000764 for productConfigProp := range productConfigProps {
765 prop, includesExists := props[productConfigProp]
766 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -0400767 var includes, excludes []string
768 var ok bool
769 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +0000770 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400771 ctx.ModuleErrorf("Could not convert product variable %s property", name)
772 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000773 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400774 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
775 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400776
Jingwen Chen58ff6802021-11-17 12:14:41 +0000777 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +0000778 dep.attribute.SetSelectValue(
779 productConfigProp.ConfigurationAxis(),
780 productConfigProp.SelectKey(),
781 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
782 )
Liz Kammer47535c52021-06-02 16:02:22 -0400783 }
784 }
Liz Kammere6583482021-10-19 13:56:10 -0400785}
Liz Kammer47535c52021-06-02 16:02:22 -0400786
Liz Kammer54309532021-12-14 12:21:22 -0500787func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
788 // if system dynamic deps have the default value, any use of a system dynamic library used will
789 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
790 // from bionic OSes.
791 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
792 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
793 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
794 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
795 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
796 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
797 }
798
Liz Kammere6583482021-10-19 13:56:10 -0400799 la.deps.ResolveExcludes()
800 la.implementationDeps.ResolveExcludes()
801 la.dynamicDeps.ResolveExcludes()
802 la.implementationDynamicDeps.ResolveExcludes()
803 la.wholeArchiveDeps.ResolveExcludes()
804 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -0500805
Jingwen Chen91220d72021-03-24 02:18:33 -0400806}
807
Jingwen Chened9c17d2021-04-13 07:14:55 +0000808// Relativize a list of root-relative paths with respect to the module's
809// directory.
810//
811// include_dirs Soong prop are root-relative (b/183742505), but
812// local_include_dirs, export_include_dirs and export_system_include_dirs are
813// module dir relative. This function makes a list of paths entirely module dir
814// relative.
815//
816// For the `include` attribute, Bazel wants the paths to be relative to the
817// module.
818func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000819 var relativePaths []string
820 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +0000821 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
822 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
823 if err != nil {
824 panic(err)
825 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000826 relativePaths = append(relativePaths, relativePath)
827 }
828 return relativePaths
829}
830
Liz Kammer5fad5012021-09-09 14:08:21 -0400831// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
832// attributes.
833type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500834 AbsoluteIncludes bazel.StringListAttribute
835 Includes bazel.StringListAttribute
836 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -0400837}
838
Liz Kammer54549442022-05-11 13:55:06 -0400839func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500840 var exported BazelIncludes
841 if includes != nil {
842 exported = *includes
843 } else {
844 exported = BazelIncludes{}
845 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000846 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
847 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
848 if len(flagExporterProperties.Export_include_dirs) > 0 {
849 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
850 }
851 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
852 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 -0400853 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400854 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000855 })
Liz Kammer1263d9b2021-12-10 14:28:20 -0500856 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -0400857 exported.Includes.DeduplicateAxesFromBase()
858 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400859
Liz Kammer5fad5012021-09-09 14:08:21 -0400860 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -0400861}
Chris Parsons953b3562021-09-20 15:14:39 -0400862
Jingwen Chen55bc8202021-11-02 06:40:51 +0000863func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400864 label := android.BazelModuleLabel(ctx, m)
Liz Kammer35ca77e2021-12-22 15:31:40 -0500865 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GenerateCcLibraryStaticOnly(m.Name()) {
866 label += "_bp2build_cc_library_static"
Chris Parsons953b3562021-09-20 15:14:39 -0400867 }
868 return label
869}
870
Jingwen Chen55bc8202021-11-02 06:40:51 +0000871func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400872 // cc_library, at it's root name, propagates the shared library, which depends on the static
873 // library.
874 return android.BazelModuleLabel(ctx, m)
875}
876
Jingwen Chen55bc8202021-11-02 06:40:51 +0000877func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400878 label := bazelLabelForStaticModule(ctx, m)
879 if aModule, ok := m.(android.Module); ok {
880 if android.IsModulePrebuilt(aModule) {
881 label += "_alwayslink"
882 }
883 }
884 return label
885}
886
Jingwen Chen55bc8202021-11-02 06:40:51 +0000887func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400888 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
889}
890
Jingwen Chen55bc8202021-11-02 06:40:51 +0000891func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400892 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
893}
894
Jingwen Chen55bc8202021-11-02 06:40:51 +0000895func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400896 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
897}
898
Jingwen Chen55bc8202021-11-02 06:40:51 +0000899func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400900 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
901}
902
Jingwen Chen55bc8202021-11-02 06:40:51 +0000903func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400904 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
905}
906
Jingwen Chen55bc8202021-11-02 06:40:51 +0000907func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400908 // This is not elegant, but bp2build's shared library targets only propagate
909 // their header information as part of the normal C++ provider.
910 return bazelLabelForSharedDeps(ctx, modules)
911}
912
Jingwen Chen55bc8202021-11-02 06:40:51 +0000913func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400914 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
915}
Liz Kammer2b8004b2021-10-04 13:55:44 -0400916
917type binaryLinkerAttrs struct {
918 Linkshared *bool
919}
920
Jingwen Chen55bc8202021-11-02 06:40:51 +0000921func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400922 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000923 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
924 linkerProps := props.(*BinaryLinkerProperties)
925 staticExecutable := linkerProps.Static_executable
926 if axis == bazel.NoConfigAxis {
927 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
928 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -0400929 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000930 } else if staticExecutable != nil {
931 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
932 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
933 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -0400934 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000935 })
Liz Kammer2b8004b2021-10-04 13:55:44 -0400936
937 return attrs
938}