rust.go 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718
  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. "android/soong/bloaty"
  17. "fmt"
  18. "strings"
  19. "github.com/google/blueprint"
  20. "github.com/google/blueprint/proptools"
  21. "android/soong/android"
  22. "android/soong/cc"
  23. cc_config "android/soong/cc/config"
  24. "android/soong/fuzz"
  25. "android/soong/rust/config"
  26. "android/soong/snapshot"
  27. )
  28. var pctx = android.NewPackageContext("android/soong/rust")
  29. func init() {
  30. android.RegisterModuleType("rust_defaults", defaultsFactory)
  31. android.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
  32. ctx.BottomUp("rust_libraries", LibraryMutator).Parallel()
  33. ctx.BottomUp("rust_stdlinkage", LibstdMutator).Parallel()
  34. ctx.BottomUp("rust_begin", BeginMutator).Parallel()
  35. })
  36. android.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
  37. ctx.BottomUp("rust_sanitizers", rustSanitizerRuntimeMutator).Parallel()
  38. })
  39. pctx.Import("android/soong/rust/config")
  40. pctx.ImportAs("cc_config", "android/soong/cc/config")
  41. android.InitRegistrationContext.RegisterSingletonType("kythe_rust_extract", kytheExtractRustFactory)
  42. }
  43. type Flags struct {
  44. GlobalRustFlags []string // Flags that apply globally to rust
  45. GlobalLinkFlags []string // Flags that apply globally to linker
  46. RustFlags []string // Flags that apply to rust
  47. LinkFlags []string // Flags that apply to linker
  48. ClippyFlags []string // Flags that apply to clippy-driver, during the linting
  49. RustdocFlags []string // Flags that apply to rustdoc
  50. Toolchain config.Toolchain
  51. Coverage bool
  52. Clippy bool
  53. EmitXrefs bool // If true, emit rules to aid cross-referencing
  54. }
  55. type BaseProperties struct {
  56. AndroidMkRlibs []string `blueprint:"mutated"`
  57. AndroidMkDylibs []string `blueprint:"mutated"`
  58. AndroidMkProcMacroLibs []string `blueprint:"mutated"`
  59. AndroidMkSharedLibs []string `blueprint:"mutated"`
  60. AndroidMkStaticLibs []string `blueprint:"mutated"`
  61. ImageVariationPrefix string `blueprint:"mutated"`
  62. VndkVersion string `blueprint:"mutated"`
  63. SubName string `blueprint:"mutated"`
  64. // SubName is used by CC for tracking image variants / SDK versions. RustSubName is used for Rust-specific
  65. // subnaming which shouldn't be visible to CC modules (such as the rlib stdlinkage subname). This should be
  66. // appended before SubName.
  67. RustSubName string `blueprint:"mutated"`
  68. // Set by imageMutator
  69. CoreVariantNeeded bool `blueprint:"mutated"`
  70. VendorRamdiskVariantNeeded bool `blueprint:"mutated"`
  71. RamdiskVariantNeeded bool `blueprint:"mutated"`
  72. RecoveryVariantNeeded bool `blueprint:"mutated"`
  73. ExtraVariants []string `blueprint:"mutated"`
  74. // Allows this module to use non-APEX version of libraries. Useful
  75. // for building binaries that are started before APEXes are activated.
  76. Bootstrap *bool
  77. // Used by vendor snapshot to record dependencies from snapshot modules.
  78. SnapshotSharedLibs []string `blueprint:"mutated"`
  79. SnapshotStaticLibs []string `blueprint:"mutated"`
  80. // Make this module available when building for ramdisk.
  81. // On device without a dedicated recovery partition, the module is only
  82. // available after switching root into
  83. // /first_stage_ramdisk. To expose the module before switching root, install
  84. // the recovery variant instead.
  85. Ramdisk_available *bool
  86. // Make this module available when building for vendor ramdisk.
  87. // On device without a dedicated recovery partition, the module is only
  88. // available after switching root into
  89. // /first_stage_ramdisk. To expose the module before switching root, install
  90. // the recovery variant instead
  91. Vendor_ramdisk_available *bool
  92. // Normally Soong uses the directory structure to decide which modules
  93. // should be included (framework) or excluded (non-framework) from the
  94. // different snapshots (vendor, recovery, etc.), but this property
  95. // allows a partner to exclude a module normally thought of as a
  96. // framework module from the vendor snapshot.
  97. Exclude_from_vendor_snapshot *bool
  98. // Normally Soong uses the directory structure to decide which modules
  99. // should be included (framework) or excluded (non-framework) from the
  100. // different snapshots (vendor, recovery, etc.), but this property
  101. // allows a partner to exclude a module normally thought of as a
  102. // framework module from the recovery snapshot.
  103. Exclude_from_recovery_snapshot *bool
  104. // Make this module available when building for recovery
  105. Recovery_available *bool
  106. // Minimum sdk version that the artifact should support when it runs as part of mainline modules(APEX).
  107. Min_sdk_version *string
  108. HideFromMake bool `blueprint:"mutated"`
  109. PreventInstall bool `blueprint:"mutated"`
  110. Installable *bool
  111. }
  112. type Module struct {
  113. fuzz.FuzzModule
  114. VendorProperties cc.VendorProperties
  115. Properties BaseProperties
  116. hod android.HostOrDeviceSupported
  117. multilib android.Multilib
  118. makeLinkType string
  119. afdo *afdo
  120. compiler compiler
  121. coverage *coverage
  122. clippy *clippy
  123. sanitize *sanitize
  124. cachedToolchain config.Toolchain
  125. sourceProvider SourceProvider
  126. subAndroidMkOnce map[SubAndroidMkProvider]bool
  127. // Output file to be installed, may be stripped or unstripped.
  128. outputFile android.OptionalPath
  129. // Cross-reference input file
  130. kytheFiles android.Paths
  131. docTimestampFile android.OptionalPath
  132. hideApexVariantFromMake bool
  133. // For apex variants, this is set as apex.min_sdk_version
  134. apexSdkVersion android.ApiLevel
  135. }
  136. func (mod *Module) Header() bool {
  137. //TODO: If Rust libraries provide header variants, this needs to be updated.
  138. return false
  139. }
  140. func (mod *Module) SetPreventInstall() {
  141. mod.Properties.PreventInstall = true
  142. }
  143. func (mod *Module) SetHideFromMake() {
  144. mod.Properties.HideFromMake = true
  145. }
  146. func (mod *Module) HiddenFromMake() bool {
  147. return mod.Properties.HideFromMake
  148. }
  149. func (mod *Module) SanitizePropDefined() bool {
  150. // Because compiler is not set for some Rust modules where sanitize might be set, check that compiler is also not
  151. // nil since we need compiler to actually sanitize.
  152. return mod.sanitize != nil && mod.compiler != nil
  153. }
  154. func (mod *Module) IsPrebuilt() bool {
  155. if _, ok := mod.compiler.(*prebuiltLibraryDecorator); ok {
  156. return true
  157. }
  158. return false
  159. }
  160. func (mod *Module) OutputFiles(tag string) (android.Paths, error) {
  161. switch tag {
  162. case "":
  163. if mod.sourceProvider != nil && (mod.compiler == nil || mod.compiler.Disabled()) {
  164. return mod.sourceProvider.Srcs(), nil
  165. } else {
  166. if mod.OutputFile().Valid() {
  167. return android.Paths{mod.OutputFile().Path()}, nil
  168. }
  169. return android.Paths{}, nil
  170. }
  171. case "unstripped":
  172. if mod.compiler != nil {
  173. return android.PathsIfNonNil(mod.compiler.unstrippedOutputFilePath()), nil
  174. }
  175. return nil, nil
  176. default:
  177. return nil, fmt.Errorf("unsupported module reference tag %q", tag)
  178. }
  179. }
  180. func (mod *Module) SelectedStl() string {
  181. return ""
  182. }
  183. func (mod *Module) NonCcVariants() bool {
  184. if mod.compiler != nil {
  185. if _, ok := mod.compiler.(libraryInterface); ok {
  186. return false
  187. }
  188. }
  189. panic(fmt.Errorf("NonCcVariants called on non-library module: %q", mod.BaseModuleName()))
  190. }
  191. func (mod *Module) Static() bool {
  192. if mod.compiler != nil {
  193. if library, ok := mod.compiler.(libraryInterface); ok {
  194. return library.static()
  195. }
  196. }
  197. return false
  198. }
  199. func (mod *Module) Shared() bool {
  200. if mod.compiler != nil {
  201. if library, ok := mod.compiler.(libraryInterface); ok {
  202. return library.shared()
  203. }
  204. }
  205. return false
  206. }
  207. func (mod *Module) Dylib() bool {
  208. if mod.compiler != nil {
  209. if library, ok := mod.compiler.(libraryInterface); ok {
  210. return library.dylib()
  211. }
  212. }
  213. return false
  214. }
  215. func (mod *Module) Rlib() bool {
  216. if mod.compiler != nil {
  217. if library, ok := mod.compiler.(libraryInterface); ok {
  218. return library.rlib()
  219. }
  220. }
  221. return false
  222. }
  223. func (mod *Module) Binary() bool {
  224. if binary, ok := mod.compiler.(binaryInterface); ok {
  225. return binary.binary()
  226. }
  227. return false
  228. }
  229. func (mod *Module) StaticExecutable() bool {
  230. if !mod.Binary() {
  231. return false
  232. }
  233. return mod.StaticallyLinked()
  234. }
  235. func (mod *Module) Object() bool {
  236. // Rust has no modules which produce only object files.
  237. return false
  238. }
  239. func (mod *Module) Toc() android.OptionalPath {
  240. if mod.compiler != nil {
  241. if lib, ok := mod.compiler.(libraryInterface); ok {
  242. return lib.toc()
  243. }
  244. }
  245. panic(fmt.Errorf("Toc() called on non-library module: %q", mod.BaseModuleName()))
  246. }
  247. func (mod *Module) UseSdk() bool {
  248. return false
  249. }
  250. func (mod *Module) RelativeInstallPath() string {
  251. if mod.compiler != nil {
  252. return mod.compiler.relativeInstallPath()
  253. }
  254. return ""
  255. }
  256. func (mod *Module) UseVndk() bool {
  257. return mod.Properties.VndkVersion != ""
  258. }
  259. func (mod *Module) Bootstrap() bool {
  260. return Bool(mod.Properties.Bootstrap)
  261. }
  262. func (mod *Module) MustUseVendorVariant() bool {
  263. return true
  264. }
  265. func (mod *Module) SubName() string {
  266. return mod.Properties.SubName
  267. }
  268. func (mod *Module) IsVndk() bool {
  269. // TODO(b/165791368)
  270. return false
  271. }
  272. func (mod *Module) IsVndkExt() bool {
  273. return false
  274. }
  275. func (mod *Module) IsVndkSp() bool {
  276. return false
  277. }
  278. func (mod *Module) IsVndkPrebuiltLibrary() bool {
  279. // Rust modules do not provide VNDK prebuilts
  280. return false
  281. }
  282. func (mod *Module) IsVendorPublicLibrary() bool {
  283. return mod.VendorProperties.IsVendorPublicLibrary
  284. }
  285. func (mod *Module) SdkAndPlatformVariantVisibleToMake() bool {
  286. // Rust modules to not provide Sdk variants
  287. return false
  288. }
  289. func (c *Module) IsVndkPrivate() bool {
  290. return false
  291. }
  292. func (c *Module) IsLlndk() bool {
  293. return false
  294. }
  295. func (c *Module) IsLlndkPublic() bool {
  296. return false
  297. }
  298. func (mod *Module) KernelHeadersDecorator() bool {
  299. return false
  300. }
  301. func (m *Module) NeedsLlndkVariants() bool {
  302. return false
  303. }
  304. func (m *Module) NeedsVendorPublicLibraryVariants() bool {
  305. return false
  306. }
  307. func (mod *Module) HasLlndkStubs() bool {
  308. return false
  309. }
  310. func (mod *Module) StubsVersion() string {
  311. panic(fmt.Errorf("StubsVersion called on non-versioned module: %q", mod.BaseModuleName()))
  312. }
  313. func (mod *Module) SdkVersion() string {
  314. return ""
  315. }
  316. func (mod *Module) AlwaysSdk() bool {
  317. return false
  318. }
  319. func (mod *Module) IsSdkVariant() bool {
  320. return false
  321. }
  322. func (mod *Module) SplitPerApiLevel() bool {
  323. return false
  324. }
  325. func (mod *Module) XrefRustFiles() android.Paths {
  326. return mod.kytheFiles
  327. }
  328. type Deps struct {
  329. Dylibs []string
  330. Rlibs []string
  331. Rustlibs []string
  332. Stdlibs []string
  333. ProcMacros []string
  334. SharedLibs []string
  335. StaticLibs []string
  336. WholeStaticLibs []string
  337. HeaderLibs []string
  338. // Used for data dependencies adjacent to tests
  339. DataLibs []string
  340. DataBins []string
  341. CrtBegin, CrtEnd []string
  342. }
  343. type PathDeps struct {
  344. DyLibs RustLibraries
  345. RLibs RustLibraries
  346. SharedLibs android.Paths
  347. SharedLibDeps android.Paths
  348. StaticLibs android.Paths
  349. ProcMacros RustLibraries
  350. AfdoProfiles android.Paths
  351. // depFlags and depLinkFlags are rustc and linker (clang) flags.
  352. depFlags []string
  353. depLinkFlags []string
  354. // linkDirs are link paths passed via -L to rustc. linkObjects are objects passed directly to the linker.
  355. // Both of these are exported and propagate to dependencies.
  356. linkDirs []string
  357. linkObjects []string
  358. // Used by bindgen modules which call clang
  359. depClangFlags []string
  360. depIncludePaths android.Paths
  361. depGeneratedHeaders android.Paths
  362. depSystemIncludePaths android.Paths
  363. CrtBegin android.Paths
  364. CrtEnd android.Paths
  365. // Paths to generated source files
  366. SrcDeps android.Paths
  367. srcProviderFiles android.Paths
  368. }
  369. type RustLibraries []RustLibrary
  370. type RustLibrary struct {
  371. Path android.Path
  372. CrateName string
  373. }
  374. type compiler interface {
  375. initialize(ctx ModuleContext)
  376. compilerFlags(ctx ModuleContext, flags Flags) Flags
  377. cfgFlags(ctx ModuleContext, flags Flags) Flags
  378. featureFlags(ctx ModuleContext, flags Flags) Flags
  379. compilerProps() []interface{}
  380. compile(ctx ModuleContext, flags Flags, deps PathDeps) buildOutput
  381. compilerDeps(ctx DepsContext, deps Deps) Deps
  382. crateName() string
  383. rustdoc(ctx ModuleContext, flags Flags, deps PathDeps) android.OptionalPath
  384. // Output directory in which source-generated code from dependencies is
  385. // copied. This is equivalent to Cargo's OUT_DIR variable.
  386. CargoOutDir() android.OptionalPath
  387. // CargoPkgVersion returns the value of the Cargo_pkg_version property.
  388. CargoPkgVersion() string
  389. // CargoEnvCompat returns whether Cargo environment variables should be used.
  390. CargoEnvCompat() bool
  391. inData() bool
  392. install(ctx ModuleContext)
  393. relativeInstallPath() string
  394. everInstallable() bool
  395. nativeCoverage() bool
  396. Disabled() bool
  397. SetDisabled()
  398. stdLinkage(ctx *depsContext) RustLinkage
  399. noStdlibs() bool
  400. unstrippedOutputFilePath() android.Path
  401. strippedOutputFilePath() android.OptionalPath
  402. }
  403. type exportedFlagsProducer interface {
  404. exportLinkDirs(...string)
  405. exportLinkObjects(...string)
  406. }
  407. type xref interface {
  408. XrefRustFiles() android.Paths
  409. }
  410. type flagExporter struct {
  411. linkDirs []string
  412. linkObjects []string
  413. }
  414. func (flagExporter *flagExporter) exportLinkDirs(dirs ...string) {
  415. flagExporter.linkDirs = android.FirstUniqueStrings(append(flagExporter.linkDirs, dirs...))
  416. }
  417. func (flagExporter *flagExporter) exportLinkObjects(flags ...string) {
  418. flagExporter.linkObjects = android.FirstUniqueStrings(append(flagExporter.linkObjects, flags...))
  419. }
  420. func (flagExporter *flagExporter) setProvider(ctx ModuleContext) {
  421. ctx.SetProvider(FlagExporterInfoProvider, FlagExporterInfo{
  422. LinkDirs: flagExporter.linkDirs,
  423. LinkObjects: flagExporter.linkObjects,
  424. })
  425. }
  426. var _ exportedFlagsProducer = (*flagExporter)(nil)
  427. func NewFlagExporter() *flagExporter {
  428. return &flagExporter{}
  429. }
  430. type FlagExporterInfo struct {
  431. Flags []string
  432. LinkDirs []string // TODO: this should be android.Paths
  433. LinkObjects []string // TODO: this should be android.Paths
  434. }
  435. var FlagExporterInfoProvider = blueprint.NewProvider(FlagExporterInfo{})
  436. func (mod *Module) isCoverageVariant() bool {
  437. return mod.coverage.Properties.IsCoverageVariant
  438. }
  439. var _ cc.Coverage = (*Module)(nil)
  440. func (mod *Module) IsNativeCoverageNeeded(ctx android.BaseModuleContext) bool {
  441. return mod.coverage != nil && mod.coverage.Properties.NeedCoverageVariant
  442. }
  443. func (mod *Module) VndkVersion() string {
  444. return mod.Properties.VndkVersion
  445. }
  446. func (mod *Module) PreventInstall() bool {
  447. return mod.Properties.PreventInstall
  448. }
  449. func (mod *Module) MarkAsCoverageVariant(coverage bool) {
  450. mod.coverage.Properties.IsCoverageVariant = coverage
  451. }
  452. func (mod *Module) EnableCoverageIfNeeded() {
  453. mod.coverage.Properties.CoverageEnabled = mod.coverage.Properties.NeedCoverageBuild
  454. }
  455. func defaultsFactory() android.Module {
  456. return DefaultsFactory()
  457. }
  458. type Defaults struct {
  459. android.ModuleBase
  460. android.DefaultsModuleBase
  461. }
  462. func DefaultsFactory(props ...interface{}) android.Module {
  463. module := &Defaults{}
  464. module.AddProperties(props...)
  465. module.AddProperties(
  466. &BaseProperties{},
  467. &cc.AfdoProperties{},
  468. &cc.VendorProperties{},
  469. &BenchmarkProperties{},
  470. &BindgenProperties{},
  471. &BaseCompilerProperties{},
  472. &BinaryCompilerProperties{},
  473. &LibraryCompilerProperties{},
  474. &ProcMacroCompilerProperties{},
  475. &PrebuiltProperties{},
  476. &SourceProviderProperties{},
  477. &TestProperties{},
  478. &cc.CoverageProperties{},
  479. &cc.RustBindgenClangProperties{},
  480. &ClippyProperties{},
  481. &SanitizeProperties{},
  482. )
  483. android.InitDefaultsModule(module)
  484. return module
  485. }
  486. func (mod *Module) CrateName() string {
  487. return mod.compiler.crateName()
  488. }
  489. func (mod *Module) CcLibrary() bool {
  490. if mod.compiler != nil {
  491. if _, ok := mod.compiler.(libraryInterface); ok {
  492. return true
  493. }
  494. }
  495. return false
  496. }
  497. func (mod *Module) CcLibraryInterface() bool {
  498. if mod.compiler != nil {
  499. // use build{Static,Shared}() instead of {static,shared}() here because this might be called before
  500. // VariantIs{Static,Shared} is set.
  501. if lib, ok := mod.compiler.(libraryInterface); ok && (lib.buildShared() || lib.buildStatic()) {
  502. return true
  503. }
  504. }
  505. return false
  506. }
  507. func (mod *Module) IsFuzzModule() bool {
  508. if _, ok := mod.compiler.(*fuzzDecorator); ok {
  509. return true
  510. }
  511. return false
  512. }
  513. func (mod *Module) FuzzModuleStruct() fuzz.FuzzModule {
  514. return mod.FuzzModule
  515. }
  516. func (mod *Module) FuzzPackagedModule() fuzz.FuzzPackagedModule {
  517. if fuzzer, ok := mod.compiler.(*fuzzDecorator); ok {
  518. return fuzzer.fuzzPackagedModule
  519. }
  520. panic(fmt.Errorf("FuzzPackagedModule called on non-fuzz module: %q", mod.BaseModuleName()))
  521. }
  522. func (mod *Module) FuzzSharedLibraries() android.Paths {
  523. if fuzzer, ok := mod.compiler.(*fuzzDecorator); ok {
  524. return fuzzer.sharedLibraries
  525. }
  526. panic(fmt.Errorf("FuzzSharedLibraries called on non-fuzz module: %q", mod.BaseModuleName()))
  527. }
  528. func (mod *Module) UnstrippedOutputFile() android.Path {
  529. if mod.compiler != nil {
  530. return mod.compiler.unstrippedOutputFilePath()
  531. }
  532. return nil
  533. }
  534. func (mod *Module) IncludeDirs() android.Paths {
  535. if mod.compiler != nil {
  536. if library, ok := mod.compiler.(*libraryDecorator); ok {
  537. return library.includeDirs
  538. }
  539. }
  540. panic(fmt.Errorf("IncludeDirs called on non-library module: %q", mod.BaseModuleName()))
  541. }
  542. func (mod *Module) SetStatic() {
  543. if mod.compiler != nil {
  544. if library, ok := mod.compiler.(libraryInterface); ok {
  545. library.setStatic()
  546. return
  547. }
  548. }
  549. panic(fmt.Errorf("SetStatic called on non-library module: %q", mod.BaseModuleName()))
  550. }
  551. func (mod *Module) SetShared() {
  552. if mod.compiler != nil {
  553. if library, ok := mod.compiler.(libraryInterface); ok {
  554. library.setShared()
  555. return
  556. }
  557. }
  558. panic(fmt.Errorf("SetShared called on non-library module: %q", mod.BaseModuleName()))
  559. }
  560. func (mod *Module) BuildStaticVariant() bool {
  561. if mod.compiler != nil {
  562. if library, ok := mod.compiler.(libraryInterface); ok {
  563. return library.buildStatic()
  564. }
  565. }
  566. panic(fmt.Errorf("BuildStaticVariant called on non-library module: %q", mod.BaseModuleName()))
  567. }
  568. func (mod *Module) BuildSharedVariant() bool {
  569. if mod.compiler != nil {
  570. if library, ok := mod.compiler.(libraryInterface); ok {
  571. return library.buildShared()
  572. }
  573. }
  574. panic(fmt.Errorf("BuildSharedVariant called on non-library module: %q", mod.BaseModuleName()))
  575. }
  576. func (mod *Module) Module() android.Module {
  577. return mod
  578. }
  579. func (mod *Module) OutputFile() android.OptionalPath {
  580. return mod.outputFile
  581. }
  582. func (mod *Module) CoverageFiles() android.Paths {
  583. if mod.compiler != nil {
  584. return android.Paths{}
  585. }
  586. panic(fmt.Errorf("CoverageFiles called on non-library module: %q", mod.BaseModuleName()))
  587. }
  588. // Rust does not produce gcno files, and therefore does not produce a coverage archive.
  589. func (mod *Module) CoverageOutputFile() android.OptionalPath {
  590. return android.OptionalPath{}
  591. }
  592. func (mod *Module) IsNdk(config android.Config) bool {
  593. return false
  594. }
  595. func (mod *Module) IsStubs() bool {
  596. return false
  597. }
  598. func (mod *Module) installable(apexInfo android.ApexInfo) bool {
  599. if !proptools.BoolDefault(mod.Installable(), mod.EverInstallable()) {
  600. return false
  601. }
  602. // The apex variant is not installable because it is included in the APEX and won't appear
  603. // in the system partition as a standalone file.
  604. if !apexInfo.IsForPlatform() {
  605. return false
  606. }
  607. return mod.OutputFile().Valid() && !mod.Properties.PreventInstall
  608. }
  609. func (ctx moduleContext) apexVariationName() string {
  610. return ctx.Provider(android.ApexInfoProvider).(android.ApexInfo).ApexVariationName
  611. }
  612. var _ cc.LinkableInterface = (*Module)(nil)
  613. func (mod *Module) Init() android.Module {
  614. mod.AddProperties(&mod.Properties)
  615. mod.AddProperties(&mod.VendorProperties)
  616. if mod.afdo != nil {
  617. mod.AddProperties(mod.afdo.props()...)
  618. }
  619. if mod.compiler != nil {
  620. mod.AddProperties(mod.compiler.compilerProps()...)
  621. }
  622. if mod.coverage != nil {
  623. mod.AddProperties(mod.coverage.props()...)
  624. }
  625. if mod.clippy != nil {
  626. mod.AddProperties(mod.clippy.props()...)
  627. }
  628. if mod.sourceProvider != nil {
  629. mod.AddProperties(mod.sourceProvider.SourceProviderProps()...)
  630. }
  631. if mod.sanitize != nil {
  632. mod.AddProperties(mod.sanitize.props()...)
  633. }
  634. android.InitAndroidArchModule(mod, mod.hod, mod.multilib)
  635. android.InitApexModule(mod)
  636. android.InitDefaultableModule(mod)
  637. return mod
  638. }
  639. func newBaseModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
  640. return &Module{
  641. hod: hod,
  642. multilib: multilib,
  643. }
  644. }
  645. func newModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
  646. module := newBaseModule(hod, multilib)
  647. module.afdo = &afdo{}
  648. module.coverage = &coverage{}
  649. module.clippy = &clippy{}
  650. module.sanitize = &sanitize{}
  651. return module
  652. }
  653. type ModuleContext interface {
  654. android.ModuleContext
  655. ModuleContextIntf
  656. }
  657. type BaseModuleContext interface {
  658. android.BaseModuleContext
  659. ModuleContextIntf
  660. }
  661. type DepsContext interface {
  662. android.BottomUpMutatorContext
  663. ModuleContextIntf
  664. }
  665. type ModuleContextIntf interface {
  666. RustModule() *Module
  667. toolchain() config.Toolchain
  668. }
  669. type depsContext struct {
  670. android.BottomUpMutatorContext
  671. }
  672. type moduleContext struct {
  673. android.ModuleContext
  674. }
  675. type baseModuleContext struct {
  676. android.BaseModuleContext
  677. }
  678. func (ctx *moduleContext) RustModule() *Module {
  679. return ctx.Module().(*Module)
  680. }
  681. func (ctx *moduleContext) toolchain() config.Toolchain {
  682. return ctx.RustModule().toolchain(ctx)
  683. }
  684. func (ctx *depsContext) RustModule() *Module {
  685. return ctx.Module().(*Module)
  686. }
  687. func (ctx *depsContext) toolchain() config.Toolchain {
  688. return ctx.RustModule().toolchain(ctx)
  689. }
  690. func (ctx *baseModuleContext) RustModule() *Module {
  691. return ctx.Module().(*Module)
  692. }
  693. func (ctx *baseModuleContext) toolchain() config.Toolchain {
  694. return ctx.RustModule().toolchain(ctx)
  695. }
  696. func (mod *Module) nativeCoverage() bool {
  697. // Bug: http://b/137883967 - native-bridge modules do not currently work with coverage
  698. if mod.Target().NativeBridge == android.NativeBridgeEnabled {
  699. return false
  700. }
  701. return mod.compiler != nil && mod.compiler.nativeCoverage()
  702. }
  703. func (mod *Module) EverInstallable() bool {
  704. return mod.compiler != nil &&
  705. // Check to see whether the module is actually ever installable.
  706. mod.compiler.everInstallable()
  707. }
  708. func (mod *Module) Installable() *bool {
  709. return mod.Properties.Installable
  710. }
  711. func (mod *Module) ProcMacro() bool {
  712. if pm, ok := mod.compiler.(procMacroInterface); ok {
  713. return pm.ProcMacro()
  714. }
  715. return false
  716. }
  717. func (mod *Module) toolchain(ctx android.BaseModuleContext) config.Toolchain {
  718. if mod.cachedToolchain == nil {
  719. mod.cachedToolchain = config.FindToolchain(ctx.Os(), ctx.Arch())
  720. }
  721. return mod.cachedToolchain
  722. }
  723. func (mod *Module) ccToolchain(ctx android.BaseModuleContext) cc_config.Toolchain {
  724. return cc_config.FindToolchain(ctx.Os(), ctx.Arch())
  725. }
  726. func (d *Defaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  727. }
  728. func (mod *Module) GenerateAndroidBuildActions(actx android.ModuleContext) {
  729. ctx := &moduleContext{
  730. ModuleContext: actx,
  731. }
  732. apexInfo := actx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  733. if !apexInfo.IsForPlatform() {
  734. mod.hideApexVariantFromMake = true
  735. }
  736. toolchain := mod.toolchain(ctx)
  737. mod.makeLinkType = cc.GetMakeLinkType(actx, mod)
  738. mod.Properties.SubName = cc.GetSubnameProperty(actx, mod)
  739. if !toolchain.Supported() {
  740. // This toolchain's unsupported, there's nothing to do for this mod.
  741. return
  742. }
  743. deps := mod.depsToPaths(ctx)
  744. flags := Flags{
  745. Toolchain: toolchain,
  746. }
  747. // Calculate rustc flags
  748. if mod.afdo != nil {
  749. flags, deps = mod.afdo.flags(ctx, flags, deps)
  750. }
  751. if mod.compiler != nil {
  752. flags = mod.compiler.compilerFlags(ctx, flags)
  753. flags = mod.compiler.cfgFlags(ctx, flags)
  754. flags = mod.compiler.featureFlags(ctx, flags)
  755. }
  756. if mod.coverage != nil {
  757. flags, deps = mod.coverage.flags(ctx, flags, deps)
  758. }
  759. if mod.clippy != nil {
  760. flags, deps = mod.clippy.flags(ctx, flags, deps)
  761. }
  762. if mod.sanitize != nil {
  763. flags, deps = mod.sanitize.flags(ctx, flags, deps)
  764. }
  765. // SourceProvider needs to call GenerateSource() before compiler calls
  766. // compile() so it can provide the source. A SourceProvider has
  767. // multiple variants (e.g. source, rlib, dylib). Only the "source"
  768. // variant is responsible for effectively generating the source. The
  769. // remaining variants relies on the "source" variant output.
  770. if mod.sourceProvider != nil {
  771. if mod.compiler.(libraryInterface).source() {
  772. mod.sourceProvider.GenerateSource(ctx, deps)
  773. mod.sourceProvider.setSubName(ctx.ModuleSubDir())
  774. } else {
  775. sourceMod := actx.GetDirectDepWithTag(mod.Name(), sourceDepTag)
  776. sourceLib := sourceMod.(*Module).compiler.(*libraryDecorator)
  777. mod.sourceProvider.setOutputFiles(sourceLib.sourceProvider.Srcs())
  778. }
  779. }
  780. if mod.compiler != nil && !mod.compiler.Disabled() {
  781. mod.compiler.initialize(ctx)
  782. buildOutput := mod.compiler.compile(ctx, flags, deps)
  783. if ctx.Failed() {
  784. return
  785. }
  786. mod.outputFile = android.OptionalPathForPath(buildOutput.outputFile)
  787. if buildOutput.kytheFile != nil {
  788. mod.kytheFiles = append(mod.kytheFiles, buildOutput.kytheFile)
  789. }
  790. bloaty.MeasureSizeForPaths(ctx, mod.compiler.strippedOutputFilePath(), android.OptionalPathForPath(mod.compiler.unstrippedOutputFilePath()))
  791. mod.docTimestampFile = mod.compiler.rustdoc(ctx, flags, deps)
  792. if mod.docTimestampFile.Valid() {
  793. ctx.CheckbuildFile(mod.docTimestampFile.Path())
  794. }
  795. // glob exported headers for snapshot, if BOARD_VNDK_VERSION is current or
  796. // RECOVERY_SNAPSHOT_VERSION is current.
  797. if lib, ok := mod.compiler.(snapshotLibraryInterface); ok {
  798. if cc.ShouldCollectHeadersForSnapshot(ctx, mod, apexInfo) {
  799. lib.collectHeadersForSnapshot(ctx, deps)
  800. }
  801. }
  802. apexInfo := actx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  803. if !proptools.BoolDefault(mod.Installable(), mod.EverInstallable()) && !mod.ProcMacro() {
  804. // If the module has been specifically configure to not be installed then
  805. // hide from make as otherwise it will break when running inside make as the
  806. // output path to install will not be specified. Not all uninstallable
  807. // modules can be hidden from make as some are needed for resolving make
  808. // side dependencies. In particular, proc-macros need to be captured in the
  809. // host snapshot.
  810. mod.HideFromMake()
  811. } else if !mod.installable(apexInfo) {
  812. mod.SkipInstall()
  813. }
  814. // Still call install though, the installs will be stored as PackageSpecs to allow
  815. // using the outputs in a genrule.
  816. if mod.OutputFile().Valid() {
  817. mod.compiler.install(ctx)
  818. if ctx.Failed() {
  819. return
  820. }
  821. }
  822. ctx.Phony("rust", ctx.RustModule().OutputFile().Path())
  823. }
  824. }
  825. func (mod *Module) deps(ctx DepsContext) Deps {
  826. deps := Deps{}
  827. if mod.compiler != nil {
  828. deps = mod.compiler.compilerDeps(ctx, deps)
  829. }
  830. if mod.sourceProvider != nil {
  831. deps = mod.sourceProvider.SourceProviderDeps(ctx, deps)
  832. }
  833. if mod.coverage != nil {
  834. deps = mod.coverage.deps(ctx, deps)
  835. }
  836. if mod.sanitize != nil {
  837. deps = mod.sanitize.deps(ctx, deps)
  838. }
  839. deps.Rlibs = android.LastUniqueStrings(deps.Rlibs)
  840. deps.Dylibs = android.LastUniqueStrings(deps.Dylibs)
  841. deps.Rustlibs = android.LastUniqueStrings(deps.Rustlibs)
  842. deps.ProcMacros = android.LastUniqueStrings(deps.ProcMacros)
  843. deps.SharedLibs = android.LastUniqueStrings(deps.SharedLibs)
  844. deps.StaticLibs = android.LastUniqueStrings(deps.StaticLibs)
  845. deps.Stdlibs = android.LastUniqueStrings(deps.Stdlibs)
  846. deps.WholeStaticLibs = android.LastUniqueStrings(deps.WholeStaticLibs)
  847. return deps
  848. }
  849. type dependencyTag struct {
  850. blueprint.BaseDependencyTag
  851. name string
  852. library bool
  853. procMacro bool
  854. dynamic bool
  855. }
  856. // InstallDepNeeded returns true for rlibs, dylibs, and proc macros so that they or their transitive
  857. // dependencies (especially C/C++ shared libs) are installed as dependencies of a rust binary.
  858. func (d dependencyTag) InstallDepNeeded() bool {
  859. return d.library || d.procMacro
  860. }
  861. var _ android.InstallNeededDependencyTag = dependencyTag{}
  862. func (d dependencyTag) LicenseAnnotations() []android.LicenseAnnotation {
  863. if d.library && d.dynamic {
  864. return []android.LicenseAnnotation{android.LicenseAnnotationSharedDependency}
  865. }
  866. return nil
  867. }
  868. var _ android.LicenseAnnotationsDependencyTag = dependencyTag{}
  869. var (
  870. customBindgenDepTag = dependencyTag{name: "customBindgenTag"}
  871. rlibDepTag = dependencyTag{name: "rlibTag", library: true}
  872. dylibDepTag = dependencyTag{name: "dylib", library: true, dynamic: true}
  873. procMacroDepTag = dependencyTag{name: "procMacro", procMacro: true}
  874. testPerSrcDepTag = dependencyTag{name: "rust_unit_tests"}
  875. sourceDepTag = dependencyTag{name: "source"}
  876. dataLibDepTag = dependencyTag{name: "data lib"}
  877. dataBinDepTag = dependencyTag{name: "data bin"}
  878. )
  879. func IsDylibDepTag(depTag blueprint.DependencyTag) bool {
  880. tag, ok := depTag.(dependencyTag)
  881. return ok && tag == dylibDepTag
  882. }
  883. func IsRlibDepTag(depTag blueprint.DependencyTag) bool {
  884. tag, ok := depTag.(dependencyTag)
  885. return ok && tag == rlibDepTag
  886. }
  887. type autoDep struct {
  888. variation string
  889. depTag dependencyTag
  890. }
  891. var (
  892. rlibVariation = "rlib"
  893. dylibVariation = "dylib"
  894. rlibAutoDep = autoDep{variation: rlibVariation, depTag: rlibDepTag}
  895. dylibAutoDep = autoDep{variation: dylibVariation, depTag: dylibDepTag}
  896. )
  897. type autoDeppable interface {
  898. autoDep(ctx android.BottomUpMutatorContext) autoDep
  899. }
  900. func (mod *Module) begin(ctx BaseModuleContext) {
  901. if mod.coverage != nil {
  902. mod.coverage.begin(ctx)
  903. }
  904. if mod.sanitize != nil {
  905. mod.sanitize.begin(ctx)
  906. }
  907. }
  908. func (mod *Module) Prebuilt() *android.Prebuilt {
  909. if p, ok := mod.compiler.(rustPrebuilt); ok {
  910. return p.prebuilt()
  911. }
  912. return nil
  913. }
  914. func rustMakeLibName(ctx android.ModuleContext, c cc.LinkableInterface, dep cc.LinkableInterface, depName string) string {
  915. if rustDep, ok := dep.(*Module); ok {
  916. // Use base module name for snapshots when exporting to Makefile.
  917. if snapshotPrebuilt, ok := rustDep.compiler.(cc.SnapshotInterface); ok {
  918. baseName := rustDep.BaseModuleName()
  919. return baseName + snapshotPrebuilt.SnapshotAndroidMkSuffix() + rustDep.AndroidMkSuffix()
  920. }
  921. }
  922. return cc.MakeLibName(ctx, c, dep, depName)
  923. }
  924. func (mod *Module) depsToPaths(ctx android.ModuleContext) PathDeps {
  925. var depPaths PathDeps
  926. directRlibDeps := []*Module{}
  927. directDylibDeps := []*Module{}
  928. directProcMacroDeps := []*Module{}
  929. directSharedLibDeps := []cc.SharedLibraryInfo{}
  930. directStaticLibDeps := [](cc.LinkableInterface){}
  931. directSrcProvidersDeps := []*Module{}
  932. directSrcDeps := [](android.SourceFileProducer){}
  933. // For the dependency from platform to apex, use the latest stubs
  934. mod.apexSdkVersion = android.FutureApiLevel
  935. apexInfo := ctx.Provider(android.ApexInfoProvider).(android.ApexInfo)
  936. if !apexInfo.IsForPlatform() {
  937. mod.apexSdkVersion = apexInfo.MinSdkVersion
  938. }
  939. if android.InList("hwaddress", ctx.Config().SanitizeDevice()) {
  940. // In hwasan build, we override apexSdkVersion to the FutureApiLevel(10000)
  941. // so that even Q(29/Android10) apexes could use the dynamic unwinder by linking the newer stubs(e.g libc(R+)).
  942. // (b/144430859)
  943. mod.apexSdkVersion = android.FutureApiLevel
  944. }
  945. ctx.VisitDirectDeps(func(dep android.Module) {
  946. depName := ctx.OtherModuleName(dep)
  947. depTag := ctx.OtherModuleDependencyTag(dep)
  948. if rustDep, ok := dep.(*Module); ok && !rustDep.CcLibraryInterface() {
  949. //Handle Rust Modules
  950. makeLibName := rustMakeLibName(ctx, mod, rustDep, depName+rustDep.Properties.RustSubName)
  951. switch depTag {
  952. case dylibDepTag:
  953. dylib, ok := rustDep.compiler.(libraryInterface)
  954. if !ok || !dylib.dylib() {
  955. ctx.ModuleErrorf("mod %q not an dylib library", depName)
  956. return
  957. }
  958. directDylibDeps = append(directDylibDeps, rustDep)
  959. mod.Properties.AndroidMkDylibs = append(mod.Properties.AndroidMkDylibs, makeLibName)
  960. case rlibDepTag:
  961. rlib, ok := rustDep.compiler.(libraryInterface)
  962. if !ok || !rlib.rlib() {
  963. ctx.ModuleErrorf("mod %q not an rlib library", makeLibName)
  964. return
  965. }
  966. directRlibDeps = append(directRlibDeps, rustDep)
  967. mod.Properties.AndroidMkRlibs = append(mod.Properties.AndroidMkRlibs, makeLibName)
  968. case procMacroDepTag:
  969. directProcMacroDeps = append(directProcMacroDeps, rustDep)
  970. mod.Properties.AndroidMkProcMacroLibs = append(mod.Properties.AndroidMkProcMacroLibs, makeLibName)
  971. }
  972. if android.IsSourceDepTagWithOutputTag(depTag, "") {
  973. // Since these deps are added in path_properties.go via AddDependencies, we need to ensure the correct
  974. // OS/Arch variant is used.
  975. var helper string
  976. if ctx.Host() {
  977. helper = "missing 'host_supported'?"
  978. } else {
  979. helper = "device module defined?"
  980. }
  981. if dep.Target().Os != ctx.Os() {
  982. ctx.ModuleErrorf("OS mismatch on dependency %q (%s)", dep.Name(), helper)
  983. return
  984. } else if dep.Target().Arch.ArchType != ctx.Arch().ArchType {
  985. ctx.ModuleErrorf("Arch mismatch on dependency %q (%s)", dep.Name(), helper)
  986. return
  987. }
  988. directSrcProvidersDeps = append(directSrcProvidersDeps, rustDep)
  989. }
  990. //Append the dependencies exportedDirs, except for proc-macros which target a different arch/OS
  991. if depTag != procMacroDepTag {
  992. exportedInfo := ctx.OtherModuleProvider(dep, FlagExporterInfoProvider).(FlagExporterInfo)
  993. depPaths.linkDirs = append(depPaths.linkDirs, exportedInfo.LinkDirs...)
  994. depPaths.depFlags = append(depPaths.depFlags, exportedInfo.Flags...)
  995. depPaths.linkObjects = append(depPaths.linkObjects, exportedInfo.LinkObjects...)
  996. }
  997. if depTag == dylibDepTag || depTag == rlibDepTag || depTag == procMacroDepTag {
  998. linkFile := rustDep.UnstrippedOutputFile()
  999. linkDir := linkPathFromFilePath(linkFile)
  1000. if lib, ok := mod.compiler.(exportedFlagsProducer); ok {
  1001. lib.exportLinkDirs(linkDir)
  1002. }
  1003. }
  1004. } else if ccDep, ok := dep.(cc.LinkableInterface); ok {
  1005. //Handle C dependencies
  1006. makeLibName := cc.MakeLibName(ctx, mod, ccDep, depName)
  1007. if _, ok := ccDep.(*Module); !ok {
  1008. if ccDep.Module().Target().Os != ctx.Os() {
  1009. ctx.ModuleErrorf("OS mismatch between %q and %q", ctx.ModuleName(), depName)
  1010. return
  1011. }
  1012. if ccDep.Module().Target().Arch.ArchType != ctx.Arch().ArchType {
  1013. ctx.ModuleErrorf("Arch mismatch between %q and %q", ctx.ModuleName(), depName)
  1014. return
  1015. }
  1016. }
  1017. linkObject := ccDep.OutputFile()
  1018. linkPath := linkPathFromFilePath(linkObject.Path())
  1019. if !linkObject.Valid() {
  1020. ctx.ModuleErrorf("Invalid output file when adding dep %q to %q", depName, ctx.ModuleName())
  1021. }
  1022. exportDep := false
  1023. switch {
  1024. case cc.IsStaticDepTag(depTag):
  1025. if cc.IsWholeStaticLib(depTag) {
  1026. // rustc will bundle static libraries when they're passed with "-lstatic=<lib>". This will fail
  1027. // if the library is not prefixed by "lib".
  1028. if mod.Binary() {
  1029. // Binaries may sometimes need to link whole static libraries that don't start with 'lib'.
  1030. // Since binaries don't need to 'rebundle' these like libraries and only use these for the
  1031. // final linkage, pass the args directly to the linker to handle these cases.
  1032. depPaths.depLinkFlags = append(depPaths.depLinkFlags, []string{"-Wl,--whole-archive", linkObject.Path().String(), "-Wl,--no-whole-archive"}...)
  1033. } else if libName, ok := libNameFromFilePath(linkObject.Path()); ok {
  1034. depPaths.depFlags = append(depPaths.depFlags, "-lstatic="+libName)
  1035. } else {
  1036. ctx.ModuleErrorf("'%q' cannot be listed as a whole_static_library in Rust modules unless the output is prefixed by 'lib'", depName, ctx.ModuleName())
  1037. }
  1038. }
  1039. // Add this to linkObjects to pass the library directly to the linker as well. This propagates
  1040. // to dependencies to avoid having to redeclare static libraries for dependents of the dylib variant.
  1041. depPaths.linkObjects = append(depPaths.linkObjects, linkObject.String())
  1042. depPaths.linkDirs = append(depPaths.linkDirs, linkPath)
  1043. exportedInfo := ctx.OtherModuleProvider(dep, cc.FlagExporterInfoProvider).(cc.FlagExporterInfo)
  1044. depPaths.depIncludePaths = append(depPaths.depIncludePaths, exportedInfo.IncludeDirs...)
  1045. depPaths.depSystemIncludePaths = append(depPaths.depSystemIncludePaths, exportedInfo.SystemIncludeDirs...)
  1046. depPaths.depClangFlags = append(depPaths.depClangFlags, exportedInfo.Flags...)
  1047. depPaths.depGeneratedHeaders = append(depPaths.depGeneratedHeaders, exportedInfo.GeneratedHeaders...)
  1048. directStaticLibDeps = append(directStaticLibDeps, ccDep)
  1049. // Record baseLibName for snapshots.
  1050. mod.Properties.SnapshotStaticLibs = append(mod.Properties.SnapshotStaticLibs, cc.BaseLibName(depName))
  1051. mod.Properties.AndroidMkStaticLibs = append(mod.Properties.AndroidMkStaticLibs, makeLibName)
  1052. case cc.IsSharedDepTag(depTag):
  1053. // For the shared lib dependencies, we may link to the stub variant
  1054. // of the dependency depending on the context (e.g. if this
  1055. // dependency crosses the APEX boundaries).
  1056. sharedLibraryInfo, exportedInfo := cc.ChooseStubOrImpl(ctx, dep)
  1057. // Re-get linkObject as ChooseStubOrImpl actually tells us which
  1058. // object (either from stub or non-stub) to use.
  1059. linkObject = android.OptionalPathForPath(sharedLibraryInfo.SharedLibrary)
  1060. linkPath = linkPathFromFilePath(linkObject.Path())
  1061. depPaths.linkDirs = append(depPaths.linkDirs, linkPath)
  1062. depPaths.linkObjects = append(depPaths.linkObjects, linkObject.String())
  1063. depPaths.depIncludePaths = append(depPaths.depIncludePaths, exportedInfo.IncludeDirs...)
  1064. depPaths.depSystemIncludePaths = append(depPaths.depSystemIncludePaths, exportedInfo.SystemIncludeDirs...)
  1065. depPaths.depClangFlags = append(depPaths.depClangFlags, exportedInfo.Flags...)
  1066. depPaths.depGeneratedHeaders = append(depPaths.depGeneratedHeaders, exportedInfo.GeneratedHeaders...)
  1067. directSharedLibDeps = append(directSharedLibDeps, sharedLibraryInfo)
  1068. // Record baseLibName for snapshots.
  1069. mod.Properties.SnapshotSharedLibs = append(mod.Properties.SnapshotSharedLibs, cc.BaseLibName(depName))
  1070. mod.Properties.AndroidMkSharedLibs = append(mod.Properties.AndroidMkSharedLibs, makeLibName)
  1071. exportDep = true
  1072. case cc.IsHeaderDepTag(depTag):
  1073. exportedInfo := ctx.OtherModuleProvider(dep, cc.FlagExporterInfoProvider).(cc.FlagExporterInfo)
  1074. depPaths.depIncludePaths = append(depPaths.depIncludePaths, exportedInfo.IncludeDirs...)
  1075. depPaths.depSystemIncludePaths = append(depPaths.depSystemIncludePaths, exportedInfo.SystemIncludeDirs...)
  1076. depPaths.depGeneratedHeaders = append(depPaths.depGeneratedHeaders, exportedInfo.GeneratedHeaders...)
  1077. case depTag == cc.CrtBeginDepTag:
  1078. depPaths.CrtBegin = append(depPaths.CrtBegin, linkObject.Path())
  1079. case depTag == cc.CrtEndDepTag:
  1080. depPaths.CrtEnd = append(depPaths.CrtEnd, linkObject.Path())
  1081. }
  1082. // Make sure these dependencies are propagated
  1083. if lib, ok := mod.compiler.(exportedFlagsProducer); ok && exportDep {
  1084. lib.exportLinkDirs(linkPath)
  1085. lib.exportLinkObjects(linkObject.String())
  1086. }
  1087. } else {
  1088. switch {
  1089. case depTag == cc.CrtBeginDepTag:
  1090. depPaths.CrtBegin = append(depPaths.CrtBegin, android.OutputFileForModule(ctx, dep, ""))
  1091. case depTag == cc.CrtEndDepTag:
  1092. depPaths.CrtEnd = append(depPaths.CrtEnd, android.OutputFileForModule(ctx, dep, ""))
  1093. }
  1094. }
  1095. if srcDep, ok := dep.(android.SourceFileProducer); ok {
  1096. if android.IsSourceDepTagWithOutputTag(depTag, "") {
  1097. // These are usually genrules which don't have per-target variants.
  1098. directSrcDeps = append(directSrcDeps, srcDep)
  1099. }
  1100. }
  1101. })
  1102. var rlibDepFiles RustLibraries
  1103. for _, dep := range directRlibDeps {
  1104. rlibDepFiles = append(rlibDepFiles, RustLibrary{Path: dep.UnstrippedOutputFile(), CrateName: dep.CrateName()})
  1105. }
  1106. var dylibDepFiles RustLibraries
  1107. for _, dep := range directDylibDeps {
  1108. dylibDepFiles = append(dylibDepFiles, RustLibrary{Path: dep.UnstrippedOutputFile(), CrateName: dep.CrateName()})
  1109. }
  1110. var procMacroDepFiles RustLibraries
  1111. for _, dep := range directProcMacroDeps {
  1112. procMacroDepFiles = append(procMacroDepFiles, RustLibrary{Path: dep.UnstrippedOutputFile(), CrateName: dep.CrateName()})
  1113. }
  1114. var staticLibDepFiles android.Paths
  1115. for _, dep := range directStaticLibDeps {
  1116. staticLibDepFiles = append(staticLibDepFiles, dep.OutputFile().Path())
  1117. }
  1118. var sharedLibFiles android.Paths
  1119. var sharedLibDepFiles android.Paths
  1120. for _, dep := range directSharedLibDeps {
  1121. sharedLibFiles = append(sharedLibFiles, dep.SharedLibrary)
  1122. if dep.TableOfContents.Valid() {
  1123. sharedLibDepFiles = append(sharedLibDepFiles, dep.TableOfContents.Path())
  1124. } else {
  1125. sharedLibDepFiles = append(sharedLibDepFiles, dep.SharedLibrary)
  1126. }
  1127. }
  1128. var srcProviderDepFiles android.Paths
  1129. for _, dep := range directSrcProvidersDeps {
  1130. srcs, _ := dep.OutputFiles("")
  1131. srcProviderDepFiles = append(srcProviderDepFiles, srcs...)
  1132. }
  1133. for _, dep := range directSrcDeps {
  1134. srcs := dep.Srcs()
  1135. srcProviderDepFiles = append(srcProviderDepFiles, srcs...)
  1136. }
  1137. depPaths.RLibs = append(depPaths.RLibs, rlibDepFiles...)
  1138. depPaths.DyLibs = append(depPaths.DyLibs, dylibDepFiles...)
  1139. depPaths.SharedLibs = append(depPaths.SharedLibs, sharedLibDepFiles...)
  1140. depPaths.SharedLibDeps = append(depPaths.SharedLibDeps, sharedLibDepFiles...)
  1141. depPaths.StaticLibs = append(depPaths.StaticLibs, staticLibDepFiles...)
  1142. depPaths.ProcMacros = append(depPaths.ProcMacros, procMacroDepFiles...)
  1143. depPaths.SrcDeps = append(depPaths.SrcDeps, srcProviderDepFiles...)
  1144. // Dedup exported flags from dependencies
  1145. depPaths.linkDirs = android.FirstUniqueStrings(depPaths.linkDirs)
  1146. depPaths.linkObjects = android.FirstUniqueStrings(depPaths.linkObjects)
  1147. depPaths.depFlags = android.FirstUniqueStrings(depPaths.depFlags)
  1148. depPaths.depClangFlags = android.FirstUniqueStrings(depPaths.depClangFlags)
  1149. depPaths.depIncludePaths = android.FirstUniquePaths(depPaths.depIncludePaths)
  1150. depPaths.depSystemIncludePaths = android.FirstUniquePaths(depPaths.depSystemIncludePaths)
  1151. return depPaths
  1152. }
  1153. func (mod *Module) InstallInData() bool {
  1154. if mod.compiler == nil {
  1155. return false
  1156. }
  1157. return mod.compiler.inData()
  1158. }
  1159. func (mod *Module) InstallInRamdisk() bool {
  1160. return mod.InRamdisk()
  1161. }
  1162. func (mod *Module) InstallInVendorRamdisk() bool {
  1163. return mod.InVendorRamdisk()
  1164. }
  1165. func (mod *Module) InstallInRecovery() bool {
  1166. return mod.InRecovery()
  1167. }
  1168. func linkPathFromFilePath(filepath android.Path) string {
  1169. return strings.Split(filepath.String(), filepath.Base())[0]
  1170. }
  1171. func (mod *Module) DepsMutator(actx android.BottomUpMutatorContext) {
  1172. ctx := &depsContext{
  1173. BottomUpMutatorContext: actx,
  1174. }
  1175. deps := mod.deps(ctx)
  1176. var commonDepVariations []blueprint.Variation
  1177. var snapshotInfo *cc.SnapshotInfo
  1178. apiImportInfo := cc.GetApiImports(mod, actx)
  1179. for idx, lib := range deps.SharedLibs {
  1180. deps.SharedLibs[idx] = cc.GetReplaceModuleName(lib, apiImportInfo.SharedLibs)
  1181. }
  1182. if ctx.Os() == android.Android {
  1183. deps.SharedLibs, _ = cc.RewriteLibs(mod, &snapshotInfo, actx, ctx.Config(), deps.SharedLibs)
  1184. }
  1185. stdLinkage := "dylib-std"
  1186. if mod.compiler.stdLinkage(ctx) == RlibLinkage {
  1187. stdLinkage = "rlib-std"
  1188. }
  1189. rlibDepVariations := commonDepVariations
  1190. if lib, ok := mod.compiler.(libraryInterface); !ok || !lib.sysroot() {
  1191. rlibDepVariations = append(rlibDepVariations,
  1192. blueprint.Variation{Mutator: "rust_stdlinkage", Variation: stdLinkage})
  1193. }
  1194. // rlibs
  1195. rlibDepVariations = append(rlibDepVariations, blueprint.Variation{Mutator: "rust_libraries", Variation: rlibVariation})
  1196. for _, lib := range deps.Rlibs {
  1197. depTag := rlibDepTag
  1198. lib = cc.GetReplaceModuleName(lib, cc.GetSnapshot(mod, &snapshotInfo, actx).Rlibs)
  1199. actx.AddVariationDependencies(rlibDepVariations, depTag, lib)
  1200. }
  1201. // dylibs
  1202. actx.AddVariationDependencies(
  1203. append(commonDepVariations, []blueprint.Variation{
  1204. {Mutator: "rust_libraries", Variation: dylibVariation}}...),
  1205. dylibDepTag, deps.Dylibs...)
  1206. // rustlibs
  1207. if deps.Rustlibs != nil && !mod.compiler.Disabled() {
  1208. autoDep := mod.compiler.(autoDeppable).autoDep(ctx)
  1209. for _, lib := range deps.Rustlibs {
  1210. if autoDep.depTag == rlibDepTag {
  1211. // Handle the rlib deptag case
  1212. addRlibDependency(actx, lib, mod, snapshotInfo, rlibDepVariations)
  1213. } else {
  1214. // autoDep.depTag is a dylib depTag. Not all rustlibs may be available as a dylib however.
  1215. // Check for the existence of the dylib deptag variant. Select it if available,
  1216. // otherwise select the rlib variant.
  1217. autoDepVariations := append(commonDepVariations,
  1218. blueprint.Variation{Mutator: "rust_libraries", Variation: autoDep.variation})
  1219. if actx.OtherModuleDependencyVariantExists(autoDepVariations, lib) {
  1220. actx.AddVariationDependencies(autoDepVariations, autoDep.depTag, lib)
  1221. } else {
  1222. // If there's no dylib dependency available, try to add the rlib dependency instead.
  1223. addRlibDependency(actx, lib, mod, snapshotInfo, rlibDepVariations)
  1224. }
  1225. }
  1226. }
  1227. }
  1228. // stdlibs
  1229. if deps.Stdlibs != nil {
  1230. if mod.compiler.stdLinkage(ctx) == RlibLinkage {
  1231. for _, lib := range deps.Stdlibs {
  1232. depTag := rlibDepTag
  1233. lib = cc.GetReplaceModuleName(lib, cc.GetSnapshot(mod, &snapshotInfo, actx).Rlibs)
  1234. actx.AddVariationDependencies(append(commonDepVariations, []blueprint.Variation{{Mutator: "rust_libraries", Variation: "rlib"}}...),
  1235. depTag, lib)
  1236. }
  1237. } else {
  1238. actx.AddVariationDependencies(
  1239. append(commonDepVariations, blueprint.Variation{Mutator: "rust_libraries", Variation: "dylib"}),
  1240. dylibDepTag, deps.Stdlibs...)
  1241. }
  1242. }
  1243. for _, lib := range deps.SharedLibs {
  1244. depTag := cc.SharedDepTag()
  1245. name, version := cc.StubsLibNameAndVersion(lib)
  1246. variations := []blueprint.Variation{
  1247. {Mutator: "link", Variation: "shared"},
  1248. }
  1249. cc.AddSharedLibDependenciesWithVersions(ctx, mod, variations, depTag, name, version, false)
  1250. }
  1251. for _, lib := range deps.WholeStaticLibs {
  1252. depTag := cc.StaticDepTag(true)
  1253. lib = cc.GetReplaceModuleName(lib, cc.GetSnapshot(mod, &snapshotInfo, actx).StaticLibs)
  1254. actx.AddVariationDependencies([]blueprint.Variation{
  1255. {Mutator: "link", Variation: "static"},
  1256. }, depTag, lib)
  1257. }
  1258. for _, lib := range deps.StaticLibs {
  1259. depTag := cc.StaticDepTag(false)
  1260. lib = cc.GetReplaceModuleName(lib, cc.GetSnapshot(mod, &snapshotInfo, actx).StaticLibs)
  1261. actx.AddVariationDependencies([]blueprint.Variation{
  1262. {Mutator: "link", Variation: "static"},
  1263. }, depTag, lib)
  1264. }
  1265. actx.AddVariationDependencies(nil, cc.HeaderDepTag(), deps.HeaderLibs...)
  1266. crtVariations := cc.GetCrtVariations(ctx, mod)
  1267. for _, crt := range deps.CrtBegin {
  1268. actx.AddVariationDependencies(crtVariations, cc.CrtBeginDepTag,
  1269. cc.GetReplaceModuleName(crt, cc.GetSnapshot(mod, &snapshotInfo, actx).Objects))
  1270. }
  1271. for _, crt := range deps.CrtEnd {
  1272. actx.AddVariationDependencies(crtVariations, cc.CrtEndDepTag,
  1273. cc.GetReplaceModuleName(crt, cc.GetSnapshot(mod, &snapshotInfo, actx).Objects))
  1274. }
  1275. if mod.sourceProvider != nil {
  1276. if bindgen, ok := mod.sourceProvider.(*bindgenDecorator); ok &&
  1277. bindgen.Properties.Custom_bindgen != "" {
  1278. actx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), customBindgenDepTag,
  1279. bindgen.Properties.Custom_bindgen)
  1280. }
  1281. }
  1282. actx.AddVariationDependencies([]blueprint.Variation{
  1283. {Mutator: "link", Variation: "shared"},
  1284. }, dataLibDepTag, deps.DataLibs...)
  1285. actx.AddVariationDependencies(nil, dataBinDepTag, deps.DataBins...)
  1286. // proc_macros are compiler plugins, and so we need the host arch variant as a dependendcy.
  1287. actx.AddFarVariationDependencies(ctx.Config().BuildOSTarget.Variations(), procMacroDepTag, deps.ProcMacros...)
  1288. }
  1289. // addRlibDependency will add an rlib dependency, rewriting to the snapshot library if available.
  1290. func addRlibDependency(actx android.BottomUpMutatorContext, lib string, mod *Module, snapshotInfo *cc.SnapshotInfo, variations []blueprint.Variation) {
  1291. lib = cc.GetReplaceModuleName(lib, cc.GetSnapshot(mod, &snapshotInfo, actx).Rlibs)
  1292. actx.AddVariationDependencies(variations, rlibDepTag, lib)
  1293. }
  1294. func BeginMutator(ctx android.BottomUpMutatorContext) {
  1295. if mod, ok := ctx.Module().(*Module); ok && mod.Enabled() {
  1296. mod.beginMutator(ctx)
  1297. }
  1298. }
  1299. func (mod *Module) beginMutator(actx android.BottomUpMutatorContext) {
  1300. ctx := &baseModuleContext{
  1301. BaseModuleContext: actx,
  1302. }
  1303. mod.begin(ctx)
  1304. }
  1305. func (mod *Module) Name() string {
  1306. name := mod.ModuleBase.Name()
  1307. if p, ok := mod.compiler.(interface {
  1308. Name(string) string
  1309. }); ok {
  1310. name = p.Name(name)
  1311. }
  1312. return name
  1313. }
  1314. func (mod *Module) disableClippy() {
  1315. if mod.clippy != nil {
  1316. mod.clippy.Properties.Clippy_lints = proptools.StringPtr("none")
  1317. }
  1318. }
  1319. var _ android.HostToolProvider = (*Module)(nil)
  1320. var _ snapshot.RelativeInstallPath = (*Module)(nil)
  1321. func (mod *Module) HostToolPath() android.OptionalPath {
  1322. if !mod.Host() {
  1323. return android.OptionalPath{}
  1324. }
  1325. if binary, ok := mod.compiler.(*binaryDecorator); ok {
  1326. return android.OptionalPathForPath(binary.baseCompiler.path)
  1327. } else if pm, ok := mod.compiler.(*procMacroDecorator); ok {
  1328. // Even though proc-macros aren't strictly "tools", since they target the compiler
  1329. // and act as compiler plugins, we treat them similarly.
  1330. return android.OptionalPathForPath(pm.baseCompiler.path)
  1331. }
  1332. return android.OptionalPath{}
  1333. }
  1334. var _ android.ApexModule = (*Module)(nil)
  1335. func (mod *Module) MinSdkVersion() string {
  1336. return String(mod.Properties.Min_sdk_version)
  1337. }
  1338. // Implements android.ApexModule
  1339. func (mod *Module) ShouldSupportSdkVersion(ctx android.BaseModuleContext, sdkVersion android.ApiLevel) error {
  1340. minSdkVersion := mod.MinSdkVersion()
  1341. if minSdkVersion == "apex_inherit" {
  1342. return nil
  1343. }
  1344. if minSdkVersion == "" {
  1345. return fmt.Errorf("min_sdk_version is not specificed")
  1346. }
  1347. // Not using nativeApiLevelFromUser because the context here is not
  1348. // necessarily a native context.
  1349. ver, err := android.ApiLevelFromUser(ctx, minSdkVersion)
  1350. if err != nil {
  1351. return err
  1352. }
  1353. if ver.GreaterThan(sdkVersion) {
  1354. return fmt.Errorf("newer SDK(%v)", ver)
  1355. }
  1356. return nil
  1357. }
  1358. // Implements android.ApexModule
  1359. func (mod *Module) DepIsInSameApex(ctx android.BaseModuleContext, dep android.Module) bool {
  1360. depTag := ctx.OtherModuleDependencyTag(dep)
  1361. if ccm, ok := dep.(*cc.Module); ok {
  1362. if ccm.HasStubsVariants() {
  1363. if cc.IsSharedDepTag(depTag) {
  1364. // dynamic dep to a stubs lib crosses APEX boundary
  1365. return false
  1366. }
  1367. if cc.IsRuntimeDepTag(depTag) {
  1368. // runtime dep to a stubs lib also crosses APEX boundary
  1369. return false
  1370. }
  1371. if cc.IsHeaderDepTag(depTag) {
  1372. return false
  1373. }
  1374. }
  1375. if mod.Static() && cc.IsSharedDepTag(depTag) {
  1376. // shared_lib dependency from a static lib is considered as crossing
  1377. // the APEX boundary because the dependency doesn't actually is
  1378. // linked; the dependency is used only during the compilation phase.
  1379. return false
  1380. }
  1381. }
  1382. if depTag == procMacroDepTag || depTag == customBindgenDepTag {
  1383. return false
  1384. }
  1385. return true
  1386. }
  1387. // Overrides ApexModule.IsInstallabeToApex()
  1388. func (mod *Module) IsInstallableToApex() bool {
  1389. if mod.compiler != nil {
  1390. if lib, ok := mod.compiler.(libraryInterface); ok && (lib.shared() || lib.dylib()) {
  1391. return true
  1392. }
  1393. if _, ok := mod.compiler.(*binaryDecorator); ok {
  1394. return true
  1395. }
  1396. }
  1397. return false
  1398. }
  1399. // If a library file has a "lib" prefix, extract the library name without the prefix.
  1400. func libNameFromFilePath(filepath android.Path) (string, bool) {
  1401. libName := strings.TrimSuffix(filepath.Base(), filepath.Ext())
  1402. if strings.HasPrefix(libName, "lib") {
  1403. libName = libName[3:]
  1404. return libName, true
  1405. }
  1406. return "", false
  1407. }
  1408. func kytheExtractRustFactory() android.Singleton {
  1409. return &kytheExtractRustSingleton{}
  1410. }
  1411. type kytheExtractRustSingleton struct {
  1412. }
  1413. func (k kytheExtractRustSingleton) GenerateBuildActions(ctx android.SingletonContext) {
  1414. var xrefTargets android.Paths
  1415. ctx.VisitAllModules(func(module android.Module) {
  1416. if rustModule, ok := module.(xref); ok {
  1417. xrefTargets = append(xrefTargets, rustModule.XrefRustFiles()...)
  1418. }
  1419. })
  1420. if len(xrefTargets) > 0 {
  1421. ctx.Phony("xref_rust", xrefTargets...)
  1422. }
  1423. }
  1424. func (c *Module) Partition() string {
  1425. return ""
  1426. }
  1427. var Bool = proptools.Bool
  1428. var BoolDefault = proptools.BoolDefault
  1429. var String = proptools.String
  1430. var StringPtr = proptools.StringPtr
  1431. var _ android.OutputFileProducer = (*Module)(nil)