library.go 93 KB

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