compiler.go 14 KB

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