library.go 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101
  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. "fmt"
  17. "io"
  18. "path/filepath"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "sync"
  23. "android/soong/android"
  24. "android/soong/bazel"
  25. "android/soong/bazel/cquery"
  26. "github.com/google/blueprint"
  27. "github.com/google/blueprint/pathtools"
  28. "github.com/google/blueprint/proptools"
  29. )
  30. // LibraryProperties is a collection of properties shared by cc library rules/cc.
  31. type LibraryProperties struct {
  32. // local file name to pass to the linker as -unexported_symbols_list
  33. Unexported_symbols_list *string `android:"path,arch_variant"`
  34. // local file name to pass to the linker as -force_symbols_not_weak_list
  35. Force_symbols_not_weak_list *string `android:"path,arch_variant"`
  36. // local file name to pass to the linker as -force_symbols_weak_list
  37. Force_symbols_weak_list *string `android:"path,arch_variant"`
  38. // rename host libraries to prevent overlap with system installed libraries
  39. Unique_host_soname *bool
  40. Aidl struct {
  41. // export headers generated from .aidl sources
  42. Export_aidl_headers *bool
  43. }
  44. Proto struct {
  45. // export headers generated from .proto sources
  46. Export_proto_headers *bool
  47. }
  48. Sysprop struct {
  49. // Whether platform owns this sysprop library.
  50. Platform *bool
  51. } `blueprint:"mutated"`
  52. Static_ndk_lib *bool
  53. // Generate stubs to make this library accessible to APEXes.
  54. Stubs struct {
  55. // Relative path to the symbol map. The symbol map provides the list of
  56. // symbols that are exported for stubs variant of this library.
  57. Symbol_file *string `android:"path"`
  58. // List versions to generate stubs libs for. The version name "current" is always
  59. // implicitly added.
  60. Versions []string
  61. // Whether to not require the implementation of the library to be installed if a
  62. // client of the stubs is installed. Defaults to true; set to false if the
  63. // implementation is made available by some other means, e.g. in a Microdroid
  64. // virtual machine.
  65. Implementation_installable *bool
  66. }
  67. // set the name of the output
  68. Stem *string `android:"arch_variant"`
  69. // set suffix of the name of the output
  70. Suffix *string `android:"arch_variant"`
  71. // Properties for ABI compatibility checker.
  72. Header_abi_checker headerAbiCheckerProperties
  73. Target struct {
  74. Vendor, Product struct {
  75. // set suffix of the name of the output
  76. Suffix *string `android:"arch_variant"`
  77. Header_abi_checker headerAbiCheckerProperties
  78. }
  79. Platform struct {
  80. Header_abi_checker headerAbiCheckerProperties
  81. }
  82. }
  83. // Names of modules to be overridden. Listed modules can only be other shared libraries
  84. // (in Make or Soong).
  85. // This does not completely prevent installation of the overridden libraries, but if both
  86. // binaries would be installed by default (in PRODUCT_PACKAGES) the other library will be removed
  87. // from PRODUCT_PACKAGES.
  88. Overrides []string
  89. // Inject boringssl hash into the shared library. This is only intended for use by external/boringssl.
  90. Inject_bssl_hash *bool `android:"arch_variant"`
  91. // If this is an LLNDK library, properties to describe the LLNDK stubs. Will be copied from
  92. // the module pointed to by llndk_stubs if it is set.
  93. Llndk llndkLibraryProperties
  94. // If this is a vendor public library, properties to describe the vendor public library stubs.
  95. Vendor_public_library vendorPublicLibraryProperties
  96. }
  97. // StaticProperties is a properties stanza to affect only attributes of the "static" variants of a
  98. // library module.
  99. type StaticProperties struct {
  100. Static StaticOrSharedProperties `android:"arch_variant"`
  101. }
  102. // SharedProperties is a properties stanza to affect only attributes of the "shared" variants of a
  103. // library module.
  104. type SharedProperties struct {
  105. Shared StaticOrSharedProperties `android:"arch_variant"`
  106. }
  107. // StaticOrSharedProperties is an embedded struct representing properties to affect attributes of
  108. // either only the "static" variants or only the "shared" variants of a library module. These override
  109. // the base properties of the same name.
  110. // Use `StaticProperties` or `SharedProperties`, depending on which variant is needed.
  111. // `StaticOrSharedProperties` exists only to avoid duplication.
  112. type StaticOrSharedProperties struct {
  113. Srcs []string `android:"path,arch_variant"`
  114. Tidy_disabled_srcs []string `android:"path,arch_variant"`
  115. Tidy_timeout_srcs []string `android:"path,arch_variant"`
  116. Sanitized Sanitized `android:"arch_variant"`
  117. Cflags []string `android:"arch_variant"`
  118. Enabled *bool `android:"arch_variant"`
  119. Whole_static_libs []string `android:"arch_variant"`
  120. Static_libs []string `android:"arch_variant"`
  121. Shared_libs []string `android:"arch_variant"`
  122. System_shared_libs []string `android:"arch_variant"`
  123. Export_shared_lib_headers []string `android:"arch_variant"`
  124. Export_static_lib_headers []string `android:"arch_variant"`
  125. Apex_available []string `android:"arch_variant"`
  126. Installable *bool `android:"arch_variant"`
  127. }
  128. type LibraryMutatedProperties struct {
  129. // Build a static variant
  130. BuildStatic bool `blueprint:"mutated"`
  131. // Build a shared variant
  132. BuildShared bool `blueprint:"mutated"`
  133. // This variant is shared
  134. VariantIsShared bool `blueprint:"mutated"`
  135. // This variant is static
  136. VariantIsStatic bool `blueprint:"mutated"`
  137. // This variant is a stubs lib
  138. BuildStubs bool `blueprint:"mutated"`
  139. // This variant is the latest version
  140. IsLatestVersion bool `blueprint:"mutated"`
  141. // Version of the stubs lib
  142. StubsVersion string `blueprint:"mutated"`
  143. // List of all stubs versions associated with an implementation lib
  144. AllStubsVersions []string `blueprint:"mutated"`
  145. }
  146. type FlagExporterProperties struct {
  147. // list of directories relative to the Blueprints file that will
  148. // be added to the include path (using -I) for this module and any module that links
  149. // against this module. Directories listed in export_include_dirs do not need to be
  150. // listed in local_include_dirs.
  151. Export_include_dirs []string `android:"arch_variant,variant_prepend"`
  152. // list of directories that will be added to the system include path
  153. // using -isystem for this module and any module that links against this module.
  154. Export_system_include_dirs []string `android:"arch_variant,variant_prepend"`
  155. Target struct {
  156. Vendor, Product struct {
  157. // list of exported include directories, like
  158. // export_include_dirs, that will be applied to
  159. // vendor or product variant of this library.
  160. // This will overwrite any other declarations.
  161. Override_export_include_dirs []string
  162. }
  163. }
  164. }
  165. func init() {
  166. RegisterLibraryBuildComponents(android.InitRegistrationContext)
  167. }
  168. func RegisterLibraryBuildComponents(ctx android.RegistrationContext) {
  169. ctx.RegisterModuleType("cc_library_static", LibraryStaticFactory)
  170. ctx.RegisterModuleType("cc_library_shared", LibrarySharedFactory)
  171. ctx.RegisterModuleType("cc_library", LibraryFactory)
  172. ctx.RegisterModuleType("cc_library_host_static", LibraryHostStaticFactory)
  173. ctx.RegisterModuleType("cc_library_host_shared", LibraryHostSharedFactory)
  174. }
  175. // TODO(b/199902614): Can this be factored to share with the other Attributes?
  176. // For bp2build conversion.
  177. type bazelCcLibraryAttributes struct {
  178. // Attributes pertaining to both static and shared variants.
  179. Srcs bazel.LabelListAttribute
  180. Srcs_c bazel.LabelListAttribute
  181. Srcs_as bazel.LabelListAttribute
  182. Copts bazel.StringListAttribute
  183. Cppflags bazel.StringListAttribute
  184. Conlyflags bazel.StringListAttribute
  185. Asflags bazel.StringListAttribute
  186. Hdrs bazel.LabelListAttribute
  187. Deps bazel.LabelListAttribute
  188. Implementation_deps bazel.LabelListAttribute
  189. Dynamic_deps bazel.LabelListAttribute
  190. Implementation_dynamic_deps bazel.LabelListAttribute
  191. Whole_archive_deps bazel.LabelListAttribute
  192. Implementation_whole_archive_deps bazel.LabelListAttribute
  193. System_dynamic_deps bazel.LabelListAttribute
  194. Export_includes bazel.StringListAttribute
  195. Export_system_includes bazel.StringListAttribute
  196. Local_includes bazel.StringListAttribute
  197. Absolute_includes bazel.StringListAttribute
  198. Linkopts bazel.StringListAttribute
  199. Rtti bazel.BoolAttribute
  200. Stl *string
  201. Cpp_std *string
  202. C_std *string
  203. // This is shared only.
  204. Additional_linker_inputs bazel.LabelListAttribute
  205. // Common properties shared between both shared and static variants.
  206. Shared staticOrSharedAttributes
  207. Static staticOrSharedAttributes
  208. Strip stripAttributes
  209. Features bazel.StringListAttribute
  210. }
  211. type aidlLibraryAttributes struct {
  212. Srcs bazel.LabelListAttribute
  213. Include_dir *string
  214. Tags bazel.StringListAttribute
  215. }
  216. type ccAidlLibraryAttributes struct {
  217. Deps bazel.LabelListAttribute
  218. Implementation_deps bazel.LabelListAttribute
  219. Implementation_dynamic_deps bazel.LabelListAttribute
  220. Tags bazel.StringListAttribute
  221. sdkAttributes
  222. includesAttributes
  223. }
  224. type stripAttributes struct {
  225. Keep_symbols bazel.BoolAttribute
  226. Keep_symbols_and_debug_frame bazel.BoolAttribute
  227. Keep_symbols_list bazel.StringListAttribute
  228. All bazel.BoolAttribute
  229. None bazel.BoolAttribute
  230. }
  231. func stripAttrsFromLinkerAttrs(la *linkerAttributes) stripAttributes {
  232. return stripAttributes{
  233. Keep_symbols: la.stripKeepSymbols,
  234. Keep_symbols_and_debug_frame: la.stripKeepSymbolsAndDebugFrame,
  235. Keep_symbols_list: la.stripKeepSymbolsList,
  236. All: la.stripAll,
  237. None: la.stripNone,
  238. }
  239. }
  240. func libraryBp2Build(ctx android.TopDownMutatorContext, m *Module) {
  241. sharedAttrs := bp2BuildParseSharedProps(ctx, m)
  242. staticAttrs := bp2BuildParseStaticProps(ctx, m)
  243. baseAttributes := bp2BuildParseBaseProps(ctx, m)
  244. compilerAttrs := baseAttributes.compilerAttributes
  245. linkerAttrs := baseAttributes.linkerAttributes
  246. exportedIncludes := bp2BuildParseExportedIncludes(ctx, m, &compilerAttrs.includes)
  247. srcs := compilerAttrs.srcs
  248. sharedAttrs.Dynamic_deps.Add(baseAttributes.protoDependency)
  249. staticAttrs.Deps.Add(baseAttributes.protoDependency)
  250. asFlags := compilerAttrs.asFlags
  251. if compilerAttrs.asSrcs.IsEmpty() && sharedAttrs.Srcs_as.IsEmpty() && staticAttrs.Srcs_as.IsEmpty() {
  252. // Skip asflags for BUILD file simplicity if there are no assembly sources.
  253. asFlags = bazel.MakeStringListAttribute(nil)
  254. }
  255. sharedFeatures := baseAttributes.features.Clone().Append(sharedAttrs.Features)
  256. sharedFeatures.DeduplicateAxesFromBase()
  257. staticFeatures := baseAttributes.features.Clone().Append(staticAttrs.Features)
  258. staticFeatures.DeduplicateAxesFromBase()
  259. staticCommonAttrs := staticOrSharedAttributes{
  260. Srcs: *srcs.Clone().Append(staticAttrs.Srcs),
  261. Srcs_c: *compilerAttrs.cSrcs.Clone().Append(staticAttrs.Srcs_c),
  262. Srcs_as: *compilerAttrs.asSrcs.Clone().Append(staticAttrs.Srcs_as),
  263. Copts: *compilerAttrs.copts.Clone().Append(staticAttrs.Copts),
  264. Hdrs: *compilerAttrs.hdrs.Clone().Append(staticAttrs.Hdrs),
  265. Deps: *linkerAttrs.deps.Clone().Append(staticAttrs.Deps),
  266. Implementation_deps: *linkerAttrs.implementationDeps.Clone().Append(staticAttrs.Implementation_deps),
  267. Dynamic_deps: *linkerAttrs.dynamicDeps.Clone().Append(staticAttrs.Dynamic_deps),
  268. Implementation_dynamic_deps: *linkerAttrs.implementationDynamicDeps.Clone().Append(staticAttrs.Implementation_dynamic_deps),
  269. Implementation_whole_archive_deps: linkerAttrs.implementationWholeArchiveDeps,
  270. Whole_archive_deps: *linkerAttrs.wholeArchiveDeps.Clone().Append(staticAttrs.Whole_archive_deps),
  271. System_dynamic_deps: *linkerAttrs.systemDynamicDeps.Clone().Append(staticAttrs.System_dynamic_deps),
  272. Runtime_deps: linkerAttrs.runtimeDeps,
  273. sdkAttributes: bp2BuildParseSdkAttributes(m),
  274. Native_coverage: baseAttributes.Native_coverage,
  275. }
  276. includeAttrs := includesAttributes{
  277. Export_includes: exportedIncludes.Includes,
  278. Export_absolute_includes: exportedIncludes.AbsoluteIncludes,
  279. Export_system_includes: exportedIncludes.SystemIncludes,
  280. Local_includes: compilerAttrs.localIncludes,
  281. Absolute_includes: compilerAttrs.absoluteIncludes,
  282. }
  283. sharedCommonAttrs := staticOrSharedAttributes{
  284. Srcs: *srcs.Clone().Append(sharedAttrs.Srcs),
  285. Srcs_c: *compilerAttrs.cSrcs.Clone().Append(sharedAttrs.Srcs_c),
  286. Srcs_as: *compilerAttrs.asSrcs.Clone().Append(sharedAttrs.Srcs_as),
  287. Copts: *compilerAttrs.copts.Clone().Append(sharedAttrs.Copts),
  288. Hdrs: *compilerAttrs.hdrs.Clone().Append(sharedAttrs.Hdrs),
  289. Deps: *linkerAttrs.deps.Clone().Append(sharedAttrs.Deps),
  290. Implementation_deps: *linkerAttrs.implementationDeps.Clone().Append(sharedAttrs.Implementation_deps),
  291. Dynamic_deps: *linkerAttrs.dynamicDeps.Clone().Append(sharedAttrs.Dynamic_deps),
  292. Implementation_dynamic_deps: *linkerAttrs.implementationDynamicDeps.Clone().Append(sharedAttrs.Implementation_dynamic_deps),
  293. Whole_archive_deps: *linkerAttrs.wholeArchiveDeps.Clone().Append(sharedAttrs.Whole_archive_deps),
  294. Implementation_whole_archive_deps: linkerAttrs.implementationWholeArchiveDeps,
  295. System_dynamic_deps: *linkerAttrs.systemDynamicDeps.Clone().Append(sharedAttrs.System_dynamic_deps),
  296. Runtime_deps: linkerAttrs.runtimeDeps,
  297. sdkAttributes: bp2BuildParseSdkAttributes(m),
  298. Native_coverage: baseAttributes.Native_coverage,
  299. }
  300. staticTargetAttrs := &bazelCcLibraryStaticAttributes{
  301. staticOrSharedAttributes: staticCommonAttrs,
  302. includesAttributes: includeAttrs,
  303. Cppflags: compilerAttrs.cppFlags,
  304. Conlyflags: compilerAttrs.conlyFlags,
  305. Asflags: asFlags,
  306. Rtti: compilerAttrs.rtti,
  307. Stl: compilerAttrs.stl,
  308. Cpp_std: compilerAttrs.cppStd,
  309. C_std: compilerAttrs.cStd,
  310. Features: *staticFeatures,
  311. }
  312. sharedTargetAttrs := &bazelCcLibrarySharedAttributes{
  313. staticOrSharedAttributes: sharedCommonAttrs,
  314. includesAttributes: includeAttrs,
  315. Cppflags: compilerAttrs.cppFlags,
  316. Conlyflags: compilerAttrs.conlyFlags,
  317. Asflags: asFlags,
  318. Linkopts: linkerAttrs.linkopts,
  319. Rtti: compilerAttrs.rtti,
  320. Stl: compilerAttrs.stl,
  321. Cpp_std: compilerAttrs.cppStd,
  322. C_std: compilerAttrs.cStd,
  323. Use_version_lib: linkerAttrs.useVersionLib,
  324. Additional_linker_inputs: linkerAttrs.additionalLinkerInputs,
  325. Strip: stripAttrsFromLinkerAttrs(&linkerAttrs),
  326. Features: *sharedFeatures,
  327. bazelCcHeaderAbiCheckerAttributes: bp2buildParseAbiCheckerProps(ctx, m),
  328. Fdo_profile: compilerAttrs.fdoProfile,
  329. }
  330. if compilerAttrs.stubsSymbolFile != nil && len(compilerAttrs.stubsVersions.Value) > 0 {
  331. sharedTargetAttrs.Stubs_symbol_file = compilerAttrs.stubsSymbolFile
  332. }
  333. sharedTargetAttrs.Stem = compilerAttrs.stem
  334. sharedTargetAttrs.Suffix = compilerAttrs.suffix
  335. for axis, configToProps := range m.GetArchVariantProperties(ctx, &LibraryProperties{}) {
  336. for cfg, props := range configToProps {
  337. if props, ok := props.(*LibraryProperties); ok {
  338. if props.Inject_bssl_hash != nil {
  339. // This is an edge case applies only to libcrypto
  340. if m.Name() == "libcrypto" || m.Name() == "libcrypto_for_testing" {
  341. sharedTargetAttrs.Inject_bssl_hash.SetSelectValue(axis, cfg, props.Inject_bssl_hash)
  342. } else {
  343. ctx.PropertyErrorf("inject_bssl_hash", "only applies to libcrypto")
  344. }
  345. }
  346. }
  347. }
  348. }
  349. staticProps := bazel.BazelTargetModuleProperties{
  350. Rule_class: "cc_library_static",
  351. Bzl_load_location: "//build/bazel/rules/cc:cc_library_static.bzl",
  352. }
  353. sharedProps := bazel.BazelTargetModuleProperties{
  354. Rule_class: "cc_library_shared",
  355. Bzl_load_location: "//build/bazel/rules/cc:cc_library_shared.bzl",
  356. }
  357. var tagsForStaticVariant bazel.StringListAttribute
  358. if compilerAttrs.stubsSymbolFile == nil && len(compilerAttrs.stubsVersions.Value) == 0 {
  359. tagsForStaticVariant = android.ApexAvailableTagsWithoutTestApexes(ctx, m)
  360. }
  361. tagsForStaticVariant.Append(bazel.StringListAttribute{Value: staticAttrs.Apex_available})
  362. tagsForSharedVariant := android.ApexAvailableTagsWithoutTestApexes(ctx, m)
  363. tagsForSharedVariant.Append(bazel.StringListAttribute{Value: sharedAttrs.Apex_available})
  364. ctx.CreateBazelTargetModuleWithRestrictions(staticProps,
  365. android.CommonAttributes{
  366. Name: m.Name() + "_bp2build_cc_library_static",
  367. Tags: tagsForStaticVariant,
  368. },
  369. staticTargetAttrs, staticAttrs.Enabled)
  370. ctx.CreateBazelTargetModuleWithRestrictions(sharedProps,
  371. android.CommonAttributes{
  372. Name: m.Name(),
  373. Tags: tagsForSharedVariant,
  374. },
  375. sharedTargetAttrs, sharedAttrs.Enabled)
  376. createStubsBazelTargetIfNeeded(ctx, m, compilerAttrs, exportedIncludes, baseAttributes)
  377. }
  378. func createStubsBazelTargetIfNeeded(ctx android.TopDownMutatorContext, m *Module, compilerAttrs compilerAttributes, exportedIncludes BazelIncludes, baseAttributes baseAttributes) {
  379. if compilerAttrs.stubsSymbolFile != nil && len(compilerAttrs.stubsVersions.Value) > 0 {
  380. stubSuitesProps := bazel.BazelTargetModuleProperties{
  381. Rule_class: "cc_stub_suite",
  382. Bzl_load_location: "//build/bazel/rules/cc:cc_stub_library.bzl",
  383. }
  384. soname := m.Name() + ".so"
  385. stubSuitesAttrs := &bazelCcStubSuiteAttributes{
  386. Symbol_file: compilerAttrs.stubsSymbolFile,
  387. Versions: compilerAttrs.stubsVersions,
  388. Export_includes: exportedIncludes.Includes,
  389. Soname: &soname,
  390. Source_library_label: proptools.StringPtr(m.GetBazelLabel(ctx, m)),
  391. Deps: baseAttributes.deps,
  392. }
  393. ctx.CreateBazelTargetModule(stubSuitesProps,
  394. android.CommonAttributes{Name: m.Name() + "_stub_libs"},
  395. stubSuitesAttrs)
  396. // Add alias for the stub shared_library in @api_surfaces repository
  397. currentModuleLibApiDir := ctx.Config().ApiSurfacesDir(android.ModuleLibApi, "current")
  398. actualLabelInMainWorkspace := bazel.Label{
  399. Label: fmt.Sprintf("@//%s:%s%s", ctx.ModuleDir(), m.Name(), stubsSuffix),
  400. }
  401. ctx.CreateBazelTargetAliasInDir(currentModuleLibApiDir, m.Name(), actualLabelInMainWorkspace)
  402. // Add alias for headers exported by the stub library
  403. headerLabelInMainWorkspace := bazel.Label{
  404. // This label is generated from cc_stub_suite macro
  405. Label: fmt.Sprintf("@//%s:%s_stub_libs_%s_headers", ctx.ModuleDir(), m.Name(), android.ModuleLibApi.String()),
  406. }
  407. headerAlias := m.Name() + "_headers"
  408. ctx.CreateBazelTargetAliasInDir(currentModuleLibApiDir, headerAlias, headerLabelInMainWorkspace)
  409. }
  410. }
  411. func apiContributionBp2Build(ctx android.TopDownMutatorContext, module *Module) {
  412. apiSurfaces := make([]string, 0)
  413. apiHeaders := make([]string, 0)
  414. // module-libapi for apexes (non-null `stubs` property)
  415. if module.HasStubsVariants() {
  416. apiSurfaces = append(apiSurfaces, android.ModuleLibApi.String())
  417. apiIncludes := getModuleLibApiIncludes(ctx, module)
  418. if !apiIncludes.isEmpty() {
  419. createApiHeaderTarget(ctx, apiIncludes)
  420. apiHeaders = append(apiHeaders, apiIncludes.name)
  421. }
  422. }
  423. // vendorapi (non-null `llndk` property)
  424. if module.HasLlndkStubs() {
  425. apiSurfaces = append(apiSurfaces, android.VendorApi.String())
  426. apiIncludes := getVendorApiIncludes(ctx, module)
  427. if !apiIncludes.isEmpty() {
  428. createApiHeaderTarget(ctx, apiIncludes)
  429. apiHeaders = append(apiHeaders, apiIncludes.name)
  430. }
  431. }
  432. // create a target only if this module contributes to an api surface
  433. // TODO: Currently this does not distinguish modulelibapi-only headers and vendrorapi-only headers
  434. // TODO: Update so that modulelibapi-only headers do not get exported to vendorapi (and vice-versa)
  435. if len(apiSurfaces) > 0 {
  436. props := bazel.BazelTargetModuleProperties{
  437. Rule_class: "cc_api_contribution",
  438. Bzl_load_location: "//build/bazel/rules/apis:cc_api_contribution.bzl",
  439. }
  440. attrs := &bazelCcApiContributionAttributes{
  441. Library_name: module.Name(),
  442. Api_surfaces: bazel.MakeStringListAttribute(apiSurfaces),
  443. Api: apiLabelAttribute(ctx, module),
  444. Hdrs: bazel.MakeLabelListAttribute(
  445. bazel.MakeLabelListFromTargetNames(apiHeaders),
  446. ),
  447. }
  448. ctx.CreateBazelTargetModule(
  449. props,
  450. android.CommonAttributes{
  451. Name: android.ApiContributionTargetName(module.Name()),
  452. SkipData: proptools.BoolPtr(true),
  453. },
  454. attrs,
  455. )
  456. }
  457. }
  458. // Native apis are versioned in a single .map.txt for all api surfaces
  459. // Pick any one of the .map.txt files
  460. func apiLabelAttribute(ctx android.TopDownMutatorContext, module *Module) bazel.LabelAttribute {
  461. var apiFile *string
  462. linker := module.linker.(*libraryDecorator)
  463. if llndkApi := linker.Properties.Llndk.Symbol_file; llndkApi != nil {
  464. apiFile = llndkApi
  465. } else if moduleLibApi := linker.Properties.Stubs.Symbol_file; moduleLibApi != nil {
  466. apiFile = moduleLibApi
  467. } else {
  468. ctx.ModuleErrorf("API surface library does not have any API file")
  469. }
  470. apiLabel := android.BazelLabelForModuleSrcSingle(ctx, proptools.String(apiFile)).Label
  471. return *bazel.MakeLabelAttribute(apiLabel)
  472. }
  473. // wrapper struct to flatten the arch and os specific export_include_dirs
  474. // flattening is necessary since we want to export apis of all arches even when we build for x86 (e.g.)
  475. type bazelCcApiLibraryHeadersAttributes struct {
  476. bazelCcLibraryHeadersAttributes
  477. Arch *string
  478. }
  479. func (a *bazelCcApiLibraryHeadersAttributes) isEmpty() bool {
  480. return a.Export_includes.IsEmpty() &&
  481. a.Export_system_includes.IsEmpty() &&
  482. a.Deps.IsEmpty()
  483. }
  484. type apiIncludes struct {
  485. name string // name of the Bazel target in the generated bp2build workspace
  486. attrs bazelCcApiLibraryHeadersAttributes
  487. }
  488. func (includes *apiIncludes) isEmpty() bool {
  489. return includes.attrs.isEmpty()
  490. }
  491. func (includes *apiIncludes) addDep(name string) {
  492. l := bazel.Label{Label: ":" + name}
  493. ll := bazel.MakeLabelList([]bazel.Label{l})
  494. lla := bazel.MakeLabelListAttribute(ll)
  495. includes.attrs.Deps.Append(lla)
  496. }
  497. // includes provided to the module-lib API surface. This API surface is used by apexes.
  498. func getModuleLibApiIncludes(ctx android.TopDownMutatorContext, c *Module) apiIncludes {
  499. flagProps := c.library.(*libraryDecorator).flagExporter.Properties
  500. linkProps := c.library.(*libraryDecorator).baseLinker.Properties
  501. includes := android.FirstUniqueStrings(flagProps.Export_include_dirs)
  502. systemIncludes := android.FirstUniqueStrings(flagProps.Export_system_include_dirs)
  503. headerLibs := android.FirstUniqueStrings(linkProps.Export_header_lib_headers)
  504. attrs := bazelCcLibraryHeadersAttributes{
  505. Export_includes: bazel.MakeStringListAttribute(includes),
  506. Export_system_includes: bazel.MakeStringListAttribute(systemIncludes),
  507. Deps: bazel.MakeLabelListAttribute(apiHeaderLabels(ctx, headerLibs)),
  508. }
  509. return apiIncludes{
  510. name: c.Name() + ".module-libapi.headers",
  511. attrs: bazelCcApiLibraryHeadersAttributes{
  512. bazelCcLibraryHeadersAttributes: attrs,
  513. },
  514. }
  515. }
  516. func getVendorApiIncludes(ctx android.TopDownMutatorContext, c *Module) apiIncludes {
  517. baseProps := c.library.(*libraryDecorator).flagExporter.Properties
  518. llndkProps := c.library.(*libraryDecorator).Properties.Llndk
  519. includes := baseProps.Export_include_dirs
  520. systemIncludes := baseProps.Export_system_include_dirs
  521. // LLNDK can override the base includes
  522. if llndkIncludes := llndkProps.Override_export_include_dirs; llndkIncludes != nil {
  523. includes = llndkIncludes
  524. }
  525. if proptools.Bool(llndkProps.Export_headers_as_system) {
  526. systemIncludes = append(systemIncludes, includes...)
  527. includes = nil
  528. }
  529. attrs := bazelCcLibraryHeadersAttributes{
  530. Export_includes: bazel.MakeStringListAttribute(includes),
  531. Export_system_includes: bazel.MakeStringListAttribute(systemIncludes),
  532. Deps: bazel.MakeLabelListAttribute(apiHeaderLabels(ctx, llndkProps.Export_llndk_headers)),
  533. }
  534. return apiIncludes{
  535. name: c.Name() + ".vendorapi.headers",
  536. attrs: bazelCcApiLibraryHeadersAttributes{
  537. bazelCcLibraryHeadersAttributes: attrs,
  538. },
  539. }
  540. }
  541. // cc_library creates both static and/or shared libraries for a device and/or
  542. // host. By default, a cc_library has a single variant that targets the device.
  543. // Specifying `host_supported: true` also creates a library that targets the
  544. // host.
  545. func LibraryFactory() android.Module {
  546. module, _ := NewLibrary(android.HostAndDeviceSupported)
  547. // Can be used as both a static and a shared library.
  548. module.sdkMemberTypes = []android.SdkMemberType{
  549. sharedLibrarySdkMemberType,
  550. staticLibrarySdkMemberType,
  551. staticAndSharedLibrarySdkMemberType,
  552. }
  553. module.bazelable = true
  554. module.bazelHandler = &ccLibraryBazelHandler{module: module}
  555. return module.Init()
  556. }
  557. // cc_library_static creates a static library for a device and/or host binary.
  558. func LibraryStaticFactory() android.Module {
  559. module, library := NewLibrary(android.HostAndDeviceSupported)
  560. library.BuildOnlyStatic()
  561. module.sdkMemberTypes = []android.SdkMemberType{staticLibrarySdkMemberType}
  562. module.bazelable = true
  563. module.bazelHandler = &ccLibraryBazelHandler{module: module}
  564. return module.Init()
  565. }
  566. // cc_library_shared creates a shared library for a device and/or host.
  567. func LibrarySharedFactory() android.Module {
  568. module, library := NewLibrary(android.HostAndDeviceSupported)
  569. library.BuildOnlyShared()
  570. module.sdkMemberTypes = []android.SdkMemberType{sharedLibrarySdkMemberType}
  571. module.bazelable = true
  572. module.bazelHandler = &ccLibraryBazelHandler{module: module}
  573. return module.Init()
  574. }
  575. // cc_library_host_static creates a static library that is linkable to a host
  576. // binary.
  577. func LibraryHostStaticFactory() android.Module {
  578. module, library := NewLibrary(android.HostSupported)
  579. library.BuildOnlyStatic()
  580. module.sdkMemberTypes = []android.SdkMemberType{staticLibrarySdkMemberType}
  581. module.bazelable = true
  582. module.bazelHandler = &ccLibraryBazelHandler{module: module}
  583. return module.Init()
  584. }
  585. // cc_library_host_shared creates a shared library that is usable on a host.
  586. func LibraryHostSharedFactory() android.Module {
  587. module, library := NewLibrary(android.HostSupported)
  588. library.BuildOnlyShared()
  589. module.sdkMemberTypes = []android.SdkMemberType{sharedLibrarySdkMemberType}
  590. module.bazelable = true
  591. module.bazelHandler = &ccLibraryBazelHandler{module: module}
  592. return module.Init()
  593. }
  594. // flagExporter is a separated portion of libraryDecorator pertaining to exported
  595. // include paths and flags. Keeping this dependency-related information separate
  596. // from the rest of library information is helpful in keeping data more structured
  597. // and explicit.
  598. type flagExporter struct {
  599. Properties FlagExporterProperties
  600. dirs android.Paths // Include directories to be included with -I
  601. systemDirs android.Paths // System include directories to be included with -isystem
  602. flags []string // Exported raw flags.
  603. deps android.Paths
  604. headers android.Paths
  605. }
  606. // exportedIncludes returns the effective include paths for this module and
  607. // any module that links against this module. This is obtained from
  608. // the export_include_dirs property in the appropriate target stanza.
  609. func (f *flagExporter) exportedIncludes(ctx ModuleContext) android.Paths {
  610. if ctx.inVendor() && f.Properties.Target.Vendor.Override_export_include_dirs != nil {
  611. return android.PathsForModuleSrc(ctx, f.Properties.Target.Vendor.Override_export_include_dirs)
  612. }
  613. if ctx.inProduct() && f.Properties.Target.Product.Override_export_include_dirs != nil {
  614. return android.PathsForModuleSrc(ctx, f.Properties.Target.Product.Override_export_include_dirs)
  615. }
  616. return android.PathsForModuleSrc(ctx, f.Properties.Export_include_dirs)
  617. }
  618. // exportIncludes registers the include directories and system include directories to be exported
  619. // transitively to modules depending on this module.
  620. func (f *flagExporter) exportIncludes(ctx ModuleContext) {
  621. f.dirs = append(f.dirs, f.exportedIncludes(ctx)...)
  622. f.systemDirs = append(f.systemDirs, android.PathsForModuleSrc(ctx, f.Properties.Export_system_include_dirs)...)
  623. }
  624. // exportIncludesAsSystem registers the include directories and system include directories to be
  625. // exported transitively both as system include directories to modules depending on this module.
  626. func (f *flagExporter) exportIncludesAsSystem(ctx ModuleContext) {
  627. // all dirs are force exported as system
  628. f.systemDirs = append(f.systemDirs, f.exportedIncludes(ctx)...)
  629. f.systemDirs = append(f.systemDirs, android.PathsForModuleSrc(ctx, f.Properties.Export_system_include_dirs)...)
  630. }
  631. // reexportDirs registers the given directories as include directories to be exported transitively
  632. // to modules depending on this module.
  633. func (f *flagExporter) reexportDirs(dirs ...android.Path) {
  634. f.dirs = append(f.dirs, dirs...)
  635. }
  636. // reexportSystemDirs registers the given directories as system include directories
  637. // to be exported transitively to modules depending on this module.
  638. func (f *flagExporter) reexportSystemDirs(dirs ...android.Path) {
  639. f.systemDirs = append(f.systemDirs, dirs...)
  640. }
  641. // reexportFlags registers the flags to be exported transitively to modules depending on this
  642. // module.
  643. func (f *flagExporter) reexportFlags(flags ...string) {
  644. if android.PrefixInList(flags, "-I") || android.PrefixInList(flags, "-isystem") {
  645. panic(fmt.Errorf("Exporting invalid flag %q: "+
  646. "use reexportDirs or reexportSystemDirs to export directories", flag))
  647. }
  648. f.flags = append(f.flags, flags...)
  649. }
  650. func (f *flagExporter) reexportDeps(deps ...android.Path) {
  651. f.deps = append(f.deps, deps...)
  652. }
  653. // addExportedGeneratedHeaders does nothing but collects generated header files.
  654. // This can be differ to exportedDeps which may contain phony files to minimize ninja.
  655. func (f *flagExporter) addExportedGeneratedHeaders(headers ...android.Path) {
  656. f.headers = append(f.headers, headers...)
  657. }
  658. func (f *flagExporter) setProvider(ctx android.ModuleContext) {
  659. ctx.SetProvider(FlagExporterInfoProvider, FlagExporterInfo{
  660. // Comes from Export_include_dirs property, and those of exported transitive deps
  661. IncludeDirs: android.FirstUniquePaths(f.dirs),
  662. // Comes from Export_system_include_dirs property, and those of exported transitive deps
  663. SystemIncludeDirs: android.FirstUniquePaths(f.systemDirs),
  664. // Used in very few places as a one-off way of adding extra defines.
  665. Flags: f.flags,
  666. // Used sparingly, for extra files that need to be explicitly exported to dependers,
  667. // or for phony files to minimize ninja.
  668. Deps: f.deps,
  669. // For exported generated headers, such as exported aidl headers, proto headers, or
  670. // sysprop headers.
  671. GeneratedHeaders: f.headers,
  672. })
  673. }
  674. // libraryDecorator wraps baseCompiler, baseLinker and baseInstaller to provide library-specific
  675. // functionality: static vs. shared linkage, reusing object files for shared libraries
  676. type libraryDecorator struct {
  677. Properties LibraryProperties
  678. StaticProperties StaticProperties
  679. SharedProperties SharedProperties
  680. MutatedProperties LibraryMutatedProperties
  681. // For reusing static library objects for shared library
  682. reuseObjects Objects
  683. // table-of-contents file to optimize out relinking when possible
  684. tocFile android.OptionalPath
  685. flagExporter
  686. flagExporterInfo *FlagExporterInfo
  687. stripper Stripper
  688. // For whole_static_libs
  689. objects Objects
  690. wholeStaticLibsFromPrebuilts android.Paths
  691. // Uses the module's name if empty, but can be overridden. Does not include
  692. // shlib suffix.
  693. libName string
  694. sabi *sabi
  695. // Output archive of gcno coverage information files
  696. coverageOutputFile android.OptionalPath
  697. // linked Source Abi Dump
  698. sAbiOutputFile android.OptionalPath
  699. // Source Abi Diff
  700. sAbiDiff android.Paths
  701. // Location of the static library in the sysroot. Empty if the library is
  702. // not included in the NDK.
  703. ndkSysrootPath android.Path
  704. // Location of the linked, unstripped library for shared libraries
  705. unstrippedOutputFile android.Path
  706. // Location of the file that should be copied to dist dir when requested
  707. distFile android.Path
  708. versionScriptPath android.OptionalPath
  709. postInstallCmds []string
  710. // If useCoreVariant is true, the vendor variant of a VNDK library is
  711. // not installed.
  712. useCoreVariant bool
  713. checkSameCoreVariant bool
  714. skipAPIDefine bool
  715. // Decorated interfaces
  716. *baseCompiler
  717. *baseLinker
  718. *baseInstaller
  719. collectedSnapshotHeaders android.Paths
  720. apiListCoverageXmlPath android.ModuleOutPath
  721. }
  722. type ccLibraryBazelHandler struct {
  723. module *Module
  724. }
  725. var _ BazelHandler = (*ccLibraryBazelHandler)(nil)
  726. // generateStaticBazelBuildActions constructs the StaticLibraryInfo Soong
  727. // provider from a Bazel shared library's CcInfo provider.
  728. func (handler *ccLibraryBazelHandler) generateStaticBazelBuildActions(ctx android.ModuleContext, label string, ccInfo cquery.CcInfo) {
  729. rootStaticArchives := ccInfo.RootStaticArchives
  730. if len(rootStaticArchives) != 1 {
  731. ctx.ModuleErrorf("expected exactly one root archive file for '%s', but got %s", label, rootStaticArchives)
  732. return
  733. }
  734. var outputFilePath android.Path = android.PathForBazelOut(ctx, rootStaticArchives[0])
  735. if len(ccInfo.TidyFiles) > 0 {
  736. handler.module.tidyFiles = android.PathsForBazelOut(ctx, ccInfo.TidyFiles)
  737. outputFilePath = android.AttachValidationActions(ctx, outputFilePath, handler.module.tidyFiles)
  738. }
  739. handler.module.outputFile = android.OptionalPathForPath(outputFilePath)
  740. objPaths := ccInfo.CcObjectFiles
  741. objFiles := make(android.Paths, len(objPaths))
  742. for i, objPath := range objPaths {
  743. objFiles[i] = android.PathForBazelOut(ctx, objPath)
  744. }
  745. objects := Objects{
  746. objFiles: objFiles,
  747. }
  748. ctx.SetProvider(StaticLibraryInfoProvider, StaticLibraryInfo{
  749. StaticLibrary: outputFilePath,
  750. ReuseObjects: objects,
  751. Objects: objects,
  752. // TODO(b/190524881): Include transitive static libraries in this provider to support
  753. // static libraries with deps.
  754. TransitiveStaticLibrariesForOrdering: android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).
  755. Direct(outputFilePath).
  756. Build(),
  757. })
  758. return
  759. }
  760. // generateSharedBazelBuildActions constructs the SharedLibraryInfo Soong
  761. // provider from a Bazel shared library's CcInfo provider.
  762. func (handler *ccLibraryBazelHandler) generateSharedBazelBuildActions(ctx android.ModuleContext, label string, ccInfo cquery.CcInfo) {
  763. rootDynamicLibraries := ccInfo.RootDynamicLibraries
  764. if len(rootDynamicLibraries) != 1 {
  765. ctx.ModuleErrorf("expected exactly one root dynamic library file for '%s', but got %s", label, rootDynamicLibraries)
  766. return
  767. }
  768. var outputFilePath android.Path = android.PathForBazelOut(ctx, rootDynamicLibraries[0])
  769. if len(ccInfo.TidyFiles) > 0 {
  770. handler.module.tidyFiles = android.PathsForBazelOut(ctx, ccInfo.TidyFiles)
  771. outputFilePath = android.AttachValidationActions(ctx, outputFilePath, handler.module.tidyFiles)
  772. }
  773. handler.module.outputFile = android.OptionalPathForPath(outputFilePath)
  774. handler.module.linker.(*libraryDecorator).unstrippedOutputFile = android.PathForBazelOut(ctx, ccInfo.UnstrippedOutput)
  775. var tocFile android.OptionalPath
  776. if len(ccInfo.TocFile) > 0 {
  777. tocFile = android.OptionalPathForPath(android.PathForBazelOut(ctx, ccInfo.TocFile))
  778. }
  779. handler.module.linker.(*libraryDecorator).tocFile = tocFile
  780. if len(ccInfo.AbiDiffFiles) > 0 {
  781. handler.module.linker.(*libraryDecorator).sAbiDiff = android.PathsForBazelOut(ctx, ccInfo.AbiDiffFiles)
  782. }
  783. ctx.SetProvider(SharedLibraryInfoProvider, SharedLibraryInfo{
  784. TableOfContents: tocFile,
  785. SharedLibrary: outputFilePath,
  786. Target: ctx.Target(),
  787. // TODO(b/190524881): Include transitive static libraries in this provider to support
  788. // static libraries with deps. The provider key for this is TransitiveStaticLibrariesForOrdering.
  789. })
  790. }
  791. func (handler *ccLibraryBazelHandler) QueueBazelCall(ctx android.BaseModuleContext, label string) {
  792. bazelCtx := ctx.Config().BazelContext
  793. bazelCtx.QueueBazelRequest(label, cquery.GetCcInfo, android.GetConfigKeyApexVariant(ctx, GetApexConfigKey(ctx)))
  794. if v := handler.module.library.stubsVersion(); v != "" {
  795. stubsLabel := label + "_stub_libs-" + v
  796. bazelCtx.QueueBazelRequest(stubsLabel, cquery.GetCcInfo, android.GetConfigKeyApexVariant(ctx, GetApexConfigKey(ctx)))
  797. }
  798. }
  799. func (handler *ccLibraryBazelHandler) ProcessBazelQueryResponse(ctx android.ModuleContext, label string) {
  800. if v := handler.module.library.stubsVersion(); v != "" {
  801. // if we are a stubs variant, just use the Bazel stubs target
  802. label = label + "_stub_libs-" + v
  803. }
  804. bazelCtx := ctx.Config().BazelContext
  805. ccInfo, err := bazelCtx.GetCcInfo(label, android.GetConfigKeyApexVariant(ctx, GetApexConfigKey(ctx)))
  806. if err != nil {
  807. ctx.ModuleErrorf("Error getting Bazel CcInfo: %s", err)
  808. return
  809. }
  810. if handler.module.static() {
  811. handler.generateStaticBazelBuildActions(ctx, label, ccInfo)
  812. } else if handler.module.Shared() {
  813. handler.generateSharedBazelBuildActions(ctx, label, ccInfo)
  814. } else {
  815. ctx.ModuleErrorf("Unhandled bazel case for %s (neither shared nor static!)", ctx.ModuleName())
  816. }
  817. handler.module.linker.(*libraryDecorator).setFlagExporterInfoFromCcInfo(ctx, ccInfo)
  818. handler.module.maybeUnhideFromMake()
  819. if i, ok := handler.module.linker.(snapshotLibraryInterface); ok {
  820. // Dependencies on this library will expect collectedSnapshotHeaders to
  821. // be set, otherwise validation will fail. For now, set this to an empty
  822. // list.
  823. // TODO(b/190533363): More closely mirror the collectHeadersForSnapshot
  824. // implementation.
  825. i.(*libraryDecorator).collectedSnapshotHeaders = android.Paths{}
  826. }
  827. handler.module.setAndroidMkVariablesFromCquery(ccInfo.CcAndroidMkInfo)
  828. cctx := moduleContextFromAndroidModuleContext(ctx, handler.module)
  829. addStubDependencyProviders(cctx)
  830. }
  831. func (library *libraryDecorator) setFlagExporterInfoFromCcInfo(ctx android.ModuleContext, ccInfo cquery.CcInfo) {
  832. flagExporterInfo := flagExporterInfoFromCcInfo(ctx, ccInfo)
  833. // flag exporters consolidates properties like includes, flags, dependencies that should be
  834. // exported from this module to other modules
  835. ctx.SetProvider(FlagExporterInfoProvider, flagExporterInfo)
  836. // Store flag info to be passed along to androidmk
  837. // TODO(b/184387147): Androidmk should be done in Bazel, not Soong.
  838. library.flagExporterInfo = &flagExporterInfo
  839. }
  840. func GlobHeadersForSnapshot(ctx android.ModuleContext, paths android.Paths) android.Paths {
  841. ret := android.Paths{}
  842. // Headers in the source tree should be globbed. On the contrast, generated headers
  843. // can't be globbed, and they should be manually collected.
  844. // So, we first filter out intermediate directories (which contains generated headers)
  845. // from exported directories, and then glob headers under remaining directories.
  846. for _, path := range paths {
  847. dir := path.String()
  848. // Skip if dir is for generated headers
  849. if strings.HasPrefix(dir, ctx.Config().OutDir()) {
  850. continue
  851. }
  852. // Filter out the generated headers from bazel.
  853. if strings.HasPrefix(dir, android.PathForBazelOut(ctx, "bazel-out").String()) {
  854. continue
  855. }
  856. // libeigen wrongly exports the root directory "external/eigen". But only two
  857. // subdirectories "Eigen" and "unsupported" contain exported header files. Even worse
  858. // some of them have no extension. So we need special treatment for libeigen in order
  859. // to glob correctly.
  860. if dir == "external/eigen" {
  861. // Only these two directories contains exported headers.
  862. for _, subdir := range []string{"Eigen", "unsupported/Eigen"} {
  863. globDir := "external/eigen/" + subdir + "/**/*"
  864. glob, err := ctx.GlobWithDeps(globDir, nil)
  865. if err != nil {
  866. ctx.ModuleErrorf("glob of %q failed: %s", globDir, err)
  867. return nil
  868. }
  869. for _, header := range glob {
  870. if strings.HasSuffix(header, "/") {
  871. continue
  872. }
  873. ext := filepath.Ext(header)
  874. if ext != "" && ext != ".h" {
  875. continue
  876. }
  877. ret = append(ret, android.PathForSource(ctx, header))
  878. }
  879. }
  880. continue
  881. }
  882. globDir := dir + "/**/*"
  883. glob, err := ctx.GlobWithDeps(globDir, nil)
  884. if err != nil {
  885. ctx.ModuleErrorf("glob of %q failed: %s", globDir, err)
  886. return nil
  887. }
  888. isLibcxx := strings.HasPrefix(dir, "external/libcxx/include")
  889. for _, header := range glob {
  890. if isLibcxx {
  891. // Glob all files under this special directory, because of C++ headers with no
  892. // extension.
  893. if strings.HasSuffix(header, "/") {
  894. continue
  895. }
  896. } else {
  897. // Filter out only the files with extensions that are headers.
  898. found := false
  899. for _, ext := range HeaderExts {
  900. if strings.HasSuffix(header, ext) {
  901. found = true
  902. break
  903. }
  904. }
  905. if !found {
  906. continue
  907. }
  908. }
  909. ret = append(ret, android.PathForSource(ctx, header))
  910. }
  911. }
  912. return ret
  913. }
  914. func GlobGeneratedHeadersForSnapshot(_ android.ModuleContext, paths android.Paths) android.Paths {
  915. ret := android.Paths{}
  916. for _, header := range paths {
  917. // TODO(b/148123511): remove exportedDeps after cleaning up genrule
  918. if strings.HasSuffix(header.Base(), "-phony") {
  919. continue
  920. }
  921. ret = append(ret, header)
  922. }
  923. return ret
  924. }
  925. // collectHeadersForSnapshot collects all exported headers from library.
  926. // It globs header files in the source tree for exported include directories,
  927. // and tracks generated header files separately.
  928. //
  929. // This is to be called from GenerateAndroidBuildActions, and then collected
  930. // header files can be retrieved by snapshotHeaders().
  931. func (l *libraryDecorator) collectHeadersForSnapshot(ctx android.ModuleContext) {
  932. ret := android.Paths{}
  933. // Headers in the source tree should be globbed. On the contrast, generated headers
  934. // can't be globbed, and they should be manually collected.
  935. // So, we first filter out intermediate directories (which contains generated headers)
  936. // from exported directories, and then glob headers under remaining directories.
  937. ret = append(ret, GlobHeadersForSnapshot(ctx, append(android.CopyOfPaths(l.flagExporter.dirs), l.flagExporter.systemDirs...))...)
  938. // Collect generated headers
  939. ret = append(ret, GlobGeneratedHeadersForSnapshot(ctx, append(android.CopyOfPaths(l.flagExporter.headers), l.flagExporter.deps...))...)
  940. l.collectedSnapshotHeaders = ret
  941. }
  942. // This returns all exported header files, both generated ones and headers from source tree.
  943. // collectHeadersForSnapshot() must be called before calling this.
  944. func (l *libraryDecorator) snapshotHeaders() android.Paths {
  945. if l.collectedSnapshotHeaders == nil {
  946. panic("snapshotHeaders() must be called after collectHeadersForSnapshot()")
  947. }
  948. return l.collectedSnapshotHeaders
  949. }
  950. // linkerProps returns the list of properties structs relevant for this library. (For example, if
  951. // the library is cc_shared_library, then static-library properties are omitted.)
  952. func (library *libraryDecorator) linkerProps() []interface{} {
  953. var props []interface{}
  954. props = append(props, library.baseLinker.linkerProps()...)
  955. props = append(props,
  956. &library.Properties,
  957. &library.MutatedProperties,
  958. &library.flagExporter.Properties,
  959. &library.stripper.StripProperties)
  960. if library.MutatedProperties.BuildShared {
  961. props = append(props, &library.SharedProperties)
  962. }
  963. if library.MutatedProperties.BuildStatic {
  964. props = append(props, &library.StaticProperties)
  965. }
  966. return props
  967. }
  968. // linkerFlags takes a Flags struct and augments it to contain linker flags that are defined by this
  969. // library, or that are implied by attributes of this library (such as whether this library is a
  970. // shared library).
  971. func (library *libraryDecorator) linkerFlags(ctx ModuleContext, flags Flags) Flags {
  972. flags = library.baseLinker.linkerFlags(ctx, flags)
  973. // MinGW spits out warnings about -fPIC even for -fpie?!) being ignored because
  974. // all code is position independent, and then those warnings get promoted to
  975. // errors.
  976. if !ctx.Windows() {
  977. flags.Global.CFlags = append(flags.Global.CFlags, "-fPIC")
  978. }
  979. if library.static() {
  980. flags.Local.CFlags = append(flags.Local.CFlags, library.StaticProperties.Static.Cflags...)
  981. } else if library.shared() {
  982. flags.Local.CFlags = append(flags.Local.CFlags, library.SharedProperties.Shared.Cflags...)
  983. }
  984. if library.shared() {
  985. libName := library.getLibName(ctx)
  986. var f []string
  987. if ctx.toolchain().Bionic() {
  988. f = append(f,
  989. "-nostdlib",
  990. "-Wl,--gc-sections",
  991. )
  992. }
  993. if ctx.Darwin() {
  994. f = append(f,
  995. "-dynamiclib",
  996. "-install_name @rpath/"+libName+flags.Toolchain.ShlibSuffix(),
  997. )
  998. if ctx.Arch().ArchType == android.X86 {
  999. f = append(f,
  1000. "-read_only_relocs suppress",
  1001. )
  1002. }
  1003. } else {
  1004. f = append(f, "-shared")
  1005. if !ctx.Windows() {
  1006. f = append(f, "-Wl,-soname,"+libName+flags.Toolchain.ShlibSuffix())
  1007. }
  1008. }
  1009. flags.Global.LdFlags = append(flags.Global.LdFlags, f...)
  1010. }
  1011. return flags
  1012. }
  1013. // compilerFlags takes a Flags and augments it to contain compile flags from global values,
  1014. // per-target values, module type values, per-module Blueprints properties, extra flags from
  1015. // `flags`, and generated sources from `deps`.
  1016. func (library *libraryDecorator) compilerFlags(ctx ModuleContext, flags Flags, deps PathDeps) Flags {
  1017. exportIncludeDirs := library.flagExporter.exportedIncludes(ctx)
  1018. if len(exportIncludeDirs) > 0 {
  1019. f := includeDirsToFlags(exportIncludeDirs)
  1020. flags.Local.CommonFlags = append(flags.Local.CommonFlags, f)
  1021. flags.Local.YasmFlags = append(flags.Local.YasmFlags, f)
  1022. }
  1023. flags = library.baseCompiler.compilerFlags(ctx, flags, deps)
  1024. if ctx.IsLlndk() {
  1025. // LLNDK libraries ignore most of the properties on the cc_library and use the
  1026. // LLNDK-specific properties instead.
  1027. // Wipe all the module-local properties, leaving only the global properties.
  1028. flags.Local = LocalOrGlobalFlags{}
  1029. }
  1030. if library.buildStubs() {
  1031. // Remove -include <file> when compiling stubs. Otherwise, the force included
  1032. // headers might cause conflicting types error with the symbols in the
  1033. // generated stubs source code. e.g.
  1034. // double acos(double); // in header
  1035. // void acos() {} // in the generated source code
  1036. removeInclude := func(flags []string) []string {
  1037. ret := flags[:0]
  1038. for _, f := range flags {
  1039. if strings.HasPrefix(f, "-include ") {
  1040. continue
  1041. }
  1042. ret = append(ret, f)
  1043. }
  1044. return ret
  1045. }
  1046. flags.Local.CommonFlags = removeInclude(flags.Local.CommonFlags)
  1047. flags.Local.CFlags = removeInclude(flags.Local.CFlags)
  1048. flags = addStubLibraryCompilerFlags(flags)
  1049. }
  1050. return flags
  1051. }
  1052. func (library *libraryDecorator) getHeaderAbiCheckerProperties(ctx android.BaseModuleContext) headerAbiCheckerProperties {
  1053. m := ctx.Module().(*Module)
  1054. variantProps := &library.Properties.Target.Platform.Header_abi_checker
  1055. if m.InVendor() {
  1056. variantProps = &library.Properties.Target.Vendor.Header_abi_checker
  1057. } else if m.InProduct() {
  1058. variantProps = &library.Properties.Target.Product.Header_abi_checker
  1059. }
  1060. props := library.Properties.Header_abi_checker
  1061. err := proptools.AppendProperties(&props, variantProps, nil)
  1062. if err != nil {
  1063. ctx.ModuleErrorf("Cannot merge headerAbiCheckerProperties: %s", err.Error())
  1064. }
  1065. return props
  1066. }
  1067. func (library *libraryDecorator) compile(ctx ModuleContext, flags Flags, deps PathDeps) Objects {
  1068. if ctx.IsLlndk() {
  1069. // This is the vendor variant of an LLNDK library, build the LLNDK stubs.
  1070. vndkVer := ctx.Module().(*Module).VndkVersion()
  1071. if !inList(vndkVer, ctx.Config().PlatformVersionActiveCodenames()) || vndkVer == "" {
  1072. // For non-enforcing devices, vndkVer is empty. Use "current" in that case, too.
  1073. vndkVer = "current"
  1074. }
  1075. if library.stubsVersion() != "" {
  1076. vndkVer = library.stubsVersion()
  1077. }
  1078. nativeAbiResult := parseNativeAbiDefinition(ctx,
  1079. String(library.Properties.Llndk.Symbol_file),
  1080. android.ApiLevelOrPanic(ctx, vndkVer), "--llndk")
  1081. objs := compileStubLibrary(ctx, flags, nativeAbiResult.stubSrc)
  1082. if !Bool(library.Properties.Llndk.Unversioned) {
  1083. library.versionScriptPath = android.OptionalPathForPath(
  1084. nativeAbiResult.versionScript)
  1085. }
  1086. return objs
  1087. }
  1088. if ctx.IsVendorPublicLibrary() {
  1089. nativeAbiResult := parseNativeAbiDefinition(ctx,
  1090. String(library.Properties.Vendor_public_library.Symbol_file),
  1091. android.FutureApiLevel, "")
  1092. objs := compileStubLibrary(ctx, flags, nativeAbiResult.stubSrc)
  1093. if !Bool(library.Properties.Vendor_public_library.Unversioned) {
  1094. library.versionScriptPath = android.OptionalPathForPath(nativeAbiResult.versionScript)
  1095. }
  1096. return objs
  1097. }
  1098. if library.buildStubs() {
  1099. symbolFile := String(library.Properties.Stubs.Symbol_file)
  1100. if symbolFile != "" && !strings.HasSuffix(symbolFile, ".map.txt") {
  1101. ctx.PropertyErrorf("symbol_file", "%q doesn't have .map.txt suffix", symbolFile)
  1102. return Objects{}
  1103. }
  1104. // b/239274367 --apex and --systemapi filters symbols tagged with # apex and #
  1105. // systemapi, respectively. The former is for symbols defined in platform libraries
  1106. // and the latter is for symbols defined in APEXes.
  1107. // A single library can contain either # apex or # systemapi, but not both.
  1108. // The stub generator (ndkstubgen) is additive, so passing _both_ of these to it should be a no-op.
  1109. // However, having this distinction helps guard accidental
  1110. // promotion or demotion of API and also helps the API review process b/191371676
  1111. var flag string
  1112. if ctx.Module().(android.ApexModule).NotInPlatform() {
  1113. flag = "--apex"
  1114. } else {
  1115. flag = "--systemapi"
  1116. }
  1117. // b/184712170, unless the lib is an NDK library, exclude all public symbols from
  1118. // the stub so that it is mandated that all symbols are explicitly marked with
  1119. // either apex or systemapi.
  1120. if !ctx.Module().(*Module).IsNdk(ctx.Config()) {
  1121. flag = flag + " --no-ndk"
  1122. }
  1123. nativeAbiResult := parseNativeAbiDefinition(ctx, symbolFile,
  1124. android.ApiLevelOrPanic(ctx, library.MutatedProperties.StubsVersion), flag)
  1125. objs := compileStubLibrary(ctx, flags, nativeAbiResult.stubSrc)
  1126. library.versionScriptPath = android.OptionalPathForPath(
  1127. nativeAbiResult.versionScript)
  1128. // Parse symbol file to get API list for coverage
  1129. if library.stubsVersion() == "current" && ctx.PrimaryArch() && !ctx.inRecovery() && !ctx.inProduct() && !ctx.inVendor() {
  1130. library.apiListCoverageXmlPath = parseSymbolFileForAPICoverage(ctx, symbolFile)
  1131. }
  1132. return objs
  1133. }
  1134. if !library.buildShared() && !library.buildStatic() {
  1135. if len(library.baseCompiler.Properties.Srcs) > 0 {
  1136. ctx.PropertyErrorf("srcs", "cc_library_headers must not have any srcs")
  1137. }
  1138. if len(library.StaticProperties.Static.Srcs) > 0 {
  1139. ctx.PropertyErrorf("static.srcs", "cc_library_headers must not have any srcs")
  1140. }
  1141. if len(library.SharedProperties.Shared.Srcs) > 0 {
  1142. ctx.PropertyErrorf("shared.srcs", "cc_library_headers must not have any srcs")
  1143. }
  1144. return Objects{}
  1145. }
  1146. if library.sabi.shouldCreateSourceAbiDump() {
  1147. exportIncludeDirs := library.flagExporter.exportedIncludes(ctx)
  1148. var SourceAbiFlags []string
  1149. for _, dir := range exportIncludeDirs.Strings() {
  1150. SourceAbiFlags = append(SourceAbiFlags, "-I"+dir)
  1151. }
  1152. for _, reexportedInclude := range library.sabi.Properties.ReexportedIncludes {
  1153. SourceAbiFlags = append(SourceAbiFlags, "-I"+reexportedInclude)
  1154. }
  1155. flags.SAbiFlags = SourceAbiFlags
  1156. totalLength := len(library.baseCompiler.Properties.Srcs) + len(deps.GeneratedSources) +
  1157. len(library.SharedProperties.Shared.Srcs) + len(library.StaticProperties.Static.Srcs)
  1158. if totalLength > 0 {
  1159. flags.SAbiDump = true
  1160. }
  1161. }
  1162. objs := library.baseCompiler.compile(ctx, flags, deps)
  1163. library.reuseObjects = objs
  1164. buildFlags := flagsToBuilderFlags(flags)
  1165. if library.static() {
  1166. srcs := android.PathsForModuleSrc(ctx, library.StaticProperties.Static.Srcs)
  1167. objs = objs.Append(compileObjs(ctx, buildFlags, android.DeviceStaticLibrary, srcs,
  1168. android.PathsForModuleSrc(ctx, library.StaticProperties.Static.Tidy_disabled_srcs),
  1169. android.PathsForModuleSrc(ctx, library.StaticProperties.Static.Tidy_timeout_srcs),
  1170. library.baseCompiler.pathDeps, library.baseCompiler.cFlagsDeps))
  1171. } else if library.shared() {
  1172. srcs := android.PathsForModuleSrc(ctx, library.SharedProperties.Shared.Srcs)
  1173. objs = objs.Append(compileObjs(ctx, buildFlags, android.DeviceSharedLibrary, srcs,
  1174. android.PathsForModuleSrc(ctx, library.SharedProperties.Shared.Tidy_disabled_srcs),
  1175. android.PathsForModuleSrc(ctx, library.SharedProperties.Shared.Tidy_timeout_srcs),
  1176. library.baseCompiler.pathDeps, library.baseCompiler.cFlagsDeps))
  1177. }
  1178. return objs
  1179. }
  1180. type libraryInterface interface {
  1181. versionedInterface
  1182. static() bool
  1183. shared() bool
  1184. objs() Objects
  1185. reuseObjs() Objects
  1186. toc() android.OptionalPath
  1187. // Returns true if the build options for the module have selected a static or shared build
  1188. buildStatic() bool
  1189. buildShared() bool
  1190. // Sets whether a specific variant is static or shared
  1191. setStatic()
  1192. setShared()
  1193. // Gets the ABI properties for vendor, product, or platform variant
  1194. getHeaderAbiCheckerProperties(ctx android.BaseModuleContext) headerAbiCheckerProperties
  1195. // Write LOCAL_ADDITIONAL_DEPENDENCIES for ABI diff
  1196. androidMkWriteAdditionalDependenciesForSourceAbiDiff(w io.Writer)
  1197. availableFor(string) bool
  1198. getAPIListCoverageXMLPath() android.ModuleOutPath
  1199. installable() *bool
  1200. }
  1201. type versionedInterface interface {
  1202. buildStubs() bool
  1203. setBuildStubs(isLatest bool)
  1204. hasStubsVariants() bool
  1205. isStubsImplementationRequired() bool
  1206. setStubsVersion(string)
  1207. stubsVersion() string
  1208. stubsVersions(ctx android.BaseMutatorContext) []string
  1209. setAllStubsVersions([]string)
  1210. allStubsVersions() []string
  1211. implementationModuleName(name string) string
  1212. hasLLNDKStubs() bool
  1213. hasLLNDKHeaders() bool
  1214. hasVendorPublicLibrary() bool
  1215. }
  1216. var _ libraryInterface = (*libraryDecorator)(nil)
  1217. var _ versionedInterface = (*libraryDecorator)(nil)
  1218. func (library *libraryDecorator) getLibNameHelper(baseModuleName string, inVendor bool, inProduct bool) string {
  1219. name := library.libName
  1220. if name == "" {
  1221. name = String(library.Properties.Stem)
  1222. if name == "" {
  1223. name = baseModuleName
  1224. }
  1225. }
  1226. suffix := ""
  1227. if inVendor {
  1228. suffix = String(library.Properties.Target.Vendor.Suffix)
  1229. } else if inProduct {
  1230. suffix = String(library.Properties.Target.Product.Suffix)
  1231. }
  1232. if suffix == "" {
  1233. suffix = String(library.Properties.Suffix)
  1234. }
  1235. return name + suffix
  1236. }
  1237. // getLibName returns the actual canonical name of the library (the name which
  1238. // should be passed to the linker via linker flags).
  1239. func (library *libraryDecorator) getLibName(ctx BaseModuleContext) string {
  1240. name := library.getLibNameHelper(ctx.baseModuleName(), ctx.inVendor(), ctx.inProduct())
  1241. if ctx.IsVndkExt() {
  1242. // vndk-ext lib should have the same name with original lib
  1243. ctx.VisitDirectDepsWithTag(vndkExtDepTag, func(module android.Module) {
  1244. originalName := module.(*Module).outputFile.Path()
  1245. name = strings.TrimSuffix(originalName.Base(), originalName.Ext())
  1246. })
  1247. }
  1248. if ctx.Host() && Bool(library.Properties.Unique_host_soname) {
  1249. if !strings.HasSuffix(name, "-host") {
  1250. name = name + "-host"
  1251. }
  1252. }
  1253. return name
  1254. }
  1255. var versioningMacroNamesListMutex sync.Mutex
  1256. func (library *libraryDecorator) linkerInit(ctx BaseModuleContext) {
  1257. location := InstallInSystem
  1258. if library.baseLinker.sanitize.inSanitizerDir() {
  1259. location = InstallInSanitizerDir
  1260. }
  1261. library.baseInstaller.location = location
  1262. library.baseLinker.linkerInit(ctx)
  1263. // Let baseLinker know whether this variant is for stubs or not, so that
  1264. // it can omit things that are not required for linking stubs.
  1265. library.baseLinker.dynamicProperties.BuildStubs = library.buildStubs()
  1266. if library.buildStubs() {
  1267. macroNames := versioningMacroNamesList(ctx.Config())
  1268. myName := versioningMacroName(ctx.ModuleName())
  1269. versioningMacroNamesListMutex.Lock()
  1270. defer versioningMacroNamesListMutex.Unlock()
  1271. if (*macroNames)[myName] == "" {
  1272. (*macroNames)[myName] = ctx.ModuleName()
  1273. } else if (*macroNames)[myName] != ctx.ModuleName() {
  1274. ctx.ModuleErrorf("Macro name %q for versioning conflicts with macro name from module %q ", myName, (*macroNames)[myName])
  1275. }
  1276. }
  1277. }
  1278. func (library *libraryDecorator) compilerDeps(ctx DepsContext, deps Deps) Deps {
  1279. if ctx.IsLlndk() {
  1280. // LLNDK libraries ignore most of the properties on the cc_library and use the
  1281. // LLNDK-specific properties instead.
  1282. return deps
  1283. }
  1284. deps = library.baseCompiler.compilerDeps(ctx, deps)
  1285. return deps
  1286. }
  1287. func (library *libraryDecorator) linkerDeps(ctx DepsContext, deps Deps) Deps {
  1288. if ctx.IsLlndk() {
  1289. // LLNDK libraries ignore most of the properties on the cc_library and use the
  1290. // LLNDK-specific properties instead.
  1291. deps.HeaderLibs = append([]string(nil), library.Properties.Llndk.Export_llndk_headers...)
  1292. deps.ReexportHeaderLibHeaders = append([]string(nil), library.Properties.Llndk.Export_llndk_headers...)
  1293. return deps
  1294. }
  1295. if ctx.IsVendorPublicLibrary() {
  1296. headers := library.Properties.Vendor_public_library.Export_public_headers
  1297. deps.HeaderLibs = append([]string(nil), headers...)
  1298. deps.ReexportHeaderLibHeaders = append([]string(nil), headers...)
  1299. return deps
  1300. }
  1301. if library.static() {
  1302. // Compare with nil because an empty list needs to be propagated.
  1303. if library.StaticProperties.Static.System_shared_libs != nil {
  1304. library.baseLinker.Properties.System_shared_libs = library.StaticProperties.Static.System_shared_libs
  1305. }
  1306. } else if library.shared() {
  1307. // Compare with nil because an empty list needs to be propagated.
  1308. if library.SharedProperties.Shared.System_shared_libs != nil {
  1309. library.baseLinker.Properties.System_shared_libs = library.SharedProperties.Shared.System_shared_libs
  1310. }
  1311. }
  1312. deps = library.baseLinker.linkerDeps(ctx, deps)
  1313. if library.static() {
  1314. deps.WholeStaticLibs = append(deps.WholeStaticLibs,
  1315. library.StaticProperties.Static.Whole_static_libs...)
  1316. deps.StaticLibs = append(deps.StaticLibs, library.StaticProperties.Static.Static_libs...)
  1317. deps.SharedLibs = append(deps.SharedLibs, library.StaticProperties.Static.Shared_libs...)
  1318. deps.ReexportSharedLibHeaders = append(deps.ReexportSharedLibHeaders, library.StaticProperties.Static.Export_shared_lib_headers...)
  1319. deps.ReexportStaticLibHeaders = append(deps.ReexportStaticLibHeaders, library.StaticProperties.Static.Export_static_lib_headers...)
  1320. } else if library.shared() {
  1321. if library.baseLinker.Properties.crt() {
  1322. deps.CrtBegin = append(deps.CrtBegin, ctx.toolchain().CrtBeginSharedLibrary()...)
  1323. deps.CrtEnd = append(deps.CrtEnd, ctx.toolchain().CrtEndSharedLibrary()...)
  1324. }
  1325. deps.WholeStaticLibs = append(deps.WholeStaticLibs, library.SharedProperties.Shared.Whole_static_libs...)
  1326. deps.StaticLibs = append(deps.StaticLibs, library.SharedProperties.Shared.Static_libs...)
  1327. deps.SharedLibs = append(deps.SharedLibs, library.SharedProperties.Shared.Shared_libs...)
  1328. deps.ReexportSharedLibHeaders = append(deps.ReexportSharedLibHeaders, library.SharedProperties.Shared.Export_shared_lib_headers...)
  1329. deps.ReexportStaticLibHeaders = append(deps.ReexportStaticLibHeaders, library.SharedProperties.Shared.Export_static_lib_headers...)
  1330. }
  1331. if ctx.inVendor() {
  1332. deps.WholeStaticLibs = removeListFromList(deps.WholeStaticLibs, library.baseLinker.Properties.Target.Vendor.Exclude_static_libs)
  1333. deps.SharedLibs = removeListFromList(deps.SharedLibs, library.baseLinker.Properties.Target.Vendor.Exclude_shared_libs)
  1334. deps.StaticLibs = removeListFromList(deps.StaticLibs, library.baseLinker.Properties.Target.Vendor.Exclude_static_libs)
  1335. deps.ReexportSharedLibHeaders = removeListFromList(deps.ReexportSharedLibHeaders, library.baseLinker.Properties.Target.Vendor.Exclude_shared_libs)
  1336. deps.ReexportStaticLibHeaders = removeListFromList(deps.ReexportStaticLibHeaders, library.baseLinker.Properties.Target.Vendor.Exclude_static_libs)
  1337. }
  1338. if ctx.inProduct() {
  1339. deps.WholeStaticLibs = removeListFromList(deps.WholeStaticLibs, library.baseLinker.Properties.Target.Product.Exclude_static_libs)
  1340. deps.SharedLibs = removeListFromList(deps.SharedLibs, library.baseLinker.Properties.Target.Product.Exclude_shared_libs)
  1341. deps.StaticLibs = removeListFromList(deps.StaticLibs, library.baseLinker.Properties.Target.Product.Exclude_static_libs)
  1342. deps.ReexportSharedLibHeaders = removeListFromList(deps.ReexportSharedLibHeaders, library.baseLinker.Properties.Target.Product.Exclude_shared_libs)
  1343. deps.ReexportStaticLibHeaders = removeListFromList(deps.ReexportStaticLibHeaders, library.baseLinker.Properties.Target.Product.Exclude_static_libs)
  1344. }
  1345. if ctx.inRecovery() {
  1346. deps.WholeStaticLibs = removeListFromList(deps.WholeStaticLibs, library.baseLinker.Properties.Target.Recovery.Exclude_static_libs)
  1347. deps.SharedLibs = removeListFromList(deps.SharedLibs, library.baseLinker.Properties.Target.Recovery.Exclude_shared_libs)
  1348. deps.StaticLibs = removeListFromList(deps.StaticLibs, library.baseLinker.Properties.Target.Recovery.Exclude_static_libs)
  1349. deps.ReexportSharedLibHeaders = removeListFromList(deps.ReexportSharedLibHeaders, library.baseLinker.Properties.Target.Recovery.Exclude_shared_libs)
  1350. deps.ReexportStaticLibHeaders = removeListFromList(deps.ReexportStaticLibHeaders, library.baseLinker.Properties.Target.Recovery.Exclude_static_libs)
  1351. }
  1352. if ctx.inRamdisk() {
  1353. deps.WholeStaticLibs = removeListFromList(deps.WholeStaticLibs, library.baseLinker.Properties.Target.Ramdisk.Exclude_static_libs)
  1354. deps.SharedLibs = removeListFromList(deps.SharedLibs, library.baseLinker.Properties.Target.Ramdisk.Exclude_shared_libs)
  1355. deps.StaticLibs = removeListFromList(deps.StaticLibs, library.baseLinker.Properties.Target.Ramdisk.Exclude_static_libs)
  1356. deps.ReexportSharedLibHeaders = removeListFromList(deps.ReexportSharedLibHeaders, library.baseLinker.Properties.Target.Ramdisk.Exclude_shared_libs)
  1357. deps.ReexportStaticLibHeaders = removeListFromList(deps.ReexportStaticLibHeaders, library.baseLinker.Properties.Target.Ramdisk.Exclude_static_libs)
  1358. }
  1359. if ctx.inVendorRamdisk() {
  1360. deps.WholeStaticLibs = removeListFromList(deps.WholeStaticLibs, library.baseLinker.Properties.Target.Vendor_ramdisk.Exclude_static_libs)
  1361. deps.SharedLibs = removeListFromList(deps.SharedLibs, library.baseLinker.Properties.Target.Vendor_ramdisk.Exclude_shared_libs)
  1362. deps.StaticLibs = removeListFromList(deps.StaticLibs, library.baseLinker.Properties.Target.Vendor_ramdisk.Exclude_static_libs)
  1363. deps.ReexportSharedLibHeaders = removeListFromList(deps.ReexportSharedLibHeaders, library.baseLinker.Properties.Target.Vendor_ramdisk.Exclude_shared_libs)
  1364. deps.ReexportStaticLibHeaders = removeListFromList(deps.ReexportStaticLibHeaders, library.baseLinker.Properties.Target.Vendor_ramdisk.Exclude_static_libs)
  1365. }
  1366. return deps
  1367. }
  1368. func (library *libraryDecorator) linkerSpecifiedDeps(specifiedDeps specifiedDeps) specifiedDeps {
  1369. specifiedDeps = library.baseLinker.linkerSpecifiedDeps(specifiedDeps)
  1370. var properties StaticOrSharedProperties
  1371. if library.static() {
  1372. properties = library.StaticProperties.Static
  1373. } else if library.shared() {
  1374. properties = library.SharedProperties.Shared
  1375. }
  1376. specifiedDeps.sharedLibs = append(specifiedDeps.sharedLibs, properties.Shared_libs...)
  1377. // Must distinguish nil and [] in system_shared_libs - ensure that [] in
  1378. // either input list doesn't come out as nil.
  1379. if specifiedDeps.systemSharedLibs == nil {
  1380. specifiedDeps.systemSharedLibs = properties.System_shared_libs
  1381. } else {
  1382. specifiedDeps.systemSharedLibs = append(specifiedDeps.systemSharedLibs, properties.System_shared_libs...)
  1383. }
  1384. specifiedDeps.sharedLibs = android.FirstUniqueStrings(specifiedDeps.sharedLibs)
  1385. if len(specifiedDeps.systemSharedLibs) > 0 {
  1386. // Skip this if systemSharedLibs is either nil or [], to ensure they are
  1387. // retained.
  1388. specifiedDeps.systemSharedLibs = android.FirstUniqueStrings(specifiedDeps.systemSharedLibs)
  1389. }
  1390. return specifiedDeps
  1391. }
  1392. func (library *libraryDecorator) linkStatic(ctx ModuleContext,
  1393. flags Flags, deps PathDeps, objs Objects) android.Path {
  1394. library.objects = deps.WholeStaticLibObjs.Copy()
  1395. library.objects = library.objects.Append(objs)
  1396. library.wholeStaticLibsFromPrebuilts = android.CopyOfPaths(deps.WholeStaticLibsFromPrebuilts)
  1397. fileName := ctx.ModuleName() + staticLibraryExtension
  1398. outputFile := android.PathForModuleOut(ctx, fileName)
  1399. builderFlags := flagsToBuilderFlags(flags)
  1400. if Bool(library.baseLinker.Properties.Use_version_lib) {
  1401. if ctx.Host() {
  1402. versionedOutputFile := outputFile
  1403. outputFile = android.PathForModuleOut(ctx, "unversioned", fileName)
  1404. library.injectVersionSymbol(ctx, outputFile, versionedOutputFile)
  1405. } else {
  1406. versionedOutputFile := android.PathForModuleOut(ctx, "versioned", fileName)
  1407. library.distFile = versionedOutputFile
  1408. library.injectVersionSymbol(ctx, outputFile, versionedOutputFile)
  1409. }
  1410. }
  1411. transformObjToStaticLib(ctx, library.objects.objFiles, deps.WholeStaticLibsFromPrebuilts, builderFlags, outputFile, nil, objs.tidyDepFiles)
  1412. library.coverageOutputFile = transformCoverageFilesToZip(ctx, library.objects, ctx.ModuleName())
  1413. ctx.CheckbuildFile(outputFile)
  1414. if library.static() {
  1415. ctx.SetProvider(StaticLibraryInfoProvider, StaticLibraryInfo{
  1416. StaticLibrary: outputFile,
  1417. ReuseObjects: library.reuseObjects,
  1418. Objects: library.objects,
  1419. WholeStaticLibsFromPrebuilts: library.wholeStaticLibsFromPrebuilts,
  1420. TransitiveStaticLibrariesForOrdering: android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).
  1421. Direct(outputFile).
  1422. Transitive(deps.TranstiveStaticLibrariesForOrdering).
  1423. Build(),
  1424. })
  1425. }
  1426. if library.header() {
  1427. ctx.SetProvider(HeaderLibraryInfoProvider, HeaderLibraryInfo{})
  1428. }
  1429. return outputFile
  1430. }
  1431. func ndkSharedLibDeps(ctx ModuleContext) android.Paths {
  1432. if ctx.Module().(*Module).IsSdkVariant() {
  1433. // The NDK sysroot timestamp file depends on all the NDK
  1434. // sysroot header and shared library files.
  1435. return android.Paths{getNdkBaseTimestampFile(ctx)}
  1436. }
  1437. return nil
  1438. }
  1439. func (library *libraryDecorator) linkShared(ctx ModuleContext,
  1440. flags Flags, deps PathDeps, objs Objects) android.Path {
  1441. var linkerDeps android.Paths
  1442. linkerDeps = append(linkerDeps, flags.LdFlagsDeps...)
  1443. linkerDeps = append(linkerDeps, ndkSharedLibDeps(ctx)...)
  1444. unexportedSymbols := ctx.ExpandOptionalSource(library.Properties.Unexported_symbols_list, "unexported_symbols_list")
  1445. forceNotWeakSymbols := ctx.ExpandOptionalSource(library.Properties.Force_symbols_not_weak_list, "force_symbols_not_weak_list")
  1446. forceWeakSymbols := ctx.ExpandOptionalSource(library.Properties.Force_symbols_weak_list, "force_symbols_weak_list")
  1447. if !ctx.Darwin() {
  1448. if unexportedSymbols.Valid() {
  1449. ctx.PropertyErrorf("unexported_symbols_list", "Only supported on Darwin")
  1450. }
  1451. if forceNotWeakSymbols.Valid() {
  1452. ctx.PropertyErrorf("force_symbols_not_weak_list", "Only supported on Darwin")
  1453. }
  1454. if forceWeakSymbols.Valid() {
  1455. ctx.PropertyErrorf("force_symbols_weak_list", "Only supported on Darwin")
  1456. }
  1457. } else {
  1458. if unexportedSymbols.Valid() {
  1459. flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,-unexported_symbols_list,"+unexportedSymbols.String())
  1460. linkerDeps = append(linkerDeps, unexportedSymbols.Path())
  1461. }
  1462. if forceNotWeakSymbols.Valid() {
  1463. flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,-force_symbols_not_weak_list,"+forceNotWeakSymbols.String())
  1464. linkerDeps = append(linkerDeps, forceNotWeakSymbols.Path())
  1465. }
  1466. if forceWeakSymbols.Valid() {
  1467. flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,-force_symbols_weak_list,"+forceWeakSymbols.String())
  1468. linkerDeps = append(linkerDeps, forceWeakSymbols.Path())
  1469. }
  1470. }
  1471. if library.versionScriptPath.Valid() {
  1472. linkerScriptFlags := "-Wl,--version-script," + library.versionScriptPath.String()
  1473. flags.Local.LdFlags = append(flags.Local.LdFlags, linkerScriptFlags)
  1474. linkerDeps = append(linkerDeps, library.versionScriptPath.Path())
  1475. }
  1476. fileName := library.getLibName(ctx) + flags.Toolchain.ShlibSuffix()
  1477. outputFile := android.PathForModuleOut(ctx, fileName)
  1478. unstrippedOutputFile := outputFile
  1479. var implicitOutputs android.WritablePaths
  1480. if ctx.Windows() {
  1481. importLibraryPath := android.PathForModuleOut(ctx, pathtools.ReplaceExtension(fileName, "lib"))
  1482. flags.Local.LdFlags = append(flags.Local.LdFlags, "-Wl,--out-implib="+importLibraryPath.String())
  1483. implicitOutputs = append(implicitOutputs, importLibraryPath)
  1484. }
  1485. builderFlags := flagsToBuilderFlags(flags)
  1486. if ctx.Darwin() && deps.DarwinSecondArchOutput.Valid() {
  1487. fatOutputFile := outputFile
  1488. outputFile = android.PathForModuleOut(ctx, "pre-fat", fileName)
  1489. transformDarwinUniversalBinary(ctx, fatOutputFile, outputFile, deps.DarwinSecondArchOutput.Path())
  1490. }
  1491. // Optimize out relinking against shared libraries whose interface hasn't changed by
  1492. // depending on a table of contents file instead of the library itself.
  1493. tocFile := outputFile.ReplaceExtension(ctx, flags.Toolchain.ShlibSuffix()[1:]+".toc")
  1494. library.tocFile = android.OptionalPathForPath(tocFile)
  1495. TransformSharedObjectToToc(ctx, outputFile, tocFile)
  1496. stripFlags := flagsToStripFlags(flags)
  1497. needsStrip := library.stripper.NeedsStrip(ctx)
  1498. if library.buildStubs() {
  1499. // No need to strip stubs libraries
  1500. needsStrip = false
  1501. }
  1502. if needsStrip {
  1503. if ctx.Darwin() {
  1504. stripFlags.StripUseGnuStrip = true
  1505. }
  1506. strippedOutputFile := outputFile
  1507. outputFile = android.PathForModuleOut(ctx, "unstripped", fileName)
  1508. library.stripper.StripExecutableOrSharedLib(ctx, outputFile, strippedOutputFile, stripFlags)
  1509. }
  1510. library.unstrippedOutputFile = outputFile
  1511. outputFile = maybeInjectBoringSSLHash(ctx, outputFile, library.Properties.Inject_bssl_hash, fileName)
  1512. if Bool(library.baseLinker.Properties.Use_version_lib) {
  1513. if ctx.Host() {
  1514. versionedOutputFile := outputFile
  1515. outputFile = android.PathForModuleOut(ctx, "unversioned", fileName)
  1516. library.injectVersionSymbol(ctx, outputFile, versionedOutputFile)
  1517. } else {
  1518. versionedOutputFile := android.PathForModuleOut(ctx, "versioned", fileName)
  1519. library.distFile = versionedOutputFile
  1520. if library.stripper.NeedsStrip(ctx) {
  1521. out := android.PathForModuleOut(ctx, "versioned-stripped", fileName)
  1522. library.distFile = out
  1523. library.stripper.StripExecutableOrSharedLib(ctx, versionedOutputFile, out, stripFlags)
  1524. }
  1525. library.injectVersionSymbol(ctx, outputFile, versionedOutputFile)
  1526. }
  1527. }
  1528. sharedLibs := deps.EarlySharedLibs
  1529. sharedLibs = append(sharedLibs, deps.SharedLibs...)
  1530. sharedLibs = append(sharedLibs, deps.LateSharedLibs...)
  1531. linkerDeps = append(linkerDeps, deps.EarlySharedLibsDeps...)
  1532. linkerDeps = append(linkerDeps, deps.SharedLibsDeps...)
  1533. linkerDeps = append(linkerDeps, deps.LateSharedLibsDeps...)
  1534. transformObjToDynamicBinary(ctx, objs.objFiles, sharedLibs,
  1535. deps.StaticLibs, deps.LateStaticLibs, deps.WholeStaticLibs,
  1536. linkerDeps, deps.CrtBegin, deps.CrtEnd, false, builderFlags, outputFile, implicitOutputs, objs.tidyDepFiles)
  1537. objs.coverageFiles = append(objs.coverageFiles, deps.StaticLibObjs.coverageFiles...)
  1538. objs.coverageFiles = append(objs.coverageFiles, deps.WholeStaticLibObjs.coverageFiles...)
  1539. objs.sAbiDumpFiles = append(objs.sAbiDumpFiles, deps.StaticLibObjs.sAbiDumpFiles...)
  1540. objs.sAbiDumpFiles = append(objs.sAbiDumpFiles, deps.WholeStaticLibObjs.sAbiDumpFiles...)
  1541. library.coverageOutputFile = transformCoverageFilesToZip(ctx, objs, library.getLibName(ctx))
  1542. library.linkSAbiDumpFiles(ctx, objs, fileName, unstrippedOutputFile)
  1543. var transitiveStaticLibrariesForOrdering *android.DepSet[android.Path]
  1544. if static := ctx.GetDirectDepsWithTag(staticVariantTag); len(static) > 0 {
  1545. s := ctx.OtherModuleProvider(static[0], StaticLibraryInfoProvider).(StaticLibraryInfo)
  1546. transitiveStaticLibrariesForOrdering = s.TransitiveStaticLibrariesForOrdering
  1547. }
  1548. ctx.SetProvider(SharedLibraryInfoProvider, SharedLibraryInfo{
  1549. TableOfContents: android.OptionalPathForPath(tocFile),
  1550. SharedLibrary: unstrippedOutputFile,
  1551. TransitiveStaticLibrariesForOrdering: transitiveStaticLibrariesForOrdering,
  1552. Target: ctx.Target(),
  1553. })
  1554. addStubDependencyProviders(ctx)
  1555. return unstrippedOutputFile
  1556. }
  1557. func addStubDependencyProviders(ctx ModuleContext) {
  1558. stubs := ctx.GetDirectDepsWithTag(stubImplDepTag)
  1559. if len(stubs) > 0 {
  1560. var stubsInfo []SharedStubLibrary
  1561. for _, stub := range stubs {
  1562. stubInfo := ctx.OtherModuleProvider(stub, SharedLibraryInfoProvider).(SharedLibraryInfo)
  1563. flagInfo := ctx.OtherModuleProvider(stub, FlagExporterInfoProvider).(FlagExporterInfo)
  1564. stubsInfo = append(stubsInfo, SharedStubLibrary{
  1565. Version: moduleLibraryInterface(stub).stubsVersion(),
  1566. SharedLibraryInfo: stubInfo,
  1567. FlagExporterInfo: flagInfo,
  1568. })
  1569. }
  1570. ctx.SetProvider(SharedLibraryStubsProvider, SharedLibraryStubsInfo{
  1571. SharedStubLibraries: stubsInfo,
  1572. IsLLNDK: ctx.IsLlndk(),
  1573. })
  1574. }
  1575. }
  1576. func (library *libraryDecorator) unstrippedOutputFilePath() android.Path {
  1577. return library.unstrippedOutputFile
  1578. }
  1579. func (library *libraryDecorator) disableStripping() {
  1580. library.stripper.StripProperties.Strip.None = BoolPtr(true)
  1581. }
  1582. func (library *libraryDecorator) nativeCoverage() bool {
  1583. if library.header() || library.buildStubs() {
  1584. return false
  1585. }
  1586. return true
  1587. }
  1588. func (library *libraryDecorator) coverageOutputFilePath() android.OptionalPath {
  1589. return library.coverageOutputFile
  1590. }
  1591. func getRefAbiDumpFile(ctx android.ModuleInstallPathContext,
  1592. versionedDumpDir, fileName string) android.OptionalPath {
  1593. currentArchType := ctx.Arch().ArchType
  1594. primaryArchType := ctx.Config().DevicePrimaryArchType()
  1595. archName := currentArchType.String()
  1596. if currentArchType != primaryArchType {
  1597. archName += "_" + primaryArchType.String()
  1598. }
  1599. return android.ExistentPathForSource(ctx, versionedDumpDir, archName, "source-based",
  1600. fileName+".lsdump")
  1601. }
  1602. func getRefAbiDumpDir(isNdk, isVndk bool) string {
  1603. var dirName string
  1604. if isNdk {
  1605. dirName = "ndk"
  1606. } else if isVndk {
  1607. dirName = "vndk"
  1608. } else {
  1609. dirName = "platform"
  1610. }
  1611. return filepath.Join("prebuilts", "abi-dumps", dirName)
  1612. }
  1613. func prevRefAbiDumpVersion(ctx ModuleContext, dumpDir string) int {
  1614. sdkVersionInt := ctx.Config().PlatformSdkVersion().FinalInt()
  1615. sdkVersionStr := ctx.Config().PlatformSdkVersion().String()
  1616. if ctx.Config().PlatformSdkFinal() {
  1617. return sdkVersionInt - 1
  1618. } else {
  1619. // The platform SDK version can be upgraded before finalization while the corresponding abi dumps hasn't
  1620. // been generated. Thus the Cross-Version Check chooses PLATFORM_SDK_VERION - 1 as previous version.
  1621. // This situation could be identified by checking the existence of the PLATFORM_SDK_VERION dump directory.
  1622. versionedDumpDir := android.ExistentPathForSource(ctx, dumpDir, sdkVersionStr)
  1623. if versionedDumpDir.Valid() {
  1624. return sdkVersionInt
  1625. } else {
  1626. return sdkVersionInt - 1
  1627. }
  1628. }
  1629. }
  1630. func currRefAbiDumpVersion(ctx ModuleContext, isVndk bool) string {
  1631. if isVndk {
  1632. // Each version of VNDK is independent, so follow the VNDK version which is the codename or PLATFORM_SDK_VERSION.
  1633. return ctx.Module().(*Module).VndkVersion()
  1634. } else if ctx.Config().PlatformSdkFinal() {
  1635. // After sdk finalization, the ABI of the latest API level must be consistent with the source code,
  1636. // so choose PLATFORM_SDK_VERSION as the current version.
  1637. return ctx.Config().PlatformSdkVersion().String()
  1638. } else {
  1639. return "current"
  1640. }
  1641. }
  1642. // sourceAbiDiff registers a build statement to compare linked sAbi dump files (.lsdump).
  1643. func (library *libraryDecorator) sourceAbiDiff(ctx android.ModuleContext, referenceDump android.Path,
  1644. baseName, nameExt string, isLlndkOrNdk, allowExtensions bool,
  1645. sourceVersion, errorMessage string) {
  1646. sourceDump := library.sAbiOutputFile.Path()
  1647. extraFlags := []string{"-target-version", sourceVersion}
  1648. headerAbiChecker := library.getHeaderAbiCheckerProperties(ctx)
  1649. if Bool(headerAbiChecker.Check_all_apis) {
  1650. extraFlags = append(extraFlags, "-check-all-apis")
  1651. } else {
  1652. extraFlags = append(extraFlags,
  1653. "-allow-unreferenced-changes",
  1654. "-allow-unreferenced-elf-symbol-changes")
  1655. }
  1656. if isLlndkOrNdk {
  1657. extraFlags = append(extraFlags, "-consider-opaque-types-different")
  1658. }
  1659. if allowExtensions {
  1660. extraFlags = append(extraFlags, "-allow-extensions")
  1661. }
  1662. extraFlags = append(extraFlags, headerAbiChecker.Diff_flags...)
  1663. library.sAbiDiff = append(
  1664. library.sAbiDiff,
  1665. transformAbiDumpToAbiDiff(ctx, sourceDump, referenceDump,
  1666. baseName, nameExt, extraFlags, errorMessage))
  1667. }
  1668. func (library *libraryDecorator) crossVersionAbiDiff(ctx android.ModuleContext, referenceDump android.Path,
  1669. baseName string, isLlndkOrNdk bool, sourceVersion, prevVersion string) {
  1670. errorMessage := "error: Please follow https://android.googlesource.com/platform/development/+/master/vndk/tools/header-checker/README.md#configure-cross_version-abi-check to resolve the ABI difference between your source code and version " + prevVersion + "."
  1671. library.sourceAbiDiff(ctx, referenceDump, baseName, prevVersion,
  1672. isLlndkOrNdk, true /* allowExtensions */, sourceVersion, errorMessage)
  1673. }
  1674. func (library *libraryDecorator) sameVersionAbiDiff(ctx android.ModuleContext, referenceDump android.Path,
  1675. baseName string, isLlndkOrNdk, allowExtensions bool) {
  1676. libName := strings.TrimSuffix(baseName, filepath.Ext(baseName))
  1677. errorMessage := "error: Please update ABI references with: $$ANDROID_BUILD_TOP/development/vndk/tools/header-checker/utils/create_reference_dumps.py -l " + libName
  1678. library.sourceAbiDiff(ctx, referenceDump, baseName, "",
  1679. isLlndkOrNdk, allowExtensions, "current", errorMessage)
  1680. }
  1681. func (library *libraryDecorator) optInAbiDiff(ctx android.ModuleContext, referenceDump android.Path,
  1682. baseName, nameExt string, isLlndkOrNdk bool, refDumpDir string) {
  1683. libName := strings.TrimSuffix(baseName, filepath.Ext(baseName))
  1684. errorMessage := "error: Please update ABI references with: $$ANDROID_BUILD_TOP/development/vndk/tools/header-checker/utils/create_reference_dumps.py -l " + libName + " -ref-dump-dir $$ANDROID_BUILD_TOP/" + refDumpDir
  1685. library.sourceAbiDiff(ctx, referenceDump, baseName, nameExt,
  1686. isLlndkOrNdk, false /* allowExtensions */, "current", errorMessage)
  1687. }
  1688. func (library *libraryDecorator) linkSAbiDumpFiles(ctx ModuleContext, objs Objects, fileName string, soFile android.Path) {
  1689. if library.sabi.shouldCreateSourceAbiDump() {
  1690. exportIncludeDirs := library.flagExporter.exportedIncludes(ctx)
  1691. var SourceAbiFlags []string
  1692. for _, dir := range exportIncludeDirs.Strings() {
  1693. SourceAbiFlags = append(SourceAbiFlags, "-I"+dir)
  1694. }
  1695. for _, reexportedInclude := range library.sabi.Properties.ReexportedIncludes {
  1696. SourceAbiFlags = append(SourceAbiFlags, "-I"+reexportedInclude)
  1697. }
  1698. exportedHeaderFlags := strings.Join(SourceAbiFlags, " ")
  1699. headerAbiChecker := library.getHeaderAbiCheckerProperties(ctx)
  1700. library.sAbiOutputFile = transformDumpToLinkedDump(ctx, objs.sAbiDumpFiles, soFile, fileName, exportedHeaderFlags,
  1701. android.OptionalPathForModuleSrc(ctx, library.symbolFileForAbiCheck(ctx)),
  1702. headerAbiChecker.Exclude_symbol_versions,
  1703. headerAbiChecker.Exclude_symbol_tags)
  1704. addLsdumpPath(classifySourceAbiDump(ctx) + ":" + library.sAbiOutputFile.String())
  1705. // The logic must be consistent with classifySourceAbiDump.
  1706. isVndk := ctx.useVndk() && ctx.isVndk()
  1707. isNdk := ctx.isNdk(ctx.Config())
  1708. isLlndk := ctx.isImplementationForLLNDKPublic()
  1709. dumpDir := getRefAbiDumpDir(isNdk, isVndk)
  1710. binderBitness := ctx.DeviceConfig().BinderBitness()
  1711. // If NDK or PLATFORM library, check against previous version ABI.
  1712. if !isVndk {
  1713. prevVersionInt := prevRefAbiDumpVersion(ctx, dumpDir)
  1714. prevVersion := strconv.Itoa(prevVersionInt)
  1715. prevDumpDir := filepath.Join(dumpDir, prevVersion, binderBitness)
  1716. prevDumpFile := getRefAbiDumpFile(ctx, prevDumpDir, fileName)
  1717. if prevDumpFile.Valid() {
  1718. library.crossVersionAbiDiff(ctx, prevDumpFile.Path(),
  1719. fileName, isLlndk || isNdk,
  1720. strconv.Itoa(prevVersionInt+1), prevVersion)
  1721. }
  1722. }
  1723. // Check against the current version.
  1724. currVersion := currRefAbiDumpVersion(ctx, isVndk)
  1725. currDumpDir := filepath.Join(dumpDir, currVersion, binderBitness)
  1726. currDumpFile := getRefAbiDumpFile(ctx, currDumpDir, fileName)
  1727. if currDumpFile.Valid() {
  1728. library.sameVersionAbiDiff(ctx, currDumpFile.Path(),
  1729. fileName, isLlndk || isNdk, ctx.IsVndkExt())
  1730. }
  1731. // Check against the opt-in reference dumps.
  1732. for i, optInDumpDir := range headerAbiChecker.Ref_dump_dirs {
  1733. optInDumpDirPath := android.PathForModuleSrc(ctx, optInDumpDir)
  1734. // Ref_dump_dirs are not versioned.
  1735. // They do not contain subdir for binder bitness because 64-bit binder has been mandatory.
  1736. optInDumpFile := getRefAbiDumpFile(ctx, optInDumpDirPath.String(), fileName)
  1737. if !optInDumpFile.Valid() {
  1738. continue
  1739. }
  1740. library.optInAbiDiff(ctx, optInDumpFile.Path(),
  1741. fileName, "opt"+strconv.Itoa(i), isLlndk || isNdk,
  1742. optInDumpDirPath.String())
  1743. }
  1744. }
  1745. }
  1746. func processLLNDKHeaders(ctx ModuleContext, srcHeaderDir string, outDir android.ModuleGenPath) (timestamp android.Path, installPaths android.WritablePaths) {
  1747. srcDir := android.PathForModuleSrc(ctx, srcHeaderDir)
  1748. srcFiles := ctx.GlobFiles(filepath.Join(srcDir.String(), "**/*.h"), nil)
  1749. for _, header := range srcFiles {
  1750. headerDir := filepath.Dir(header.String())
  1751. relHeaderDir, err := filepath.Rel(srcDir.String(), headerDir)
  1752. if err != nil {
  1753. ctx.ModuleErrorf("filepath.Rel(%q, %q) failed: %s",
  1754. srcDir.String(), headerDir, err)
  1755. continue
  1756. }
  1757. installPaths = append(installPaths, outDir.Join(ctx, relHeaderDir, header.Base()))
  1758. }
  1759. return processHeadersWithVersioner(ctx, srcDir, outDir, srcFiles, installPaths), installPaths
  1760. }
  1761. // link registers actions to link this library, and sets various fields
  1762. // on this library to reflect information that should be exported up the build
  1763. // tree (for example, exported flags and include paths).
  1764. func (library *libraryDecorator) link(ctx ModuleContext,
  1765. flags Flags, deps PathDeps, objs Objects) android.Path {
  1766. if ctx.IsLlndk() {
  1767. if len(library.Properties.Llndk.Export_preprocessed_headers) > 0 {
  1768. // This is the vendor variant of an LLNDK library with preprocessed headers.
  1769. genHeaderOutDir := android.PathForModuleGen(ctx, "include")
  1770. var timestampFiles android.Paths
  1771. for _, dir := range library.Properties.Llndk.Export_preprocessed_headers {
  1772. timestampFile, installPaths := processLLNDKHeaders(ctx, dir, genHeaderOutDir)
  1773. timestampFiles = append(timestampFiles, timestampFile)
  1774. library.addExportedGeneratedHeaders(installPaths.Paths()...)
  1775. }
  1776. if Bool(library.Properties.Llndk.Export_headers_as_system) {
  1777. library.reexportSystemDirs(genHeaderOutDir)
  1778. } else {
  1779. library.reexportDirs(genHeaderOutDir)
  1780. }
  1781. library.reexportDeps(timestampFiles...)
  1782. }
  1783. // override the module's export_include_dirs with llndk.override_export_include_dirs
  1784. // if it is set.
  1785. if override := library.Properties.Llndk.Override_export_include_dirs; override != nil {
  1786. library.flagExporter.Properties.Export_include_dirs = override
  1787. }
  1788. if Bool(library.Properties.Llndk.Export_headers_as_system) {
  1789. library.flagExporter.Properties.Export_system_include_dirs = append(
  1790. library.flagExporter.Properties.Export_system_include_dirs,
  1791. library.flagExporter.Properties.Export_include_dirs...)
  1792. library.flagExporter.Properties.Export_include_dirs = nil
  1793. }
  1794. }
  1795. if ctx.IsVendorPublicLibrary() {
  1796. // override the module's export_include_dirs with vendor_public_library.override_export_include_dirs
  1797. // if it is set.
  1798. if override := library.Properties.Vendor_public_library.Override_export_include_dirs; override != nil {
  1799. library.flagExporter.Properties.Export_include_dirs = override
  1800. }
  1801. }
  1802. // Linking this library consists of linking `deps.Objs` (.o files in dependencies
  1803. // of this library), together with `objs` (.o files created by compiling this
  1804. // library).
  1805. objs = deps.Objs.Copy().Append(objs)
  1806. var out android.Path
  1807. if library.static() || library.header() {
  1808. out = library.linkStatic(ctx, flags, deps, objs)
  1809. } else {
  1810. out = library.linkShared(ctx, flags, deps, objs)
  1811. }
  1812. // Export include paths and flags to be propagated up the tree.
  1813. library.exportIncludes(ctx)
  1814. library.reexportDirs(deps.ReexportedDirs...)
  1815. library.reexportSystemDirs(deps.ReexportedSystemDirs...)
  1816. library.reexportFlags(deps.ReexportedFlags...)
  1817. library.reexportDeps(deps.ReexportedDeps...)
  1818. library.addExportedGeneratedHeaders(deps.ReexportedGeneratedHeaders...)
  1819. // Optionally export aidl headers.
  1820. if Bool(library.Properties.Aidl.Export_aidl_headers) {
  1821. if library.baseCompiler.hasAidl(deps) {
  1822. if library.baseCompiler.hasSrcExt(".aidl") {
  1823. dir := android.PathForModuleGen(ctx, "aidl")
  1824. library.reexportDirs(dir)
  1825. }
  1826. if len(deps.AidlLibraryInfos) > 0 {
  1827. dir := android.PathForModuleGen(ctx, "aidl_library")
  1828. library.reexportDirs(dir)
  1829. }
  1830. library.reexportDeps(library.baseCompiler.aidlOrderOnlyDeps...)
  1831. library.addExportedGeneratedHeaders(library.baseCompiler.aidlHeaders...)
  1832. }
  1833. }
  1834. // Optionally export proto headers.
  1835. if Bool(library.Properties.Proto.Export_proto_headers) {
  1836. if library.baseCompiler.hasSrcExt(".proto") {
  1837. var includes android.Paths
  1838. if flags.proto.CanonicalPathFromRoot {
  1839. includes = append(includes, flags.proto.SubDir)
  1840. }
  1841. includes = append(includes, flags.proto.Dir)
  1842. library.reexportDirs(includes...)
  1843. library.reexportDeps(library.baseCompiler.protoOrderOnlyDeps...)
  1844. library.addExportedGeneratedHeaders(library.baseCompiler.protoHeaders...)
  1845. }
  1846. }
  1847. // If the library is sysprop_library, expose either public or internal header selectively.
  1848. if library.baseCompiler.hasSrcExt(".sysprop") {
  1849. dir := android.PathForModuleGen(ctx, "sysprop", "include")
  1850. if library.Properties.Sysprop.Platform != nil {
  1851. isOwnerPlatform := Bool(library.Properties.Sysprop.Platform)
  1852. // If the owner is different from the user, expose public header. That is,
  1853. // 1) if the user is product (as owner can only be platform / vendor)
  1854. // 2) if the owner is platform and the client is vendor
  1855. // We don't care Platform -> Vendor dependency as it's already forbidden.
  1856. if ctx.Device() && (ctx.ProductSpecific() || (isOwnerPlatform && ctx.inVendor())) {
  1857. dir = android.PathForModuleGen(ctx, "sysprop/public", "include")
  1858. }
  1859. }
  1860. // Make sure to only export headers which are within the include directory.
  1861. _, headers := android.FilterPathListPredicate(library.baseCompiler.syspropHeaders, func(path android.Path) bool {
  1862. _, isRel := android.MaybeRel(ctx, dir.String(), path.String())
  1863. return isRel
  1864. })
  1865. // Add sysprop-related directories to the exported directories of this library.
  1866. library.reexportDirs(dir)
  1867. library.reexportDeps(library.baseCompiler.syspropOrderOnlyDeps...)
  1868. library.addExportedGeneratedHeaders(headers...)
  1869. }
  1870. // Add stub-related flags if this library is a stub library.
  1871. library.exportVersioningMacroIfNeeded(ctx)
  1872. // Propagate a Provider containing information about exported flags, deps, and include paths.
  1873. library.flagExporter.setProvider(ctx)
  1874. return out
  1875. }
  1876. func (library *libraryDecorator) exportVersioningMacroIfNeeded(ctx android.BaseModuleContext) {
  1877. if library.buildStubs() && library.stubsVersion() != "" && !library.skipAPIDefine {
  1878. name := versioningMacroName(ctx.Module().(*Module).ImplementationModuleName(ctx))
  1879. apiLevel, err := android.ApiLevelFromUser(ctx, library.stubsVersion())
  1880. if err != nil {
  1881. ctx.ModuleErrorf("Can't export version macro: %s", err.Error())
  1882. }
  1883. library.reexportFlags("-D" + name + "=" + strconv.Itoa(apiLevel.FinalOrPreviewInt()))
  1884. }
  1885. }
  1886. // buildStatic returns true if this library should be built as a static library.
  1887. func (library *libraryDecorator) buildStatic() bool {
  1888. return library.MutatedProperties.BuildStatic &&
  1889. BoolDefault(library.StaticProperties.Static.Enabled, true)
  1890. }
  1891. // buildShared returns true if this library should be built as a shared library.
  1892. func (library *libraryDecorator) buildShared() bool {
  1893. return library.MutatedProperties.BuildShared &&
  1894. BoolDefault(library.SharedProperties.Shared.Enabled, true)
  1895. }
  1896. func (library *libraryDecorator) objs() Objects {
  1897. return library.objects
  1898. }
  1899. func (library *libraryDecorator) reuseObjs() Objects {
  1900. return library.reuseObjects
  1901. }
  1902. func (library *libraryDecorator) toc() android.OptionalPath {
  1903. return library.tocFile
  1904. }
  1905. func (library *libraryDecorator) installSymlinkToRuntimeApex(ctx ModuleContext, file android.Path) {
  1906. dir := library.baseInstaller.installDir(ctx)
  1907. dirOnDevice := android.InstallPathToOnDevicePath(ctx, dir)
  1908. // libc_hwasan has relative_install_dir set, which would mess up the dir.Base() logic.
  1909. // hardcode here because it's the only target, if we have other targets that use this
  1910. // we can generalise this.
  1911. var target string
  1912. if ctx.baseModuleName() == "libc_hwasan" {
  1913. target = "/" + filepath.Join("apex", "com.android.runtime", "lib64", "bionic", "hwasan", file.Base())
  1914. } else {
  1915. base := dir.Base()
  1916. target = "/" + filepath.Join("apex", "com.android.runtime", base, "bionic", file.Base())
  1917. }
  1918. ctx.InstallAbsoluteSymlink(dir, file.Base(), target)
  1919. library.postInstallCmds = append(library.postInstallCmds, makeSymlinkCmd(dirOnDevice, file.Base(), target))
  1920. }
  1921. func (library *libraryDecorator) install(ctx ModuleContext, file android.Path) {
  1922. if library.shared() {
  1923. if ctx.Device() && ctx.useVndk() {
  1924. // set subDir for VNDK extensions
  1925. if ctx.IsVndkExt() {
  1926. if ctx.isVndkSp() {
  1927. library.baseInstaller.subDir = "vndk-sp"
  1928. } else {
  1929. library.baseInstaller.subDir = "vndk"
  1930. }
  1931. }
  1932. // In some cases we want to use core variant for VNDK-Core libs.
  1933. // Skip product variant since VNDKs use only the vendor variant.
  1934. if ctx.isVndk() && !ctx.isVndkSp() && !ctx.IsVndkExt() && !ctx.inProduct() {
  1935. mayUseCoreVariant := true
  1936. if ctx.mustUseVendorVariant() {
  1937. mayUseCoreVariant = false
  1938. }
  1939. if ctx.Config().CFIEnabledForPath(ctx.ModuleDir()) {
  1940. mayUseCoreVariant = false
  1941. }
  1942. if mayUseCoreVariant {
  1943. library.checkSameCoreVariant = true
  1944. if ctx.DeviceConfig().VndkUseCoreVariant() {
  1945. library.useCoreVariant = true
  1946. }
  1947. }
  1948. }
  1949. // do not install vndk libs
  1950. // vndk libs are packaged into VNDK APEX
  1951. if ctx.isVndk() && !ctx.IsVndkExt() {
  1952. return
  1953. }
  1954. } else if library.hasStubsVariants() && !ctx.Host() && ctx.directlyInAnyApex() {
  1955. // Bionic libraries (e.g. libc.so) is installed to the bootstrap subdirectory.
  1956. // The original path becomes a symlink to the corresponding file in the
  1957. // runtime APEX.
  1958. translatedArch := ctx.Target().NativeBridge == android.NativeBridgeEnabled
  1959. if InstallToBootstrap(ctx.baseModuleName(), ctx.Config()) && !library.buildStubs() &&
  1960. !translatedArch && !ctx.inRamdisk() && !ctx.inVendorRamdisk() && !ctx.inRecovery() {
  1961. if ctx.Device() {
  1962. library.installSymlinkToRuntimeApex(ctx, file)
  1963. }
  1964. library.baseInstaller.subDir = "bootstrap"
  1965. }
  1966. } else if ctx.directlyInAnyApex() && ctx.IsLlndk() && !isBionic(ctx.baseModuleName()) {
  1967. // Skip installing LLNDK (non-bionic) libraries moved to APEX.
  1968. ctx.Module().HideFromMake()
  1969. }
  1970. library.baseInstaller.install(ctx, file)
  1971. }
  1972. if Bool(library.Properties.Static_ndk_lib) && library.static() &&
  1973. !ctx.useVndk() && !ctx.inRamdisk() && !ctx.inVendorRamdisk() && !ctx.inRecovery() && ctx.Device() &&
  1974. library.baseLinker.sanitize.isUnsanitizedVariant() &&
  1975. ctx.isForPlatform() && !ctx.isPreventInstall() {
  1976. installPath := getUnversionedLibraryInstallPath(ctx).Join(ctx, file.Base())
  1977. ctx.ModuleBuild(pctx, android.ModuleBuildParams{
  1978. Rule: android.Cp,
  1979. Description: "install " + installPath.Base(),
  1980. Output: installPath,
  1981. Input: file,
  1982. })
  1983. library.ndkSysrootPath = installPath
  1984. }
  1985. }
  1986. func (library *libraryDecorator) everInstallable() bool {
  1987. // Only shared and static libraries are installed. Header libraries (which are
  1988. // neither static or shared) are not installed.
  1989. return library.shared() || library.static()
  1990. }
  1991. // static returns true if this library is for a "static' variant.
  1992. func (library *libraryDecorator) static() bool {
  1993. return library.MutatedProperties.VariantIsStatic
  1994. }
  1995. // shared returns true if this library is for a "shared' variant.
  1996. func (library *libraryDecorator) shared() bool {
  1997. return library.MutatedProperties.VariantIsShared
  1998. }
  1999. // header returns true if this library is for a header-only variant.
  2000. func (library *libraryDecorator) header() bool {
  2001. // Neither "static" nor "shared" implies this library is header-only.
  2002. return !library.static() && !library.shared()
  2003. }
  2004. // setStatic marks the library variant as "static".
  2005. func (library *libraryDecorator) setStatic() {
  2006. library.MutatedProperties.VariantIsStatic = true
  2007. library.MutatedProperties.VariantIsShared = false
  2008. }
  2009. // setShared marks the library variant as "shared".
  2010. func (library *libraryDecorator) setShared() {
  2011. library.MutatedProperties.VariantIsStatic = false
  2012. library.MutatedProperties.VariantIsShared = true
  2013. }
  2014. // BuildOnlyStatic disables building this library as a shared library.
  2015. func (library *libraryDecorator) BuildOnlyStatic() {
  2016. library.MutatedProperties.BuildShared = false
  2017. }
  2018. // BuildOnlyShared disables building this library as a static library.
  2019. func (library *libraryDecorator) BuildOnlyShared() {
  2020. library.MutatedProperties.BuildStatic = false
  2021. }
  2022. // HeaderOnly disables building this library as a shared or static library;
  2023. // the library only exists to propagate header file dependencies up the build graph.
  2024. func (library *libraryDecorator) HeaderOnly() {
  2025. library.MutatedProperties.BuildShared = false
  2026. library.MutatedProperties.BuildStatic = false
  2027. }
  2028. // hasLLNDKStubs returns true if this cc_library module has a variant that will build LLNDK stubs.
  2029. func (library *libraryDecorator) hasLLNDKStubs() bool {
  2030. return String(library.Properties.Llndk.Symbol_file) != ""
  2031. }
  2032. // hasLLNDKStubs returns true if this cc_library module has a variant that will build LLNDK stubs.
  2033. func (library *libraryDecorator) hasLLNDKHeaders() bool {
  2034. return Bool(library.Properties.Llndk.Llndk_headers)
  2035. }
  2036. // hasVendorPublicLibrary returns true if this cc_library module has a variant that will build
  2037. // vendor public library stubs.
  2038. func (library *libraryDecorator) hasVendorPublicLibrary() bool {
  2039. return String(library.Properties.Vendor_public_library.Symbol_file) != ""
  2040. }
  2041. func (library *libraryDecorator) implementationModuleName(name string) string {
  2042. return name
  2043. }
  2044. func (library *libraryDecorator) buildStubs() bool {
  2045. return library.MutatedProperties.BuildStubs
  2046. }
  2047. func (library *libraryDecorator) symbolFileForAbiCheck(ctx ModuleContext) *string {
  2048. if props := library.getHeaderAbiCheckerProperties(ctx); props.Symbol_file != nil {
  2049. return props.Symbol_file
  2050. }
  2051. if ctx.Module().(*Module).IsLlndk() {
  2052. return library.Properties.Llndk.Symbol_file
  2053. }
  2054. if library.hasStubsVariants() && library.Properties.Stubs.Symbol_file != nil {
  2055. return library.Properties.Stubs.Symbol_file
  2056. }
  2057. return nil
  2058. }
  2059. func (library *libraryDecorator) hasStubsVariants() bool {
  2060. // Just having stubs.symbol_file is enough to create a stub variant. In that case
  2061. // the stub for the future API level is created.
  2062. return library.Properties.Stubs.Symbol_file != nil ||
  2063. len(library.Properties.Stubs.Versions) > 0
  2064. }
  2065. func (library *libraryDecorator) isStubsImplementationRequired() bool {
  2066. return BoolDefault(library.Properties.Stubs.Implementation_installable, true)
  2067. }
  2068. func (library *libraryDecorator) stubsVersions(ctx android.BaseMutatorContext) []string {
  2069. if !library.hasStubsVariants() {
  2070. return nil
  2071. }
  2072. if library.hasLLNDKStubs() && ctx.Module().(*Module).UseVndk() {
  2073. // LLNDK libraries only need a single stubs variant.
  2074. return []string{android.FutureApiLevel.String()}
  2075. }
  2076. // Future API level is implicitly added if there isn't
  2077. return addCurrentVersionIfNotPresent(library.Properties.Stubs.Versions)
  2078. }
  2079. func addCurrentVersionIfNotPresent(vers []string) []string {
  2080. if inList(android.FutureApiLevel.String(), vers) {
  2081. return vers
  2082. }
  2083. // In some cases, people use the raw value "10000" in the versions property.
  2084. // We shouldn't add the future API level in that case, otherwise there will
  2085. // be two identical versions.
  2086. if inList(strconv.Itoa(android.FutureApiLevel.FinalOrFutureInt()), vers) {
  2087. return vers
  2088. }
  2089. return append(vers, android.FutureApiLevel.String())
  2090. }
  2091. func (library *libraryDecorator) setStubsVersion(version string) {
  2092. library.MutatedProperties.StubsVersion = version
  2093. }
  2094. func (library *libraryDecorator) stubsVersion() string {
  2095. return library.MutatedProperties.StubsVersion
  2096. }
  2097. func (library *libraryDecorator) setBuildStubs(isLatest bool) {
  2098. library.MutatedProperties.BuildStubs = true
  2099. library.MutatedProperties.IsLatestVersion = isLatest
  2100. }
  2101. func (library *libraryDecorator) setAllStubsVersions(versions []string) {
  2102. library.MutatedProperties.AllStubsVersions = versions
  2103. }
  2104. func (library *libraryDecorator) allStubsVersions() []string {
  2105. return library.MutatedProperties.AllStubsVersions
  2106. }
  2107. func (library *libraryDecorator) isLatestStubVersion() bool {
  2108. return library.MutatedProperties.IsLatestVersion
  2109. }
  2110. func (library *libraryDecorator) availableFor(what string) bool {
  2111. var list []string
  2112. if library.static() {
  2113. list = library.StaticProperties.Static.Apex_available
  2114. } else if library.shared() {
  2115. list = library.SharedProperties.Shared.Apex_available
  2116. }
  2117. if len(list) == 0 {
  2118. return false
  2119. }
  2120. return android.CheckAvailableForApex(what, list)
  2121. }
  2122. func (library *libraryDecorator) installable() *bool {
  2123. if library.static() {
  2124. return library.StaticProperties.Static.Installable
  2125. } else if library.shared() {
  2126. return library.SharedProperties.Shared.Installable
  2127. }
  2128. return nil
  2129. }
  2130. func (library *libraryDecorator) makeUninstallable(mod *Module) {
  2131. if library.static() && library.buildStatic() && !library.buildStubs() {
  2132. // If we're asked to make a static library uninstallable we don't do
  2133. // anything since AndroidMkEntries always sets LOCAL_UNINSTALLABLE_MODULE
  2134. // for these entries. This is done to still get the make targets for NOTICE
  2135. // files from notice_files.mk, which other libraries might depend on.
  2136. return
  2137. }
  2138. mod.ModuleBase.MakeUninstallable()
  2139. }
  2140. func (library *libraryDecorator) getPartition() string {
  2141. return library.path.Partition()
  2142. }
  2143. func (library *libraryDecorator) getAPIListCoverageXMLPath() android.ModuleOutPath {
  2144. return library.apiListCoverageXmlPath
  2145. }
  2146. func (library *libraryDecorator) overriddenModules() []string {
  2147. return library.Properties.Overrides
  2148. }
  2149. var _ overridable = (*libraryDecorator)(nil)
  2150. var versioningMacroNamesListKey = android.NewOnceKey("versioningMacroNamesList")
  2151. // versioningMacroNamesList returns a singleton map, where keys are "version macro names",
  2152. // and values are the module name responsible for registering the version macro name.
  2153. //
  2154. // Version macros are used when building against stubs, to provide version information about
  2155. // the stub. Only stub libraries should have an entry in this list.
  2156. //
  2157. // For example, when building against libFoo#ver, __LIBFOO_API__ macro is set to ver so
  2158. // that headers from libFoo can be conditionally compiled (this may hide APIs
  2159. // that are not available for the version).
  2160. //
  2161. // This map is used to ensure that there aren't conflicts between these version macro names.
  2162. func versioningMacroNamesList(config android.Config) *map[string]string {
  2163. return config.Once(versioningMacroNamesListKey, func() interface{} {
  2164. m := make(map[string]string)
  2165. return &m
  2166. }).(*map[string]string)
  2167. }
  2168. // alphanumeric and _ characters are preserved.
  2169. // other characters are all converted to _
  2170. var charsNotForMacro = regexp.MustCompile("[^a-zA-Z0-9_]+")
  2171. // versioningMacroName returns the canonical version macro name for the given module.
  2172. func versioningMacroName(moduleName string) string {
  2173. macroName := charsNotForMacro.ReplaceAllString(moduleName, "_")
  2174. macroName = strings.ToUpper(macroName)
  2175. return "__" + macroName + "_API__"
  2176. }
  2177. // NewLibrary builds and returns a new Module corresponding to a C++ library.
  2178. // Individual module implementations which comprise a C++ library (or something like
  2179. // a C++ library) should call this function, set some fields on the result, and
  2180. // then call the Init function.
  2181. func NewLibrary(hod android.HostOrDeviceSupported) (*Module, *libraryDecorator) {
  2182. module := newModule(hod, android.MultilibBoth)
  2183. library := &libraryDecorator{
  2184. MutatedProperties: LibraryMutatedProperties{
  2185. BuildShared: true,
  2186. BuildStatic: true,
  2187. },
  2188. baseCompiler: NewBaseCompiler(),
  2189. baseLinker: NewBaseLinker(module.sanitize),
  2190. baseInstaller: NewBaseInstaller("lib", "lib64", InstallInSystem),
  2191. sabi: module.sabi,
  2192. }
  2193. module.compiler = library
  2194. module.linker = library
  2195. module.installer = library
  2196. module.library = library
  2197. return module, library
  2198. }
  2199. // connects a shared library to a static library in order to reuse its .o files to avoid
  2200. // compiling source files twice.
  2201. func reuseStaticLibrary(mctx android.BottomUpMutatorContext, static, shared *Module) {
  2202. if staticCompiler, ok := static.compiler.(*libraryDecorator); ok {
  2203. sharedCompiler := shared.compiler.(*libraryDecorator)
  2204. // Check libraries in addition to cflags, since libraries may be exporting different
  2205. // include directories.
  2206. if len(staticCompiler.StaticProperties.Static.Cflags) == 0 &&
  2207. len(sharedCompiler.SharedProperties.Shared.Cflags) == 0 &&
  2208. len(staticCompiler.StaticProperties.Static.Whole_static_libs) == 0 &&
  2209. len(sharedCompiler.SharedProperties.Shared.Whole_static_libs) == 0 &&
  2210. len(staticCompiler.StaticProperties.Static.Static_libs) == 0 &&
  2211. len(sharedCompiler.SharedProperties.Shared.Static_libs) == 0 &&
  2212. len(staticCompiler.StaticProperties.Static.Shared_libs) == 0 &&
  2213. len(sharedCompiler.SharedProperties.Shared.Shared_libs) == 0 &&
  2214. // Compare System_shared_libs properties with nil because empty lists are
  2215. // semantically significant for them.
  2216. staticCompiler.StaticProperties.Static.System_shared_libs == nil &&
  2217. sharedCompiler.SharedProperties.Shared.System_shared_libs == nil {
  2218. mctx.AddInterVariantDependency(reuseObjTag, shared, static)
  2219. sharedCompiler.baseCompiler.Properties.OriginalSrcs =
  2220. sharedCompiler.baseCompiler.Properties.Srcs
  2221. sharedCompiler.baseCompiler.Properties.Srcs = nil
  2222. sharedCompiler.baseCompiler.Properties.Generated_sources = nil
  2223. }
  2224. // This dep is just to reference static variant from shared variant
  2225. mctx.AddInterVariantDependency(staticVariantTag, shared, static)
  2226. }
  2227. }
  2228. // LinkageMutator adds "static" or "shared" variants for modules depending
  2229. // on whether the module can be built as a static library or a shared library.
  2230. func LinkageMutator(mctx android.BottomUpMutatorContext) {
  2231. ccPrebuilt := false
  2232. if m, ok := mctx.Module().(*Module); ok && m.linker != nil {
  2233. _, ccPrebuilt = m.linker.(prebuiltLibraryInterface)
  2234. }
  2235. if ccPrebuilt {
  2236. library := mctx.Module().(*Module).linker.(prebuiltLibraryInterface)
  2237. // Differentiate between header only and building an actual static/shared library
  2238. buildStatic := library.buildStatic()
  2239. buildShared := library.buildShared()
  2240. if buildStatic || buildShared {
  2241. // Always create both the static and shared variants for prebuilt libraries, and then disable the one
  2242. // that is not being used. This allows them to share the name of a cc_library module, which requires that
  2243. // all the variants of the cc_library also exist on the prebuilt.
  2244. modules := mctx.CreateLocalVariations("static", "shared")
  2245. static := modules[0].(*Module)
  2246. shared := modules[1].(*Module)
  2247. static.linker.(prebuiltLibraryInterface).setStatic()
  2248. shared.linker.(prebuiltLibraryInterface).setShared()
  2249. if buildShared {
  2250. mctx.AliasVariation("shared")
  2251. } else if buildStatic {
  2252. mctx.AliasVariation("static")
  2253. }
  2254. if !buildStatic {
  2255. static.linker.(prebuiltLibraryInterface).disablePrebuilt()
  2256. }
  2257. if !buildShared {
  2258. shared.linker.(prebuiltLibraryInterface).disablePrebuilt()
  2259. }
  2260. } else {
  2261. // Header only
  2262. }
  2263. } else if library, ok := mctx.Module().(LinkableInterface); ok && library.CcLibraryInterface() {
  2264. // Non-cc.Modules may need an empty variant for their mutators.
  2265. variations := []string{}
  2266. if library.NonCcVariants() {
  2267. variations = append(variations, "")
  2268. }
  2269. isLLNDK := false
  2270. if m, ok := mctx.Module().(*Module); ok {
  2271. isLLNDK = m.IsLlndk()
  2272. }
  2273. buildStatic := library.BuildStaticVariant() && !isLLNDK
  2274. buildShared := library.BuildSharedVariant()
  2275. if buildStatic && buildShared {
  2276. variations := append([]string{"static", "shared"}, variations...)
  2277. modules := mctx.CreateLocalVariations(variations...)
  2278. static := modules[0].(LinkableInterface)
  2279. shared := modules[1].(LinkableInterface)
  2280. static.SetStatic()
  2281. shared.SetShared()
  2282. if _, ok := library.(*Module); ok {
  2283. reuseStaticLibrary(mctx, static.(*Module), shared.(*Module))
  2284. }
  2285. mctx.AliasVariation("shared")
  2286. } else if buildStatic {
  2287. variations := append([]string{"static"}, variations...)
  2288. modules := mctx.CreateLocalVariations(variations...)
  2289. modules[0].(LinkableInterface).SetStatic()
  2290. mctx.AliasVariation("static")
  2291. } else if buildShared {
  2292. variations := append([]string{"shared"}, variations...)
  2293. modules := mctx.CreateLocalVariations(variations...)
  2294. modules[0].(LinkableInterface).SetShared()
  2295. mctx.AliasVariation("shared")
  2296. } else if len(variations) > 0 {
  2297. mctx.CreateLocalVariations(variations...)
  2298. mctx.AliasVariation(variations[0])
  2299. }
  2300. }
  2301. }
  2302. // normalizeVersions modifies `versions` in place, so that each raw version
  2303. // string becomes its normalized canonical form.
  2304. // Validates that the versions in `versions` are specified in least to greatest order.
  2305. func normalizeVersions(ctx android.BazelConversionPathContext, versions []string) {
  2306. var previous android.ApiLevel
  2307. for i, v := range versions {
  2308. ver, err := android.ApiLevelFromUser(ctx, v)
  2309. if err != nil {
  2310. ctx.PropertyErrorf("versions", "%s", err.Error())
  2311. return
  2312. }
  2313. if i > 0 && ver.LessThanOrEqualTo(previous) {
  2314. ctx.PropertyErrorf("versions", "not sorted: %v", versions)
  2315. }
  2316. versions[i] = ver.String()
  2317. previous = ver
  2318. }
  2319. }
  2320. func createVersionVariations(mctx android.BottomUpMutatorContext, versions []string) {
  2321. // "" is for the non-stubs (implementation) variant for system modules, or the LLNDK variant
  2322. // for LLNDK modules.
  2323. variants := append(android.CopyOf(versions), "")
  2324. m := mctx.Module().(*Module)
  2325. isLLNDK := m.IsLlndk()
  2326. isVendorPublicLibrary := m.IsVendorPublicLibrary()
  2327. isImportedApiLibrary := m.isImportedApiLibrary()
  2328. modules := mctx.CreateLocalVariations(variants...)
  2329. for i, m := range modules {
  2330. if variants[i] != "" || isLLNDK || isVendorPublicLibrary || isImportedApiLibrary {
  2331. // A stubs or LLNDK stubs variant.
  2332. c := m.(*Module)
  2333. c.sanitize = nil
  2334. c.stl = nil
  2335. c.Properties.PreventInstall = true
  2336. lib := moduleLibraryInterface(m)
  2337. isLatest := i == (len(versions) - 1)
  2338. lib.setBuildStubs(isLatest)
  2339. if variants[i] != "" {
  2340. // A non-LLNDK stubs module is hidden from make and has a dependency from the
  2341. // implementation module to the stubs module.
  2342. c.Properties.HideFromMake = true
  2343. lib.setStubsVersion(variants[i])
  2344. mctx.AddInterVariantDependency(stubImplDepTag, modules[len(modules)-1], modules[i])
  2345. }
  2346. }
  2347. }
  2348. mctx.AliasVariation("")
  2349. latestVersion := ""
  2350. if len(versions) > 0 {
  2351. latestVersion = versions[len(versions)-1]
  2352. }
  2353. mctx.CreateAliasVariation("latest", latestVersion)
  2354. }
  2355. func createPerApiVersionVariations(mctx android.BottomUpMutatorContext, minSdkVersion string) {
  2356. from, err := nativeApiLevelFromUser(mctx, minSdkVersion)
  2357. if err != nil {
  2358. mctx.PropertyErrorf("min_sdk_version", err.Error())
  2359. return
  2360. }
  2361. versionStrs := ndkLibraryVersions(mctx, from)
  2362. modules := mctx.CreateLocalVariations(versionStrs...)
  2363. for i, module := range modules {
  2364. module.(*Module).Properties.Sdk_version = StringPtr(versionStrs[i])
  2365. module.(*Module).Properties.Min_sdk_version = StringPtr(versionStrs[i])
  2366. }
  2367. }
  2368. func canBeOrLinkAgainstVersionVariants(module interface {
  2369. Host() bool
  2370. InRamdisk() bool
  2371. InVendorRamdisk() bool
  2372. }) bool {
  2373. return !module.Host() && !module.InRamdisk() && !module.InVendorRamdisk()
  2374. }
  2375. func canBeVersionVariant(module interface {
  2376. Host() bool
  2377. InRamdisk() bool
  2378. InVendorRamdisk() bool
  2379. CcLibraryInterface() bool
  2380. Shared() bool
  2381. }) bool {
  2382. return canBeOrLinkAgainstVersionVariants(module) &&
  2383. module.CcLibraryInterface() && module.Shared()
  2384. }
  2385. func moduleLibraryInterface(module blueprint.Module) libraryInterface {
  2386. if m, ok := module.(*Module); ok {
  2387. return m.library
  2388. }
  2389. return nil
  2390. }
  2391. // setStubsVersions normalizes the versions in the Stubs.Versions property into MutatedProperties.AllStubsVersions.
  2392. func setStubsVersions(mctx android.BottomUpMutatorContext, library libraryInterface, module *Module) {
  2393. if !library.buildShared() || !canBeVersionVariant(module) {
  2394. return
  2395. }
  2396. versions := library.stubsVersions(mctx)
  2397. if len(versions) <= 0 {
  2398. return
  2399. }
  2400. normalizeVersions(mctx, versions)
  2401. if mctx.Failed() {
  2402. return
  2403. }
  2404. // Set the versions on the pre-mutated module so they can be read by any llndk modules that
  2405. // depend on the implementation library and haven't been mutated yet.
  2406. library.setAllStubsVersions(versions)
  2407. }
  2408. // versionMutator splits a module into the mandatory non-stubs variant
  2409. // (which is unnamed) and zero or more stubs variants.
  2410. func versionMutator(mctx android.BottomUpMutatorContext) {
  2411. if mctx.Os() != android.Android {
  2412. return
  2413. }
  2414. m, ok := mctx.Module().(*Module)
  2415. if library := moduleLibraryInterface(mctx.Module()); library != nil && canBeVersionVariant(m) {
  2416. setStubsVersions(mctx, library, m)
  2417. createVersionVariations(mctx, library.allStubsVersions())
  2418. return
  2419. }
  2420. if ok {
  2421. if m.SplitPerApiLevel() && m.IsSdkVariant() {
  2422. createPerApiVersionVariations(mctx, m.MinSdkVersion())
  2423. }
  2424. }
  2425. }
  2426. // maybeInjectBoringSSLHash adds a rule to run bssl_inject_hash on the output file if the module has the
  2427. // inject_bssl_hash or if any static library dependencies have inject_bssl_hash set. It returns the output path
  2428. // that the linked output file should be written to.
  2429. // TODO(b/137267623): Remove this in favor of a cc_genrule when they support operating on shared libraries.
  2430. func maybeInjectBoringSSLHash(ctx android.ModuleContext, outputFile android.ModuleOutPath,
  2431. inject *bool, fileName string) android.ModuleOutPath {
  2432. // TODO(b/137267623): Remove this in favor of a cc_genrule when they support operating on shared libraries.
  2433. injectBoringSSLHash := Bool(inject)
  2434. ctx.VisitDirectDeps(func(dep android.Module) {
  2435. if tag, ok := ctx.OtherModuleDependencyTag(dep).(libraryDependencyTag); ok && tag.static() {
  2436. if cc, ok := dep.(*Module); ok {
  2437. if library, ok := cc.linker.(*libraryDecorator); ok {
  2438. if Bool(library.Properties.Inject_bssl_hash) {
  2439. injectBoringSSLHash = true
  2440. }
  2441. }
  2442. }
  2443. }
  2444. })
  2445. if injectBoringSSLHash {
  2446. hashedOutputfile := outputFile
  2447. outputFile = android.PathForModuleOut(ctx, "unhashed", fileName)
  2448. rule := android.NewRuleBuilder(pctx, ctx)
  2449. rule.Command().
  2450. BuiltTool("bssl_inject_hash").
  2451. FlagWithInput("-in-object ", outputFile).
  2452. FlagWithOutput("-o ", hashedOutputfile)
  2453. rule.Build("injectCryptoHash", "inject crypto hash")
  2454. }
  2455. return outputFile
  2456. }
  2457. func bp2buildParseAbiCheckerProps(ctx android.TopDownMutatorContext, module *Module) bazelCcHeaderAbiCheckerAttributes {
  2458. lib, ok := module.linker.(*libraryDecorator)
  2459. if !ok {
  2460. return bazelCcHeaderAbiCheckerAttributes{}
  2461. }
  2462. abiChecker := lib.getHeaderAbiCheckerProperties(ctx)
  2463. abiCheckerAttrs := bazelCcHeaderAbiCheckerAttributes{
  2464. Abi_checker_enabled: abiChecker.Enabled,
  2465. Abi_checker_exclude_symbol_versions: abiChecker.Exclude_symbol_versions,
  2466. Abi_checker_exclude_symbol_tags: abiChecker.Exclude_symbol_tags,
  2467. Abi_checker_check_all_apis: abiChecker.Check_all_apis,
  2468. Abi_checker_diff_flags: abiChecker.Diff_flags,
  2469. }
  2470. if abiChecker.Symbol_file != nil {
  2471. symbolFile := android.BazelLabelForModuleSrcSingle(ctx, *abiChecker.Symbol_file)
  2472. abiCheckerAttrs.Abi_checker_symbol_file = &symbolFile
  2473. }
  2474. return abiCheckerAttrs
  2475. }
  2476. func sharedOrStaticLibraryBp2Build(ctx android.TopDownMutatorContext, module *Module, isStatic bool) {
  2477. baseAttributes := bp2BuildParseBaseProps(ctx, module)
  2478. compilerAttrs := baseAttributes.compilerAttributes
  2479. linkerAttrs := baseAttributes.linkerAttributes
  2480. exportedIncludes := bp2BuildParseExportedIncludes(ctx, module, &compilerAttrs.includes)
  2481. includeAttrs := includesAttributes{
  2482. Export_includes: exportedIncludes.Includes,
  2483. Export_absolute_includes: exportedIncludes.AbsoluteIncludes,
  2484. Export_system_includes: exportedIncludes.SystemIncludes,
  2485. Local_includes: compilerAttrs.localIncludes,
  2486. Absolute_includes: compilerAttrs.absoluteIncludes,
  2487. }
  2488. // Append shared/static{} stanza properties. These won't be specified on
  2489. // cc_library_* itself, but may be specified in cc_defaults that this module
  2490. // depends on.
  2491. libSharedOrStaticAttrs := bp2BuildParseLibProps(ctx, module, isStatic)
  2492. compilerAttrs.srcs.Append(libSharedOrStaticAttrs.Srcs)
  2493. compilerAttrs.cSrcs.Append(libSharedOrStaticAttrs.Srcs_c)
  2494. compilerAttrs.asSrcs.Append(libSharedOrStaticAttrs.Srcs_as)
  2495. compilerAttrs.copts.Append(libSharedOrStaticAttrs.Copts)
  2496. linkerAttrs.deps.Append(libSharedOrStaticAttrs.Deps)
  2497. linkerAttrs.implementationDeps.Append(libSharedOrStaticAttrs.Implementation_deps)
  2498. linkerAttrs.dynamicDeps.Append(libSharedOrStaticAttrs.Dynamic_deps)
  2499. linkerAttrs.implementationDynamicDeps.Append(libSharedOrStaticAttrs.Implementation_dynamic_deps)
  2500. linkerAttrs.systemDynamicDeps.Append(libSharedOrStaticAttrs.System_dynamic_deps)
  2501. asFlags := compilerAttrs.asFlags
  2502. if compilerAttrs.asSrcs.IsEmpty() {
  2503. // Skip asflags for BUILD file simplicity if there are no assembly sources.
  2504. asFlags = bazel.MakeStringListAttribute(nil)
  2505. }
  2506. features := baseAttributes.features.Clone().Append(libSharedOrStaticAttrs.Features)
  2507. features.DeduplicateAxesFromBase()
  2508. commonAttrs := staticOrSharedAttributes{
  2509. Srcs: compilerAttrs.srcs,
  2510. Srcs_c: compilerAttrs.cSrcs,
  2511. Srcs_as: compilerAttrs.asSrcs,
  2512. Copts: compilerAttrs.copts,
  2513. Hdrs: compilerAttrs.hdrs,
  2514. Deps: linkerAttrs.deps,
  2515. Implementation_deps: linkerAttrs.implementationDeps,
  2516. Dynamic_deps: linkerAttrs.dynamicDeps,
  2517. Implementation_dynamic_deps: linkerAttrs.implementationDynamicDeps,
  2518. Whole_archive_deps: linkerAttrs.wholeArchiveDeps,
  2519. Implementation_whole_archive_deps: linkerAttrs.implementationWholeArchiveDeps,
  2520. System_dynamic_deps: linkerAttrs.systemDynamicDeps,
  2521. sdkAttributes: bp2BuildParseSdkAttributes(module),
  2522. Runtime_deps: linkerAttrs.runtimeDeps,
  2523. Native_coverage: baseAttributes.Native_coverage,
  2524. }
  2525. module.convertTidyAttributes(ctx, &commonAttrs.tidyAttributes)
  2526. var attrs interface{}
  2527. if isStatic {
  2528. commonAttrs.Deps.Add(baseAttributes.protoDependency)
  2529. attrs = &bazelCcLibraryStaticAttributes{
  2530. staticOrSharedAttributes: commonAttrs,
  2531. Rtti: compilerAttrs.rtti,
  2532. Stl: compilerAttrs.stl,
  2533. Cpp_std: compilerAttrs.cppStd,
  2534. C_std: compilerAttrs.cStd,
  2535. includesAttributes: includeAttrs,
  2536. Cppflags: compilerAttrs.cppFlags,
  2537. Conlyflags: compilerAttrs.conlyFlags,
  2538. Asflags: asFlags,
  2539. Features: *features,
  2540. }
  2541. } else {
  2542. commonAttrs.Dynamic_deps.Add(baseAttributes.protoDependency)
  2543. sharedLibAttrs := &bazelCcLibrarySharedAttributes{
  2544. staticOrSharedAttributes: commonAttrs,
  2545. Cppflags: compilerAttrs.cppFlags,
  2546. Conlyflags: compilerAttrs.conlyFlags,
  2547. Asflags: asFlags,
  2548. Linkopts: linkerAttrs.linkopts,
  2549. Use_version_lib: linkerAttrs.useVersionLib,
  2550. Rtti: compilerAttrs.rtti,
  2551. Stl: compilerAttrs.stl,
  2552. Cpp_std: compilerAttrs.cppStd,
  2553. C_std: compilerAttrs.cStd,
  2554. includesAttributes: includeAttrs,
  2555. Additional_linker_inputs: linkerAttrs.additionalLinkerInputs,
  2556. Strip: stripAttrsFromLinkerAttrs(&linkerAttrs),
  2557. Features: *features,
  2558. Stem: compilerAttrs.stem,
  2559. Suffix: compilerAttrs.suffix,
  2560. bazelCcHeaderAbiCheckerAttributes: bp2buildParseAbiCheckerProps(ctx, module),
  2561. Fdo_profile: compilerAttrs.fdoProfile,
  2562. }
  2563. if compilerAttrs.stubsSymbolFile != nil && len(compilerAttrs.stubsVersions.Value) > 0 {
  2564. sharedLibAttrs.Stubs_symbol_file = compilerAttrs.stubsSymbolFile
  2565. }
  2566. attrs = sharedLibAttrs
  2567. }
  2568. var modType string
  2569. if isStatic {
  2570. modType = "cc_library_static"
  2571. } else {
  2572. modType = "cc_library_shared"
  2573. createStubsBazelTargetIfNeeded(ctx, module, compilerAttrs, exportedIncludes, baseAttributes)
  2574. }
  2575. props := bazel.BazelTargetModuleProperties{
  2576. Rule_class: modType,
  2577. Bzl_load_location: fmt.Sprintf("//build/bazel/rules/cc:%s.bzl", modType),
  2578. }
  2579. tags := android.ApexAvailableTagsWithoutTestApexes(ctx, module)
  2580. ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: module.Name(), Tags: tags}, attrs)
  2581. }
  2582. type includesAttributes struct {
  2583. Export_includes bazel.StringListAttribute
  2584. Export_absolute_includes bazel.StringListAttribute
  2585. Export_system_includes bazel.StringListAttribute
  2586. Local_includes bazel.StringListAttribute
  2587. Absolute_includes bazel.StringListAttribute
  2588. }
  2589. // TODO(b/199902614): Can this be factored to share with the other Attributes?
  2590. type bazelCcLibraryStaticAttributes struct {
  2591. staticOrSharedAttributes
  2592. includesAttributes
  2593. Use_version_lib bazel.BoolAttribute
  2594. Rtti bazel.BoolAttribute
  2595. Stl *string
  2596. Cpp_std *string
  2597. C_std *string
  2598. Hdrs bazel.LabelListAttribute
  2599. Cppflags bazel.StringListAttribute
  2600. Conlyflags bazel.StringListAttribute
  2601. Asflags bazel.StringListAttribute
  2602. Features bazel.StringListAttribute
  2603. }
  2604. // TODO(b/199902614): Can this be factored to share with the other Attributes?
  2605. type bazelCcLibrarySharedAttributes struct {
  2606. staticOrSharedAttributes
  2607. includesAttributes
  2608. Linkopts bazel.StringListAttribute
  2609. Use_version_lib bazel.BoolAttribute
  2610. Rtti bazel.BoolAttribute
  2611. Stl *string
  2612. Cpp_std *string
  2613. C_std *string
  2614. Hdrs bazel.LabelListAttribute
  2615. Strip stripAttributes
  2616. Additional_linker_inputs bazel.LabelListAttribute
  2617. Cppflags bazel.StringListAttribute
  2618. Conlyflags bazel.StringListAttribute
  2619. Asflags bazel.StringListAttribute
  2620. Features bazel.StringListAttribute
  2621. Stubs_symbol_file *string
  2622. Inject_bssl_hash bazel.BoolAttribute
  2623. Stem bazel.StringAttribute
  2624. Suffix bazel.StringAttribute
  2625. bazelCcHeaderAbiCheckerAttributes
  2626. Fdo_profile bazel.LabelAttribute
  2627. }
  2628. type bazelCcStubSuiteAttributes struct {
  2629. Symbol_file *string
  2630. Versions bazel.StringListAttribute
  2631. Export_includes bazel.StringListAttribute
  2632. Source_library_label *string
  2633. Soname *string
  2634. Deps bazel.LabelListAttribute
  2635. }
  2636. type bazelCcHeaderAbiCheckerAttributes struct {
  2637. Abi_checker_enabled *bool
  2638. Abi_checker_symbol_file *bazel.Label
  2639. Abi_checker_exclude_symbol_versions []string
  2640. Abi_checker_exclude_symbol_tags []string
  2641. Abi_checker_check_all_apis *bool
  2642. Abi_checker_diff_flags []string
  2643. }