library.go 115 KB

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