prebuilt.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. // Copyright 2016 Google Inc. All rights reserved.
  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 cc
  15. import (
  16. "path/filepath"
  17. "android/soong/android"
  18. "android/soong/bazel"
  19. "android/soong/bazel/cquery"
  20. )
  21. func init() {
  22. RegisterPrebuiltBuildComponents(android.InitRegistrationContext)
  23. }
  24. func RegisterPrebuiltBuildComponents(ctx android.RegistrationContext) {
  25. ctx.RegisterModuleType("cc_prebuilt_library", PrebuiltLibraryFactory)
  26. ctx.RegisterModuleType("cc_prebuilt_library_shared", PrebuiltSharedLibraryFactory)
  27. ctx.RegisterModuleType("cc_prebuilt_library_static", PrebuiltStaticLibraryFactory)
  28. ctx.RegisterModuleType("cc_prebuilt_test_library_shared", PrebuiltSharedTestLibraryFactory)
  29. ctx.RegisterModuleType("cc_prebuilt_object", PrebuiltObjectFactory)
  30. ctx.RegisterModuleType("cc_prebuilt_binary", PrebuiltBinaryFactory)
  31. }
  32. type prebuiltLinkerInterface interface {
  33. Name(string) string
  34. prebuilt() *android.Prebuilt
  35. }
  36. type prebuiltLinkerProperties struct {
  37. // a prebuilt library or binary. Can reference a genrule module that generates an executable file.
  38. Srcs []string `android:"path,arch_variant"`
  39. Sanitized Sanitized `android:"arch_variant"`
  40. // Check the prebuilt ELF files (e.g. DT_SONAME, DT_NEEDED, resolution of undefined
  41. // symbols, etc), default true.
  42. Check_elf_files *bool
  43. // if set, add an extra objcopy --prefix-symbols= step
  44. Prefix_symbols *string
  45. // Optionally provide an import library if this is a Windows PE DLL prebuilt.
  46. // This is needed only if this library is linked by other modules in build time.
  47. // Only makes sense for the Windows target.
  48. Windows_import_lib *string `android:"path,arch_variant"`
  49. // MixedBuildsDisabled is true if and only if building this prebuilt is explicitly disabled in mixed builds for either
  50. // its static or shared version on the current build variant. This is to prevent Bazel targets for build variants with
  51. // which either the static or shared version is incompatible from participating in mixed buiods. Please note that this
  52. // is an override and does not fully determine whether Bazel or Soong will be used. For the full determination, see
  53. // cc.ProcessBazelQueryResponse, cc.QueueBazelCall, and cc.MixedBuildsDisabled.
  54. MixedBuildsDisabled bool `blueprint:"mutated"`
  55. }
  56. type prebuiltLinker struct {
  57. android.Prebuilt
  58. properties prebuiltLinkerProperties
  59. }
  60. func (p *prebuiltLinker) prebuilt() *android.Prebuilt {
  61. return &p.Prebuilt
  62. }
  63. func (p *prebuiltLinker) PrebuiltSrcs() []string {
  64. return p.properties.Srcs
  65. }
  66. type prebuiltLibraryInterface interface {
  67. libraryInterface
  68. prebuiltLinkerInterface
  69. disablePrebuilt()
  70. }
  71. type prebuiltLibraryLinker struct {
  72. *libraryDecorator
  73. prebuiltLinker
  74. }
  75. var _ prebuiltLinkerInterface = (*prebuiltLibraryLinker)(nil)
  76. var _ prebuiltLibraryInterface = (*prebuiltLibraryLinker)(nil)
  77. func (p *prebuiltLibraryLinker) linkerInit(ctx BaseModuleContext) {}
  78. func (p *prebuiltLibraryLinker) linkerDeps(ctx DepsContext, deps Deps) Deps {
  79. return p.libraryDecorator.linkerDeps(ctx, deps)
  80. }
  81. func (p *prebuiltLibraryLinker) linkerFlags(ctx ModuleContext, flags Flags) Flags {
  82. return flags
  83. }
  84. func (p *prebuiltLibraryLinker) linkerProps() []interface{} {
  85. return p.libraryDecorator.linkerProps()
  86. }
  87. func (p *prebuiltLibraryLinker) link(ctx ModuleContext,
  88. flags Flags, deps PathDeps, objs Objects) android.Path {
  89. p.libraryDecorator.flagExporter.exportIncludes(ctx)
  90. p.libraryDecorator.flagExporter.reexportDirs(deps.ReexportedDirs...)
  91. p.libraryDecorator.flagExporter.reexportSystemDirs(deps.ReexportedSystemDirs...)
  92. p.libraryDecorator.flagExporter.reexportFlags(deps.ReexportedFlags...)
  93. p.libraryDecorator.flagExporter.reexportDeps(deps.ReexportedDeps...)
  94. p.libraryDecorator.flagExporter.addExportedGeneratedHeaders(deps.ReexportedGeneratedHeaders...)
  95. p.libraryDecorator.flagExporter.setProvider(ctx)
  96. // TODO(ccross): verify shared library dependencies
  97. srcs := p.prebuiltSrcs(ctx)
  98. if len(srcs) > 0 {
  99. if len(srcs) > 1 {
  100. ctx.PropertyErrorf("srcs", "multiple prebuilt source files")
  101. return nil
  102. }
  103. p.libraryDecorator.exportVersioningMacroIfNeeded(ctx)
  104. in := android.PathForModuleSrc(ctx, srcs[0])
  105. if String(p.prebuiltLinker.properties.Prefix_symbols) != "" {
  106. prefixed := android.PathForModuleOut(ctx, "prefixed", srcs[0])
  107. transformBinaryPrefixSymbols(ctx, String(p.prebuiltLinker.properties.Prefix_symbols),
  108. in, flagsToBuilderFlags(flags), prefixed)
  109. in = prefixed
  110. }
  111. if p.static() {
  112. depSet := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).Direct(in).Build()
  113. ctx.SetProvider(StaticLibraryInfoProvider, StaticLibraryInfo{
  114. StaticLibrary: in,
  115. TransitiveStaticLibrariesForOrdering: depSet,
  116. })
  117. return in
  118. }
  119. if p.shared() {
  120. p.unstrippedOutputFile = in
  121. libName := p.libraryDecorator.getLibName(ctx) + flags.Toolchain.ShlibSuffix()
  122. outputFile := android.PathForModuleOut(ctx, libName)
  123. var implicits android.Paths
  124. if p.stripper.NeedsStrip(ctx) {
  125. stripFlags := flagsToStripFlags(flags)
  126. stripped := android.PathForModuleOut(ctx, "stripped", libName)
  127. p.stripper.StripExecutableOrSharedLib(ctx, in, stripped, stripFlags)
  128. in = stripped
  129. }
  130. // Optimize out relinking against shared libraries whose interface hasn't changed by
  131. // depending on a table of contents file instead of the library itself.
  132. tocFile := android.PathForModuleOut(ctx, libName+".toc")
  133. p.tocFile = android.OptionalPathForPath(tocFile)
  134. TransformSharedObjectToToc(ctx, outputFile, tocFile)
  135. if ctx.Windows() && p.properties.Windows_import_lib != nil {
  136. // Consumers of this library actually links to the import library in build
  137. // time and dynamically links to the DLL in run time. i.e.
  138. // a.exe <-- static link --> foo.lib <-- dynamic link --> foo.dll
  139. importLibSrc := android.PathForModuleSrc(ctx, String(p.properties.Windows_import_lib))
  140. importLibName := p.libraryDecorator.getLibName(ctx) + ".lib"
  141. importLibOutputFile := android.PathForModuleOut(ctx, importLibName)
  142. implicits = append(implicits, importLibOutputFile)
  143. ctx.Build(pctx, android.BuildParams{
  144. Rule: android.Cp,
  145. Description: "prebuilt import library",
  146. Input: importLibSrc,
  147. Output: importLibOutputFile,
  148. Args: map[string]string{
  149. "cpFlags": "-L",
  150. },
  151. })
  152. }
  153. ctx.Build(pctx, android.BuildParams{
  154. Rule: android.Cp,
  155. Description: "prebuilt shared library",
  156. Implicits: implicits,
  157. Input: in,
  158. Output: outputFile,
  159. Args: map[string]string{
  160. "cpFlags": "-L",
  161. },
  162. })
  163. ctx.SetProvider(SharedLibraryInfoProvider, SharedLibraryInfo{
  164. SharedLibrary: outputFile,
  165. Target: ctx.Target(),
  166. TableOfContents: p.tocFile,
  167. })
  168. // TODO(b/220898484): Mainline module sdk prebuilts of stub libraries use a stub
  169. // library as their source and must not be installed, but other prebuilts like
  170. // libclang_rt.* libraries set `stubs` property because they are LLNDK libraries,
  171. // but use an implementation library as their source and need to be installed.
  172. // This discrepancy should be resolved without the prefix hack below.
  173. isModuleSdkPrebuilts := android.HasAnyPrefix(ctx.ModuleDir(), []string{
  174. "prebuilts/runtime/mainline/", "prebuilts/module_sdk/"})
  175. if p.hasStubsVariants() && !p.buildStubs() && !ctx.Host() && isModuleSdkPrebuilts {
  176. ctx.Module().MakeUninstallable()
  177. }
  178. return outputFile
  179. }
  180. }
  181. if p.header() {
  182. ctx.SetProvider(HeaderLibraryInfoProvider, HeaderLibraryInfo{})
  183. // Need to return an output path so that the AndroidMk logic doesn't skip
  184. // the prebuilt header. For compatibility, in case Android.mk files use a
  185. // header lib in LOCAL_STATIC_LIBRARIES, create an empty ar file as
  186. // placeholder, just like non-prebuilt header modules do in linkStatic().
  187. ph := android.PathForModuleOut(ctx, ctx.ModuleName()+staticLibraryExtension)
  188. transformObjToStaticLib(ctx, nil, nil, builderFlags{}, ph, nil, nil)
  189. return ph
  190. }
  191. return nil
  192. }
  193. func (p *prebuiltLibraryLinker) prebuiltSrcs(ctx android.BaseModuleContext) []string {
  194. sanitize := ctx.Module().(*Module).sanitize
  195. srcs := p.properties.Srcs
  196. srcs = append(srcs, srcsForSanitizer(sanitize, p.properties.Sanitized)...)
  197. if p.static() {
  198. srcs = append(srcs, p.libraryDecorator.StaticProperties.Static.Srcs...)
  199. srcs = append(srcs, srcsForSanitizer(sanitize, p.libraryDecorator.StaticProperties.Static.Sanitized)...)
  200. }
  201. if p.shared() {
  202. srcs = append(srcs, p.libraryDecorator.SharedProperties.Shared.Srcs...)
  203. srcs = append(srcs, srcsForSanitizer(sanitize, p.libraryDecorator.SharedProperties.Shared.Sanitized)...)
  204. }
  205. return srcs
  206. }
  207. func (p *prebuiltLibraryLinker) shared() bool {
  208. return p.libraryDecorator.shared()
  209. }
  210. func (p *prebuiltLibraryLinker) nativeCoverage() bool {
  211. return false
  212. }
  213. func (p *prebuiltLibraryLinker) disablePrebuilt() {
  214. p.properties.Srcs = nil
  215. p.properties.MixedBuildsDisabled = true
  216. }
  217. // Implements versionedInterface
  218. func (p *prebuiltLibraryLinker) implementationModuleName(name string) string {
  219. return android.RemoveOptionalPrebuiltPrefix(name)
  220. }
  221. func NewPrebuiltLibrary(hod android.HostOrDeviceSupported, srcsProperty string) (*Module, *libraryDecorator) {
  222. module, library := NewLibrary(hod)
  223. module.compiler = nil
  224. module.bazelable = true
  225. module.bazelHandler = &prebuiltLibraryBazelHandler{module: module, library: library}
  226. prebuilt := &prebuiltLibraryLinker{
  227. libraryDecorator: library,
  228. }
  229. module.linker = prebuilt
  230. module.library = prebuilt
  231. module.AddProperties(&prebuilt.properties)
  232. if srcsProperty == "" {
  233. android.InitPrebuiltModuleWithoutSrcs(module)
  234. } else {
  235. srcsSupplier := func(ctx android.BaseModuleContext, _ android.Module) []string {
  236. return prebuilt.prebuiltSrcs(ctx)
  237. }
  238. android.InitPrebuiltModuleWithSrcSupplier(module, srcsSupplier, srcsProperty)
  239. }
  240. return module, library
  241. }
  242. // cc_prebuilt_library installs a precompiled shared library that are
  243. // listed in the srcs property in the device's directory.
  244. func PrebuiltLibraryFactory() android.Module {
  245. module, _ := NewPrebuiltLibrary(android.HostAndDeviceSupported, "srcs")
  246. // Prebuilt shared libraries can be included in APEXes
  247. android.InitApexModule(module)
  248. return module.Init()
  249. }
  250. // cc_prebuilt_library_shared installs a precompiled shared library that are
  251. // listed in the srcs property in the device's directory.
  252. func PrebuiltSharedLibraryFactory() android.Module {
  253. module, _ := NewPrebuiltSharedLibrary(android.HostAndDeviceSupported)
  254. return module.Init()
  255. }
  256. // cc_prebuilt_test_library_shared installs a precompiled shared library
  257. // to be used as a data dependency of a test-related module (such as cc_test, or
  258. // cc_test_library).
  259. func PrebuiltSharedTestLibraryFactory() android.Module {
  260. module, library := NewPrebuiltLibrary(android.HostAndDeviceSupported, "srcs")
  261. library.BuildOnlyShared()
  262. library.baseInstaller = NewTestInstaller()
  263. return module.Init()
  264. }
  265. func NewPrebuiltSharedLibrary(hod android.HostOrDeviceSupported) (*Module, *libraryDecorator) {
  266. module, library := NewPrebuiltLibrary(hod, "srcs")
  267. library.BuildOnlyShared()
  268. // Prebuilt shared libraries can be included in APEXes
  269. android.InitApexModule(module)
  270. return module, library
  271. }
  272. // cc_prebuilt_library_static installs a precompiled static library that are
  273. // listed in the srcs property in the device's directory.
  274. func PrebuiltStaticLibraryFactory() android.Module {
  275. module, _ := NewPrebuiltStaticLibrary(android.HostAndDeviceSupported)
  276. return module.Init()
  277. }
  278. func NewPrebuiltStaticLibrary(hod android.HostOrDeviceSupported) (*Module, *libraryDecorator) {
  279. module, library := NewPrebuiltLibrary(hod, "srcs")
  280. library.BuildOnlyStatic()
  281. return module, library
  282. }
  283. type bazelPrebuiltLibraryStaticAttributes struct {
  284. Static_library bazel.LabelAttribute
  285. Export_includes bazel.StringListAttribute
  286. Export_system_includes bazel.StringListAttribute
  287. Alwayslink bazel.BoolAttribute
  288. }
  289. // TODO(b/228623543): The below is not entirely true until the bug is fixed. For now, both targets are always generated
  290. // Implements bp2build for cc_prebuilt_library modules. This will generate:
  291. // - Only a cc_prebuilt_library_static if the shared.enabled property is set to false across all variants.
  292. // - Only a cc_prebuilt_library_shared if the static.enabled property is set to false across all variants
  293. // - Both a cc_prebuilt_library_static and cc_prebuilt_library_shared if the aforementioned properties are not false across
  294. // all variants
  295. //
  296. // In all cases, cc_prebuilt_library_static target names will be appended with "_bp2build_cc_library_static".
  297. func prebuiltLibraryBp2Build(ctx android.TopDownMutatorContext, module *Module) {
  298. prebuiltLibraryStaticBp2Build(ctx, module, true)
  299. prebuiltLibrarySharedBp2Build(ctx, module)
  300. }
  301. func prebuiltLibraryStaticBp2Build(ctx android.TopDownMutatorContext, module *Module, fullBuild bool) {
  302. prebuiltAttrs := Bp2BuildParsePrebuiltLibraryProps(ctx, module, true)
  303. exportedIncludes := bp2BuildParseExportedIncludes(ctx, module, nil)
  304. attrs := &bazelPrebuiltLibraryStaticAttributes{
  305. Static_library: prebuiltAttrs.Src,
  306. Export_includes: exportedIncludes.Includes,
  307. Export_system_includes: exportedIncludes.SystemIncludes,
  308. // TODO: ¿Alwayslink?
  309. }
  310. props := bazel.BazelTargetModuleProperties{
  311. Rule_class: "cc_prebuilt_library_static",
  312. Bzl_load_location: "//build/bazel/rules/cc:cc_prebuilt_library_static.bzl",
  313. }
  314. name := android.RemoveOptionalPrebuiltPrefix(module.Name())
  315. if fullBuild {
  316. name += "_bp2build_cc_library_static"
  317. }
  318. tags := android.ApexAvailableTagsWithoutTestApexes(ctx, module)
  319. ctx.CreateBazelTargetModuleWithRestrictions(props, android.CommonAttributes{Name: name, Tags: tags}, attrs, prebuiltAttrs.Enabled)
  320. _true := true
  321. alwayslinkAttrs := *attrs
  322. alwayslinkAttrs.Alwayslink.SetValue(&_true)
  323. ctx.CreateBazelTargetModuleWithRestrictions(props, android.CommonAttributes{Name: name + "_alwayslink", Tags: tags}, &alwayslinkAttrs, prebuiltAttrs.Enabled)
  324. }
  325. type bazelPrebuiltLibrarySharedAttributes struct {
  326. Shared_library bazel.LabelAttribute
  327. Export_includes bazel.StringListAttribute
  328. Export_system_includes bazel.StringListAttribute
  329. }
  330. func prebuiltLibrarySharedBp2Build(ctx android.TopDownMutatorContext, module *Module) {
  331. prebuiltAttrs := Bp2BuildParsePrebuiltLibraryProps(ctx, module, false)
  332. exportedIncludes := bp2BuildParseExportedIncludes(ctx, module, nil)
  333. attrs := &bazelPrebuiltLibrarySharedAttributes{
  334. Shared_library: prebuiltAttrs.Src,
  335. Export_includes: exportedIncludes.Includes,
  336. Export_system_includes: exportedIncludes.SystemIncludes,
  337. }
  338. props := bazel.BazelTargetModuleProperties{
  339. Rule_class: "cc_prebuilt_library_shared",
  340. Bzl_load_location: "//build/bazel/rules/cc:cc_prebuilt_library_shared.bzl",
  341. }
  342. name := android.RemoveOptionalPrebuiltPrefix(module.Name())
  343. tags := android.ApexAvailableTagsWithoutTestApexes(ctx, module)
  344. ctx.CreateBazelTargetModuleWithRestrictions(props, android.CommonAttributes{Name: name, Tags: tags}, attrs, prebuiltAttrs.Enabled)
  345. }
  346. type prebuiltObjectProperties struct {
  347. Srcs []string `android:"path,arch_variant"`
  348. }
  349. type prebuiltObjectLinker struct {
  350. android.Prebuilt
  351. objectLinker
  352. properties prebuiltObjectProperties
  353. }
  354. type prebuiltLibraryBazelHandler struct {
  355. module *Module
  356. library *libraryDecorator
  357. }
  358. var _ BazelHandler = (*prebuiltLibraryBazelHandler)(nil)
  359. func (h *prebuiltLibraryBazelHandler) QueueBazelCall(ctx android.BaseModuleContext, label string) {
  360. if h.module.linker.(*prebuiltLibraryLinker).properties.MixedBuildsDisabled {
  361. return
  362. }
  363. bazelCtx := ctx.Config().BazelContext
  364. bazelCtx.QueueBazelRequest(label, cquery.GetCcInfo, android.GetConfigKey(ctx))
  365. }
  366. func (h *prebuiltLibraryBazelHandler) ProcessBazelQueryResponse(ctx android.ModuleContext, label string) {
  367. if h.module.linker.(*prebuiltLibraryLinker).properties.MixedBuildsDisabled {
  368. return
  369. }
  370. bazelCtx := ctx.Config().BazelContext
  371. ccInfo, err := bazelCtx.GetCcInfo(label, android.GetConfigKey(ctx))
  372. if err != nil {
  373. ctx.ModuleErrorf(err.Error())
  374. return
  375. }
  376. if h.module.static() {
  377. if ok := h.processStaticBazelQueryResponse(ctx, label, ccInfo); !ok {
  378. return
  379. }
  380. } else if h.module.Shared() {
  381. if ok := h.processSharedBazelQueryResponse(ctx, label, ccInfo); !ok {
  382. return
  383. }
  384. } else {
  385. return
  386. }
  387. h.module.maybeUnhideFromMake()
  388. h.module.setAndroidMkVariablesFromCquery(ccInfo.CcAndroidMkInfo)
  389. }
  390. func (h *prebuiltLibraryBazelHandler) processStaticBazelQueryResponse(ctx android.ModuleContext, label string, ccInfo cquery.CcInfo) bool {
  391. staticLibs := ccInfo.CcStaticLibraryFiles
  392. if len(staticLibs) > 1 {
  393. ctx.ModuleErrorf("expected 1 static library from bazel target %q, got %s", label, staticLibs)
  394. return false
  395. }
  396. // TODO(b/184543518): cc_prebuilt_library_static may have properties for re-exporting flags
  397. // TODO(eakammer):Add stub-related flags if this library is a stub library.
  398. // h.library.exportVersioningMacroIfNeeded(ctx)
  399. // Dependencies on this library will expect collectedSnapshotHeaders to be set, otherwise
  400. // validation will fail. For now, set this to an empty list.
  401. // TODO(cparsons): More closely mirror the collectHeadersForSnapshot implementation.
  402. h.library.collectedSnapshotHeaders = android.Paths{}
  403. if len(staticLibs) == 0 {
  404. h.module.outputFile = android.OptionalPath{}
  405. return true
  406. }
  407. var outputPath android.Path = android.PathForBazelOut(ctx, staticLibs[0])
  408. if len(ccInfo.TidyFiles) > 0 {
  409. h.module.tidyFiles = android.PathsForBazelOut(ctx, ccInfo.TidyFiles)
  410. outputPath = android.AttachValidationActions(ctx, outputPath, h.module.tidyFiles)
  411. }
  412. h.module.outputFile = android.OptionalPathForPath(outputPath)
  413. depSet := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).Direct(outputPath).Build()
  414. ctx.SetProvider(StaticLibraryInfoProvider, StaticLibraryInfo{
  415. StaticLibrary: outputPath,
  416. TransitiveStaticLibrariesForOrdering: depSet,
  417. })
  418. return true
  419. }
  420. func (h *prebuiltLibraryBazelHandler) processSharedBazelQueryResponse(ctx android.ModuleContext, label string, ccInfo cquery.CcInfo) bool {
  421. sharedLibs := ccInfo.CcSharedLibraryFiles
  422. if len(sharedLibs) > 1 {
  423. ctx.ModuleErrorf("expected 1 shared library from bazel target %s, got %q", label, sharedLibs)
  424. return false
  425. }
  426. // TODO(b/184543518): cc_prebuilt_library_shared may have properties for re-exporting flags
  427. // TODO(eakammer):Add stub-related flags if this library is a stub library.
  428. // h.library.exportVersioningMacroIfNeeded(ctx)
  429. if len(sharedLibs) == 0 {
  430. h.module.outputFile = android.OptionalPath{}
  431. return true
  432. }
  433. var outputPath android.Path = android.PathForBazelOut(ctx, sharedLibs[0])
  434. if len(ccInfo.TidyFiles) > 0 {
  435. h.module.tidyFiles = android.PathsForBazelOut(ctx, ccInfo.TidyFiles)
  436. outputPath = android.AttachValidationActions(ctx, outputPath, h.module.tidyFiles)
  437. }
  438. h.module.outputFile = android.OptionalPathForPath(outputPath)
  439. // FIXME(b/214600441): We don't yet strip prebuilt shared libraries
  440. h.library.unstrippedOutputFile = outputPath
  441. var toc android.Path
  442. if len(ccInfo.TocFile) > 0 {
  443. toc = android.PathForBazelOut(ctx, ccInfo.TocFile)
  444. } else {
  445. toc = outputPath // Just reuse `out` so ninja still gets an input but won't matter
  446. }
  447. info := SharedLibraryInfo{
  448. SharedLibrary: outputPath,
  449. TableOfContents: android.OptionalPathForPath(toc),
  450. Target: ctx.Target(),
  451. }
  452. ctx.SetProvider(SharedLibraryInfoProvider, info)
  453. h.library.setFlagExporterInfoFromCcInfo(ctx, ccInfo)
  454. h.module.maybeUnhideFromMake()
  455. return true
  456. }
  457. func (p *prebuiltObjectLinker) prebuilt() *android.Prebuilt {
  458. return &p.Prebuilt
  459. }
  460. var _ prebuiltLinkerInterface = (*prebuiltObjectLinker)(nil)
  461. func (p *prebuiltObjectLinker) link(ctx ModuleContext,
  462. flags Flags, deps PathDeps, objs Objects) android.Path {
  463. if len(p.properties.Srcs) > 0 {
  464. // Copy objects to a name matching the final installed name
  465. in := p.Prebuilt.SingleSourcePath(ctx)
  466. outputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".o")
  467. ctx.Build(pctx, android.BuildParams{
  468. Rule: android.CpExecutable,
  469. Description: "prebuilt",
  470. Output: outputFile,
  471. Input: in,
  472. })
  473. return outputFile
  474. }
  475. return nil
  476. }
  477. func (p *prebuiltObjectLinker) object() bool {
  478. return true
  479. }
  480. func NewPrebuiltObject(hod android.HostOrDeviceSupported) *Module {
  481. module := newObject(hod)
  482. module.bazelHandler = &prebuiltObjectBazelHandler{module: module}
  483. module.bazelable = true
  484. prebuilt := &prebuiltObjectLinker{
  485. objectLinker: objectLinker{
  486. baseLinker: NewBaseLinker(nil),
  487. },
  488. }
  489. module.linker = prebuilt
  490. module.AddProperties(&prebuilt.properties)
  491. android.InitPrebuiltModule(module, &prebuilt.properties.Srcs)
  492. return module
  493. }
  494. type prebuiltObjectBazelHandler struct {
  495. module *Module
  496. }
  497. var _ BazelHandler = (*prebuiltObjectBazelHandler)(nil)
  498. func (h *prebuiltObjectBazelHandler) QueueBazelCall(ctx android.BaseModuleContext, label string) {
  499. bazelCtx := ctx.Config().BazelContext
  500. bazelCtx.QueueBazelRequest(label, cquery.GetOutputFiles, android.GetConfigKey(ctx))
  501. }
  502. func (h *prebuiltObjectBazelHandler) ProcessBazelQueryResponse(ctx android.ModuleContext, label string) {
  503. bazelCtx := ctx.Config().BazelContext
  504. outputs, err := bazelCtx.GetOutputFiles(label, android.GetConfigKey(ctx))
  505. if err != nil {
  506. ctx.ModuleErrorf(err.Error())
  507. return
  508. }
  509. if len(outputs) != 1 {
  510. ctx.ModuleErrorf("Expected a single output for `%s`, but got:\n%v", label, outputs)
  511. return
  512. }
  513. out := android.PathForBazelOut(ctx, outputs[0])
  514. h.module.outputFile = android.OptionalPathForPath(out)
  515. h.module.maybeUnhideFromMake()
  516. }
  517. type bazelPrebuiltObjectAttributes struct {
  518. Src bazel.LabelAttribute
  519. }
  520. func prebuiltObjectBp2Build(ctx android.TopDownMutatorContext, module *Module) {
  521. prebuiltAttrs := bp2BuildParsePrebuiltObjectProps(ctx, module)
  522. attrs := &bazelPrebuiltObjectAttributes{
  523. Src: prebuiltAttrs.Src,
  524. }
  525. props := bazel.BazelTargetModuleProperties{
  526. Rule_class: "cc_prebuilt_object",
  527. Bzl_load_location: "//build/bazel/rules/cc:cc_prebuilt_object.bzl",
  528. }
  529. name := android.RemoveOptionalPrebuiltPrefix(module.Name())
  530. tags := android.ApexAvailableTagsWithoutTestApexes(ctx, module)
  531. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name, Tags: tags}, attrs)
  532. }
  533. func PrebuiltObjectFactory() android.Module {
  534. module := NewPrebuiltObject(android.HostAndDeviceSupported)
  535. return module.Init()
  536. }
  537. type prebuiltBinaryLinker struct {
  538. *binaryDecorator
  539. prebuiltLinker
  540. toolPath android.OptionalPath
  541. }
  542. var _ prebuiltLinkerInterface = (*prebuiltBinaryLinker)(nil)
  543. func (p *prebuiltBinaryLinker) hostToolPath() android.OptionalPath {
  544. return p.toolPath
  545. }
  546. func (p *prebuiltBinaryLinker) link(ctx ModuleContext,
  547. flags Flags, deps PathDeps, objs Objects) android.Path {
  548. // TODO(ccross): verify shared library dependencies
  549. if len(p.properties.Srcs) > 0 {
  550. fileName := p.getStem(ctx) + flags.Toolchain.ExecutableSuffix()
  551. in := p.Prebuilt.SingleSourcePath(ctx)
  552. outputFile := android.PathForModuleOut(ctx, fileName)
  553. p.unstrippedOutputFile = in
  554. if ctx.Host() {
  555. // Host binaries are symlinked to their prebuilt source locations. That
  556. // way they are executed directly from there so the linker resolves their
  557. // shared library dependencies relative to that location (using
  558. // $ORIGIN/../lib(64):$ORIGIN/lib(64) as RUNPATH). This way the prebuilt
  559. // repository can supply the expected versions of the shared libraries
  560. // without interference from what is in the out tree.
  561. // These shared lib paths may point to copies of the libs in
  562. // .intermediates, which isn't where the binary will load them from, but
  563. // it's fine for dependency tracking. If a library dependency is updated,
  564. // the symlink will get a new timestamp, along with any installed symlinks
  565. // handled in make.
  566. sharedLibPaths := deps.EarlySharedLibs
  567. sharedLibPaths = append(sharedLibPaths, deps.SharedLibs...)
  568. sharedLibPaths = append(sharedLibPaths, deps.LateSharedLibs...)
  569. var fromPath = in.String()
  570. if !filepath.IsAbs(fromPath) {
  571. fromPath = "$$PWD/" + fromPath
  572. }
  573. ctx.Build(pctx, android.BuildParams{
  574. Rule: android.Symlink,
  575. Output: outputFile,
  576. Input: in,
  577. Implicits: sharedLibPaths,
  578. Args: map[string]string{
  579. "fromPath": fromPath,
  580. },
  581. })
  582. p.toolPath = android.OptionalPathForPath(outputFile)
  583. } else {
  584. if p.stripper.NeedsStrip(ctx) {
  585. stripped := android.PathForModuleOut(ctx, "stripped", fileName)
  586. p.stripper.StripExecutableOrSharedLib(ctx, in, stripped, flagsToStripFlags(flags))
  587. in = stripped
  588. }
  589. // Copy binaries to a name matching the final installed name
  590. ctx.Build(pctx, android.BuildParams{
  591. Rule: android.CpExecutable,
  592. Description: "prebuilt",
  593. Output: outputFile,
  594. Input: in,
  595. })
  596. }
  597. return outputFile
  598. }
  599. return nil
  600. }
  601. func (p *prebuiltBinaryLinker) binary() bool {
  602. return true
  603. }
  604. // cc_prebuilt_binary installs a precompiled executable in srcs property in the
  605. // device's directory, for both the host and device
  606. func PrebuiltBinaryFactory() android.Module {
  607. module, _ := NewPrebuiltBinary(android.HostAndDeviceSupported)
  608. return module.Init()
  609. }
  610. type prebuiltBinaryBazelHandler struct {
  611. module *Module
  612. decorator *binaryDecorator
  613. }
  614. func NewPrebuiltBinary(hod android.HostOrDeviceSupported) (*Module, *binaryDecorator) {
  615. module, binary := newBinary(hod, true)
  616. module.compiler = nil
  617. module.bazelHandler = &prebuiltBinaryBazelHandler{module, binary}
  618. prebuilt := &prebuiltBinaryLinker{
  619. binaryDecorator: binary,
  620. }
  621. module.linker = prebuilt
  622. module.installer = prebuilt
  623. module.AddProperties(&prebuilt.properties)
  624. android.InitPrebuiltModule(module, &prebuilt.properties.Srcs)
  625. return module, binary
  626. }
  627. var _ BazelHandler = (*prebuiltBinaryBazelHandler)(nil)
  628. func (h *prebuiltBinaryBazelHandler) QueueBazelCall(ctx android.BaseModuleContext, label string) {
  629. bazelCtx := ctx.Config().BazelContext
  630. bazelCtx.QueueBazelRequest(label, cquery.GetOutputFiles, android.GetConfigKeyApexVariant(ctx, GetApexConfigKey(ctx)))
  631. }
  632. func (h *prebuiltBinaryBazelHandler) ProcessBazelQueryResponse(ctx android.ModuleContext, label string) {
  633. bazelCtx := ctx.Config().BazelContext
  634. outputs, err := bazelCtx.GetOutputFiles(label, android.GetConfigKeyApexVariant(ctx, GetApexConfigKey(ctx)))
  635. if err != nil {
  636. ctx.ModuleErrorf(err.Error())
  637. return
  638. }
  639. if len(outputs) != 1 {
  640. ctx.ModuleErrorf("Expected a single output for `%s`, but got:\n%v", label, outputs)
  641. return
  642. }
  643. out := android.PathForBazelOut(ctx, outputs[0])
  644. h.module.outputFile = android.OptionalPathForPath(out)
  645. h.module.maybeUnhideFromMake()
  646. }
  647. type bazelPrebuiltBinaryAttributes struct {
  648. Src bazel.LabelAttribute
  649. Strip stripAttributes
  650. }
  651. func prebuiltBinaryBp2Build(ctx android.TopDownMutatorContext, module *Module) {
  652. prebuiltAttrs := bp2BuildParsePrebuiltBinaryProps(ctx, module)
  653. var la linkerAttributes
  654. la.convertStripProps(ctx, module)
  655. attrs := &bazelPrebuiltBinaryAttributes{
  656. Src: prebuiltAttrs.Src,
  657. Strip: stripAttrsFromLinkerAttrs(&la),
  658. }
  659. props := bazel.BazelTargetModuleProperties{
  660. Rule_class: "cc_prebuilt_binary",
  661. Bzl_load_location: "//build/bazel/rules/cc:cc_prebuilt_binary.bzl",
  662. }
  663. name := android.RemoveOptionalPrebuiltPrefix(module.Name())
  664. tags := android.ApexAvailableTagsWithoutTestApexes(ctx, module)
  665. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: name, Tags: tags}, attrs)
  666. }
  667. type Sanitized struct {
  668. None struct {
  669. Srcs []string `android:"path,arch_variant"`
  670. } `android:"arch_variant"`
  671. Address struct {
  672. Srcs []string `android:"path,arch_variant"`
  673. } `android:"arch_variant"`
  674. Hwaddress struct {
  675. Srcs []string `android:"path,arch_variant"`
  676. } `android:"arch_variant"`
  677. }
  678. func srcsForSanitizer(sanitize *sanitize, sanitized Sanitized) []string {
  679. if sanitize == nil {
  680. return nil
  681. }
  682. if sanitize.isSanitizerEnabled(Asan) && sanitized.Address.Srcs != nil {
  683. return sanitized.Address.Srcs
  684. }
  685. if sanitize.isSanitizerEnabled(Hwasan) && sanitized.Hwaddress.Srcs != nil {
  686. return sanitized.Hwaddress.Srcs
  687. }
  688. return sanitized.None.Srcs
  689. }