blob: 811e22886d432fcaca679820fd25acb050bfcd33 [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
Jingwen Chen55bc8202021-11-02 06:40:51 +0000144func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400145 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000146
Liz Kammer9abd62d2021-05-21 08:37:59 -0400147 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Liz Kammercac7f692021-12-16 14:19:32 -0500148 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000149 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400150 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400151
Liz Kammer2b8004b2021-10-04 13:55:44 -0400152 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400153 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
154 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
155
Liz Kammer2b8004b2021-10-04 13:55:44 -0400156 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400157 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
158 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
159
160 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500161 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000162 }
Liz Kammer135bf552021-08-11 10:46:06 -0400163 // system_dynamic_deps distinguishes between nil/empty list behavior:
164 // nil -> use default values
165 // empty list -> no values specified
166 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000167
168 if isStatic {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400169 for axis, configToProps := range module.GetArchVariantProperties(ctx, &StaticProperties{}) {
170 for config, props := range configToProps {
171 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
172 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000173 }
174 }
175 }
176 } else {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400177 for axis, configToProps := range module.GetArchVariantProperties(ctx, &SharedProperties{}) {
178 for config, props := range configToProps {
179 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
180 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000181 }
182 }
183 }
184 }
185
Liz Kammerae3994e2021-10-19 09:45:48 -0400186 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
187 attrs.Srcs = partitionedSrcs[cppSrcPartition]
188 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
189 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000190
Liz Kammer12615db2021-09-28 09:19:17 -0400191 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
192 // TODO(b/208815215): determine whether this is used and add support if necessary
193 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
194 }
195
Jingwen Chenbcf53042021-05-26 04:42:42 +0000196 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000197}
198
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400199// Convenience struct to hold all attributes parsed from prebuilt properties.
200type prebuiltAttributes struct {
201 Src bazel.LabelAttribute
202}
203
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000204// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Jingwen Chen55bc8202021-11-02 06:40:51 +0000205func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400206 var srcLabelAttribute bazel.LabelAttribute
207
Liz Kammer9abd62d2021-05-21 08:37:59 -0400208 for axis, configToProps := range module.GetArchVariantProperties(ctx, &prebuiltLinkerProperties{}) {
209 for config, props := range configToProps {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400210 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
211 if len(prebuiltLinkerProperties.Srcs) > 1 {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400212 ctx.ModuleErrorf("Bp2BuildParsePrebuiltLibraryProps: Expected at most once source file for %s %s\n", axis, config)
213 continue
214 } else if len(prebuiltLinkerProperties.Srcs) == 0 {
215 continue
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400216 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400217 src := android.BazelLabelForModuleSrcSingle(ctx, prebuiltLinkerProperties.Srcs[0])
218 srcLabelAttribute.SetSelectValue(axis, config, src)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400219 }
220 }
221 }
222
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400223 return prebuiltAttributes{
224 Src: srcLabelAttribute,
225 }
226}
227
Liz Kammere6583482021-10-19 13:56:10 -0400228type baseAttributes struct {
229 compilerAttributes
230 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400231
232 protoDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400233}
234
Jingwen Chen107c0de2021-04-09 10:43:12 +0000235// Convenience struct to hold all attributes parsed from compiler properties.
236type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400237 // Options for all languages
238 copts bazel.StringListAttribute
239 // Assembly options and sources
240 asFlags bazel.StringListAttribute
241 asSrcs bazel.LabelListAttribute
242 // C options and sources
243 conlyFlags bazel.StringListAttribute
244 cSrcs bazel.LabelListAttribute
245 // C++ options and sources
246 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000247 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400248
Liz Kammere6583482021-10-19 13:56:10 -0400249 hdrs bazel.LabelListAttribute
250
Chris Parsons2c788392021-08-10 11:58:07 -0400251 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000252
253 // Not affected by arch variants
254 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500255 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000256 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400257
258 localIncludes bazel.StringListAttribute
259 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400260
Liz Kammer1263d9b2021-12-10 14:28:20 -0500261 includes BazelIncludes
262
Liz Kammer12615db2021-09-28 09:19:17 -0400263 protoSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000264
265 stubsSymbolFile *string
266 stubsVersions bazel.StringListAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000267}
268
Liz Kammercac7f692021-12-16 14:19:32 -0500269type filterOutFn func(string) bool
270
271func filterOutStdFlag(flag string) bool {
272 return strings.HasPrefix(flag, "-std=")
273}
274
275func parseCommandLineFlags(soongFlags []string, filterOut filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400276 var result []string
277 for _, flag := range soongFlags {
Liz Kammercac7f692021-12-16 14:19:32 -0500278 if filterOut != nil && filterOut(flag) {
279 continue
280 }
Liz Kammere6583482021-10-19 13:56:10 -0400281 // Soong's cflags can contain spaces, like `-include header.h`. For
282 // Bazel's copts, split them up to be compatible with the
283 // no_copts_tokenization feature.
284 result = append(result, strings.Split(flag, " ")...)
285 }
286 return result
287}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000288
Jingwen Chen55bc8202021-11-02 06:40:51 +0000289func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400290 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
291 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
292 if srcsList, ok := parseSrcs(ctx, props); ok {
293 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400294 }
295
Liz Kammere6583482021-10-19 13:56:10 -0400296 localIncludeDirs := props.Local_include_dirs
297 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500298 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400299 if includeBuildDirectory(props.Include_build_directory) {
300 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400301 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000302 }
303
Liz Kammere6583482021-10-19 13:56:10 -0400304 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
305 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
306
Liz Kammercac7f692021-12-16 14:19:32 -0500307 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
308 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
309 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
310 // cases.
311 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
312 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
313 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, nil))
314 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, nil))
Liz Kammere6583482021-10-19 13:56:10 -0400315 ca.rtti.SetSelectValue(axis, config, props.Rtti)
316}
317
Jingwen Chen55bc8202021-11-02 06:40:51 +0000318func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Liz Kammere6583482021-10-19 13:56:10 -0400319 stlPropsByArch := module.GetArchVariantProperties(ctx, &StlProperties{})
320 for _, configToProps := range stlPropsByArch {
321 for _, props := range configToProps {
322 if stlProps, ok := props.(*StlProperties); ok {
323 if stlProps.Stl == nil {
324 continue
Liz Kammer9abd62d2021-05-21 08:37:59 -0400325 }
Liz Kammere6583482021-10-19 13:56:10 -0400326 if ca.stl == nil {
327 ca.stl = stlProps.Stl
328 } else if ca.stl != stlProps.Stl {
329 ctx.ModuleErrorf("Unsupported conversion: module with different stl for different variants: %s and %s", *ca.stl, stlProps.Stl)
Liz Kammerae3994e2021-10-19 09:45:48 -0400330 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400331 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000332 }
333 }
Liz Kammere6583482021-10-19 13:56:10 -0400334}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000335
Jingwen Chen55bc8202021-11-02 06:40:51 +0000336func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400337 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400338 "Cflags": &ca.copts,
339 "Asflags": &ca.asFlags,
340 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400341 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400342 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000343 if productConfigProps, exists := productVariableProps[propName]; exists {
344 for productConfigProp, prop := range productConfigProps {
345 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400346 if !ok {
347 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
348 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000349 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
350 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400351 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400352 }
353 }
Liz Kammere6583482021-10-19 13:56:10 -0400354}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400355
Jingwen Chen55bc8202021-11-02 06:40:51 +0000356func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400357 ca.srcs.ResolveExcludes()
358 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
359
Liz Kammer12615db2021-09-28 09:19:17 -0400360 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
361
Liz Kammere6583482021-10-19 13:56:10 -0400362 for p, lla := range partitionedSrcs {
363 // if there are no sources, there is no need for headers
364 if lla.IsEmpty() {
365 continue
366 }
367 lla.Append(implementationHdrs)
368 partitionedSrcs[p] = lla
369 }
370
371 ca.srcs = partitionedSrcs[cppSrcPartition]
372 ca.cSrcs = partitionedSrcs[cSrcPartition]
373 ca.asSrcs = partitionedSrcs[asSrcPartition]
374
375 ca.absoluteIncludes.DeduplicateAxesFromBase()
376 ca.localIncludes.DeduplicateAxesFromBase()
377}
378
379// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000380func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400381 anySrcs := false
382 // Add srcs-like dependencies such as generated files.
383 // First create a LabelList containing these dependencies, then merge the values with srcs.
384 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
385 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
386 anySrcs = true
387 }
388
389 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
390 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
391 anySrcs = true
392 }
393 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
394}
395
Chris Parsons79bd2b72021-11-29 17:52:41 -0500396func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
397 var cStdVal, cppStdVal string
398 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
399 // Defaults are handled by the toolchain definition.
400 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammere6583482021-10-19 13:56:10 -0400401 if cpp_std != nil {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500402 cppStdVal = parseCppStd(cpp_std)
Liz Kammere6583482021-10-19 13:56:10 -0400403 } else if gnu_extensions != nil && !*gnu_extensions {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500404 cppStdVal = "c++17"
Liz Kammere6583482021-10-19 13:56:10 -0400405 }
Chris Parsons79bd2b72021-11-29 17:52:41 -0500406 if c_std != nil {
407 cStdVal = parseCStd(c_std)
408 } else if gnu_extensions != nil && !*gnu_extensions {
409 cStdVal = "c99"
410 }
411
412 cStdVal, cppStdVal = maybeReplaceGnuToC(gnu_extensions, cStdVal, cppStdVal)
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500413 var c_std_prop, cpp_std_prop *string
414 if cStdVal != "" {
415 c_std_prop = &cStdVal
416 }
417 if cppStdVal != "" {
418 cpp_std_prop = &cppStdVal
419 }
420
421 return c_std_prop, cpp_std_prop
Liz Kammere6583482021-10-19 13:56:10 -0400422}
423
Liz Kammer1263d9b2021-12-10 14:28:20 -0500424// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
425// is fully-qualified.
426// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
427func packageFromLabel(label string) (string, bool) {
428 split := strings.Split(label, ":")
429 if len(split) != 2 {
430 return "", false
431 }
432 if split[0] == "" {
433 return ".", false
434 }
435 // remove leading "//"
436 return split[0][2:], true
437}
438
439// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
440func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
441 for _, hdr := range labelList.Includes {
442 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
443 absolute = append(absolute, pkg)
444 } else if pkg != "" {
445 relative = append(relative, pkg)
446 }
447 }
448 return relative, absolute
449}
450
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000451// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400452func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400453 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
454 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000455 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400456
457 var implementationHdrs bazel.LabelListAttribute
458
459 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
460 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
461 for axis, configMap := range cp {
462 if _, ok := axisToConfigs[axis]; !ok {
463 axisToConfigs[axis] = map[string]bool{}
464 }
465 for config, _ := range configMap {
466 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400467 }
468 }
469 }
Liz Kammere6583482021-10-19 13:56:10 -0400470 allAxesAndConfigs(archVariantCompilerProps)
471 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000472 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400473
Liz Kammere6583482021-10-19 13:56:10 -0400474 compilerAttrs := compilerAttributes{}
475 linkerAttrs := linkerAttributes{}
476
477 for axis, configs := range axisToConfigs {
478 for config, _ := range configs {
479 var allHdrs []string
480 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
481 allHdrs = baseCompilerProps.Generated_headers
482
483 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
484 }
485
486 var exportHdrs []string
487
488 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
489 exportHdrs = baseLinkerProps.Export_generated_headers
490
491 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
492 }
493 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
494 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
495 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500496
497 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
498 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
499 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
500
501 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
502 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
503 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
504 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
505 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
506 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
507 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000508
509 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
510 if axis == bazel.NoConfigAxis {
511 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
512 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
513 }
514 }
Liz Kammere6583482021-10-19 13:56:10 -0400515 }
516 }
517
518 compilerAttrs.convertStlProps(ctx, module)
519 (&linkerAttrs).convertStripProps(ctx, module)
520
521 productVariableProps := android.ProductVariableProperties(ctx)
522
523 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
524 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
525
526 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500527 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400528
Liz Kammer12615db2021-09-28 09:19:17 -0400529 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
530
531 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
532 // which. This will add the newly generated proto library to the appropriate attribute and nothing
533 // to the other
534 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
535 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
536
Liz Kammere6583482021-10-19 13:56:10 -0400537 return baseAttributes{
538 compilerAttrs,
539 linkerAttrs,
Liz Kammer12615db2021-09-28 09:19:17 -0400540 protoDep.protoDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000541 }
542}
543
Yu Liufc603162022-03-01 15:44:08 -0800544func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
545 return sdkAttributes {
546 Sdk_version: module.Properties.Sdk_version,
547 Min_sdk_version: module.Properties.Min_sdk_version,
548 }
549}
550
551type sdkAttributes struct {
552 Sdk_version *string
553 Min_sdk_version *string
554}
555
Jingwen Chen107c0de2021-04-09 10:43:12 +0000556// Convenience struct to hold all attributes parsed from linker properties.
557type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500558 deps bazel.LabelListAttribute
559 implementationDeps bazel.LabelListAttribute
560 dynamicDeps bazel.LabelListAttribute
561 implementationDynamicDeps bazel.LabelListAttribute
562 wholeArchiveDeps bazel.LabelListAttribute
563 implementationWholeArchiveDeps bazel.LabelListAttribute
564 systemDynamicDeps bazel.LabelListAttribute
565 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400566
Jingwen Chen6ada5892021-09-17 11:38:09 +0000567 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000568 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500569 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000570 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400571 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000572 stripKeepSymbols bazel.BoolAttribute
573 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
574 stripKeepSymbolsList bazel.StringListAttribute
575 stripAll bazel.BoolAttribute
576 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400577 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400578}
579
Liz Kammer54309532021-12-14 12:21:22 -0500580var (
581 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
582)
583
Jingwen Chen55bc8202021-11-02 06:40:51 +0000584func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400585 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
586 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400587
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400588 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
589 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammere6583482021-10-19 13:56:10 -0400590 // Excludes to parallel Soong:
591 // 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 -0400592 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
593
Liz Kammere6583482021-10-19 13:56:10 -0400594 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, staticLibs, props.Exclude_static_libs, props.Export_static_lib_headers, bazelLabelForStaticDepsExcludes)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400595
Liz Kammere6583482021-10-19 13:56:10 -0400596 headerLibs := android.FirstUniqueStrings(props.Header_libs)
597 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400598
Liz Kammere6583482021-10-19 13:56:10 -0400599 (&hDeps.export).Append(staticDeps.export)
600 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000601
Liz Kammere6583482021-10-19 13:56:10 -0400602 (&hDeps.implementation).Append(staticDeps.implementation)
603 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400604
Liz Kammere6583482021-10-19 13:56:10 -0400605 systemSharedLibs := props.System_shared_libs
606 // systemSharedLibs distinguishes between nil/empty list behavior:
607 // nil -> use default values
608 // empty list -> no values specified
609 if len(systemSharedLibs) > 0 {
610 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
611 }
612 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
613
614 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500615 excludeSharedLibs := props.Exclude_shared_libs
616 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
617 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
618 })
619 for _, el := range usedSystem {
620 if la.usedSystemDynamicDepAsDynamicDep == nil {
621 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
622 }
623 la.usedSystemDynamicDepAsDynamicDep[el] = true
624 }
625
Liz Kammere6583482021-10-19 13:56:10 -0400626 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, sharedLibs, props.Exclude_shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDepsExcludes)
627 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
628 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
629
630 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
631 axisFeatures = append(axisFeatures, "disable_pack_relocations")
632 }
633
634 if Bool(props.Allow_undefined_symbols) {
635 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
636 }
637
638 var linkerFlags []string
639 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -0500640 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -0400641 // binaries remove static flag if -shared is in the linker flags
642 if isBinary && android.InList("-shared", linkerFlags) {
643 axisFeatures = append(axisFeatures, "-static_flag")
644 }
645 }
646 if props.Version_script != nil {
647 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
648 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
649 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
650 }
651 la.linkopts.SetSelectValue(axis, config, linkerFlags)
652 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
653
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500654 if axis == bazel.NoConfigAxis {
655 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
656 }
657
Liz Kammere6583482021-10-19 13:56:10 -0400658 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
659 if props.crt() != nil {
660 if axis == bazel.NoConfigAxis {
661 la.linkCrt.SetSelectValue(axis, config, props.crt())
662 } else if axis == bazel.ArchConfigurationAxis {
663 ctx.ModuleErrorf("nocrt is not supported for arch variants")
664 }
665 }
666
667 if axisFeatures != nil {
668 la.features.SetSelectValue(axis, config, axisFeatures)
669 }
670}
671
Jingwen Chen55bc8202021-11-02 06:40:51 +0000672func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000673 for axis, configToProps := range module.GetArchVariantProperties(ctx, &StripProperties{}) {
674 for config, props := range configToProps {
675 if stripProperties, ok := props.(*StripProperties); ok {
Liz Kammere6583482021-10-19 13:56:10 -0400676 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
677 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
678 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
679 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
680 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000681 }
682 }
683 }
Liz Kammere6583482021-10-19 13:56:10 -0400684}
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000685
Jingwen Chen55bc8202021-11-02 06:40:51 +0000686func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +0000687
Liz Kammer47535c52021-06-02 16:02:22 -0400688 type productVarDep struct {
689 // the name of the corresponding excludes field, if one exists
690 excludesField string
691 // reference to the bazel attribute that should be set for the given product variable config
692 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400693
Jingwen Chen55bc8202021-11-02 06:40:51 +0000694 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -0400695 }
696
697 productVarToDepFields := map[string]productVarDep{
698 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +0000699 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
700 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
701 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -0400702 }
703
Liz Kammer47535c52021-06-02 16:02:22 -0400704 for name, dep := range productVarToDepFields {
705 props, exists := productVariableProps[name]
706 excludeProps, excludesExists := productVariableProps[dep.excludesField]
707 // if neither an include or excludes property exists, then skip it
708 if !exists && !excludesExists {
709 continue
710 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000711 // Collect all the configurations that an include or exclude property exists for.
712 // We want to iterate all configurations rather than either the include or exclude because, for a
713 // particular configuration, we may have either only an include or an exclude to handle.
714 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
715 for p := range props {
716 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400717 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000718 for p := range excludeProps {
719 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400720 }
721
Jingwen Chen25825ca2021-11-15 12:28:43 +0000722 for productConfigProp := range productConfigProps {
723 prop, includesExists := props[productConfigProp]
724 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -0400725 var includes, excludes []string
726 var ok bool
727 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +0000728 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400729 ctx.ModuleErrorf("Could not convert product variable %s property", name)
730 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000731 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400732 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
733 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400734
Jingwen Chen58ff6802021-11-17 12:14:41 +0000735 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +0000736 dep.attribute.SetSelectValue(
737 productConfigProp.ConfigurationAxis(),
738 productConfigProp.SelectKey(),
739 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
740 )
Liz Kammer47535c52021-06-02 16:02:22 -0400741 }
742 }
Liz Kammere6583482021-10-19 13:56:10 -0400743}
Liz Kammer47535c52021-06-02 16:02:22 -0400744
Liz Kammer54309532021-12-14 12:21:22 -0500745func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
746 // if system dynamic deps have the default value, any use of a system dynamic library used will
747 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
748 // from bionic OSes.
749 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
750 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
751 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
752 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
753 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
754 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
755 }
756
Liz Kammere6583482021-10-19 13:56:10 -0400757 la.deps.ResolveExcludes()
758 la.implementationDeps.ResolveExcludes()
759 la.dynamicDeps.ResolveExcludes()
760 la.implementationDynamicDeps.ResolveExcludes()
761 la.wholeArchiveDeps.ResolveExcludes()
762 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -0500763
Jingwen Chen91220d72021-03-24 02:18:33 -0400764}
765
Jingwen Chened9c17d2021-04-13 07:14:55 +0000766// Relativize a list of root-relative paths with respect to the module's
767// directory.
768//
769// include_dirs Soong prop are root-relative (b/183742505), but
770// local_include_dirs, export_include_dirs and export_system_include_dirs are
771// module dir relative. This function makes a list of paths entirely module dir
772// relative.
773//
774// For the `include` attribute, Bazel wants the paths to be relative to the
775// module.
776func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000777 var relativePaths []string
778 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +0000779 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
780 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
781 if err != nil {
782 panic(err)
783 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000784 relativePaths = append(relativePaths, relativePath)
785 }
786 return relativePaths
787}
788
Liz Kammer5fad5012021-09-09 14:08:21 -0400789// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
790// attributes.
791type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500792 AbsoluteIncludes bazel.StringListAttribute
793 Includes bazel.StringListAttribute
794 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -0400795}
796
Liz Kammer1263d9b2021-12-10 14:28:20 -0500797func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, existingIncludes BazelIncludes) BazelIncludes {
Jingwen Chen91220d72021-03-24 02:18:33 -0400798 libraryDecorator := module.linker.(*libraryDecorator)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500799 return bp2BuildParseExportedIncludesHelper(ctx, module, libraryDecorator, &existingIncludes)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400800}
Jingwen Chen91220d72021-03-24 02:18:33 -0400801
Liz Kammer5fad5012021-09-09 14:08:21 -0400802// Bp2buildParseExportedIncludesForPrebuiltLibrary returns a BazelIncludes with Bazel-ified values
803// to export includes from the underlying module's properties.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000804func Bp2BuildParseExportedIncludesForPrebuiltLibrary(ctx android.BazelConversionPathContext, module *Module) BazelIncludes {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400805 prebuiltLibraryLinker := module.linker.(*prebuiltLibraryLinker)
806 libraryDecorator := prebuiltLibraryLinker.libraryDecorator
Liz Kammer1263d9b2021-12-10 14:28:20 -0500807 return bp2BuildParseExportedIncludesHelper(ctx, module, libraryDecorator, nil)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400808}
809
810// bp2BuildParseExportedIncludes creates a string list attribute contains the
811// exported included directories of a module.
Liz Kammer1263d9b2021-12-10 14:28:20 -0500812func bp2BuildParseExportedIncludesHelper(ctx android.BazelConversionPathContext, module *Module, libraryDecorator *libraryDecorator, includes *BazelIncludes) BazelIncludes {
813 var exported BazelIncludes
814 if includes != nil {
815 exported = *includes
816 } else {
817 exported = BazelIncludes{}
818 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400819 for axis, configToProps := range module.GetArchVariantProperties(ctx, &FlagExporterProperties{}) {
820 for config, props := range configToProps {
821 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
Liz Kammer5fad5012021-09-09 14:08:21 -0400822 if len(flagExporterProperties.Export_include_dirs) > 0 {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500823 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
Liz Kammer5fad5012021-09-09 14:08:21 -0400824 }
825 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500826 exported.SystemIncludes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.SystemIncludes.SelectValue(axis, config), flagExporterProperties.Export_system_include_dirs...)))
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400827 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400828 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400829 }
830 }
Liz Kammer1263d9b2021-12-10 14:28:20 -0500831 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -0400832 exported.Includes.DeduplicateAxesFromBase()
833 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400834
Liz Kammer5fad5012021-09-09 14:08:21 -0400835 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -0400836}
Chris Parsons953b3562021-09-20 15:14:39 -0400837
Jingwen Chen55bc8202021-11-02 06:40:51 +0000838func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400839 label := android.BazelModuleLabel(ctx, m)
Liz Kammer35ca77e2021-12-22 15:31:40 -0500840 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GenerateCcLibraryStaticOnly(m.Name()) {
841 label += "_bp2build_cc_library_static"
Chris Parsons953b3562021-09-20 15:14:39 -0400842 }
843 return label
844}
845
Jingwen Chen55bc8202021-11-02 06:40:51 +0000846func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400847 // cc_library, at it's root name, propagates the shared library, which depends on the static
848 // library.
849 return android.BazelModuleLabel(ctx, m)
850}
851
Jingwen Chen55bc8202021-11-02 06:40:51 +0000852func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400853 label := bazelLabelForStaticModule(ctx, m)
854 if aModule, ok := m.(android.Module); ok {
855 if android.IsModulePrebuilt(aModule) {
856 label += "_alwayslink"
857 }
858 }
859 return label
860}
861
Jingwen Chen55bc8202021-11-02 06:40:51 +0000862func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400863 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
864}
865
Jingwen Chen55bc8202021-11-02 06:40:51 +0000866func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400867 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
868}
869
Jingwen Chen55bc8202021-11-02 06:40:51 +0000870func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400871 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
872}
873
Jingwen Chen55bc8202021-11-02 06:40:51 +0000874func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400875 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
876}
877
Jingwen Chen55bc8202021-11-02 06:40:51 +0000878func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400879 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
880}
881
Jingwen Chen55bc8202021-11-02 06:40:51 +0000882func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400883 // This is not elegant, but bp2build's shared library targets only propagate
884 // their header information as part of the normal C++ provider.
885 return bazelLabelForSharedDeps(ctx, modules)
886}
887
Jingwen Chen55bc8202021-11-02 06:40:51 +0000888func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400889 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
890}
Liz Kammer2b8004b2021-10-04 13:55:44 -0400891
892type binaryLinkerAttrs struct {
893 Linkshared *bool
894}
895
Jingwen Chen55bc8202021-11-02 06:40:51 +0000896func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400897 attrs := binaryLinkerAttrs{}
898 archVariantProps := m.GetArchVariantProperties(ctx, &BinaryLinkerProperties{})
899 for axis, configToProps := range archVariantProps {
900 for _, p := range configToProps {
901 props := p.(*BinaryLinkerProperties)
902 staticExecutable := props.Static_executable
903 if axis == bazel.NoConfigAxis {
904 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
905 attrs.Linkshared = &linkBinaryShared
906 }
907 } else if staticExecutable != nil {
908 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
909 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
910 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
911 }
912 }
913 }
914
915 return attrs
916}