prebuilt.go 27 KB

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