blob: 1d2fb58c3ebef3f3bfade3c1ef20ea2ec5a5bf9f [file] [log] [blame]
Ivan Lozanoffee3342019-08-27 12:03:00 -07001// Copyright 2019 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 (
Colin Cross225a37a2023-01-11 14:17:39 -080018 "android/soong/cc"
Matthew Maurera28404a2023-11-20 23:33:28 +000019 "errors"
Ivan Lozanoffee3342019-08-27 12:03:00 -070020 "fmt"
21 "path/filepath"
Ivan Lozano45a9e312021-07-27 12:29:12 -040022 "strings"
Ivan Lozanoffee3342019-08-27 12:03:00 -070023
Ivan Lozanoad8b18b2019-10-31 19:38:29 -070024 "github.com/google/blueprint/proptools"
25
Ivan Lozanoffee3342019-08-27 12:03:00 -070026 "android/soong/android"
27 "android/soong/rust/config"
28)
29
Ivan Lozanodd055472020-09-28 13:22:45 -040030type RustLinkage int
31
32const (
Ivan Lozano806efd32024-12-11 21:38:53 +000033 DylibLinkage RustLinkage = iota
Ivan Lozanodd055472020-09-28 13:22:45 -040034 RlibLinkage
Ivan Lozanodd055472020-09-28 13:22:45 -040035)
36
Matthew Maurer689d6f62023-11-20 17:49:25 +000037type compiler interface {
38 initialize(ctx ModuleContext)
39 compilerFlags(ctx ModuleContext, flags Flags) Flags
40 cfgFlags(ctx ModuleContext, flags Flags) Flags
Jihoon Kang091ffd82024-10-03 01:13:24 +000041 featureFlags(ctx ModuleContext, module *Module, flags Flags) Flags
Ivan Lozano9587f452025-01-08 03:17:19 +000042 baseCompilerProps() BaseCompilerProperties
Matthew Maurer689d6f62023-11-20 17:49:25 +000043 compilerProps() []interface{}
44 compile(ctx ModuleContext, flags Flags, deps PathDeps) buildOutput
45 compilerDeps(ctx DepsContext, deps Deps) Deps
46 crateName() string
Matthew Maurerdb72f7e2023-11-21 00:20:02 +000047 edition() string
Jihoon Kang091ffd82024-10-03 01:13:24 +000048 features(ctx android.ConfigurableEvaluatorContext, module *Module) []string
Matthew Maurer689d6f62023-11-20 17:49:25 +000049 rustdoc(ctx ModuleContext, flags Flags, deps PathDeps) android.OptionalPath
Ivan Lozanoab586472024-05-15 10:59:47 -040050 Thinlto() bool
Matthew Maurer689d6f62023-11-20 17:49:25 +000051
52 // Output directory in which source-generated code from dependencies is
53 // copied. This is equivalent to Cargo's OUT_DIR variable.
Matthew Maurercd416532023-11-20 17:52:01 +000054 cargoOutDir() android.OptionalPath
Matthew Maurer689d6f62023-11-20 17:49:25 +000055
Matthew Maurercd416532023-11-20 17:52:01 +000056 // cargoPkgVersion returns the value of the Cargo_pkg_version property.
57 cargoPkgVersion() string
Matthew Maurer689d6f62023-11-20 17:49:25 +000058
Matthew Maurercd416532023-11-20 17:52:01 +000059 // cargoEnvCompat returns whether Cargo environment variables should be used.
60 cargoEnvCompat() bool
Matthew Maurer689d6f62023-11-20 17:49:25 +000061
62 inData() bool
63 install(ctx ModuleContext)
64 relativeInstallPath() string
65 everInstallable() bool
66
67 nativeCoverage() bool
68
69 Disabled() bool
70 SetDisabled()
71
Ivan Lozano806efd32024-12-11 21:38:53 +000072 stdLinkage(device bool) RustLinkage
Matthew Maurer689d6f62023-11-20 17:49:25 +000073 noStdlibs() bool
74
75 unstrippedOutputFilePath() android.Path
76 strippedOutputFilePath() android.OptionalPath
Matthew Maurerd221d312023-11-20 21:02:40 +000077
Matthew Maurera28404a2023-11-20 23:33:28 +000078 checkedCrateRootPath() (android.Path, error)
Andrew Walbran52533232024-03-19 11:36:04 +000079
80 Aliases() map[string]string
Matthew Maurer689d6f62023-11-20 17:49:25 +000081}
82
Thiébaud Weksteene81c9242020-08-03 10:46:28 +020083func (compiler *baseCompiler) edition() string {
Chih-Hung Hsieh961a30c2019-10-03 09:47:06 -070084 return proptools.StringDefault(compiler.Properties.Edition, config.DefaultEdition)
85}
86
Matthew Maurer99020b02019-10-31 10:44:40 -070087func (compiler *baseCompiler) setNoStdlibs() {
88 compiler.Properties.No_stdlibs = proptools.BoolPtr(true)
89}
90
Thiébaud Weksteen9e8451e2020-08-13 12:55:59 +020091func (compiler *baseCompiler) disableLints() {
92 compiler.Properties.Lints = proptools.StringPtr("none")
Stephen Craneda931d42020-08-04 13:02:28 -070093}
94
Chih-Hung Hsieh9a4a7ba2019-12-12 19:36:05 -080095func NewBaseCompiler(dir, dir64 string, location installLocation) *baseCompiler {
Ivan Lozanoffee3342019-08-27 12:03:00 -070096 return &baseCompiler{
Chih-Hung Hsieh961a30c2019-10-03 09:47:06 -070097 Properties: BaseCompilerProperties{},
98 dir: dir,
99 dir64: dir64,
Chih-Hung Hsieh9a4a7ba2019-12-12 19:36:05 -0800100 location: location,
Ivan Lozanoffee3342019-08-27 12:03:00 -0700101 }
102}
103
Chih-Hung Hsieh9a4a7ba2019-12-12 19:36:05 -0800104type installLocation int
105
106const (
107 InstallInSystem installLocation = 0
108 InstallInData = iota
Ivan Lozano43845682020-07-09 21:03:28 -0400109
110 incorrectSourcesError = "srcs can only contain one path for a rust file and source providers prefixed by \":\""
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100111 genSubDir = "out/"
Chih-Hung Hsieh9a4a7ba2019-12-12 19:36:05 -0800112)
113
Ivan Lozanoffee3342019-08-27 12:03:00 -0700114type BaseCompilerProperties struct {
Ivan Lozanoe4db0032021-08-11 13:39:33 -0400115 // path to the source file that is the main entry point of the program (e.g. main.rs or lib.rs).
116 // Only a single source file can be defined. Modules which generate source can be included by prefixing
117 // the module name with ":", for example ":libfoo_bindgen"
118 //
119 // If no source file is defined, a single generated source module can be defined to be used as the main source.
Ivan Lozano8a23fa42020-06-16 10:26:57 -0400120 Srcs []string `android:"path,arch_variant"`
121
Sam Delmerico63ca14e2023-09-25 12:13:17 +0000122 // Entry point that is passed to rustc to begin the compilation. E.g. main.rs or lib.rs.
123 // When this property is set,
124 // * sandboxing is enabled for this module, and
125 // * the srcs attribute is interpreted as a list of all source files potentially
126 // used in compilation, including the entrypoint, and
127 // * compile_data can be used to add additional files used in compilation that
128 // not directly used as source files.
129 Crate_root *string `android:"path,arch_variant"`
130
Thiébaud Weksteen9e8451e2020-08-13 12:55:59 +0200131 // name of the lint set that should be used to validate this module.
132 //
133 // Possible values are "default" (for using a sensible set of lints
134 // depending on the module's location), "android" (for the strictest
135 // lint set that applies to all Android platform code), "vendor" (for
136 // a relaxed set) and "none" (for ignoring all lint warnings and
137 // errors). The default value is "default".
138 Lints *string
Chih-Hung Hsiehefdd7ac2019-09-26 18:59:27 -0700139
Thiébaud Weksteenc44e7372021-04-07 14:53:06 +0200140 // flags to pass to rustc. To enable configuration options or features, use the "cfgs" or "features" properties.
Liz Kammereda93982021-04-20 10:15:41 -0400141 Flags []string `android:"arch_variant"`
Ivan Lozanoffee3342019-08-27 12:03:00 -0700142
143 // flags to pass to the linker
Liz Kammereda93982021-04-20 10:15:41 -0400144 Ld_flags []string `android:"arch_variant"`
Ivan Lozanoffee3342019-08-27 12:03:00 -0700145
Andrew Walbran52533232024-03-19 11:36:04 +0000146 // Rust crate dependencies to rename. Each entry should be a string of the form "dependencyname:alias".
147 //
148 // "dependencyname" here should be the name of the crate, not the Android module. This is
149 // equivalent to writing `alias = { package = "dependencyname" }` in a `Cargo.toml`.
150 Aliases []string
151
Ivan Lozanoffee3342019-08-27 12:03:00 -0700152 // list of rust rlib crate dependencies
Ivan Lozano9587f452025-01-08 03:17:19 +0000153 Rlibs proptools.Configurable[[]string] `android:"arch_variant"`
Ivan Lozanoffee3342019-08-27 12:03:00 -0700154
Vinh Tran4eeb2a92023-08-14 13:29:30 -0400155 // list of rust automatic crate dependencies.
156 // Rustlibs linkage is rlib for host targets and dylib for device targets.
Jihoon Kang127f95c2024-10-07 22:19:59 +0000157 Rustlibs proptools.Configurable[[]string] `android:"arch_variant"`
Matthew Maurer0f003b12020-06-29 14:34:06 -0700158
Ivan Lozanoffee3342019-08-27 12:03:00 -0700159 // list of rust proc_macro crate dependencies
Ivan Lozano9587f452025-01-08 03:17:19 +0000160 Proc_macros proptools.Configurable[[]string] `android:"arch_variant"`
Ivan Lozanoffee3342019-08-27 12:03:00 -0700161
162 // list of C shared library dependencies
Ivan Lozano9587f452025-01-08 03:17:19 +0000163 Shared_libs proptools.Configurable[[]string] `android:"arch_variant"`
Ivan Lozanoffee3342019-08-27 12:03:00 -0700164
Ivan Lozano63bb7682021-03-23 15:53:44 -0400165 // list of C static library dependencies. These dependencies do not normally propagate to dependents
166 // and may need to be redeclared. See whole_static_libs for bundling static dependencies into a library.
Ivan Lozano9587f452025-01-08 03:17:19 +0000167 Static_libs proptools.Configurable[[]string] `android:"arch_variant"`
Ivan Lozanoffee3342019-08-27 12:03:00 -0700168
Ivan Lozano63bb7682021-03-23 15:53:44 -0400169 // Similar to static_libs, but will bundle the static library dependency into a library. This is helpful
170 // to avoid having to redeclare the dependency for dependents of this library, but in some cases may also
171 // result in bloat if multiple dependencies all include the same static library whole.
172 //
173 // The common use case for this is when the static library is unlikely to be a dependency of other modules to avoid
174 // having to redeclare the static library dependency for every dependent module.
175 // If you are not sure what to, for rust_library modules most static dependencies should go in static_libraries,
176 // and for rust_ffi modules most static dependencies should go into whole_static_libraries.
177 //
178 // For rust_ffi static variants, these libraries will be included in the resulting static library archive.
179 //
180 // For rust_library rlib variants, these libraries will be bundled into the resulting rlib library. This will
181 // include all of the static libraries symbols in any dylibs or binaries which use this rlib as well.
Ivan Lozano9587f452025-01-08 03:17:19 +0000182 Whole_static_libs proptools.Configurable[[]string] `android:"arch_variant"`
Ivan Lozano63bb7682021-03-23 15:53:44 -0400183
Andrew Walbran797e4be2022-03-07 15:41:53 +0000184 // list of Rust system library dependencies.
185 //
186 // This is usually only needed when `no_stdlibs` is true, in which case it can be used to depend on system crates
187 // like `core` and `alloc`.
Ivan Lozano9587f452025-01-08 03:17:19 +0000188 Stdlibs proptools.Configurable[[]string] `android:"arch_variant"`
Andrew Walbran797e4be2022-03-07 15:41:53 +0000189
Ivan Lozano26ecd6c2020-07-31 13:40:31 -0400190 // crate name, required for modules which produce Rust libraries: rust_library, rust_ffi and SourceProvider
191 // modules which create library variants (rust_bindgen). This must be the expected extern crate name used in
192 // source, and is required to conform to an enforced format matching library output files (if the output file is
193 // lib<someName><suffix>, the crate_name property must be <someName>).
Ivan Lozanoffee3342019-08-27 12:03:00 -0700194 Crate_name string `android:"arch_variant"`
195
196 // list of features to enable for this crate
Jihoon Kang091ffd82024-10-03 01:13:24 +0000197 Features proptools.Configurable[[]string] `android:"arch_variant"`
Ivan Lozanoffee3342019-08-27 12:03:00 -0700198
Thiébaud Weksteenc44e7372021-04-07 14:53:06 +0200199 // list of configuration options to enable for this crate. To enable features, use the "features" property.
Cole Faustfdec8722024-05-22 11:38:29 -0700200 Cfgs proptools.Configurable[[]string] `android:"arch_variant"`
Thiébaud Weksteenc44e7372021-04-07 14:53:06 +0200201
Ivan Lozanoffee3342019-08-27 12:03:00 -0700202 // specific rust edition that should be used if the default version is not desired
203 Edition *string `android:"arch_variant"`
204
205 // sets name of the output
206 Stem *string `android:"arch_variant"`
207
208 // append to name of output
209 Suffix *string `android:"arch_variant"`
210
211 // install to a subdirectory of the default install path for the module
212 Relative_install_path *string `android:"arch_variant"`
Matthew Maurer99020b02019-10-31 10:44:40 -0700213
214 // whether to suppress inclusion of standard crates - defaults to false
Ivan Lozanoc5182022023-11-14 10:23:31 -0500215 No_stdlibs *bool `android:"arch_variant"`
Ivan Lozanoea086132020-12-08 14:43:00 -0500216
217 // Change the rustlibs linkage to select rlib linkage by default for device targets.
218 // Also link libstd as an rlib as well on device targets.
219 // Note: This is the default behavior for host targets.
220 //
221 // This is primarily meant for rust_binary and rust_ffi modules where the default
222 // linkage of libstd might need to be overridden in some use cases. This should
223 // generally be avoided with other module types since it may cause collisions at
Martin Geisler46329e92022-09-29 13:12:23 +0000224 // linkage if all dependencies of the root binary module do not link against libstd
Ivan Lozanoea086132020-12-08 14:43:00 -0500225 // the same way.
226 Prefer_rlib *bool `android:"arch_variant"`
Ivan Lozanoa9a1fc02021-08-11 15:13:43 -0400227
228 // Enables emitting certain Cargo environment variables. Only intended to be used for compatibility purposes.
229 // Will set CARGO_CRATE_NAME to the crate_name property's value.
230 // Will set CARGO_BIN_NAME to the output filename value without the extension.
231 Cargo_env_compat *bool
232
233 // If cargo_env_compat is true, sets the CARGO_PKG_VERSION env var to this value.
234 Cargo_pkg_version *string
Ivan Lozanoab586472024-05-15 10:59:47 -0400235
236 // Control whether LTO is used for the final (Rust) linkage. This does not impact
237 // cross-language LTO.
238 Lto struct {
239 // Whether thin LTO should be enabled. By default this is true.
240 // LTO provides such a large code size benefit for Rust, this should always
241 // be enabled for production builds unless there's a clear need to disable it.
242 Thin *bool `android:"arch_variant"`
243 } `android:"arch_variant"`
Ivan Lozanoffee3342019-08-27 12:03:00 -0700244}
245
246type baseCompiler struct {
Joel Galensonfa049382021-01-14 16:03:18 -0800247 Properties BaseCompilerProperties
Ivan Lozanoffee3342019-08-27 12:03:00 -0700248
249 // Install related
250 dir string
251 dir64 string
252 subDir string
253 relative string
Colin Cross70dda7e2019-10-01 22:05:35 -0700254 path android.InstallPath
Chih-Hung Hsieh9a4a7ba2019-12-12 19:36:05 -0800255 location installLocation
Ivan Lozano6cd99e62020-02-11 08:24:25 -0500256 sanitize *sanitize
Ivan Lozano8a23fa42020-06-16 10:26:57 -0400257
Joel Galensonfa049382021-01-14 16:03:18 -0800258 distFile android.OptionalPath
Ivan Lozano8d10fc32021-11-05 16:36:47 -0400259
Colin Cross5c1d5fb2023-11-15 12:39:40 -0800260 installDeps android.InstallPaths
261
Ivan Lozano8d10fc32021-11-05 16:36:47 -0400262 // unstripped output file.
263 unstrippedOutputFile android.Path
264
265 // stripped output file.
Thiébaud Weksteenfabaff62020-08-27 13:48:36 +0200266 strippedOutputFile android.OptionalPath
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100267
268 // If a crate has a source-generated dependency, a copy of the source file
269 // will be available in cargoOutDir (equivalent to Cargo OUT_DIR).
Matthew Maurercd416532023-11-20 17:52:01 +0000270 // This is stored internally because it may not be available during
271 // singleton-generation passes like rustdoc/rust_project.json, but should
272 // be stashed during initial generation.
273 cachedCargoOutDir android.ModuleOutPath
Matthew Maurera28404a2023-11-20 23:33:28 +0000274 // Calculated crate root cached internally because ModuleContext is not
275 // available to singleton targets like rustdoc/rust_project.json
276 cachedCrateRootPath android.Path
277 // If cachedCrateRootPath is nil after initialization, this will contain
278 // an explanation of why
279 cachedCrateRootError error
Ivan Lozanoffee3342019-08-27 12:03:00 -0700280}
281
Ivan Lozano26ecd6c2020-07-31 13:40:31 -0400282func (compiler *baseCompiler) Disabled() bool {
283 return false
284}
285
Ivan Lozanoab586472024-05-15 10:59:47 -0400286// Thin LTO is enabled by default.
287func (compiler *baseCompiler) Thinlto() bool {
288 return BoolDefault(compiler.Properties.Lto.Thin, true)
289}
290
Ivan Lozano26ecd6c2020-07-31 13:40:31 -0400291func (compiler *baseCompiler) SetDisabled() {
292 panic("baseCompiler does not implement SetDisabled()")
293}
294
Ivan Lozano9ef9cb82023-02-14 10:56:14 -0500295func (compiler *baseCompiler) noStdlibs() bool {
296 return Bool(compiler.Properties.No_stdlibs)
297}
298
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400299func (compiler *baseCompiler) coverageOutputZipPath() android.OptionalPath {
300 panic("baseCompiler does not implement coverageOutputZipPath()")
301}
302
Ivan Lozanoea086132020-12-08 14:43:00 -0500303func (compiler *baseCompiler) preferRlib() bool {
304 return Bool(compiler.Properties.Prefer_rlib)
305}
306
Andrew Walbran52533232024-03-19 11:36:04 +0000307func (compiler *baseCompiler) Aliases() map[string]string {
308 aliases := map[string]string{}
309 for _, entry := range compiler.Properties.Aliases {
310 dep, alias, found := strings.Cut(entry, ":")
311 if !found {
312 panic(fmt.Errorf("invalid aliases entry %q missing ':'", entry))
313 }
314 aliases[dep] = alias
315 }
316 return aliases
317}
318
Ivan Lozano806efd32024-12-11 21:38:53 +0000319func (compiler *baseCompiler) stdLinkage(device bool) RustLinkage {
Ivan Lozano2b081132020-09-08 12:46:52 -0400320 // For devices, we always link stdlibs in as dylibs by default.
Ivan Lozanoea086132020-12-08 14:43:00 -0500321 if compiler.preferRlib() {
322 return RlibLinkage
Ivan Lozano806efd32024-12-11 21:38:53 +0000323 } else if device {
Ivan Lozanodd055472020-09-28 13:22:45 -0400324 return DylibLinkage
Ivan Lozano2b081132020-09-08 12:46:52 -0400325 } else {
Ivan Lozanodd055472020-09-28 13:22:45 -0400326 return RlibLinkage
Ivan Lozano2b081132020-09-08 12:46:52 -0400327 }
Ivan Lozano042504f2020-08-18 14:31:23 -0400328}
329
Ivan Lozanoffee3342019-08-27 12:03:00 -0700330var _ compiler = (*baseCompiler)(nil)
331
Chih-Hung Hsieh9a4a7ba2019-12-12 19:36:05 -0800332func (compiler *baseCompiler) inData() bool {
333 return compiler.location == InstallInData
334}
335
Ivan Lozanoffee3342019-08-27 12:03:00 -0700336func (compiler *baseCompiler) compilerProps() []interface{} {
337 return []interface{}{&compiler.Properties}
338}
339
Ivan Lozano9587f452025-01-08 03:17:19 +0000340func (compiler *baseCompiler) baseCompilerProps() BaseCompilerProperties {
341 return compiler.Properties
342}
343
Ivan Lozano28ed8f42024-05-06 21:46:39 -0400344func cfgsToFlags(cfgs []string) []string {
Cole Faustfdec8722024-05-22 11:38:29 -0700345 flags := make([]string, 0, len(cfgs))
Ivan Lozano28ed8f42024-05-06 21:46:39 -0400346 for _, cfg := range cfgs {
Thiébaud Weksteenc44e7372021-04-07 14:53:06 +0200347 flags = append(flags, "--cfg '"+cfg+"'")
348 }
Ivan Lozano67eada32021-09-23 11:50:33 -0400349
Thiébaud Weksteenc44e7372021-04-07 14:53:06 +0200350 return flags
351}
352
Jihoon Kang091ffd82024-10-03 01:13:24 +0000353func (compiler *baseCompiler) features(ctx android.ConfigurableEvaluatorContext, module *Module) []string {
354 eval := module.ConfigurableEvaluator(ctx)
355 return compiler.Properties.Features.GetOrDefault(eval, nil)
Matthew Maurerdb72f7e2023-11-21 00:20:02 +0000356}
357
Jihoon Kang091ffd82024-10-03 01:13:24 +0000358func (compiler *baseCompiler) featuresToFlags(ctx android.ConfigurableEvaluatorContext, module *Module) []string {
Thiébaud Weksteenc44e7372021-04-07 14:53:06 +0200359 flags := []string{}
Jihoon Kang091ffd82024-10-03 01:13:24 +0000360 for _, feature := range compiler.features(ctx, module) {
Ivan Lozanoffee3342019-08-27 12:03:00 -0700361 flags = append(flags, "--cfg 'feature=\""+feature+"\"'")
362 }
Ivan Lozano67eada32021-09-23 11:50:33 -0400363
364 return flags
365}
366
Jihoon Kang091ffd82024-10-03 01:13:24 +0000367func (compiler *baseCompiler) featureFlags(ctx ModuleContext, module *Module, flags Flags) Flags {
368 flags.RustFlags = append(flags.RustFlags, compiler.featuresToFlags(ctx, module)...)
369 flags.RustdocFlags = append(flags.RustdocFlags, compiler.featuresToFlags(ctx, module)...)
Ivan Lozano67eada32021-09-23 11:50:33 -0400370
371 return flags
372}
373
Ivan Lozano28ed8f42024-05-06 21:46:39 -0400374func CommonDefaultCfgFlags(flags Flags, vendor bool, product bool) Flags {
375 var cfgs []string
376 if vendor || product {
377 cfgs = append(cfgs, "android_vndk")
378 if vendor {
379 cfgs = append(cfgs, "android_vendor")
380 } else if product {
381 cfgs = append(cfgs, "android_product")
Matthew Maurer65a54a82023-02-24 19:19:22 +0000382 }
Ivan Lozano67eada32021-09-23 11:50:33 -0400383 }
384
Ivan Lozano28ed8f42024-05-06 21:46:39 -0400385 flags.RustFlags = append(flags.RustFlags, cfgsToFlags(cfgs)...)
386 flags.RustdocFlags = append(flags.RustdocFlags, cfgsToFlags(cfgs)...)
387 return flags
388}
389
390func (compiler *baseCompiler) cfgFlags(ctx ModuleContext, flags Flags) Flags {
391 flags = CommonDefaultCfgFlags(flags, ctx.RustModule().InVendor(), ctx.RustModule().InProduct())
392
Cole Faustfdec8722024-05-22 11:38:29 -0700393 cfgFlags := cfgsToFlags(compiler.Properties.Cfgs.GetOrDefault(ctx, nil))
394 flags.RustFlags = append(flags.RustFlags, cfgFlags...)
395 flags.RustdocFlags = append(flags.RustdocFlags, cfgFlags...)
Ivan Lozano28ed8f42024-05-06 21:46:39 -0400396
397 return flags
398}
399
400func CommonDefaultFlags(ctx android.ModuleContext, toolchain config.Toolchain, flags Flags) Flags {
401 flags.GlobalRustFlags = append(flags.GlobalRustFlags, config.GlobalRustFlags...)
402 flags.GlobalRustFlags = append(flags.GlobalRustFlags, toolchain.ToolchainRustFlags())
403 flags.GlobalLinkFlags = append(flags.GlobalLinkFlags, toolchain.ToolchainLinkFlags())
404 flags.EmitXrefs = ctx.Config().EmitXrefRules()
405
406 if ctx.Host() && !ctx.Windows() {
407 flags.LinkFlags = append(flags.LinkFlags, cc.RpathFlags(ctx)...)
408 }
409
410 if ctx.Os() == android.Linux {
411 // Add -lc, -lrt, -ldl, -lpthread, -lm and -lgcc_s to glibc builds to match
412 // the default behavior of device builds.
413 flags.LinkFlags = append(flags.LinkFlags, config.LinuxHostGlobalLinkFlags...)
414 } else if ctx.Os() == android.Darwin {
415 // Add -lc, -ldl, -lpthread and -lm to glibc darwin builds to match the default
416 // behavior of device builds.
417 flags.LinkFlags = append(flags.LinkFlags,
418 "-lc",
419 "-ldl",
420 "-lpthread",
421 "-lm",
422 )
423 }
Ivan Lozanoffee3342019-08-27 12:03:00 -0700424 return flags
425}
426
427func (compiler *baseCompiler) compilerFlags(ctx ModuleContext, flags Flags) Flags {
428
Ivan Lozano28ed8f42024-05-06 21:46:39 -0400429 flags = CommonDefaultFlags(ctx, ctx.toolchain(), flags)
Thiébaud Weksteen9e8451e2020-08-13 12:55:59 +0200430 lintFlags, err := config.RustcLintsForDir(ctx.ModuleDir(), compiler.Properties.Lints)
431 if err != nil {
432 ctx.PropertyErrorf("lints", err.Error())
Chih-Hung Hsiehefdd7ac2019-09-26 18:59:27 -0700433 }
Ivan Lozano45a9e312021-07-27 12:29:12 -0400434
435 // linkage-related flags are disallowed.
436 for _, s := range compiler.Properties.Ld_flags {
437 if strings.HasPrefix(s, "-Wl,-l") || strings.HasPrefix(s, "-Wl,-L") {
438 ctx.PropertyErrorf("ld_flags", "'-Wl,-l' and '-Wl,-L' flags cannot be manually specified")
439 }
440 }
441 for _, s := range compiler.Properties.Flags {
442 if strings.HasPrefix(s, "-l") || strings.HasPrefix(s, "-L") {
443 ctx.PropertyErrorf("flags", "'-l' and '-L' flags cannot be manually specified")
444 }
445 if strings.HasPrefix(s, "--extern") {
446 ctx.PropertyErrorf("flags", "'--extern' flag cannot be manually specified")
447 }
448 if strings.HasPrefix(s, "-Clink-args=") || strings.HasPrefix(s, "-C link-args=") {
449 ctx.PropertyErrorf("flags", "'-C link-args' flag cannot be manually specified")
450 }
451 }
452
Thiébaud Weksteen9e8451e2020-08-13 12:55:59 +0200453 flags.RustFlags = append(flags.RustFlags, lintFlags)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700454 flags.RustFlags = append(flags.RustFlags, compiler.Properties.Flags...)
Thiébaud Weksteene81c9242020-08-03 10:46:28 +0200455 flags.RustFlags = append(flags.RustFlags, "--edition="+compiler.edition())
Dan Albert06feee92021-03-19 15:06:02 -0700456 flags.RustdocFlags = append(flags.RustdocFlags, "--edition="+compiler.edition())
Ivan Lozanoffee3342019-08-27 12:03:00 -0700457 flags.LinkFlags = append(flags.LinkFlags, compiler.Properties.Ld_flags...)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700458
Ivan Lozanoffee3342019-08-27 12:03:00 -0700459 return flags
460}
461
Sasha Smundaka76acba2022-04-18 20:12:56 -0700462func (compiler *baseCompiler) compile(ctx ModuleContext, flags Flags, deps PathDeps) buildOutput {
Ivan Lozanoffee3342019-08-27 12:03:00 -0700463 panic(fmt.Errorf("baseCrater doesn't know how to crate things!"))
464}
465
Dan Albert06feee92021-03-19 15:06:02 -0700466func (compiler *baseCompiler) rustdoc(ctx ModuleContext, flags Flags,
467 deps PathDeps) android.OptionalPath {
468
469 return android.OptionalPath{}
470}
471
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100472func (compiler *baseCompiler) initialize(ctx ModuleContext) {
Matthew Maurercd416532023-11-20 17:52:01 +0000473 compiler.cachedCargoOutDir = android.PathForModuleOut(ctx, genSubDir)
Matthew Maurera28404a2023-11-20 23:33:28 +0000474 if compiler.Properties.Crate_root == nil {
475 compiler.cachedCrateRootPath, compiler.cachedCrateRootError = srcPathFromModuleSrcs(ctx, compiler.Properties.Srcs)
476 } else {
477 compiler.cachedCrateRootPath = android.PathForModuleSrc(ctx, *compiler.Properties.Crate_root)
478 compiler.cachedCrateRootError = nil
479 }
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100480}
481
Matthew Maurercd416532023-11-20 17:52:01 +0000482func (compiler *baseCompiler) cargoOutDir() android.OptionalPath {
483 return android.OptionalPathForPath(compiler.cachedCargoOutDir)
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100484}
485
Matthew Maurercd416532023-11-20 17:52:01 +0000486func (compiler *baseCompiler) cargoEnvCompat() bool {
Ivan Lozanoa9a1fc02021-08-11 15:13:43 -0400487 return Bool(compiler.Properties.Cargo_env_compat)
488}
489
Matthew Maurercd416532023-11-20 17:52:01 +0000490func (compiler *baseCompiler) cargoPkgVersion() string {
Ivan Lozanoa9a1fc02021-08-11 15:13:43 -0400491 return String(compiler.Properties.Cargo_pkg_version)
492}
493
Ivan Lozano8d10fc32021-11-05 16:36:47 -0400494func (compiler *baseCompiler) unstrippedOutputFilePath() android.Path {
495 return compiler.unstrippedOutputFile
496}
497
Jiyong Parke54f07e2021-04-07 15:08:04 +0900498func (compiler *baseCompiler) strippedOutputFilePath() android.OptionalPath {
499 return compiler.strippedOutputFile
500}
501
Ivan Lozanoffee3342019-08-27 12:03:00 -0700502func (compiler *baseCompiler) compilerDeps(ctx DepsContext, deps Deps) Deps {
Ivan Lozano9587f452025-01-08 03:17:19 +0000503 deps.Rlibs = append(deps.Rlibs, compiler.Properties.Rlibs.GetOrDefault(ctx, nil)...)
Jihoon Kang127f95c2024-10-07 22:19:59 +0000504 deps.Rustlibs = append(deps.Rustlibs, compiler.Properties.Rustlibs.GetOrDefault(ctx, nil)...)
Ivan Lozano9587f452025-01-08 03:17:19 +0000505 deps.ProcMacros = append(deps.ProcMacros, compiler.Properties.Proc_macros.GetOrDefault(ctx, nil)...)
506 deps.StaticLibs = append(deps.StaticLibs, compiler.Properties.Static_libs.GetOrDefault(ctx, nil)...)
507 deps.WholeStaticLibs = append(deps.WholeStaticLibs, compiler.Properties.Whole_static_libs.GetOrDefault(ctx, nil)...)
508 deps.SharedLibs = append(deps.SharedLibs, compiler.Properties.Shared_libs.GetOrDefault(ctx, nil)...)
509 deps.Stdlibs = append(deps.Stdlibs, compiler.Properties.Stdlibs.GetOrDefault(ctx, nil)...)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700510
Matthew Maurer99020b02019-10-31 10:44:40 -0700511 if !Bool(compiler.Properties.No_stdlibs) {
512 for _, stdlib := range config.Stdlibs {
Colin Crossa8941ec2022-07-01 11:17:22 -0700513 // If we're building for the build host, use the prebuilt stdlibs, unless the host
514 // is linux_bionic which doesn't have prebuilts.
515 if ctx.Host() && !ctx.Target().HostCross && ctx.Target().Os != android.LinuxBionic {
Ivan Lozanofba2aa22021-11-11 09:29:07 -0500516 stdlib = "prebuilt_" + stdlib
Matthew Maurer99020b02019-10-31 10:44:40 -0700517 }
Ivan Lozano2b081132020-09-08 12:46:52 -0400518 deps.Stdlibs = append(deps.Stdlibs, stdlib)
Matthew Maurer99020b02019-10-31 10:44:40 -0700519 }
520 }
Ivan Lozanoffee3342019-08-27 12:03:00 -0700521 return deps
522}
523
Thiébaud Weksteenf1ff54a2021-03-22 14:24:54 +0100524func bionicDeps(ctx DepsContext, deps Deps, static bool) Deps {
Ivan Lozanobf63d002020-10-02 10:03:23 -0400525 bionicLibs := []string{}
526 bionicLibs = append(bionicLibs, "liblog")
527 bionicLibs = append(bionicLibs, "libc")
528 bionicLibs = append(bionicLibs, "libm")
529 bionicLibs = append(bionicLibs, "libdl")
530
531 if static {
532 deps.StaticLibs = append(deps.StaticLibs, bionicLibs...)
533 } else {
534 deps.SharedLibs = append(deps.SharedLibs, bionicLibs...)
535 }
Ivan Lozano8711c5c2021-08-13 13:14:06 -0400536 if ctx.RustModule().StaticExecutable() {
537 deps.StaticLibs = append(deps.StaticLibs, "libunwind")
538 }
Thiébaud Weksteenf1ff54a2021-03-22 14:24:54 +0100539 if libRuntimeBuiltins := config.BuiltinsRuntimeLibrary(ctx.toolchain()); libRuntimeBuiltins != "" {
540 deps.StaticLibs = append(deps.StaticLibs, libRuntimeBuiltins)
541 }
Ivan Lozanof1c84332019-09-20 11:00:37 -0700542 return deps
543}
544
Colin Crosse32f0932022-01-23 20:48:36 -0800545func muslDeps(ctx DepsContext, deps Deps, static bool) Deps {
546 muslLibs := []string{"libc_musl"}
547 if static {
548 deps.StaticLibs = append(deps.StaticLibs, muslLibs...)
549 } else {
550 deps.SharedLibs = append(deps.SharedLibs, muslLibs...)
551 }
552 if libRuntimeBuiltins := config.BuiltinsRuntimeLibrary(ctx.toolchain()); libRuntimeBuiltins != "" {
553 deps.StaticLibs = append(deps.StaticLibs, libRuntimeBuiltins)
554 }
555
556 return deps
557}
558
Ivan Lozanoffee3342019-08-27 12:03:00 -0700559func (compiler *baseCompiler) crateName() string {
560 return compiler.Properties.Crate_name
561}
562
Ivan Lozanod7586b62021-04-01 09:49:36 -0400563func (compiler *baseCompiler) everInstallable() bool {
564 // Most modules are installable, so return true by default.
565 return true
566}
567
Colin Cross70dda7e2019-10-01 22:05:35 -0700568func (compiler *baseCompiler) installDir(ctx ModuleContext) android.InstallPath {
Ivan Lozanoffee3342019-08-27 12:03:00 -0700569 dir := compiler.dir
570 if ctx.toolchain().Is64Bit() && compiler.dir64 != "" {
571 dir = compiler.dir64
572 }
Ivan Lozanod6fdca82020-04-07 12:30:33 -0400573 if ctx.Target().NativeBridge == android.NativeBridgeEnabled {
574 dir = filepath.Join(dir, ctx.Target().NativeBridgeRelativePath)
575 }
576 if !ctx.Host() && ctx.Config().HasMultilibConflict(ctx.Arch().ArchType) {
Ivan Lozanoffee3342019-08-27 12:03:00 -0700577 dir = filepath.Join(dir, ctx.Arch().ArchType.String())
578 }
Ivan Lozanoc08897c2021-04-02 12:41:32 -0400579
Kiyoung Kimaa394802024-01-08 12:55:45 +0900580 if compiler.location == InstallInData && ctx.RustModule().InVendorOrProduct() {
Matthew Maurer9f59e8d2021-08-19 13:10:05 -0700581 if ctx.RustModule().InProduct() {
582 dir = filepath.Join(dir, "product")
583 } else if ctx.RustModule().InVendor() {
584 dir = filepath.Join(dir, "vendor")
585 } else {
586 ctx.ModuleErrorf("Unknown data+VNDK installation kind")
587 }
Ivan Lozanoc08897c2021-04-02 12:41:32 -0400588 }
Matthew Maurer9f59e8d2021-08-19 13:10:05 -0700589
Ivan Lozanoffee3342019-08-27 12:03:00 -0700590 return android.PathForModuleInstall(ctx, dir, compiler.subDir,
591 compiler.relativeInstallPath(), compiler.relative)
592}
593
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400594func (compiler *baseCompiler) nativeCoverage() bool {
595 return false
596}
597
Thiébaud Weksteenfabaff62020-08-27 13:48:36 +0200598func (compiler *baseCompiler) install(ctx ModuleContext) {
Jiyong Parke54f07e2021-04-07 15:08:04 +0900599 path := ctx.RustModule().OutputFile()
Colin Cross5c1d5fb2023-11-15 12:39:40 -0800600 compiler.path = ctx.InstallFile(compiler.installDir(ctx), path.Path().Base(), path.Path(), compiler.installDeps...)
601}
602
603func (compiler *baseCompiler) installTestData(ctx ModuleContext, data []android.DataPath) {
604 installedData := ctx.InstallTestData(compiler.installDir(ctx), data)
605 compiler.installDeps = append(compiler.installDeps, installedData...)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700606}
607
Ivan Lozano28ed8f42024-05-06 21:46:39 -0400608func (compiler *baseCompiler) getStem(ctx android.ModuleContext) string {
Ivan Lozanoffee3342019-08-27 12:03:00 -0700609 return compiler.getStemWithoutSuffix(ctx) + String(compiler.Properties.Suffix)
610}
611
Ivan Lozano28ed8f42024-05-06 21:46:39 -0400612func (compiler *baseCompiler) getStemWithoutSuffix(ctx android.BaseModuleContext) string {
Thiébaud Weksteen1f7f70f2020-06-24 11:32:48 +0200613 stem := ctx.ModuleName()
Ivan Lozanoffee3342019-08-27 12:03:00 -0700614 if String(compiler.Properties.Stem) != "" {
615 stem = String(compiler.Properties.Stem)
616 }
617
618 return stem
619}
Ivan Lozanoad8b18b2019-10-31 19:38:29 -0700620
Ivan Lozanoffee3342019-08-27 12:03:00 -0700621func (compiler *baseCompiler) relativeInstallPath() string {
622 return String(compiler.Properties.Relative_install_path)
623}
624
Matthew Maurera28404a2023-11-20 23:33:28 +0000625func (compiler *baseCompiler) checkedCrateRootPath() (android.Path, error) {
626 return compiler.cachedCrateRootPath, compiler.cachedCrateRootError
627}
Seth Moore3afac0b2021-10-13 15:32:18 -0700628
Matthew Maurera28404a2023-11-20 23:33:28 +0000629func crateRootPath(ctx ModuleContext, compiler compiler) android.Path {
630 root, err := compiler.checkedCrateRootPath()
631 if err != nil {
632 ctx.PropertyErrorf("srcs", err.Error())
Matthew Maurerd221d312023-11-20 21:02:40 +0000633 }
Matthew Maurera28404a2023-11-20 23:33:28 +0000634 return root
Matthew Maurerd221d312023-11-20 21:02:40 +0000635}
636
Ivan Lozano43845682020-07-09 21:03:28 -0400637// Returns the Path for the main source file along with Paths for generated source files from modules listed in srcs.
Matthew Maurera28404a2023-11-20 23:33:28 +0000638func srcPathFromModuleSrcs(ctx ModuleContext, srcs []string) (android.Path, error) {
Chih-Hung Hsiehbbd25ae2020-05-15 17:36:30 -0700639 // The srcs can contain strings with prefix ":".
640 // They are dependent modules of this module, with android.SourceDepTag.
641 // They are not the main source file compiled by rustc.
642 numSrcs := 0
643 srcIndex := 0
644 for i, s := range srcs {
645 if android.SrcIsModule(s) == "" {
646 numSrcs++
647 srcIndex = i
648 }
Ivan Lozanoffee3342019-08-27 12:03:00 -0700649 }
Ivan Lozanoe4db0032021-08-11 13:39:33 -0400650 if numSrcs > 1 {
Matthew Maurera28404a2023-11-20 23:33:28 +0000651 return nil, errors.New(incorrectSourcesError)
Chih-Hung Hsiehbbd25ae2020-05-15 17:36:30 -0700652 }
Ivan Lozanoe4db0032021-08-11 13:39:33 -0400653
654 // If a main source file is not provided we expect only a single SourceProvider module to be defined
655 // within srcs, with the expectation that the first source it provides is the entry point.
Chih-Hung Hsiehbbd25ae2020-05-15 17:36:30 -0700656 if srcIndex != 0 {
Matthew Maurera28404a2023-11-20 23:33:28 +0000657 return nil, errors.New("main source file must be the first in srcs")
Ivan Lozanoe4db0032021-08-11 13:39:33 -0400658 } else if numSrcs > 1 {
Matthew Maurera28404a2023-11-20 23:33:28 +0000659 return nil, errors.New("only a single generated source module can be defined without a main source file.")
Chih-Hung Hsiehbbd25ae2020-05-15 17:36:30 -0700660 }
Ivan Lozanoe4db0032021-08-11 13:39:33 -0400661
Sam Delmerico63ca14e2023-09-25 12:13:17 +0000662 // TODO: b/297264540 - once all modules are sandboxed, we need to select the proper
663 // entry point file from Srcs rather than taking the first one
Chih-Hung Hsiehbbd25ae2020-05-15 17:36:30 -0700664 paths := android.PathsForModuleSrc(ctx, srcs)
Matthew Maurera28404a2023-11-20 23:33:28 +0000665 if len(paths) == 0 {
666 return nil, errors.New("srcs must not be empty")
667 }
668 return paths[srcIndex], nil
Ivan Lozanoffee3342019-08-27 12:03:00 -0700669}