compiler.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. // 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. package rust
  15. import (
  16. "fmt"
  17. "path/filepath"
  18. "strings"
  19. "github.com/google/blueprint/proptools"
  20. "android/soong/android"
  21. "android/soong/rust/config"
  22. )
  23. type RustLinkage int
  24. const (
  25. DefaultLinkage RustLinkage = iota
  26. RlibLinkage
  27. DylibLinkage
  28. )
  29. func (compiler *baseCompiler) edition() string {
  30. return proptools.StringDefault(compiler.Properties.Edition, config.DefaultEdition)
  31. }
  32. func (compiler *baseCompiler) setNoStdlibs() {
  33. compiler.Properties.No_stdlibs = proptools.BoolPtr(true)
  34. }
  35. func (compiler *baseCompiler) disableLints() {
  36. compiler.Properties.Lints = proptools.StringPtr("none")
  37. }
  38. func NewBaseCompiler(dir, dir64 string, location installLocation) *baseCompiler {
  39. return &baseCompiler{
  40. Properties: BaseCompilerProperties{},
  41. dir: dir,
  42. dir64: dir64,
  43. location: location,
  44. }
  45. }
  46. type installLocation int
  47. const (
  48. InstallInSystem installLocation = 0
  49. InstallInData = iota
  50. incorrectSourcesError = "srcs can only contain one path for a rust file and source providers prefixed by \":\""
  51. genSubDir = "out/"
  52. )
  53. type BaseCompilerProperties struct {
  54. // path to the source file that is the main entry point of the program (e.g. main.rs or lib.rs).
  55. // Only a single source file can be defined. Modules which generate source can be included by prefixing
  56. // the module name with ":", for example ":libfoo_bindgen"
  57. //
  58. // If no source file is defined, a single generated source module can be defined to be used as the main source.
  59. Srcs []string `android:"path,arch_variant"`
  60. // name of the lint set that should be used to validate this module.
  61. //
  62. // Possible values are "default" (for using a sensible set of lints
  63. // depending on the module's location), "android" (for the strictest
  64. // lint set that applies to all Android platform code), "vendor" (for
  65. // a relaxed set) and "none" (for ignoring all lint warnings and
  66. // errors). The default value is "default".
  67. Lints *string
  68. // flags to pass to rustc. To enable configuration options or features, use the "cfgs" or "features" properties.
  69. Flags []string `android:"arch_variant"`
  70. // flags to pass to the linker
  71. Ld_flags []string `android:"arch_variant"`
  72. // list of rust rlib crate dependencies
  73. Rlibs []string `android:"arch_variant"`
  74. // list of rust dylib crate dependencies
  75. Dylibs []string `android:"arch_variant"`
  76. // list of rust automatic crate dependencies
  77. Rustlibs []string `android:"arch_variant"`
  78. // list of rust proc_macro crate dependencies
  79. Proc_macros []string `android:"arch_variant"`
  80. // list of C shared library dependencies
  81. Shared_libs []string `android:"arch_variant"`
  82. // list of C static library dependencies. These dependencies do not normally propagate to dependents
  83. // and may need to be redeclared. See whole_static_libs for bundling static dependencies into a library.
  84. Static_libs []string `android:"arch_variant"`
  85. // Similar to static_libs, but will bundle the static library dependency into a library. This is helpful
  86. // to avoid having to redeclare the dependency for dependents of this library, but in some cases may also
  87. // result in bloat if multiple dependencies all include the same static library whole.
  88. //
  89. // The common use case for this is when the static library is unlikely to be a dependency of other modules to avoid
  90. // having to redeclare the static library dependency for every dependent module.
  91. // If you are not sure what to, for rust_library modules most static dependencies should go in static_libraries,
  92. // and for rust_ffi modules most static dependencies should go into whole_static_libraries.
  93. //
  94. // For rust_ffi static variants, these libraries will be included in the resulting static library archive.
  95. //
  96. // For rust_library rlib variants, these libraries will be bundled into the resulting rlib library. This will
  97. // include all of the static libraries symbols in any dylibs or binaries which use this rlib as well.
  98. Whole_static_libs []string `android:"arch_variant"`
  99. // crate name, required for modules which produce Rust libraries: rust_library, rust_ffi and SourceProvider
  100. // modules which create library variants (rust_bindgen). This must be the expected extern crate name used in
  101. // source, and is required to conform to an enforced format matching library output files (if the output file is
  102. // lib<someName><suffix>, the crate_name property must be <someName>).
  103. Crate_name string `android:"arch_variant"`
  104. // list of features to enable for this crate
  105. Features []string `android:"arch_variant"`
  106. // list of configuration options to enable for this crate. To enable features, use the "features" property.
  107. Cfgs []string `android:"arch_variant"`
  108. // specific rust edition that should be used if the default version is not desired
  109. Edition *string `android:"arch_variant"`
  110. // sets name of the output
  111. Stem *string `android:"arch_variant"`
  112. // append to name of output
  113. Suffix *string `android:"arch_variant"`
  114. // install to a subdirectory of the default install path for the module
  115. Relative_install_path *string `android:"arch_variant"`
  116. // whether to suppress inclusion of standard crates - defaults to false
  117. No_stdlibs *bool
  118. // Change the rustlibs linkage to select rlib linkage by default for device targets.
  119. // Also link libstd as an rlib as well on device targets.
  120. // Note: This is the default behavior for host targets.
  121. //
  122. // This is primarily meant for rust_binary and rust_ffi modules where the default
  123. // linkage of libstd might need to be overridden in some use cases. This should
  124. // generally be avoided with other module types since it may cause collisions at
  125. // linkage if all dependencies of the root binary module do not link against libstd\
  126. // the same way.
  127. Prefer_rlib *bool `android:"arch_variant"`
  128. // Enables emitting certain Cargo environment variables. Only intended to be used for compatibility purposes.
  129. // Will set CARGO_CRATE_NAME to the crate_name property's value.
  130. // Will set CARGO_BIN_NAME to the output filename value without the extension.
  131. Cargo_env_compat *bool
  132. // If cargo_env_compat is true, sets the CARGO_PKG_VERSION env var to this value.
  133. Cargo_pkg_version *string
  134. }
  135. type baseCompiler struct {
  136. Properties BaseCompilerProperties
  137. // Install related
  138. dir string
  139. dir64 string
  140. subDir string
  141. relative string
  142. path android.InstallPath
  143. location installLocation
  144. sanitize *sanitize
  145. distFile android.OptionalPath
  146. // Stripped output file. If Valid(), this file will be installed instead of outputFile.
  147. strippedOutputFile android.OptionalPath
  148. // If a crate has a source-generated dependency, a copy of the source file
  149. // will be available in cargoOutDir (equivalent to Cargo OUT_DIR).
  150. cargoOutDir android.ModuleOutPath
  151. }
  152. func (compiler *baseCompiler) Disabled() bool {
  153. return false
  154. }
  155. func (compiler *baseCompiler) SetDisabled() {
  156. panic("baseCompiler does not implement SetDisabled()")
  157. }
  158. func (compiler *baseCompiler) coverageOutputZipPath() android.OptionalPath {
  159. panic("baseCompiler does not implement coverageOutputZipPath()")
  160. }
  161. func (compiler *baseCompiler) preferRlib() bool {
  162. return Bool(compiler.Properties.Prefer_rlib)
  163. }
  164. func (compiler *baseCompiler) stdLinkage(ctx *depsContext) RustLinkage {
  165. // For devices, we always link stdlibs in as dylibs by default.
  166. if compiler.preferRlib() {
  167. return RlibLinkage
  168. } else if ctx.Device() {
  169. return DylibLinkage
  170. } else {
  171. return RlibLinkage
  172. }
  173. }
  174. var _ compiler = (*baseCompiler)(nil)
  175. func (compiler *baseCompiler) inData() bool {
  176. return compiler.location == InstallInData
  177. }
  178. func (compiler *baseCompiler) compilerProps() []interface{} {
  179. return []interface{}{&compiler.Properties}
  180. }
  181. func (compiler *baseCompiler) cfgsToFlags() []string {
  182. flags := []string{}
  183. for _, cfg := range compiler.Properties.Cfgs {
  184. flags = append(flags, "--cfg '"+cfg+"'")
  185. }
  186. return flags
  187. }
  188. func (compiler *baseCompiler) featuresToFlags() []string {
  189. flags := []string{}
  190. for _, feature := range compiler.Properties.Features {
  191. flags = append(flags, "--cfg 'feature=\""+feature+"\"'")
  192. }
  193. return flags
  194. }
  195. func (compiler *baseCompiler) featureFlags(ctx ModuleContext, flags Flags) Flags {
  196. flags.RustFlags = append(flags.RustFlags, compiler.featuresToFlags()...)
  197. flags.RustdocFlags = append(flags.RustdocFlags, compiler.featuresToFlags()...)
  198. return flags
  199. }
  200. func (compiler *baseCompiler) cfgFlags(ctx ModuleContext, flags Flags) Flags {
  201. if ctx.RustModule().UseVndk() {
  202. compiler.Properties.Cfgs = append(compiler.Properties.Cfgs, "android_vndk")
  203. }
  204. flags.RustFlags = append(flags.RustFlags, compiler.cfgsToFlags()...)
  205. flags.RustdocFlags = append(flags.RustdocFlags, compiler.cfgsToFlags()...)
  206. return flags
  207. }
  208. func (compiler *baseCompiler) compilerFlags(ctx ModuleContext, flags Flags) Flags {
  209. lintFlags, err := config.RustcLintsForDir(ctx.ModuleDir(), compiler.Properties.Lints)
  210. if err != nil {
  211. ctx.PropertyErrorf("lints", err.Error())
  212. }
  213. // linkage-related flags are disallowed.
  214. for _, s := range compiler.Properties.Ld_flags {
  215. if strings.HasPrefix(s, "-Wl,-l") || strings.HasPrefix(s, "-Wl,-L") {
  216. ctx.PropertyErrorf("ld_flags", "'-Wl,-l' and '-Wl,-L' flags cannot be manually specified")
  217. }
  218. }
  219. for _, s := range compiler.Properties.Flags {
  220. if strings.HasPrefix(s, "-l") || strings.HasPrefix(s, "-L") {
  221. ctx.PropertyErrorf("flags", "'-l' and '-L' flags cannot be manually specified")
  222. }
  223. if strings.HasPrefix(s, "--extern") {
  224. ctx.PropertyErrorf("flags", "'--extern' flag cannot be manually specified")
  225. }
  226. if strings.HasPrefix(s, "-Clink-args=") || strings.HasPrefix(s, "-C link-args=") {
  227. ctx.PropertyErrorf("flags", "'-C link-args' flag cannot be manually specified")
  228. }
  229. }
  230. flags.RustFlags = append(flags.RustFlags, lintFlags)
  231. flags.RustFlags = append(flags.RustFlags, compiler.Properties.Flags...)
  232. flags.RustFlags = append(flags.RustFlags, "--edition="+compiler.edition())
  233. flags.RustdocFlags = append(flags.RustdocFlags, "--edition="+compiler.edition())
  234. flags.LinkFlags = append(flags.LinkFlags, compiler.Properties.Ld_flags...)
  235. flags.GlobalRustFlags = append(flags.GlobalRustFlags, config.GlobalRustFlags...)
  236. flags.GlobalRustFlags = append(flags.GlobalRustFlags, ctx.toolchain().ToolchainRustFlags())
  237. flags.GlobalLinkFlags = append(flags.GlobalLinkFlags, ctx.toolchain().ToolchainLinkFlags())
  238. if ctx.Host() && !ctx.Windows() {
  239. rpathPrefix := `\$$ORIGIN/`
  240. if ctx.Darwin() {
  241. rpathPrefix = "@loader_path/"
  242. }
  243. var rpath string
  244. if ctx.toolchain().Is64Bit() {
  245. rpath = "lib64"
  246. } else {
  247. rpath = "lib"
  248. }
  249. flags.LinkFlags = append(flags.LinkFlags, "-Wl,-rpath,"+rpathPrefix+rpath)
  250. flags.LinkFlags = append(flags.LinkFlags, "-Wl,-rpath,"+rpathPrefix+"../"+rpath)
  251. }
  252. return flags
  253. }
  254. func (compiler *baseCompiler) compile(ctx ModuleContext, flags Flags, deps PathDeps) android.Path {
  255. panic(fmt.Errorf("baseCrater doesn't know how to crate things!"))
  256. }
  257. func (compiler *baseCompiler) rustdoc(ctx ModuleContext, flags Flags,
  258. deps PathDeps) android.OptionalPath {
  259. return android.OptionalPath{}
  260. }
  261. func (compiler *baseCompiler) initialize(ctx ModuleContext) {
  262. compiler.cargoOutDir = android.PathForModuleOut(ctx, genSubDir)
  263. }
  264. func (compiler *baseCompiler) CargoOutDir() android.OptionalPath {
  265. return android.OptionalPathForPath(compiler.cargoOutDir)
  266. }
  267. func (compiler *baseCompiler) CargoEnvCompat() bool {
  268. return Bool(compiler.Properties.Cargo_env_compat)
  269. }
  270. func (compiler *baseCompiler) CargoPkgVersion() string {
  271. return String(compiler.Properties.Cargo_pkg_version)
  272. }
  273. func (compiler *baseCompiler) strippedOutputFilePath() android.OptionalPath {
  274. return compiler.strippedOutputFile
  275. }
  276. func (compiler *baseCompiler) compilerDeps(ctx DepsContext, deps Deps) Deps {
  277. deps.Rlibs = append(deps.Rlibs, compiler.Properties.Rlibs...)
  278. deps.Dylibs = append(deps.Dylibs, compiler.Properties.Dylibs...)
  279. deps.Rustlibs = append(deps.Rustlibs, compiler.Properties.Rustlibs...)
  280. deps.ProcMacros = append(deps.ProcMacros, compiler.Properties.Proc_macros...)
  281. deps.StaticLibs = append(deps.StaticLibs, compiler.Properties.Static_libs...)
  282. deps.WholeStaticLibs = append(deps.WholeStaticLibs, compiler.Properties.Whole_static_libs...)
  283. deps.SharedLibs = append(deps.SharedLibs, compiler.Properties.Shared_libs...)
  284. if !Bool(compiler.Properties.No_stdlibs) {
  285. for _, stdlib := range config.Stdlibs {
  286. // If we're building for the primary arch of the build host, use the compiler's stdlibs
  287. if ctx.Target().Os == ctx.Config().BuildOS {
  288. stdlib = stdlib + "_" + ctx.toolchain().RustTriple()
  289. }
  290. deps.Stdlibs = append(deps.Stdlibs, stdlib)
  291. }
  292. }
  293. return deps
  294. }
  295. func bionicDeps(ctx DepsContext, deps Deps, static bool) Deps {
  296. bionicLibs := []string{}
  297. bionicLibs = append(bionicLibs, "liblog")
  298. bionicLibs = append(bionicLibs, "libc")
  299. bionicLibs = append(bionicLibs, "libm")
  300. bionicLibs = append(bionicLibs, "libdl")
  301. if static {
  302. deps.StaticLibs = append(deps.StaticLibs, bionicLibs...)
  303. } else {
  304. deps.SharedLibs = append(deps.SharedLibs, bionicLibs...)
  305. }
  306. if ctx.RustModule().StaticExecutable() {
  307. deps.StaticLibs = append(deps.StaticLibs, "libunwind")
  308. }
  309. if libRuntimeBuiltins := config.BuiltinsRuntimeLibrary(ctx.toolchain()); libRuntimeBuiltins != "" {
  310. deps.StaticLibs = append(deps.StaticLibs, libRuntimeBuiltins)
  311. }
  312. return deps
  313. }
  314. func (compiler *baseCompiler) crateName() string {
  315. return compiler.Properties.Crate_name
  316. }
  317. func (compiler *baseCompiler) everInstallable() bool {
  318. // Most modules are installable, so return true by default.
  319. return true
  320. }
  321. func (compiler *baseCompiler) installDir(ctx ModuleContext) android.InstallPath {
  322. dir := compiler.dir
  323. if ctx.toolchain().Is64Bit() && compiler.dir64 != "" {
  324. dir = compiler.dir64
  325. }
  326. if ctx.Target().NativeBridge == android.NativeBridgeEnabled {
  327. dir = filepath.Join(dir, ctx.Target().NativeBridgeRelativePath)
  328. }
  329. if !ctx.Host() && ctx.Config().HasMultilibConflict(ctx.Arch().ArchType) {
  330. dir = filepath.Join(dir, ctx.Arch().ArchType.String())
  331. }
  332. if compiler.location == InstallInData && ctx.RustModule().UseVndk() {
  333. if ctx.RustModule().InProduct() {
  334. dir = filepath.Join(dir, "product")
  335. } else if ctx.RustModule().InVendor() {
  336. dir = filepath.Join(dir, "vendor")
  337. } else {
  338. ctx.ModuleErrorf("Unknown data+VNDK installation kind")
  339. }
  340. }
  341. return android.PathForModuleInstall(ctx, dir, compiler.subDir,
  342. compiler.relativeInstallPath(), compiler.relative)
  343. }
  344. func (compiler *baseCompiler) nativeCoverage() bool {
  345. return false
  346. }
  347. func (compiler *baseCompiler) install(ctx ModuleContext) {
  348. path := ctx.RustModule().OutputFile()
  349. compiler.path = ctx.InstallFile(compiler.installDir(ctx), path.Path().Base(), path.Path())
  350. }
  351. func (compiler *baseCompiler) getStem(ctx ModuleContext) string {
  352. return compiler.getStemWithoutSuffix(ctx) + String(compiler.Properties.Suffix)
  353. }
  354. func (compiler *baseCompiler) getStemWithoutSuffix(ctx BaseModuleContext) string {
  355. stem := ctx.ModuleName()
  356. if String(compiler.Properties.Stem) != "" {
  357. stem = String(compiler.Properties.Stem)
  358. }
  359. return stem
  360. }
  361. func (compiler *baseCompiler) relativeInstallPath() string {
  362. return String(compiler.Properties.Relative_install_path)
  363. }
  364. // Returns the Path for the main source file along with Paths for generated source files from modules listed in srcs.
  365. func srcPathFromModuleSrcs(ctx ModuleContext, srcs []string) (android.Path, android.Paths) {
  366. if len(srcs) == 0 {
  367. ctx.PropertyErrorf("srcs", "srcs must not be empty")
  368. }
  369. // The srcs can contain strings with prefix ":".
  370. // They are dependent modules of this module, with android.SourceDepTag.
  371. // They are not the main source file compiled by rustc.
  372. numSrcs := 0
  373. srcIndex := 0
  374. for i, s := range srcs {
  375. if android.SrcIsModule(s) == "" {
  376. numSrcs++
  377. srcIndex = i
  378. }
  379. }
  380. if numSrcs > 1 {
  381. ctx.PropertyErrorf("srcs", incorrectSourcesError)
  382. }
  383. // If a main source file is not provided we expect only a single SourceProvider module to be defined
  384. // within srcs, with the expectation that the first source it provides is the entry point.
  385. if srcIndex != 0 {
  386. ctx.PropertyErrorf("srcs", "main source file must be the first in srcs")
  387. } else if numSrcs > 1 {
  388. ctx.PropertyErrorf("srcs", "only a single generated source module can be defined without a main source file.")
  389. }
  390. paths := android.PathsForModuleSrc(ctx, srcs)
  391. return paths[srcIndex], paths[1:]
  392. }