blob: 96645b07561d76fbdaaa810f5be2784f1f3c4519 [file] [log] [blame]
Ivan Lozano4fef93c2020-07-08 08:39:44 -04001// Copyright 2020 The Android Open Source Project
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.
14
15package rust
16
17import (
Ivan Lozano4fef93c2020-07-08 08:39:44 -040018 "strings"
19
Ivan Lozano45901ed2020-07-24 16:05:01 -040020 "github.com/google/blueprint"
Stephen Crane12e2cb72020-08-04 12:26:10 -070021 "github.com/google/blueprint/proptools"
Ivan Lozano45901ed2020-07-24 16:05:01 -040022
Ivan Lozano4fef93c2020-07-08 08:39:44 -040023 "android/soong/android"
Ivan Lozanobc9e4212020-09-25 16:08:34 -040024 "android/soong/cc"
Ivan Lozano3d947522020-09-23 13:26:25 -040025 cc_config "android/soong/cc/config"
Ivan Lozano4fef93c2020-07-08 08:39:44 -040026)
27
28var (
Ivan Lozanoec54eec2020-07-22 16:48:53 -040029 defaultBindgenFlags = []string{""}
Ivan Lozano4fef93c2020-07-08 08:39:44 -040030
31 // bindgen should specify its own Clang revision so updating Clang isn't potentially blocked on bindgen failures.
Yi Kong6974c7e2023-05-12 15:03:29 +010032 bindgenClangVersion = "clang-r487747c"
Ivan Lozano4fef93c2020-07-08 08:39:44 -040033
Peter Collingbourne9a868f12020-12-30 20:23:01 -080034 _ = pctx.VariableFunc("bindgenClangVersion", func(ctx android.PackageVarContext) string {
35 if override := ctx.Config().Getenv("LLVM_BINDGEN_PREBUILTS_VERSION"); override != "" {
36 return override
37 }
38 return bindgenClangVersion
39 })
40
Ivan Lozano4fef93c2020-07-08 08:39:44 -040041 //TODO(b/160803703) Use a prebuilt bindgen instead of the built bindgen.
Shao-Chuan Leeaa3231c2020-11-05 22:20:17 +090042 _ = pctx.HostBinToolVariable("bindgenCmd", "bindgen")
Colin Cross567d3422022-04-28 15:30:09 -070043 _ = pctx.VariableFunc("bindgenHostPrebuiltTag", func(ctx android.PackageVarContext) string {
44 if ctx.Config().UseHostMusl() {
45 // This is a hack to use the glibc bindgen binary until we have a musl version checked in.
46 return "linux-x86"
47 } else {
48 return "${config.HostPrebuiltTag}"
49 }
50 })
51 _ = pctx.VariableFunc("bindgenClangLibdir", func(ctx android.PackageVarContext) string {
52 if ctx.Config().UseHostMusl() {
Colin Cross645874d2022-10-14 14:18:21 -070053 return "musl/lib/"
Colin Cross567d3422022-04-28 15:30:09 -070054 } else {
Yi Kongbd188812023-02-08 19:51:59 +090055 return "lib/"
Colin Cross567d3422022-04-28 15:30:09 -070056 }
57 })
Ivan Lozano4fef93c2020-07-08 08:39:44 -040058 _ = pctx.SourcePathVariable("bindgenClang",
Colin Cross567d3422022-04-28 15:30:09 -070059 "${cc_config.ClangBase}/${bindgenHostPrebuiltTag}/${bindgenClangVersion}/bin/clang")
Ivan Lozano4fef93c2020-07-08 08:39:44 -040060 _ = pctx.SourcePathVariable("bindgenLibClang",
Colin Cross567d3422022-04-28 15:30:09 -070061 "${cc_config.ClangBase}/${bindgenHostPrebuiltTag}/${bindgenClangVersion}/${bindgenClangLibdir}")
Ivan Lozano4fef93c2020-07-08 08:39:44 -040062
63 //TODO(ivanlozano) Switch this to RuleBuilder
64 bindgen = pctx.AndroidStaticRule("bindgen",
65 blueprint.RuleParams{
Ivan Lozanoec54eec2020-07-22 16:48:53 -040066 Command: "CLANG_PATH=$bindgenClang LIBCLANG_PATH=$bindgenLibClang RUSTFMT=${config.RustBin}/rustfmt " +
Ivan Lozanoc564d2d2020-08-04 15:43:37 -040067 "$cmd $flags $in -o $out -- -MD -MF $out.d $cflags",
68 CommandDeps: []string{"$cmd"},
Ivan Lozanoe1e844b2020-07-24 15:16:30 -040069 Deps: blueprint.DepsGCC,
70 Depfile: "$out.d",
Ivan Lozano4fef93c2020-07-08 08:39:44 -040071 },
Ivan Lozanoc564d2d2020-08-04 15:43:37 -040072 "cmd", "flags", "cflags")
Ivan Lozano4fef93c2020-07-08 08:39:44 -040073)
74
75func init() {
76 android.RegisterModuleType("rust_bindgen", RustBindgenFactory)
Ivan Lozanof6fe9952020-07-22 16:30:20 -040077 android.RegisterModuleType("rust_bindgen_host", RustBindgenHostFactory)
Ivan Lozano4fef93c2020-07-08 08:39:44 -040078}
79
80var _ SourceProvider = (*bindgenDecorator)(nil)
81
82type BindgenProperties struct {
Ivan Lozano3d947522020-09-23 13:26:25 -040083 // The wrapper header file. By default this is assumed to be a C header unless the extension is ".hh" or ".hpp".
84 // This is used to specify how to interpret the header and determines which '-std' flag to use by default.
85 //
86 // If your C++ header must have some other extension, then the default behavior can be overridden by setting the
87 // cpp_std property.
Ivan Lozano4fef93c2020-07-08 08:39:44 -040088 Wrapper_src *string `android:"path,arch_variant"`
89
90 // list of bindgen-specific flags and options
Ivan Lozano26ecd6c2020-07-31 13:40:31 -040091 Bindgen_flags []string `android:"arch_variant"`
Ivan Lozano4fef93c2020-07-08 08:39:44 -040092
Ivan Lozanoc564d2d2020-08-04 15:43:37 -040093 // module name of a custom binary/script which should be used instead of the 'bindgen' binary. This custom
94 // binary must expect arguments in a similar fashion to bindgen, e.g.
95 //
96 // "my_bindgen [flags] wrapper_header.h -o [output_path] -- [clang flags]"
Liz Kammereda93982021-04-20 10:15:41 -040097 Custom_bindgen string
Ivan Lozano4fef93c2020-07-08 08:39:44 -040098}
99
100type bindgenDecorator struct {
Andrei Homescuc7767922020-08-05 06:36:19 -0700101 *BaseSourceProvider
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400102
Ivan Lozanobc9e4212020-09-25 16:08:34 -0400103 Properties BindgenProperties
104 ClangProperties cc.RustBindgenClangProperties
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400105}
106
Ivan Lozano3d947522020-09-23 13:26:25 -0400107func (b *bindgenDecorator) getStdVersion(ctx ModuleContext, src android.Path) (string, bool) {
108 // Assume headers are C headers
109 isCpp := false
110 stdVersion := ""
111
112 switch src.Ext() {
113 case ".hpp", ".hh":
114 isCpp = true
115 }
116
Ivan Lozanobc9e4212020-09-25 16:08:34 -0400117 if String(b.ClangProperties.Cpp_std) != "" && String(b.ClangProperties.C_std) != "" {
Ivan Lozano3d947522020-09-23 13:26:25 -0400118 ctx.PropertyErrorf("c_std", "c_std and cpp_std cannot both be defined at the same time.")
119 }
120
Ivan Lozanobc9e4212020-09-25 16:08:34 -0400121 if String(b.ClangProperties.Cpp_std) != "" {
122 if String(b.ClangProperties.Cpp_std) == "experimental" {
Ivan Lozano3d947522020-09-23 13:26:25 -0400123 stdVersion = cc_config.ExperimentalCppStdVersion
Ivan Lozanobc9e4212020-09-25 16:08:34 -0400124 } else if String(b.ClangProperties.Cpp_std) == "default" {
Ivan Lozano3d947522020-09-23 13:26:25 -0400125 stdVersion = cc_config.CppStdVersion
126 } else {
Ivan Lozanobc9e4212020-09-25 16:08:34 -0400127 stdVersion = String(b.ClangProperties.Cpp_std)
Ivan Lozano3d947522020-09-23 13:26:25 -0400128 }
Ivan Lozanobc9e4212020-09-25 16:08:34 -0400129 } else if b.ClangProperties.C_std != nil {
130 if String(b.ClangProperties.C_std) == "experimental" {
Ivan Lozano3d947522020-09-23 13:26:25 -0400131 stdVersion = cc_config.ExperimentalCStdVersion
Ivan Lozanobc9e4212020-09-25 16:08:34 -0400132 } else if String(b.ClangProperties.C_std) == "default" {
Ivan Lozano3d947522020-09-23 13:26:25 -0400133 stdVersion = cc_config.CStdVersion
134 } else {
Ivan Lozanobc9e4212020-09-25 16:08:34 -0400135 stdVersion = String(b.ClangProperties.C_std)
Ivan Lozano3d947522020-09-23 13:26:25 -0400136 }
137 } else if isCpp {
138 stdVersion = cc_config.CppStdVersion
139 } else {
140 stdVersion = cc_config.CStdVersion
141 }
142
143 return stdVersion, isCpp
144}
145
ThiƩbaud Weksteen31f1bb82020-08-27 13:37:29 +0200146func (b *bindgenDecorator) GenerateSource(ctx ModuleContext, deps PathDeps) android.Path {
147 ccToolchain := ctx.RustModule().ccToolchain(ctx)
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400148
149 var cflags []string
Ivan Lozano45901ed2020-07-24 16:05:01 -0400150 var implicits android.Paths
151
Ivan Lozanoddd0bdb2020-08-28 17:00:26 -0400152 implicits = append(implicits, deps.depGeneratedHeaders...)
Ivan Lozano45901ed2020-07-24 16:05:01 -0400153
154 // Default clang flags
Colin Cross0523ba22021-07-14 18:45:05 -0700155 cflags = append(cflags, "${cc_config.CommonGlobalCflags}")
Ivan Lozano45901ed2020-07-24 16:05:01 -0400156 if ctx.Device() {
Colin Cross0523ba22021-07-14 18:45:05 -0700157 cflags = append(cflags, "${cc_config.DeviceGlobalCflags}")
Ivan Lozano45901ed2020-07-24 16:05:01 -0400158 }
159
160 // Toolchain clang flags
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400161 cflags = append(cflags, "-target "+ccToolchain.ClangTriple())
Colin Cross33bac242021-07-14 17:03:16 -0700162 cflags = append(cflags, strings.ReplaceAll(ccToolchain.Cflags(), "${config.", "${cc_config."))
163 cflags = append(cflags, strings.ReplaceAll(ccToolchain.ToolchainCflags(), "${config.", "${cc_config."))
Ivan Lozano45901ed2020-07-24 16:05:01 -0400164
Ivan Lozanoe950cda2021-11-09 11:26:04 -0500165 if ctx.RustModule().UseVndk() {
166 cflags = append(cflags, "-D__ANDROID_VNDK__")
167 if ctx.RustModule().InVendor() {
168 cflags = append(cflags, "-D__ANDROID_VENDOR__")
169 } else if ctx.RustModule().InProduct() {
170 cflags = append(cflags, "-D__ANDROID_PRODUCT__")
171 }
172 }
173
174 if ctx.RustModule().InRecovery() {
175 cflags = append(cflags, "-D__ANDROID_RECOVERY__")
176 }
177
178 if mctx, ok := ctx.(*moduleContext); ok && mctx.apexVariationName() != "" {
179 cflags = append(cflags, "-D__ANDROID_APEX__")
Ivan Lozanoe950cda2021-11-09 11:26:04 -0500180 }
181
182 if ctx.Target().NativeBridge == android.NativeBridgeEnabled {
183 cflags = append(cflags, "-D__ANDROID_NATIVE_BRIDGE__")
184 }
185
Ivan Lozano45901ed2020-07-24 16:05:01 -0400186 // Dependency clang flags and include paths
187 cflags = append(cflags, deps.depClangFlags...)
188 for _, include := range deps.depIncludePaths {
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400189 cflags = append(cflags, "-I"+include.String())
190 }
Ivan Lozano45901ed2020-07-24 16:05:01 -0400191 for _, include := range deps.depSystemIncludePaths {
192 cflags = append(cflags, "-isystem "+include.String())
193 }
194
Stephen Crane12e2cb72020-08-04 12:26:10 -0700195 esc := proptools.NinjaAndShellEscapeList
196
Ivan Lozano0a2a1152020-10-16 10:49:08 -0400197 // Filter out invalid cflags
198 for _, flag := range b.ClangProperties.Cflags {
199 if flag == "-x c++" || flag == "-xc++" {
200 ctx.PropertyErrorf("cflags",
201 "-x c++ should not be specified in cflags; setting cpp_std specifies this is a C++ header, or change the file extension to '.hpp' or '.hh'")
202 }
203 if strings.HasPrefix(flag, "-std=") {
204 ctx.PropertyErrorf("cflags",
205 "-std should not be specified in cflags; instead use c_std or cpp_std")
206 }
207 }
208
Ivan Lozano45901ed2020-07-24 16:05:01 -0400209 // Module defined clang flags and include paths
Ivan Lozanobc9e4212020-09-25 16:08:34 -0400210 cflags = append(cflags, esc(b.ClangProperties.Cflags)...)
211 for _, include := range b.ClangProperties.Local_include_dirs {
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400212 cflags = append(cflags, "-I"+android.PathForModuleSrc(ctx, include).String())
Ivan Lozano45901ed2020-07-24 16:05:01 -0400213 implicits = append(implicits, android.PathForModuleSrc(ctx, include))
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400214 }
215
216 bindgenFlags := defaultBindgenFlags
Stephen Crane12e2cb72020-08-04 12:26:10 -0700217 bindgenFlags = append(bindgenFlags, esc(b.Properties.Bindgen_flags)...)
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400218
219 wrapperFile := android.OptionalPathForModuleSrc(ctx, b.Properties.Wrapper_src)
220 if !wrapperFile.Valid() {
221 ctx.PropertyErrorf("wrapper_src", "invalid path to wrapper source")
222 }
223
Ivan Lozano3d947522020-09-23 13:26:25 -0400224 // Add C std version flag
225 stdVersion, isCpp := b.getStdVersion(ctx, wrapperFile.Path())
226 cflags = append(cflags, "-std="+stdVersion)
227
228 // Specify the header source language to avoid ambiguity.
229 if isCpp {
230 cflags = append(cflags, "-x c++")
Ivan Lozanobc9e4212020-09-25 16:08:34 -0400231 // Add any C++ only flags.
232 cflags = append(cflags, esc(b.ClangProperties.Cppflags)...)
Ivan Lozano3d947522020-09-23 13:26:25 -0400233 } else {
234 cflags = append(cflags, "-x c")
235 }
236
Colin Cross8a5a1e22022-10-14 15:53:02 -0700237 // clang-r468909b complains about the -x c in the flags in clang-sys parse_search_paths:
238 // clang: error: '-x c' after last input file has no effect [-Werror,-Wunused-command-line-argument]
239 cflags = append(cflags, "-Wno-unused-command-line-argument")
240
Yi Kong4f664e92022-07-14 20:36:15 +0800241 // LLVM_NEXT may contain flags that bindgen doesn't recognise. Turn off unknown flags warning.
242 if ctx.Config().IsEnvTrue("LLVM_NEXT") {
243 cflags = append(cflags, "-Wno-unknown-warning-option")
244 }
245
Andrei Homescuc7767922020-08-05 06:36:19 -0700246 outputFile := android.PathForModuleOut(ctx, b.BaseSourceProvider.getStem(ctx)+".rs")
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400247
Ivan Lozanoc564d2d2020-08-04 15:43:37 -0400248 var cmd, cmdDesc string
249 if b.Properties.Custom_bindgen != "" {
250 cmd = ctx.GetDirectDepWithTag(b.Properties.Custom_bindgen, customBindgenDepTag).(*Module).HostToolPath().String()
251 cmdDesc = b.Properties.Custom_bindgen
252 } else {
253 cmd = "$bindgenCmd"
254 cmdDesc = "bindgen"
255 }
256
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400257 ctx.Build(pctx, android.BuildParams{
258 Rule: bindgen,
Ivan Lozanoc564d2d2020-08-04 15:43:37 -0400259 Description: strings.Join([]string{cmdDesc, wrapperFile.Path().Rel()}, " "),
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400260 Output: outputFile,
261 Input: wrapperFile.Path(),
Ivan Lozano45901ed2020-07-24 16:05:01 -0400262 Implicits: implicits,
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400263 Args: map[string]string{
Ivan Lozanoc564d2d2020-08-04 15:43:37 -0400264 "cmd": cmd,
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400265 "flags": strings.Join(bindgenFlags, " "),
266 "cflags": strings.Join(cflags, " "),
267 },
268 })
Ivan Lozanoc564d2d2020-08-04 15:43:37 -0400269
Chih-Hung Hsiehc49649c2020-10-01 21:25:05 -0700270 b.BaseSourceProvider.OutputFiles = android.Paths{outputFile}
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400271 return outputFile
272}
273
Andrei Homescuc7767922020-08-05 06:36:19 -0700274func (b *bindgenDecorator) SourceProviderProps() []interface{} {
275 return append(b.BaseSourceProvider.SourceProviderProps(),
Ivan Lozanobc9e4212020-09-25 16:08:34 -0400276 &b.Properties, &b.ClangProperties)
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400277}
278
Ivan Lozano10735d92020-07-22 09:14:47 -0400279// rust_bindgen generates Rust FFI bindings to C libraries using bindgen given a wrapper header as the primary input.
280// Bindgen has a number of flags to control the generated source, and additional flags can be passed to clang to ensure
ThiƩbaud Weksteen295c72b2020-09-23 18:10:17 +0200281// the header and generated source is appropriately handled. It is recommended to add it as a dependency in the
282// rlibs, dylibs or rustlibs property. It may also be added in the srcs property for external crates, using the ":"
283// prefix.
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400284func RustBindgenFactory() android.Module {
285 module, _ := NewRustBindgen(android.HostAndDeviceSupported)
286 return module.Init()
287}
288
Ivan Lozanof6fe9952020-07-22 16:30:20 -0400289func RustBindgenHostFactory() android.Module {
290 module, _ := NewRustBindgen(android.HostSupported)
291 return module.Init()
292}
293
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400294func NewRustBindgen(hod android.HostOrDeviceSupported) (*Module, *bindgenDecorator) {
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400295 bindgen := &bindgenDecorator{
Andrei Homescuc7767922020-08-05 06:36:19 -0700296 BaseSourceProvider: NewSourceProvider(),
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400297 Properties: BindgenProperties{},
Ivan Lozanobc9e4212020-09-25 16:08:34 -0400298 ClangProperties: cc.RustBindgenClangProperties{},
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400299 }
Ivan Lozano26ecd6c2020-07-31 13:40:31 -0400300
Matthew Maurere94f3e72022-08-10 20:25:50 +0000301 module := NewSourceProviderModule(hod, bindgen, false, true)
302
303 android.AddLoadHook(module, func(ctx android.LoadHookContext) {
304 type stub_props struct {
305 Visibility []string
306 }
307 props := &stub_props{[]string{":__subpackages__"}}
308 ctx.PrependProperties(props)
309 })
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400310
311 return module, bindgen
312}
313
Andrei Homescuc7767922020-08-05 06:36:19 -0700314func (b *bindgenDecorator) SourceProviderDeps(ctx DepsContext, deps Deps) Deps {
315 deps = b.BaseSourceProvider.SourceProviderDeps(ctx, deps)
Dan Albert30e66dc2023-02-23 19:17:50 +0000316 if ctx.toolchain().Bionic() && !ctx.RustModule().compiler.noStdlibs() {
ThiƩbaud Weksteenf1ff54a2021-03-22 14:24:54 +0100317 deps = bionicDeps(ctx, deps, false)
Colin Crosse32f0932022-01-23 20:48:36 -0800318 } else if ctx.Os() == android.LinuxMusl {
319 deps = muslDeps(ctx, deps, false)
Ivan Lozano45901ed2020-07-24 16:05:01 -0400320 }
321
Ivan Lozanobc9e4212020-09-25 16:08:34 -0400322 deps.SharedLibs = append(deps.SharedLibs, b.ClangProperties.Shared_libs...)
323 deps.StaticLibs = append(deps.StaticLibs, b.ClangProperties.Static_libs...)
Ivan Lozano9b443832020-11-17 13:39:30 -0500324 deps.HeaderLibs = append(deps.StaticLibs, b.ClangProperties.Header_libs...)
Ivan Lozano4fef93c2020-07-08 08:39:44 -0400325 return deps
326}