module.go 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804
  1. // Copyright 2015 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 android
  15. import (
  16. "fmt"
  17. "net/url"
  18. "os"
  19. "path"
  20. "path/filepath"
  21. "reflect"
  22. "regexp"
  23. "sort"
  24. "strings"
  25. "text/scanner"
  26. "android/soong/bazel"
  27. "github.com/google/blueprint"
  28. "github.com/google/blueprint/proptools"
  29. )
  30. var (
  31. DeviceSharedLibrary = "shared_library"
  32. DeviceStaticLibrary = "static_library"
  33. )
  34. type BuildParams struct {
  35. Rule blueprint.Rule
  36. Deps blueprint.Deps
  37. Depfile WritablePath
  38. Description string
  39. Output WritablePath
  40. Outputs WritablePaths
  41. SymlinkOutput WritablePath
  42. SymlinkOutputs WritablePaths
  43. ImplicitOutput WritablePath
  44. ImplicitOutputs WritablePaths
  45. Input Path
  46. Inputs Paths
  47. Implicit Path
  48. Implicits Paths
  49. OrderOnly Paths
  50. Validation Path
  51. Validations Paths
  52. Default bool
  53. Args map[string]string
  54. }
  55. type ModuleBuildParams BuildParams
  56. // EarlyModuleContext provides methods that can be called early, as soon as the properties have
  57. // been parsed into the module and before any mutators have run.
  58. type EarlyModuleContext interface {
  59. // Module returns the current module as a Module. It should rarely be necessary, as the module already has a
  60. // reference to itself.
  61. Module() Module
  62. // ModuleName returns the name of the module. This is generally the value that was returned by Module.Name() when
  63. // the module was created, but may have been modified by calls to BaseMutatorContext.Rename.
  64. ModuleName() string
  65. // ModuleDir returns the path to the directory that contains the definition of the module.
  66. ModuleDir() string
  67. // ModuleType returns the name of the module type that was used to create the module, as specified in
  68. // RegisterModuleType.
  69. ModuleType() string
  70. // BlueprintFile returns the name of the blueprint file that contains the definition of this
  71. // module.
  72. BlueprintsFile() string
  73. // ContainsProperty returns true if the specified property name was set in the module definition.
  74. ContainsProperty(name string) bool
  75. // Errorf reports an error at the specified position of the module definition file.
  76. Errorf(pos scanner.Position, fmt string, args ...interface{})
  77. // ModuleErrorf reports an error at the line number of the module type in the module definition.
  78. ModuleErrorf(fmt string, args ...interface{})
  79. // PropertyErrorf reports an error at the line number of a property in the module definition.
  80. PropertyErrorf(property, fmt string, args ...interface{})
  81. // Failed returns true if any errors have been reported. In most cases the module can continue with generating
  82. // build rules after an error, allowing it to report additional errors in a single run, but in cases where the error
  83. // has prevented the module from creating necessary data it can return early when Failed returns true.
  84. Failed() bool
  85. // AddNinjaFileDeps adds dependencies on the specified files to the rule that creates the ninja manifest. The
  86. // primary builder will be rerun whenever the specified files are modified.
  87. AddNinjaFileDeps(deps ...string)
  88. DeviceSpecific() bool
  89. SocSpecific() bool
  90. ProductSpecific() bool
  91. SystemExtSpecific() bool
  92. Platform() bool
  93. Config() Config
  94. DeviceConfig() DeviceConfig
  95. // Deprecated: use Config()
  96. AConfig() Config
  97. // GlobWithDeps returns a list of files that match the specified pattern but do not match any
  98. // of the patterns in excludes. It also adds efficient dependencies to rerun the primary
  99. // builder whenever a file matching the pattern as added or removed, without rerunning if a
  100. // file that does not match the pattern is added to a searched directory.
  101. GlobWithDeps(pattern string, excludes []string) ([]string, error)
  102. Glob(globPattern string, excludes []string) Paths
  103. GlobFiles(globPattern string, excludes []string) Paths
  104. IsSymlink(path Path) bool
  105. Readlink(path Path) string
  106. // Namespace returns the Namespace object provided by the NameInterface set by Context.SetNameInterface, or the
  107. // default SimpleNameInterface if Context.SetNameInterface was not called.
  108. Namespace() *Namespace
  109. }
  110. // BaseModuleContext is the same as blueprint.BaseModuleContext except that Config() returns
  111. // a Config instead of an interface{}, and some methods have been wrapped to use an android.Module
  112. // instead of a blueprint.Module, plus some extra methods that return Android-specific information
  113. // about the current module.
  114. type BaseModuleContext interface {
  115. EarlyModuleContext
  116. blueprintBaseModuleContext() blueprint.BaseModuleContext
  117. // OtherModuleName returns the name of another Module. See BaseModuleContext.ModuleName for more information.
  118. // It is intended for use inside the visit functions of Visit* and WalkDeps.
  119. OtherModuleName(m blueprint.Module) string
  120. // OtherModuleDir returns the directory of another Module. See BaseModuleContext.ModuleDir for more information.
  121. // It is intended for use inside the visit functions of Visit* and WalkDeps.
  122. OtherModuleDir(m blueprint.Module) string
  123. // OtherModuleErrorf reports an error on another Module. See BaseModuleContext.ModuleErrorf for more information.
  124. // It is intended for use inside the visit functions of Visit* and WalkDeps.
  125. OtherModuleErrorf(m blueprint.Module, fmt string, args ...interface{})
  126. // OtherModuleDependencyTag returns the dependency tag used to depend on a module, or nil if there is no dependency
  127. // on the module. When called inside a Visit* method with current module being visited, and there are multiple
  128. // dependencies on the module being visited, it returns the dependency tag used for the current dependency.
  129. OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
  130. // OtherModuleExists returns true if a module with the specified name exists, as determined by the NameInterface
  131. // passed to Context.SetNameInterface, or SimpleNameInterface if it was not called.
  132. OtherModuleExists(name string) bool
  133. // OtherModuleDependencyVariantExists returns true if a module with the
  134. // specified name and variant exists. The variant must match the given
  135. // variations. It must also match all the non-local variations of the current
  136. // module. In other words, it checks for the module that AddVariationDependencies
  137. // would add a dependency on with the same arguments.
  138. OtherModuleDependencyVariantExists(variations []blueprint.Variation, name string) bool
  139. // OtherModuleFarDependencyVariantExists returns true if a module with the
  140. // specified name and variant exists. The variant must match the given
  141. // variations, but not the non-local variations of the current module. In
  142. // other words, it checks for the module that AddFarVariationDependencies
  143. // would add a dependency on with the same arguments.
  144. OtherModuleFarDependencyVariantExists(variations []blueprint.Variation, name string) bool
  145. // OtherModuleReverseDependencyVariantExists returns true if a module with the
  146. // specified name exists with the same variations as the current module. In
  147. // other words, it checks for the module that AddReverseDependency would add a
  148. // dependency on with the same argument.
  149. OtherModuleReverseDependencyVariantExists(name string) bool
  150. // OtherModuleType returns the type of another Module. See BaseModuleContext.ModuleType for more information.
  151. // It is intended for use inside the visit functions of Visit* and WalkDeps.
  152. OtherModuleType(m blueprint.Module) string
  153. // OtherModuleProvider returns the value for a provider for the given module. If the value is
  154. // not set it returns the zero value of the type of the provider, so the return value can always
  155. // be type asserted to the type of the provider. The value returned may be a deep copy of the
  156. // value originally passed to SetProvider.
  157. OtherModuleProvider(m blueprint.Module, provider blueprint.ProviderKey) interface{}
  158. // OtherModuleHasProvider returns true if the provider for the given module has been set.
  159. OtherModuleHasProvider(m blueprint.Module, provider blueprint.ProviderKey) bool
  160. // Provider returns the value for a provider for the current module. If the value is
  161. // not set it returns the zero value of the type of the provider, so the return value can always
  162. // be type asserted to the type of the provider. It panics if called before the appropriate
  163. // mutator or GenerateBuildActions pass for the provider. The value returned may be a deep
  164. // copy of the value originally passed to SetProvider.
  165. Provider(provider blueprint.ProviderKey) interface{}
  166. // HasProvider returns true if the provider for the current module has been set.
  167. HasProvider(provider blueprint.ProviderKey) bool
  168. // SetProvider sets the value for a provider for the current module. It panics if not called
  169. // during the appropriate mutator or GenerateBuildActions pass for the provider, if the value
  170. // is not of the appropriate type, or if the value has already been set. The value should not
  171. // be modified after being passed to SetProvider.
  172. SetProvider(provider blueprint.ProviderKey, value interface{})
  173. GetDirectDepsWithTag(tag blueprint.DependencyTag) []Module
  174. // GetDirectDepWithTag returns the Module the direct dependency with the specified name, or nil if
  175. // none exists. It panics if the dependency does not have the specified tag. It skips any
  176. // dependencies that are not an android.Module.
  177. GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module
  178. // GetDirectDep returns the Module and DependencyTag for the direct dependency with the specified
  179. // name, or nil if none exists. If there are multiple dependencies on the same module it returns
  180. // the first DependencyTag.
  181. GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
  182. ModuleFromName(name string) (blueprint.Module, bool)
  183. // VisitDirectDepsBlueprint calls visit for each direct dependency. If there are multiple
  184. // direct dependencies on the same module visit will be called multiple times on that module
  185. // and OtherModuleDependencyTag will return a different tag for each.
  186. //
  187. // The Module passed to the visit function should not be retained outside of the visit
  188. // function, it may be invalidated by future mutators.
  189. VisitDirectDepsBlueprint(visit func(blueprint.Module))
  190. // VisitDirectDeps calls visit for each direct dependency. If there are multiple
  191. // direct dependencies on the same module visit will be called multiple times on that module
  192. // and OtherModuleDependencyTag will return a different tag for each. It raises an error if any of the
  193. // dependencies are not an android.Module.
  194. //
  195. // The Module passed to the visit function should not be retained outside of the visit
  196. // function, it may be invalidated by future mutators.
  197. VisitDirectDeps(visit func(Module))
  198. VisitDirectDepsWithTag(tag blueprint.DependencyTag, visit func(Module))
  199. // VisitDirectDepsIf calls pred for each direct dependency, and if pred returns true calls visit. If there are
  200. // multiple direct dependencies on the same module pred and visit will be called multiple times on that module and
  201. // OtherModuleDependencyTag will return a different tag for each. It skips any
  202. // dependencies that are not an android.Module.
  203. //
  204. // The Module passed to the visit function should not be retained outside of the visit function, it may be
  205. // invalidated by future mutators.
  206. VisitDirectDepsIf(pred func(Module) bool, visit func(Module))
  207. // Deprecated: use WalkDeps instead to support multiple dependency tags on the same module
  208. VisitDepsDepthFirst(visit func(Module))
  209. // Deprecated: use WalkDeps instead to support multiple dependency tags on the same module
  210. VisitDepsDepthFirstIf(pred func(Module) bool, visit func(Module))
  211. // WalkDeps calls visit for each transitive dependency, traversing the dependency tree in top down order. visit may
  212. // be called multiple times for the same (child, parent) pair if there are multiple direct dependencies between the
  213. // child and parent with different tags. OtherModuleDependencyTag will return the tag for the currently visited
  214. // (child, parent) pair. If visit returns false WalkDeps will not continue recursing down to child. It skips
  215. // any dependencies that are not an android.Module.
  216. //
  217. // The Modules passed to the visit function should not be retained outside of the visit function, they may be
  218. // invalidated by future mutators.
  219. WalkDeps(visit func(child, parent Module) bool)
  220. // WalkDepsBlueprint calls visit for each transitive dependency, traversing the dependency
  221. // tree in top down order. visit may be called multiple times for the same (child, parent)
  222. // pair if there are multiple direct dependencies between the child and parent with different
  223. // tags. OtherModuleDependencyTag will return the tag for the currently visited
  224. // (child, parent) pair. If visit returns false WalkDeps will not continue recursing down
  225. // to child.
  226. //
  227. // The Modules passed to the visit function should not be retained outside of the visit function, they may be
  228. // invalidated by future mutators.
  229. WalkDepsBlueprint(visit func(blueprint.Module, blueprint.Module) bool)
  230. // GetWalkPath is supposed to be called in visit function passed in WalkDeps()
  231. // and returns a top-down dependency path from a start module to current child module.
  232. GetWalkPath() []Module
  233. // PrimaryModule returns the first variant of the current module. Variants of a module are always visited in
  234. // order by mutators and GenerateBuildActions, so the data created by the current mutator can be read from the
  235. // Module returned by PrimaryModule without data races. This can be used to perform singleton actions that are
  236. // only done once for all variants of a module.
  237. PrimaryModule() Module
  238. // FinalModule returns the last variant of the current module. Variants of a module are always visited in
  239. // order by mutators and GenerateBuildActions, so the data created by the current mutator can be read from all
  240. // variants using VisitAllModuleVariants if the current module == FinalModule(). This can be used to perform
  241. // singleton actions that are only done once for all variants of a module.
  242. FinalModule() Module
  243. // VisitAllModuleVariants calls visit for each variant of the current module. Variants of a module are always
  244. // visited in order by mutators and GenerateBuildActions, so the data created by the current mutator can be read
  245. // from all variants if the current module == FinalModule(). Otherwise, care must be taken to not access any
  246. // data modified by the current mutator.
  247. VisitAllModuleVariants(visit func(Module))
  248. // GetTagPath is supposed to be called in visit function passed in WalkDeps()
  249. // and returns a top-down dependency tags path from a start module to current child module.
  250. // It has one less entry than GetWalkPath() as it contains the dependency tags that
  251. // exist between each adjacent pair of modules in the GetWalkPath().
  252. // GetTagPath()[i] is the tag between GetWalkPath()[i] and GetWalkPath()[i+1]
  253. GetTagPath() []blueprint.DependencyTag
  254. // GetPathString is supposed to be called in visit function passed in WalkDeps()
  255. // and returns a multi-line string showing the modules and dependency tags
  256. // among them along the top-down dependency path from a start module to current child module.
  257. // skipFirst when set to true, the output doesn't include the start module,
  258. // which is already printed when this function is used along with ModuleErrorf().
  259. GetPathString(skipFirst bool) string
  260. AddMissingDependencies(missingDeps []string)
  261. // AddUnconvertedBp2buildDep stores module name of a direct dependency that was not converted via bp2build
  262. AddUnconvertedBp2buildDep(dep string)
  263. // AddMissingBp2buildDep stores the module name of a direct dependency that was not found.
  264. AddMissingBp2buildDep(dep string)
  265. Target() Target
  266. TargetPrimary() bool
  267. // The additional arch specific targets (e.g. 32/64 bit) that this module variant is
  268. // responsible for creating.
  269. MultiTargets() []Target
  270. Arch() Arch
  271. Os() OsType
  272. Host() bool
  273. Device() bool
  274. Darwin() bool
  275. Windows() bool
  276. Debug() bool
  277. PrimaryArch() bool
  278. }
  279. // Deprecated: use EarlyModuleContext instead
  280. type BaseContext interface {
  281. EarlyModuleContext
  282. }
  283. type ModuleContext interface {
  284. BaseModuleContext
  285. blueprintModuleContext() blueprint.ModuleContext
  286. // Deprecated: use ModuleContext.Build instead.
  287. ModuleBuild(pctx PackageContext, params ModuleBuildParams)
  288. // Returns a list of paths expanded from globs and modules referenced using ":module" syntax. The property must
  289. // be tagged with `android:"path" to support automatic source module dependency resolution.
  290. //
  291. // Deprecated: use PathsForModuleSrc or PathsForModuleSrcExcludes instead.
  292. ExpandSources(srcFiles, excludes []string) Paths
  293. // Returns a single path expanded from globs and modules referenced using ":module" syntax. The property must
  294. // be tagged with `android:"path" to support automatic source module dependency resolution.
  295. //
  296. // Deprecated: use PathForModuleSrc instead.
  297. ExpandSource(srcFile, prop string) Path
  298. ExpandOptionalSource(srcFile *string, prop string) OptionalPath
  299. // InstallExecutable creates a rule to copy srcPath to name in the installPath directory,
  300. // with the given additional dependencies. The file is marked executable after copying.
  301. //
  302. // The installed file will be returned by FilesToInstall(), and the PackagingSpec for the
  303. // installed file will be returned by PackagingSpecs() on this module or by
  304. // TransitivePackagingSpecs() on modules that depend on this module through dependency tags
  305. // for which IsInstallDepNeeded returns true.
  306. InstallExecutable(installPath InstallPath, name string, srcPath Path, deps ...Path) InstallPath
  307. // InstallFile creates a rule to copy srcPath to name in the installPath directory,
  308. // with the given additional dependencies.
  309. //
  310. // The installed file will be returned by FilesToInstall(), and the PackagingSpec for the
  311. // installed file will be returned by PackagingSpecs() on this module or by
  312. // TransitivePackagingSpecs() on modules that depend on this module through dependency tags
  313. // for which IsInstallDepNeeded returns true.
  314. InstallFile(installPath InstallPath, name string, srcPath Path, deps ...Path) InstallPath
  315. // InstallFileWithExtraFilesZip creates a rule to copy srcPath to name in the installPath
  316. // directory, and also unzip a zip file containing extra files to install into the same
  317. // directory.
  318. //
  319. // The installed file will be returned by FilesToInstall(), and the PackagingSpec for the
  320. // installed file will be returned by PackagingSpecs() on this module or by
  321. // TransitivePackagingSpecs() on modules that depend on this module through dependency tags
  322. // for which IsInstallDepNeeded returns true.
  323. InstallFileWithExtraFilesZip(installPath InstallPath, name string, srcPath Path, extraZip Path, deps ...Path) InstallPath
  324. // InstallSymlink creates a rule to create a symlink from src srcPath to name in the installPath
  325. // directory.
  326. //
  327. // The installed symlink will be returned by FilesToInstall(), and the PackagingSpec for the
  328. // installed file will be returned by PackagingSpecs() on this module or by
  329. // TransitivePackagingSpecs() on modules that depend on this module through dependency tags
  330. // for which IsInstallDepNeeded returns true.
  331. InstallSymlink(installPath InstallPath, name string, srcPath InstallPath) InstallPath
  332. // InstallAbsoluteSymlink creates a rule to create an absolute symlink from src srcPath to name
  333. // in the installPath directory.
  334. //
  335. // The installed symlink will be returned by FilesToInstall(), and the PackagingSpec for the
  336. // installed file will be returned by PackagingSpecs() on this module or by
  337. // TransitivePackagingSpecs() on modules that depend on this module through dependency tags
  338. // for which IsInstallDepNeeded returns true.
  339. InstallAbsoluteSymlink(installPath InstallPath, name string, absPath string) InstallPath
  340. // PackageFile creates a PackagingSpec as if InstallFile was called, but without creating
  341. // the rule to copy the file. This is useful to define how a module would be packaged
  342. // without installing it into the global installation directories.
  343. //
  344. // The created PackagingSpec for the will be returned by PackagingSpecs() on this module or by
  345. // TransitivePackagingSpecs() on modules that depend on this module through dependency tags
  346. // for which IsInstallDepNeeded returns true.
  347. PackageFile(installPath InstallPath, name string, srcPath Path) PackagingSpec
  348. CheckbuildFile(srcPath Path)
  349. InstallInData() bool
  350. InstallInTestcases() bool
  351. InstallInSanitizerDir() bool
  352. InstallInRamdisk() bool
  353. InstallInVendorRamdisk() bool
  354. InstallInDebugRamdisk() bool
  355. InstallInRecovery() bool
  356. InstallInRoot() bool
  357. InstallInVendor() bool
  358. InstallForceOS() (*OsType, *ArchType)
  359. RequiredModuleNames() []string
  360. HostRequiredModuleNames() []string
  361. TargetRequiredModuleNames() []string
  362. ModuleSubDir() string
  363. Variable(pctx PackageContext, name, value string)
  364. Rule(pctx PackageContext, name string, params blueprint.RuleParams, argNames ...string) blueprint.Rule
  365. // Similar to blueprint.ModuleContext.Build, but takes Paths instead of []string,
  366. // and performs more verification.
  367. Build(pctx PackageContext, params BuildParams)
  368. // Phony creates a Make-style phony rule, a rule with no commands that can depend on other
  369. // phony rules or real files. Phony can be called on the same name multiple times to add
  370. // additional dependencies.
  371. Phony(phony string, deps ...Path)
  372. // GetMissingDependencies returns the list of dependencies that were passed to AddDependencies or related methods,
  373. // but do not exist.
  374. GetMissingDependencies() []string
  375. // LicenseMetadataFile returns the path where the license metadata for this module will be
  376. // generated.
  377. LicenseMetadataFile() Path
  378. }
  379. type Module interface {
  380. blueprint.Module
  381. // GenerateAndroidBuildActions is analogous to Blueprints' GenerateBuildActions,
  382. // but GenerateAndroidBuildActions also has access to Android-specific information.
  383. // For more information, see Module.GenerateBuildActions within Blueprint's module_ctx.go
  384. GenerateAndroidBuildActions(ModuleContext)
  385. // Add dependencies to the components of a module, i.e. modules that are created
  386. // by the module and which are considered to be part of the creating module.
  387. //
  388. // This is called before prebuilts are renamed so as to allow a dependency to be
  389. // added directly to a prebuilt child module instead of depending on a source module
  390. // and relying on prebuilt processing to switch to the prebuilt module if preferred.
  391. //
  392. // A dependency on a prebuilt must include the "prebuilt_" prefix.
  393. ComponentDepsMutator(ctx BottomUpMutatorContext)
  394. DepsMutator(BottomUpMutatorContext)
  395. base() *ModuleBase
  396. Disable()
  397. Enabled() bool
  398. Target() Target
  399. MultiTargets() []Target
  400. // ImageVariation returns the image variation of this module.
  401. //
  402. // The returned structure has its Mutator field set to "image" and its Variation field set to the
  403. // image variation, e.g. recovery, ramdisk, etc.. The Variation field is "" for host modules and
  404. // device modules that have no image variation.
  405. ImageVariation() blueprint.Variation
  406. Owner() string
  407. InstallInData() bool
  408. InstallInTestcases() bool
  409. InstallInSanitizerDir() bool
  410. InstallInRamdisk() bool
  411. InstallInVendorRamdisk() bool
  412. InstallInDebugRamdisk() bool
  413. InstallInRecovery() bool
  414. InstallInRoot() bool
  415. InstallInVendor() bool
  416. InstallForceOS() (*OsType, *ArchType)
  417. HideFromMake()
  418. IsHideFromMake() bool
  419. IsSkipInstall() bool
  420. MakeUninstallable()
  421. ReplacedByPrebuilt()
  422. IsReplacedByPrebuilt() bool
  423. ExportedToMake() bool
  424. InitRc() Paths
  425. VintfFragments() Paths
  426. EffectiveLicenseFiles() Paths
  427. AddProperties(props ...interface{})
  428. GetProperties() []interface{}
  429. // IsConvertedByBp2build returns whether this module was converted via bp2build
  430. IsConvertedByBp2build() bool
  431. // Bp2buildTargets returns the target(s) generated for Bazel via bp2build for this module
  432. Bp2buildTargets() []bp2buildInfo
  433. GetUnconvertedBp2buildDeps() []string
  434. GetMissingBp2buildDeps() []string
  435. BuildParamsForTests() []BuildParams
  436. RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams
  437. VariablesForTests() map[string]string
  438. // String returns a string that includes the module name and variants for printing during debugging.
  439. String() string
  440. // Get the qualified module id for this module.
  441. qualifiedModuleId(ctx BaseModuleContext) qualifiedModuleName
  442. // Get information about the properties that can contain visibility rules.
  443. visibilityProperties() []visibilityProperty
  444. RequiredModuleNames() []string
  445. HostRequiredModuleNames() []string
  446. TargetRequiredModuleNames() []string
  447. FilesToInstall() InstallPaths
  448. PackagingSpecs() []PackagingSpec
  449. // TransitivePackagingSpecs returns the PackagingSpecs for this module and any transitive
  450. // dependencies with dependency tags for which IsInstallDepNeeded() returns true.
  451. TransitivePackagingSpecs() []PackagingSpec
  452. }
  453. // Qualified id for a module
  454. type qualifiedModuleName struct {
  455. // The package (i.e. directory) in which the module is defined, without trailing /
  456. pkg string
  457. // The name of the module, empty string if package.
  458. name string
  459. }
  460. func (q qualifiedModuleName) String() string {
  461. if q.name == "" {
  462. return "//" + q.pkg
  463. }
  464. return "//" + q.pkg + ":" + q.name
  465. }
  466. func (q qualifiedModuleName) isRootPackage() bool {
  467. return q.pkg == "" && q.name == ""
  468. }
  469. // Get the id for the package containing this module.
  470. func (q qualifiedModuleName) getContainingPackageId() qualifiedModuleName {
  471. pkg := q.pkg
  472. if q.name == "" {
  473. if pkg == "" {
  474. panic(fmt.Errorf("Cannot get containing package id of root package"))
  475. }
  476. index := strings.LastIndex(pkg, "/")
  477. if index == -1 {
  478. pkg = ""
  479. } else {
  480. pkg = pkg[:index]
  481. }
  482. }
  483. return newPackageId(pkg)
  484. }
  485. func newPackageId(pkg string) qualifiedModuleName {
  486. // A qualified id for a package module has no name.
  487. return qualifiedModuleName{pkg: pkg, name: ""}
  488. }
  489. type Dist struct {
  490. // Copy the output of this module to the $DIST_DIR when `dist` is specified on the
  491. // command line and any of these targets are also on the command line, or otherwise
  492. // built
  493. Targets []string `android:"arch_variant"`
  494. // The name of the output artifact. This defaults to the basename of the output of
  495. // the module.
  496. Dest *string `android:"arch_variant"`
  497. // The directory within the dist directory to store the artifact. Defaults to the
  498. // top level directory ("").
  499. Dir *string `android:"arch_variant"`
  500. // A suffix to add to the artifact file name (before any extension).
  501. Suffix *string `android:"arch_variant"`
  502. // If true, then the artifact file will be appended with _<product name>. For
  503. // example, if the product is coral and the module is an android_app module
  504. // of name foo, then the artifact would be foo_coral.apk. If false, there is
  505. // no change to the artifact file name.
  506. Append_artifact_with_product *bool `android:"arch_variant"`
  507. // A string tag to select the OutputFiles associated with the tag.
  508. //
  509. // If no tag is specified then it will select the default dist paths provided
  510. // by the module type. If a tag of "" is specified then it will return the
  511. // default output files provided by the modules, i.e. the result of calling
  512. // OutputFiles("").
  513. Tag *string `android:"arch_variant"`
  514. }
  515. // NamedPath associates a path with a name. e.g. a license text path with a package name
  516. type NamedPath struct {
  517. Path Path
  518. Name string
  519. }
  520. // String returns an escaped string representing the `NamedPath`.
  521. func (p NamedPath) String() string {
  522. if len(p.Name) > 0 {
  523. return p.Path.String() + ":" + url.QueryEscape(p.Name)
  524. }
  525. return p.Path.String()
  526. }
  527. // NamedPaths describes a list of paths each associated with a name.
  528. type NamedPaths []NamedPath
  529. // Strings returns a list of escaped strings representing each `NamedPath` in the list.
  530. func (l NamedPaths) Strings() []string {
  531. result := make([]string, 0, len(l))
  532. for _, p := range l {
  533. result = append(result, p.String())
  534. }
  535. return result
  536. }
  537. // SortedUniqueNamedPaths modifies `l` in place to return the sorted unique subset.
  538. func SortedUniqueNamedPaths(l NamedPaths) NamedPaths {
  539. if len(l) == 0 {
  540. return l
  541. }
  542. sort.Slice(l, func(i, j int) bool {
  543. return l[i].String() < l[j].String()
  544. })
  545. k := 0
  546. for i := 1; i < len(l); i++ {
  547. if l[i].String() == l[k].String() {
  548. continue
  549. }
  550. k++
  551. if k < i {
  552. l[k] = l[i]
  553. }
  554. }
  555. return l[:k+1]
  556. }
  557. type nameProperties struct {
  558. // The name of the module. Must be unique across all modules.
  559. Name *string
  560. }
  561. type commonProperties struct {
  562. // emit build rules for this module
  563. //
  564. // Disabling a module should only be done for those modules that cannot be built
  565. // in the current environment. Modules that can build in the current environment
  566. // but are not usually required (e.g. superceded by a prebuilt) should not be
  567. // disabled as that will prevent them from being built by the checkbuild target
  568. // and so prevent early detection of changes that have broken those modules.
  569. Enabled *bool `android:"arch_variant"`
  570. // Controls the visibility of this module to other modules. Allowable values are one or more of
  571. // these formats:
  572. //
  573. // ["//visibility:public"]: Anyone can use this module.
  574. // ["//visibility:private"]: Only rules in the module's package (not its subpackages) can use
  575. // this module.
  576. // ["//visibility:override"]: Discards any rules inherited from defaults or a creating module.
  577. // Can only be used at the beginning of a list of visibility rules.
  578. // ["//some/package:__pkg__", "//other/package:__pkg__"]: Only modules in some/package and
  579. // other/package (defined in some/package/*.bp and other/package/*.bp) have access to
  580. // this module. Note that sub-packages do not have access to the rule; for example,
  581. // //some/package/foo:bar or //other/package/testing:bla wouldn't have access. __pkg__
  582. // is a special module and must be used verbatim. It represents all of the modules in the
  583. // package.
  584. // ["//project:__subpackages__", "//other:__subpackages__"]: Only modules in packages project
  585. // or other or in one of their sub-packages have access to this module. For example,
  586. // //project:rule, //project/library:lib or //other/testing/internal:munge are allowed
  587. // to depend on this rule (but not //independent:evil)
  588. // ["//project"]: This is shorthand for ["//project:__pkg__"]
  589. // [":__subpackages__"]: This is shorthand for ["//project:__subpackages__"] where
  590. // //project is the module's package. e.g. using [":__subpackages__"] in
  591. // packages/apps/Settings/Android.bp is equivalent to
  592. // //packages/apps/Settings:__subpackages__.
  593. // ["//visibility:legacy_public"]: The default visibility, behaves as //visibility:public
  594. // for now. It is an error if it is used in a module.
  595. //
  596. // If a module does not specify the `visibility` property then it uses the
  597. // `default_visibility` property of the `package` module in the module's package.
  598. //
  599. // If the `default_visibility` property is not set for the module's package then
  600. // it will use the `default_visibility` of its closest ancestor package for which
  601. // a `default_visibility` property is specified.
  602. //
  603. // If no `default_visibility` property can be found then the module uses the
  604. // global default of `//visibility:legacy_public`.
  605. //
  606. // The `visibility` property has no effect on a defaults module although it does
  607. // apply to any non-defaults module that uses it. To set the visibility of a
  608. // defaults module, use the `defaults_visibility` property on the defaults module;
  609. // not to be confused with the `default_visibility` property on the package module.
  610. //
  611. // See https://android.googlesource.com/platform/build/soong/+/master/README.md#visibility for
  612. // more details.
  613. Visibility []string
  614. // Describes the licenses applicable to this module. Must reference license modules.
  615. Licenses []string
  616. // Flattened from direct license dependencies. Equal to Licenses unless particular module adds more.
  617. Effective_licenses []string `blueprint:"mutated"`
  618. // Override of module name when reporting licenses
  619. Effective_package_name *string `blueprint:"mutated"`
  620. // Notice files
  621. Effective_license_text NamedPaths `blueprint:"mutated"`
  622. // License names
  623. Effective_license_kinds []string `blueprint:"mutated"`
  624. // License conditions
  625. Effective_license_conditions []string `blueprint:"mutated"`
  626. // control whether this module compiles for 32-bit, 64-bit, or both. Possible values
  627. // are "32" (compile for 32-bit only), "64" (compile for 64-bit only), "both" (compile for both
  628. // architectures), or "first" (compile for 64-bit on a 64-bit platform, and 32-bit on a 32-bit
  629. // platform).
  630. Compile_multilib *string `android:"arch_variant"`
  631. Target struct {
  632. Host struct {
  633. Compile_multilib *string
  634. }
  635. Android struct {
  636. Compile_multilib *string
  637. }
  638. }
  639. // If set to true then the archMutator will create variants for each arch specific target
  640. // (e.g. 32/64) that the module is required to produce. If set to false then it will only
  641. // create a variant for the architecture and will list the additional arch specific targets
  642. // that the variant needs to produce in the CompileMultiTargets property.
  643. UseTargetVariants bool `blueprint:"mutated"`
  644. Default_multilib string `blueprint:"mutated"`
  645. // whether this is a proprietary vendor module, and should be installed into /vendor
  646. Proprietary *bool
  647. // vendor who owns this module
  648. Owner *string
  649. // whether this module is specific to an SoC (System-On-a-Chip). When set to true,
  650. // it is installed into /vendor (or /system/vendor if vendor partition does not exist).
  651. // Use `soc_specific` instead for better meaning.
  652. Vendor *bool
  653. // whether this module is specific to an SoC (System-On-a-Chip). When set to true,
  654. // it is installed into /vendor (or /system/vendor if vendor partition does not exist).
  655. Soc_specific *bool
  656. // whether this module is specific to a device, not only for SoC, but also for off-chip
  657. // peripherals. When set to true, it is installed into /odm (or /vendor/odm if odm partition
  658. // does not exist, or /system/vendor/odm if both odm and vendor partitions do not exist).
  659. // This implies `soc_specific:true`.
  660. Device_specific *bool
  661. // whether this module is specific to a software configuration of a product (e.g. country,
  662. // network operator, etc). When set to true, it is installed into /product (or
  663. // /system/product if product partition does not exist).
  664. Product_specific *bool
  665. // whether this module extends system. When set to true, it is installed into /system_ext
  666. // (or /system/system_ext if system_ext partition does not exist).
  667. System_ext_specific *bool
  668. // Whether this module is installed to recovery partition
  669. Recovery *bool
  670. // Whether this module is installed to ramdisk
  671. Ramdisk *bool
  672. // Whether this module is installed to vendor ramdisk
  673. Vendor_ramdisk *bool
  674. // Whether this module is installed to debug ramdisk
  675. Debug_ramdisk *bool
  676. // Whether this module is built for non-native architectures (also known as native bridge binary)
  677. Native_bridge_supported *bool `android:"arch_variant"`
  678. // init.rc files to be installed if this module is installed
  679. Init_rc []string `android:"arch_variant,path"`
  680. // VINTF manifest fragments to be installed if this module is installed
  681. Vintf_fragments []string `android:"path"`
  682. // names of other modules to install if this module is installed
  683. Required []string `android:"arch_variant"`
  684. // names of other modules to install on host if this module is installed
  685. Host_required []string `android:"arch_variant"`
  686. // names of other modules to install on target if this module is installed
  687. Target_required []string `android:"arch_variant"`
  688. // The OsType of artifacts that this module variant is responsible for creating.
  689. //
  690. // Set by osMutator
  691. CompileOS OsType `blueprint:"mutated"`
  692. // The Target of artifacts that this module variant is responsible for creating.
  693. //
  694. // Set by archMutator
  695. CompileTarget Target `blueprint:"mutated"`
  696. // The additional arch specific targets (e.g. 32/64 bit) that this module variant is
  697. // responsible for creating.
  698. //
  699. // By default this is nil as, where necessary, separate variants are created for the
  700. // different multilib types supported and that information is encapsulated in the
  701. // CompileTarget so the module variant simply needs to create artifacts for that.
  702. //
  703. // However, if UseTargetVariants is set to false (e.g. by
  704. // InitAndroidMultiTargetsArchModule) then no separate variants are created for the
  705. // multilib targets. Instead a single variant is created for the architecture and
  706. // this contains the multilib specific targets that this variant should create.
  707. //
  708. // Set by archMutator
  709. CompileMultiTargets []Target `blueprint:"mutated"`
  710. // True if the module variant's CompileTarget is the primary target
  711. //
  712. // Set by archMutator
  713. CompilePrimary bool `blueprint:"mutated"`
  714. // Set by InitAndroidModule
  715. HostOrDeviceSupported HostOrDeviceSupported `blueprint:"mutated"`
  716. ArchSpecific bool `blueprint:"mutated"`
  717. // If set to true then a CommonOS variant will be created which will have dependencies
  718. // on all its OsType specific variants. Used by sdk/module_exports to create a snapshot
  719. // that covers all os and architecture variants.
  720. //
  721. // The OsType specific variants can be retrieved by calling
  722. // GetOsSpecificVariantsOfCommonOSVariant
  723. //
  724. // Set at module initialization time by calling InitCommonOSAndroidMultiTargetsArchModule
  725. CreateCommonOSVariant bool `blueprint:"mutated"`
  726. // If set to true then this variant is the CommonOS variant that has dependencies on its
  727. // OsType specific variants.
  728. //
  729. // Set by osMutator.
  730. CommonOSVariant bool `blueprint:"mutated"`
  731. // When HideFromMake is set to true, no entry for this variant will be emitted in the
  732. // generated Android.mk file.
  733. HideFromMake bool `blueprint:"mutated"`
  734. // When SkipInstall is set to true, calls to ctx.InstallFile, ctx.InstallExecutable,
  735. // ctx.InstallSymlink and ctx.InstallAbsoluteSymlink act like calls to ctx.PackageFile
  736. // and don't create a rule to install the file.
  737. SkipInstall bool `blueprint:"mutated"`
  738. // Whether the module has been replaced by a prebuilt
  739. ReplacedByPrebuilt bool `blueprint:"mutated"`
  740. // Disabled by mutators. If set to true, it overrides Enabled property.
  741. ForcedDisabled bool `blueprint:"mutated"`
  742. NamespaceExportedToMake bool `blueprint:"mutated"`
  743. MissingDeps []string `blueprint:"mutated"`
  744. // Name and variant strings stored by mutators to enable Module.String()
  745. DebugName string `blueprint:"mutated"`
  746. DebugMutators []string `blueprint:"mutated"`
  747. DebugVariations []string `blueprint:"mutated"`
  748. // ImageVariation is set by ImageMutator to specify which image this variation is for,
  749. // for example "" for core or "recovery" for recovery. It will often be set to one of the
  750. // constants in image.go, but can also be set to a custom value by individual module types.
  751. ImageVariation string `blueprint:"mutated"`
  752. // Bazel conversion status
  753. BazelConversionStatus BazelConversionStatus `blueprint:"mutated"`
  754. }
  755. // CommonAttributes represents the common Bazel attributes from which properties
  756. // in `commonProperties` are translated/mapped; such properties are annotated in
  757. // a list their corresponding attribute. It is embedded within `bp2buildInfo`.
  758. type CommonAttributes struct {
  759. // Soong nameProperties -> Bazel name
  760. Name string
  761. // Data mapped from: Required
  762. Data bazel.LabelListAttribute
  763. }
  764. // constraintAttributes represents Bazel attributes pertaining to build constraints,
  765. // which make restrict building a Bazel target for some set of platforms.
  766. type constraintAttributes struct {
  767. // Constraint values this target can be built for.
  768. Target_compatible_with bazel.LabelListAttribute
  769. }
  770. type distProperties struct {
  771. // configuration to distribute output files from this module to the distribution
  772. // directory (default: $OUT/dist, configurable with $DIST_DIR)
  773. Dist Dist `android:"arch_variant"`
  774. // a list of configurations to distribute output files from this module to the
  775. // distribution directory (default: $OUT/dist, configurable with $DIST_DIR)
  776. Dists []Dist `android:"arch_variant"`
  777. }
  778. // CommonTestOptions represents the common `test_options` properties in
  779. // Android.bp.
  780. type CommonTestOptions struct {
  781. // If the test is a hostside (no device required) unittest that shall be run
  782. // during presubmit check.
  783. Unit_test *bool
  784. }
  785. // SetAndroidMkEntries sets AndroidMkEntries according to the value of base
  786. // `test_options`.
  787. func (t *CommonTestOptions) SetAndroidMkEntries(entries *AndroidMkEntries) {
  788. entries.SetBoolIfTrue("LOCAL_IS_UNIT_TEST", Bool(t.Unit_test))
  789. }
  790. // The key to use in TaggedDistFiles when a Dist structure does not specify a
  791. // tag property. This intentionally does not use "" as the default because that
  792. // would mean that an empty tag would have a different meaning when used in a dist
  793. // structure that when used to reference a specific set of output paths using the
  794. // :module{tag} syntax, which passes tag to the OutputFiles(tag) method.
  795. const DefaultDistTag = "<default-dist-tag>"
  796. // A map of OutputFile tag keys to Paths, for disting purposes.
  797. type TaggedDistFiles map[string]Paths
  798. // addPathsForTag adds a mapping from the tag to the paths. If the map is nil
  799. // then it will create a map, update it and then return it. If a mapping already
  800. // exists for the tag then the paths are appended to the end of the current list
  801. // of paths, ignoring any duplicates.
  802. func (t TaggedDistFiles) addPathsForTag(tag string, paths ...Path) TaggedDistFiles {
  803. if t == nil {
  804. t = make(TaggedDistFiles)
  805. }
  806. for _, distFile := range paths {
  807. if distFile != nil && !t[tag].containsPath(distFile) {
  808. t[tag] = append(t[tag], distFile)
  809. }
  810. }
  811. return t
  812. }
  813. // merge merges the entries from the other TaggedDistFiles object into this one.
  814. // If the TaggedDistFiles is nil then it will create a new instance, merge the
  815. // other into it, and then return it.
  816. func (t TaggedDistFiles) merge(other TaggedDistFiles) TaggedDistFiles {
  817. for tag, paths := range other {
  818. t = t.addPathsForTag(tag, paths...)
  819. }
  820. return t
  821. }
  822. func MakeDefaultDistFiles(paths ...Path) TaggedDistFiles {
  823. for _, p := range paths {
  824. if p == nil {
  825. panic("The path to a dist file cannot be nil.")
  826. }
  827. }
  828. // The default OutputFile tag is the empty "" string.
  829. return TaggedDistFiles{DefaultDistTag: paths}
  830. }
  831. type hostAndDeviceProperties struct {
  832. // If set to true, build a variant of the module for the host. Defaults to false.
  833. Host_supported *bool
  834. // If set to true, build a variant of the module for the device. Defaults to true.
  835. Device_supported *bool
  836. }
  837. type Multilib string
  838. const (
  839. MultilibBoth Multilib = "both"
  840. MultilibFirst Multilib = "first"
  841. MultilibCommon Multilib = "common"
  842. MultilibCommonFirst Multilib = "common_first"
  843. )
  844. type HostOrDeviceSupported int
  845. const (
  846. hostSupported = 1 << iota
  847. hostCrossSupported
  848. deviceSupported
  849. hostDefault
  850. deviceDefault
  851. // Host and HostCross are built by default. Device is not supported.
  852. HostSupported = hostSupported | hostCrossSupported | hostDefault
  853. // Host is built by default. HostCross and Device are not supported.
  854. HostSupportedNoCross = hostSupported | hostDefault
  855. // Device is built by default. Host and HostCross are not supported.
  856. DeviceSupported = deviceSupported | deviceDefault
  857. // By default, _only_ device variant is built. Device variant can be disabled with `device_supported: false`
  858. // Host and HostCross are disabled by default and can be enabled with `host_supported: true`
  859. HostAndDeviceSupported = hostSupported | hostCrossSupported | deviceSupported | deviceDefault
  860. // Host, HostCross, and Device are built by default.
  861. // Building Device can be disabled with `device_supported: false`
  862. // Building Host and HostCross can be disabled with `host_supported: false`
  863. HostAndDeviceDefault = hostSupported | hostCrossSupported | hostDefault |
  864. deviceSupported | deviceDefault
  865. // Nothing is supported. This is not exposed to the user, but used to mark a
  866. // host only module as unsupported when the module type is not supported on
  867. // the host OS. E.g. benchmarks are supported on Linux but not Darwin.
  868. NeitherHostNorDeviceSupported = 0
  869. )
  870. type moduleKind int
  871. const (
  872. platformModule moduleKind = iota
  873. deviceSpecificModule
  874. socSpecificModule
  875. productSpecificModule
  876. systemExtSpecificModule
  877. )
  878. func (k moduleKind) String() string {
  879. switch k {
  880. case platformModule:
  881. return "platform"
  882. case deviceSpecificModule:
  883. return "device-specific"
  884. case socSpecificModule:
  885. return "soc-specific"
  886. case productSpecificModule:
  887. return "product-specific"
  888. case systemExtSpecificModule:
  889. return "systemext-specific"
  890. default:
  891. panic(fmt.Errorf("unknown module kind %d", k))
  892. }
  893. }
  894. func initAndroidModuleBase(m Module) {
  895. m.base().module = m
  896. }
  897. // InitAndroidModule initializes the Module as an Android module that is not architecture-specific.
  898. // It adds the common properties, for example "name" and "enabled".
  899. func InitAndroidModule(m Module) {
  900. initAndroidModuleBase(m)
  901. base := m.base()
  902. m.AddProperties(
  903. &base.nameProperties,
  904. &base.commonProperties,
  905. &base.distProperties)
  906. initProductVariableModule(m)
  907. // The default_visibility property needs to be checked and parsed by the visibility module during
  908. // its checking and parsing phases so make it the primary visibility property.
  909. setPrimaryVisibilityProperty(m, "visibility", &base.commonProperties.Visibility)
  910. // The default_applicable_licenses property needs to be checked and parsed by the licenses module during
  911. // its checking and parsing phases so make it the primary licenses property.
  912. setPrimaryLicensesProperty(m, "licenses", &base.commonProperties.Licenses)
  913. }
  914. // InitAndroidArchModule initializes the Module as an Android module that is architecture-specific.
  915. // It adds the common properties, for example "name" and "enabled", as well as runtime generated
  916. // property structs for architecture-specific versions of generic properties tagged with
  917. // `android:"arch_variant"`.
  918. //
  919. // InitAndroidModule should not be called if InitAndroidArchModule was called.
  920. func InitAndroidArchModule(m Module, hod HostOrDeviceSupported, defaultMultilib Multilib) {
  921. InitAndroidModule(m)
  922. base := m.base()
  923. base.commonProperties.HostOrDeviceSupported = hod
  924. base.commonProperties.Default_multilib = string(defaultMultilib)
  925. base.commonProperties.ArchSpecific = true
  926. base.commonProperties.UseTargetVariants = true
  927. if hod&hostSupported != 0 && hod&deviceSupported != 0 {
  928. m.AddProperties(&base.hostAndDeviceProperties)
  929. }
  930. initArchModule(m)
  931. }
  932. // InitAndroidMultiTargetsArchModule initializes the Module as an Android module that is
  933. // architecture-specific, but will only have a single variant per OS that handles all the
  934. // architectures simultaneously. The list of Targets that it must handle will be available from
  935. // ModuleContext.MultiTargets. It adds the common properties, for example "name" and "enabled", as
  936. // well as runtime generated property structs for architecture-specific versions of generic
  937. // properties tagged with `android:"arch_variant"`.
  938. //
  939. // InitAndroidModule or InitAndroidArchModule should not be called if
  940. // InitAndroidMultiTargetsArchModule was called.
  941. func InitAndroidMultiTargetsArchModule(m Module, hod HostOrDeviceSupported, defaultMultilib Multilib) {
  942. InitAndroidArchModule(m, hod, defaultMultilib)
  943. m.base().commonProperties.UseTargetVariants = false
  944. }
  945. // InitCommonOSAndroidMultiTargetsArchModule initializes the Module as an Android module that is
  946. // architecture-specific, but will only have a single variant per OS that handles all the
  947. // architectures simultaneously, and will also have an additional CommonOS variant that has
  948. // dependencies on all the OS-specific variants. The list of Targets that it must handle will be
  949. // available from ModuleContext.MultiTargets. It adds the common properties, for example "name" and
  950. // "enabled", as well as runtime generated property structs for architecture-specific versions of
  951. // generic properties tagged with `android:"arch_variant"`.
  952. //
  953. // InitAndroidModule, InitAndroidArchModule or InitAndroidMultiTargetsArchModule should not be
  954. // called if InitCommonOSAndroidMultiTargetsArchModule was called.
  955. func InitCommonOSAndroidMultiTargetsArchModule(m Module, hod HostOrDeviceSupported, defaultMultilib Multilib) {
  956. InitAndroidArchModule(m, hod, defaultMultilib)
  957. m.base().commonProperties.UseTargetVariants = false
  958. m.base().commonProperties.CreateCommonOSVariant = true
  959. }
  960. func (attrs *CommonAttributes) fillCommonBp2BuildModuleAttrs(ctx *topDownMutatorContext,
  961. enabledPropertyOverrides bazel.BoolAttribute) constraintAttributes {
  962. mod := ctx.Module().base()
  963. // Assert passed-in attributes include Name
  964. if len(attrs.Name) == 0 {
  965. ctx.ModuleErrorf("CommonAttributes in fillCommonBp2BuildModuleAttrs expects a `.Name`!")
  966. }
  967. depsToLabelList := func(deps []string) bazel.LabelListAttribute {
  968. return bazel.MakeLabelListAttribute(BazelLabelForModuleDeps(ctx, deps))
  969. }
  970. var enabledProperty bazel.BoolAttribute
  971. onlyAndroid := false
  972. neitherHostNorDevice := false
  973. osSupport := map[string]bool{}
  974. // if the target is enabled and supports arch variance, determine the defaults based on the module
  975. // type's host or device property and host_supported/device_supported properties
  976. if mod.commonProperties.ArchSpecific {
  977. moduleSupportsDevice := mod.DeviceSupported()
  978. moduleSupportsHost := mod.HostSupported()
  979. if moduleSupportsHost && !moduleSupportsDevice {
  980. // for host only, we specify as unsupported on android rather than listing all host osSupport
  981. // TODO(b/220874839): consider replacing this with a constraint that covers all host osSupport
  982. // instead
  983. enabledProperty.SetSelectValue(bazel.OsConfigurationAxis, Android.Name, proptools.BoolPtr(false))
  984. } else if moduleSupportsDevice && !moduleSupportsHost {
  985. enabledProperty.SetSelectValue(bazel.OsConfigurationAxis, Android.Name, proptools.BoolPtr(true))
  986. // specify as a positive to ensure any target-specific enabled can be resolved
  987. // also save that a target is only android, as if there is only the positive restriction on
  988. // android, it'll be dropped, so we may need to add it back later
  989. onlyAndroid = true
  990. } else if !moduleSupportsHost && !moduleSupportsDevice {
  991. neitherHostNorDevice = true
  992. }
  993. for _, osType := range OsTypeList() {
  994. if osType.Class == Host {
  995. osSupport[osType.Name] = moduleSupportsHost
  996. } else if osType.Class == Device {
  997. osSupport[osType.Name] = moduleSupportsDevice
  998. }
  999. }
  1000. }
  1001. if neitherHostNorDevice {
  1002. // we can't build this, disable
  1003. enabledProperty.Value = proptools.BoolPtr(false)
  1004. } else if mod.commonProperties.Enabled != nil {
  1005. enabledProperty.SetValue(mod.commonProperties.Enabled)
  1006. if !*mod.commonProperties.Enabled {
  1007. for oss, enabled := range osSupport {
  1008. if val := enabledProperty.SelectValue(bazel.OsConfigurationAxis, oss); enabled && val != nil && *val {
  1009. // if this should be disabled by default, clear out any enabling we've done
  1010. enabledProperty.SetSelectValue(bazel.OsConfigurationAxis, oss, nil)
  1011. }
  1012. }
  1013. }
  1014. }
  1015. required := depsToLabelList(mod.commonProperties.Required)
  1016. archVariantProps := mod.GetArchVariantProperties(ctx, &commonProperties{})
  1017. for axis, configToProps := range archVariantProps {
  1018. for config, _props := range configToProps {
  1019. if archProps, ok := _props.(*commonProperties); ok {
  1020. // TODO(b/234748998) Remove this requiredFiltered workaround when aapt2 converts successfully
  1021. requiredFiltered := archProps.Required
  1022. if attrs.Name == "apexer" {
  1023. requiredFiltered = make([]string, 0, len(archProps.Required))
  1024. for _, req := range archProps.Required {
  1025. if req != "aapt2" && req != "apexer" {
  1026. requiredFiltered = append(requiredFiltered, req)
  1027. }
  1028. }
  1029. }
  1030. required.SetSelectValue(axis, config, depsToLabelList(requiredFiltered).Value)
  1031. if !neitherHostNorDevice {
  1032. if archProps.Enabled != nil {
  1033. if axis != bazel.OsConfigurationAxis || osSupport[config] {
  1034. enabledProperty.SetSelectValue(axis, config, archProps.Enabled)
  1035. }
  1036. }
  1037. }
  1038. }
  1039. }
  1040. }
  1041. if !neitherHostNorDevice {
  1042. if enabledPropertyOverrides.Value != nil {
  1043. enabledProperty.Value = enabledPropertyOverrides.Value
  1044. }
  1045. for _, axis := range enabledPropertyOverrides.SortedConfigurationAxes() {
  1046. configToBools := enabledPropertyOverrides.ConfigurableValues[axis]
  1047. for cfg, val := range configToBools {
  1048. if axis != bazel.OsConfigurationAxis || osSupport[cfg] {
  1049. enabledProperty.SetSelectValue(axis, cfg, &val)
  1050. }
  1051. }
  1052. }
  1053. }
  1054. productConfigEnabledLabels := []bazel.Label{}
  1055. // TODO(b/234497586): Soong config variables and product variables have different overriding behavior, we
  1056. // should handle it correctly
  1057. if !proptools.BoolDefault(enabledProperty.Value, true) && !neitherHostNorDevice {
  1058. // If the module is not enabled by default, then we can check if a
  1059. // product variable enables it
  1060. productConfigEnabledLabels = productVariableConfigEnableLabels(ctx)
  1061. if len(productConfigEnabledLabels) > 0 {
  1062. // In this case, an existing product variable configuration overrides any
  1063. // module-level `enable: false` definition
  1064. newValue := true
  1065. enabledProperty.Value = &newValue
  1066. }
  1067. }
  1068. productConfigEnabledAttribute := bazel.MakeLabelListAttribute(bazel.LabelList{
  1069. productConfigEnabledLabels, nil,
  1070. })
  1071. platformEnabledAttribute, err := enabledProperty.ToLabelListAttribute(
  1072. bazel.LabelList{[]bazel.Label{{Label: "@platforms//:incompatible"}}, nil},
  1073. bazel.LabelList{[]bazel.Label{}, nil})
  1074. if err != nil {
  1075. ctx.ModuleErrorf("Error processing platform enabled attribute: %s", err)
  1076. }
  1077. // if android is the only arch/os enabled, then add a restriction to only be compatible with android
  1078. if platformEnabledAttribute.IsNil() && onlyAndroid {
  1079. l := bazel.LabelAttribute{}
  1080. l.SetValue(bazel.Label{Label: bazel.OsConfigurationAxis.SelectKey(Android.Name)})
  1081. platformEnabledAttribute.Add(&l)
  1082. }
  1083. attrs.Data.Append(required)
  1084. moduleEnableConstraints := bazel.LabelListAttribute{}
  1085. moduleEnableConstraints.Append(platformEnabledAttribute)
  1086. moduleEnableConstraints.Append(productConfigEnabledAttribute)
  1087. return constraintAttributes{Target_compatible_with: moduleEnableConstraints}
  1088. }
  1089. // Check product variables for `enabled: true` flag override.
  1090. // Returns a list of the constraint_value targets who enable this override.
  1091. func productVariableConfigEnableLabels(ctx *topDownMutatorContext) []bazel.Label {
  1092. productVariableProps := ProductVariableProperties(ctx)
  1093. productConfigEnablingTargets := []bazel.Label{}
  1094. const propName = "Enabled"
  1095. if productConfigProps, exists := productVariableProps[propName]; exists {
  1096. for productConfigProp, prop := range productConfigProps {
  1097. flag, ok := prop.(*bool)
  1098. if !ok {
  1099. ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
  1100. }
  1101. if *flag {
  1102. axis := productConfigProp.ConfigurationAxis()
  1103. targetLabel := axis.SelectKey(productConfigProp.SelectKey())
  1104. productConfigEnablingTargets = append(productConfigEnablingTargets, bazel.Label{
  1105. Label: targetLabel,
  1106. })
  1107. } else {
  1108. // TODO(b/210546943): handle negative case where `enabled: false`
  1109. ctx.ModuleErrorf("`enabled: false` is not currently supported for configuration variables. See b/210546943", proptools.PropertyNameForField(propName))
  1110. }
  1111. }
  1112. }
  1113. return productConfigEnablingTargets
  1114. }
  1115. // A ModuleBase object contains the properties that are common to all Android
  1116. // modules. It should be included as an anonymous field in every module
  1117. // struct definition. InitAndroidModule should then be called from the module's
  1118. // factory function, and the return values from InitAndroidModule should be
  1119. // returned from the factory function.
  1120. //
  1121. // The ModuleBase type is responsible for implementing the GenerateBuildActions
  1122. // method to support the blueprint.Module interface. This method will then call
  1123. // the module's GenerateAndroidBuildActions method once for each build variant
  1124. // that is to be built. GenerateAndroidBuildActions is passed a ModuleContext
  1125. // rather than the usual blueprint.ModuleContext.
  1126. // ModuleContext exposes extra functionality specific to the Android build
  1127. // system including details about the particular build variant that is to be
  1128. // generated.
  1129. //
  1130. // For example:
  1131. //
  1132. // import (
  1133. // "android/soong/android"
  1134. // )
  1135. //
  1136. // type myModule struct {
  1137. // android.ModuleBase
  1138. // properties struct {
  1139. // MyProperty string
  1140. // }
  1141. // }
  1142. //
  1143. // func NewMyModule() android.Module {
  1144. // m := &myModule{}
  1145. // m.AddProperties(&m.properties)
  1146. // android.InitAndroidModule(m)
  1147. // return m
  1148. // }
  1149. //
  1150. // func (m *myModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  1151. // // Get the CPU architecture for the current build variant.
  1152. // variantArch := ctx.Arch()
  1153. //
  1154. // // ...
  1155. // }
  1156. type ModuleBase struct {
  1157. // Putting the curiously recurring thing pointing to the thing that contains
  1158. // the thing pattern to good use.
  1159. // TODO: remove this
  1160. module Module
  1161. nameProperties nameProperties
  1162. commonProperties commonProperties
  1163. distProperties distProperties
  1164. variableProperties interface{}
  1165. hostAndDeviceProperties hostAndDeviceProperties
  1166. // Arch specific versions of structs in GetProperties() prior to
  1167. // initialization in InitAndroidArchModule, lets call it `generalProperties`.
  1168. // The outer index has the same order as generalProperties and the inner index
  1169. // chooses the props specific to the architecture. The interface{} value is an
  1170. // archPropRoot that is filled with arch specific values by the arch mutator.
  1171. archProperties [][]interface{}
  1172. // Properties specific to the Blueprint to BUILD migration.
  1173. bazelTargetModuleProperties bazel.BazelTargetModuleProperties
  1174. // Information about all the properties on the module that contains visibility rules that need
  1175. // checking.
  1176. visibilityPropertyInfo []visibilityProperty
  1177. // The primary visibility property, may be nil, that controls access to the module.
  1178. primaryVisibilityProperty visibilityProperty
  1179. // The primary licenses property, may be nil, records license metadata for the module.
  1180. primaryLicensesProperty applicableLicensesProperty
  1181. noAddressSanitizer bool
  1182. installFiles InstallPaths
  1183. installFilesDepSet *installPathsDepSet
  1184. checkbuildFiles Paths
  1185. packagingSpecs []PackagingSpec
  1186. packagingSpecsDepSet *packagingSpecsDepSet
  1187. // katiInstalls tracks the install rules that were created by Soong but are being exported
  1188. // to Make to convert to ninja rules so that Make can add additional dependencies.
  1189. katiInstalls katiInstalls
  1190. katiSymlinks katiInstalls
  1191. // The files to copy to the dist as explicitly specified in the .bp file.
  1192. distFiles TaggedDistFiles
  1193. // Used by buildTargetSingleton to create checkbuild and per-directory build targets
  1194. // Only set on the final variant of each module
  1195. installTarget WritablePath
  1196. checkbuildTarget WritablePath
  1197. blueprintDir string
  1198. hooks hooks
  1199. registerProps []interface{}
  1200. // For tests
  1201. buildParams []BuildParams
  1202. ruleParams map[blueprint.Rule]blueprint.RuleParams
  1203. variables map[string]string
  1204. initRcPaths Paths
  1205. vintfFragmentsPaths Paths
  1206. // set of dependency module:location mappings used to populate the license metadata for
  1207. // apex containers.
  1208. licenseInstallMap []string
  1209. // The path to the generated license metadata file for the module.
  1210. licenseMetadataFile WritablePath
  1211. }
  1212. // A struct containing all relevant information about a Bazel target converted via bp2build.
  1213. type bp2buildInfo struct {
  1214. Dir string
  1215. BazelProps bazel.BazelTargetModuleProperties
  1216. CommonAttrs CommonAttributes
  1217. ConstraintAttrs constraintAttributes
  1218. Attrs interface{}
  1219. }
  1220. // TargetName returns the Bazel target name of a bp2build converted target.
  1221. func (b bp2buildInfo) TargetName() string {
  1222. return b.CommonAttrs.Name
  1223. }
  1224. // TargetPackage returns the Bazel package of a bp2build converted target.
  1225. func (b bp2buildInfo) TargetPackage() string {
  1226. return b.Dir
  1227. }
  1228. // BazelRuleClass returns the Bazel rule class of a bp2build converted target.
  1229. func (b bp2buildInfo) BazelRuleClass() string {
  1230. return b.BazelProps.Rule_class
  1231. }
  1232. // BazelRuleLoadLocation returns the location of the Bazel rule of a bp2build converted target.
  1233. // This may be empty as native Bazel rules do not need to be loaded.
  1234. func (b bp2buildInfo) BazelRuleLoadLocation() string {
  1235. return b.BazelProps.Bzl_load_location
  1236. }
  1237. // BazelAttributes returns the Bazel attributes of a bp2build converted target.
  1238. func (b bp2buildInfo) BazelAttributes() []interface{} {
  1239. return []interface{}{&b.CommonAttrs, &b.ConstraintAttrs, b.Attrs}
  1240. }
  1241. func (m *ModuleBase) addBp2buildInfo(info bp2buildInfo) {
  1242. m.commonProperties.BazelConversionStatus.Bp2buildInfo = append(m.commonProperties.BazelConversionStatus.Bp2buildInfo, info)
  1243. }
  1244. // IsConvertedByBp2build returns whether this module was converted via bp2build.
  1245. func (m *ModuleBase) IsConvertedByBp2build() bool {
  1246. return len(m.commonProperties.BazelConversionStatus.Bp2buildInfo) > 0
  1247. }
  1248. // Bp2buildTargets returns the Bazel targets bp2build generated for this module.
  1249. func (m *ModuleBase) Bp2buildTargets() []bp2buildInfo {
  1250. return m.commonProperties.BazelConversionStatus.Bp2buildInfo
  1251. }
  1252. // AddUnconvertedBp2buildDep stores module name of a dependency that was not converted to Bazel.
  1253. func (b *baseModuleContext) AddUnconvertedBp2buildDep(dep string) {
  1254. unconvertedDeps := &b.Module().base().commonProperties.BazelConversionStatus.UnconvertedDeps
  1255. *unconvertedDeps = append(*unconvertedDeps, dep)
  1256. }
  1257. // AddMissingBp2buildDep stores module name of a dependency that was not found in a Android.bp file.
  1258. func (b *baseModuleContext) AddMissingBp2buildDep(dep string) {
  1259. missingDeps := &b.Module().base().commonProperties.BazelConversionStatus.MissingDeps
  1260. *missingDeps = append(*missingDeps, dep)
  1261. }
  1262. // GetUnconvertedBp2buildDeps returns the list of module names of this module's direct dependencies that
  1263. // were not converted to Bazel.
  1264. func (m *ModuleBase) GetUnconvertedBp2buildDeps() []string {
  1265. return FirstUniqueStrings(m.commonProperties.BazelConversionStatus.UnconvertedDeps)
  1266. }
  1267. // GetMissingBp2buildDeps eturns the list of module names that were not found in Android.bp files.
  1268. func (m *ModuleBase) GetMissingBp2buildDeps() []string {
  1269. return FirstUniqueStrings(m.commonProperties.BazelConversionStatus.MissingDeps)
  1270. }
  1271. func (m *ModuleBase) AddJSONData(d *map[string]interface{}) {
  1272. (*d)["Android"] = map[string]interface{}{
  1273. // Properties set in Blueprint or in blueprint of a defaults modules
  1274. "SetProperties": m.propertiesWithValues(),
  1275. }
  1276. }
  1277. type propInfo struct {
  1278. Name string
  1279. Type string
  1280. Value string
  1281. Values []string
  1282. }
  1283. func (m *ModuleBase) propertiesWithValues() []propInfo {
  1284. var info []propInfo
  1285. props := m.GetProperties()
  1286. var propsWithValues func(name string, v reflect.Value)
  1287. propsWithValues = func(name string, v reflect.Value) {
  1288. kind := v.Kind()
  1289. switch kind {
  1290. case reflect.Ptr, reflect.Interface:
  1291. if v.IsNil() {
  1292. return
  1293. }
  1294. propsWithValues(name, v.Elem())
  1295. case reflect.Struct:
  1296. if v.IsZero() {
  1297. return
  1298. }
  1299. for i := 0; i < v.NumField(); i++ {
  1300. namePrefix := name
  1301. sTyp := v.Type().Field(i)
  1302. if proptools.ShouldSkipProperty(sTyp) {
  1303. continue
  1304. }
  1305. if name != "" && !strings.HasSuffix(namePrefix, ".") {
  1306. namePrefix += "."
  1307. }
  1308. if !proptools.IsEmbedded(sTyp) {
  1309. namePrefix += sTyp.Name
  1310. }
  1311. sVal := v.Field(i)
  1312. propsWithValues(namePrefix, sVal)
  1313. }
  1314. case reflect.Array, reflect.Slice:
  1315. if v.IsNil() {
  1316. return
  1317. }
  1318. elKind := v.Type().Elem().Kind()
  1319. info = append(info, propInfo{Name: name, Type: elKind.String() + " " + kind.String(), Values: sliceReflectionValue(v)})
  1320. default:
  1321. info = append(info, propInfo{Name: name, Type: kind.String(), Value: reflectionValue(v)})
  1322. }
  1323. }
  1324. for _, p := range props {
  1325. propsWithValues("", reflect.ValueOf(p).Elem())
  1326. }
  1327. sort.Slice(info, func(i, j int) bool {
  1328. return info[i].Name < info[j].Name
  1329. })
  1330. return info
  1331. }
  1332. func reflectionValue(value reflect.Value) string {
  1333. switch value.Kind() {
  1334. case reflect.Bool:
  1335. return fmt.Sprintf("%t", value.Bool())
  1336. case reflect.Int64:
  1337. return fmt.Sprintf("%d", value.Int())
  1338. case reflect.String:
  1339. return fmt.Sprintf("%s", value.String())
  1340. case reflect.Struct:
  1341. if value.IsZero() {
  1342. return "{}"
  1343. }
  1344. length := value.NumField()
  1345. vals := make([]string, length, length)
  1346. for i := 0; i < length; i++ {
  1347. sTyp := value.Type().Field(i)
  1348. if proptools.ShouldSkipProperty(sTyp) {
  1349. continue
  1350. }
  1351. name := sTyp.Name
  1352. vals[i] = fmt.Sprintf("%s: %s", name, reflectionValue(value.Field(i)))
  1353. }
  1354. return fmt.Sprintf("%s{%s}", value.Type(), strings.Join(vals, ", "))
  1355. case reflect.Array, reflect.Slice:
  1356. vals := sliceReflectionValue(value)
  1357. return fmt.Sprintf("[%s]", strings.Join(vals, ", "))
  1358. }
  1359. return ""
  1360. }
  1361. func sliceReflectionValue(value reflect.Value) []string {
  1362. length := value.Len()
  1363. vals := make([]string, length, length)
  1364. for i := 0; i < length; i++ {
  1365. vals[i] = reflectionValue(value.Index(i))
  1366. }
  1367. return vals
  1368. }
  1369. func (m *ModuleBase) ComponentDepsMutator(BottomUpMutatorContext) {}
  1370. func (m *ModuleBase) DepsMutator(BottomUpMutatorContext) {}
  1371. // AddProperties "registers" the provided props
  1372. // each value in props MUST be a pointer to a struct
  1373. func (m *ModuleBase) AddProperties(props ...interface{}) {
  1374. m.registerProps = append(m.registerProps, props...)
  1375. }
  1376. func (m *ModuleBase) GetProperties() []interface{} {
  1377. return m.registerProps
  1378. }
  1379. func (m *ModuleBase) BuildParamsForTests() []BuildParams {
  1380. // Expand the references to module variables like $flags[0-9]*,
  1381. // so we do not need to change many existing unit tests.
  1382. // This looks like undoing the shareFlags optimization in cc's
  1383. // transformSourceToObj, and should only affects unit tests.
  1384. vars := m.VariablesForTests()
  1385. buildParams := append([]BuildParams(nil), m.buildParams...)
  1386. for i := range buildParams {
  1387. newArgs := make(map[string]string)
  1388. for k, v := range buildParams[i].Args {
  1389. newArgs[k] = v
  1390. // Replaces both ${flags1} and $flags1 syntax.
  1391. if strings.HasPrefix(v, "${") && strings.HasSuffix(v, "}") {
  1392. if value, found := vars[v[2:len(v)-1]]; found {
  1393. newArgs[k] = value
  1394. }
  1395. } else if strings.HasPrefix(v, "$") {
  1396. if value, found := vars[v[1:]]; found {
  1397. newArgs[k] = value
  1398. }
  1399. }
  1400. }
  1401. buildParams[i].Args = newArgs
  1402. }
  1403. return buildParams
  1404. }
  1405. func (m *ModuleBase) RuleParamsForTests() map[blueprint.Rule]blueprint.RuleParams {
  1406. return m.ruleParams
  1407. }
  1408. func (m *ModuleBase) VariablesForTests() map[string]string {
  1409. return m.variables
  1410. }
  1411. // Name returns the name of the module. It may be overridden by individual module types, for
  1412. // example prebuilts will prepend prebuilt_ to the name.
  1413. func (m *ModuleBase) Name() string {
  1414. return String(m.nameProperties.Name)
  1415. }
  1416. // String returns a string that includes the module name and variants for printing during debugging.
  1417. func (m *ModuleBase) String() string {
  1418. sb := strings.Builder{}
  1419. sb.WriteString(m.commonProperties.DebugName)
  1420. sb.WriteString("{")
  1421. for i := range m.commonProperties.DebugMutators {
  1422. if i != 0 {
  1423. sb.WriteString(",")
  1424. }
  1425. sb.WriteString(m.commonProperties.DebugMutators[i])
  1426. sb.WriteString(":")
  1427. sb.WriteString(m.commonProperties.DebugVariations[i])
  1428. }
  1429. sb.WriteString("}")
  1430. return sb.String()
  1431. }
  1432. // BaseModuleName returns the name of the module as specified in the blueprints file.
  1433. func (m *ModuleBase) BaseModuleName() string {
  1434. return String(m.nameProperties.Name)
  1435. }
  1436. func (m *ModuleBase) base() *ModuleBase {
  1437. return m
  1438. }
  1439. func (m *ModuleBase) qualifiedModuleId(ctx BaseModuleContext) qualifiedModuleName {
  1440. return qualifiedModuleName{pkg: ctx.ModuleDir(), name: ctx.ModuleName()}
  1441. }
  1442. func (m *ModuleBase) visibilityProperties() []visibilityProperty {
  1443. return m.visibilityPropertyInfo
  1444. }
  1445. func (m *ModuleBase) Dists() []Dist {
  1446. if len(m.distProperties.Dist.Targets) > 0 {
  1447. // Make a copy of the underlying Dists slice to protect against
  1448. // backing array modifications with repeated calls to this method.
  1449. distsCopy := append([]Dist(nil), m.distProperties.Dists...)
  1450. return append(distsCopy, m.distProperties.Dist)
  1451. } else {
  1452. return m.distProperties.Dists
  1453. }
  1454. }
  1455. func (m *ModuleBase) GenerateTaggedDistFiles(ctx BaseModuleContext) TaggedDistFiles {
  1456. var distFiles TaggedDistFiles
  1457. for _, dist := range m.Dists() {
  1458. // If no tag is specified then it means to use the default dist paths so use
  1459. // the special tag name which represents that.
  1460. tag := proptools.StringDefault(dist.Tag, DefaultDistTag)
  1461. if outputFileProducer, ok := m.module.(OutputFileProducer); ok {
  1462. // Call the OutputFiles(tag) method to get the paths associated with the tag.
  1463. distFilesForTag, err := outputFileProducer.OutputFiles(tag)
  1464. // If the tag was not supported and is not DefaultDistTag then it is an error.
  1465. // Failing to find paths for DefaultDistTag is not an error. It just means
  1466. // that the module type requires the legacy behavior.
  1467. if err != nil && tag != DefaultDistTag {
  1468. ctx.PropertyErrorf("dist.tag", "%s", err.Error())
  1469. }
  1470. distFiles = distFiles.addPathsForTag(tag, distFilesForTag...)
  1471. } else if tag != DefaultDistTag {
  1472. // If the tag was specified then it is an error if the module does not
  1473. // implement OutputFileProducer because there is no other way of accessing
  1474. // the paths for the specified tag.
  1475. ctx.PropertyErrorf("dist.tag",
  1476. "tag %s not supported because the module does not implement OutputFileProducer", tag)
  1477. }
  1478. }
  1479. return distFiles
  1480. }
  1481. func (m *ModuleBase) Target() Target {
  1482. return m.commonProperties.CompileTarget
  1483. }
  1484. func (m *ModuleBase) TargetPrimary() bool {
  1485. return m.commonProperties.CompilePrimary
  1486. }
  1487. func (m *ModuleBase) MultiTargets() []Target {
  1488. return m.commonProperties.CompileMultiTargets
  1489. }
  1490. func (m *ModuleBase) Os() OsType {
  1491. return m.Target().Os
  1492. }
  1493. func (m *ModuleBase) Host() bool {
  1494. return m.Os().Class == Host
  1495. }
  1496. func (m *ModuleBase) Device() bool {
  1497. return m.Os().Class == Device
  1498. }
  1499. func (m *ModuleBase) Arch() Arch {
  1500. return m.Target().Arch
  1501. }
  1502. func (m *ModuleBase) ArchSpecific() bool {
  1503. return m.commonProperties.ArchSpecific
  1504. }
  1505. // True if the current variant is a CommonOS variant, false otherwise.
  1506. func (m *ModuleBase) IsCommonOSVariant() bool {
  1507. return m.commonProperties.CommonOSVariant
  1508. }
  1509. // supportsTarget returns true if the given Target is supported by the current module.
  1510. func (m *ModuleBase) supportsTarget(target Target) bool {
  1511. switch target.Os.Class {
  1512. case Host:
  1513. if target.HostCross {
  1514. return m.HostCrossSupported()
  1515. } else {
  1516. return m.HostSupported()
  1517. }
  1518. case Device:
  1519. return m.DeviceSupported()
  1520. default:
  1521. return false
  1522. }
  1523. }
  1524. // DeviceSupported returns true if the current module is supported and enabled for device targets,
  1525. // i.e. the factory method set the HostOrDeviceSupported value to include device support and
  1526. // the device support is enabled by default or enabled by the device_supported property.
  1527. func (m *ModuleBase) DeviceSupported() bool {
  1528. hod := m.commonProperties.HostOrDeviceSupported
  1529. // deviceEnabled is true if the device_supported property is true or the HostOrDeviceSupported
  1530. // value has the deviceDefault bit set.
  1531. deviceEnabled := proptools.BoolDefault(m.hostAndDeviceProperties.Device_supported, hod&deviceDefault != 0)
  1532. return hod&deviceSupported != 0 && deviceEnabled
  1533. }
  1534. // HostSupported returns true if the current module is supported and enabled for host targets,
  1535. // i.e. the factory method set the HostOrDeviceSupported value to include host support and
  1536. // the host support is enabled by default or enabled by the host_supported property.
  1537. func (m *ModuleBase) HostSupported() bool {
  1538. hod := m.commonProperties.HostOrDeviceSupported
  1539. // hostEnabled is true if the host_supported property is true or the HostOrDeviceSupported
  1540. // value has the hostDefault bit set.
  1541. hostEnabled := proptools.BoolDefault(m.hostAndDeviceProperties.Host_supported, hod&hostDefault != 0)
  1542. return hod&hostSupported != 0 && hostEnabled
  1543. }
  1544. // HostCrossSupported returns true if the current module is supported and enabled for host cross
  1545. // targets, i.e. the factory method set the HostOrDeviceSupported value to include host cross
  1546. // support and the host cross support is enabled by default or enabled by the
  1547. // host_supported property.
  1548. func (m *ModuleBase) HostCrossSupported() bool {
  1549. hod := m.commonProperties.HostOrDeviceSupported
  1550. // hostEnabled is true if the host_supported property is true or the HostOrDeviceSupported
  1551. // value has the hostDefault bit set.
  1552. hostEnabled := proptools.BoolDefault(m.hostAndDeviceProperties.Host_supported, hod&hostDefault != 0)
  1553. return hod&hostCrossSupported != 0 && hostEnabled
  1554. }
  1555. func (m *ModuleBase) Platform() bool {
  1556. return !m.DeviceSpecific() && !m.SocSpecific() && !m.ProductSpecific() && !m.SystemExtSpecific()
  1557. }
  1558. func (m *ModuleBase) DeviceSpecific() bool {
  1559. return Bool(m.commonProperties.Device_specific)
  1560. }
  1561. func (m *ModuleBase) SocSpecific() bool {
  1562. return Bool(m.commonProperties.Vendor) || Bool(m.commonProperties.Proprietary) || Bool(m.commonProperties.Soc_specific)
  1563. }
  1564. func (m *ModuleBase) ProductSpecific() bool {
  1565. return Bool(m.commonProperties.Product_specific)
  1566. }
  1567. func (m *ModuleBase) SystemExtSpecific() bool {
  1568. return Bool(m.commonProperties.System_ext_specific)
  1569. }
  1570. // RequiresStableAPIs returns true if the module will be installed to a partition that may
  1571. // be updated separately from the system image.
  1572. func (m *ModuleBase) RequiresStableAPIs(ctx BaseModuleContext) bool {
  1573. return m.SocSpecific() || m.DeviceSpecific() ||
  1574. (m.ProductSpecific() && ctx.Config().EnforceProductPartitionInterface())
  1575. }
  1576. func (m *ModuleBase) PartitionTag(config DeviceConfig) string {
  1577. partition := "system"
  1578. if m.SocSpecific() {
  1579. // A SoC-specific module could be on the vendor partition at
  1580. // "vendor" or the system partition at "system/vendor".
  1581. if config.VendorPath() == "vendor" {
  1582. partition = "vendor"
  1583. }
  1584. } else if m.DeviceSpecific() {
  1585. // A device-specific module could be on the odm partition at
  1586. // "odm", the vendor partition at "vendor/odm", or the system
  1587. // partition at "system/vendor/odm".
  1588. if config.OdmPath() == "odm" {
  1589. partition = "odm"
  1590. } else if strings.HasPrefix(config.OdmPath(), "vendor/") {
  1591. partition = "vendor"
  1592. }
  1593. } else if m.ProductSpecific() {
  1594. // A product-specific module could be on the product partition
  1595. // at "product" or the system partition at "system/product".
  1596. if config.ProductPath() == "product" {
  1597. partition = "product"
  1598. }
  1599. } else if m.SystemExtSpecific() {
  1600. // A system_ext-specific module could be on the system_ext
  1601. // partition at "system_ext" or the system partition at
  1602. // "system/system_ext".
  1603. if config.SystemExtPath() == "system_ext" {
  1604. partition = "system_ext"
  1605. }
  1606. }
  1607. return partition
  1608. }
  1609. func (m *ModuleBase) Enabled() bool {
  1610. if m.commonProperties.ForcedDisabled {
  1611. return false
  1612. }
  1613. if m.commonProperties.Enabled == nil {
  1614. return !m.Os().DefaultDisabled
  1615. }
  1616. return *m.commonProperties.Enabled
  1617. }
  1618. func (m *ModuleBase) Disable() {
  1619. m.commonProperties.ForcedDisabled = true
  1620. }
  1621. // HideFromMake marks this variant so that it is not emitted in the generated Android.mk file.
  1622. func (m *ModuleBase) HideFromMake() {
  1623. m.commonProperties.HideFromMake = true
  1624. }
  1625. // IsHideFromMake returns true if HideFromMake was previously called.
  1626. func (m *ModuleBase) IsHideFromMake() bool {
  1627. return m.commonProperties.HideFromMake == true
  1628. }
  1629. // SkipInstall marks this variant to not create install rules when ctx.Install* are called.
  1630. func (m *ModuleBase) SkipInstall() {
  1631. m.commonProperties.SkipInstall = true
  1632. }
  1633. // IsSkipInstall returns true if this variant is marked to not create install
  1634. // rules when ctx.Install* are called.
  1635. func (m *ModuleBase) IsSkipInstall() bool {
  1636. return m.commonProperties.SkipInstall
  1637. }
  1638. // Similar to HideFromMake, but if the AndroidMk entry would set
  1639. // LOCAL_UNINSTALLABLE_MODULE then this variant may still output that entry
  1640. // rather than leaving it out altogether. That happens in cases where it would
  1641. // have other side effects, in particular when it adds a NOTICE file target,
  1642. // which other install targets might depend on.
  1643. func (m *ModuleBase) MakeUninstallable() {
  1644. m.HideFromMake()
  1645. }
  1646. func (m *ModuleBase) ReplacedByPrebuilt() {
  1647. m.commonProperties.ReplacedByPrebuilt = true
  1648. m.HideFromMake()
  1649. }
  1650. func (m *ModuleBase) IsReplacedByPrebuilt() bool {
  1651. return m.commonProperties.ReplacedByPrebuilt
  1652. }
  1653. func (m *ModuleBase) ExportedToMake() bool {
  1654. return m.commonProperties.NamespaceExportedToMake
  1655. }
  1656. func (m *ModuleBase) EffectiveLicenseFiles() Paths {
  1657. result := make(Paths, 0, len(m.commonProperties.Effective_license_text))
  1658. for _, p := range m.commonProperties.Effective_license_text {
  1659. result = append(result, p.Path)
  1660. }
  1661. return result
  1662. }
  1663. // computeInstallDeps finds the installed paths of all dependencies that have a dependency
  1664. // tag that is annotated as needing installation via the IsInstallDepNeeded method.
  1665. func (m *ModuleBase) computeInstallDeps(ctx ModuleContext) ([]*installPathsDepSet, []*packagingSpecsDepSet) {
  1666. var installDeps []*installPathsDepSet
  1667. var packagingSpecs []*packagingSpecsDepSet
  1668. ctx.VisitDirectDeps(func(dep Module) {
  1669. if IsInstallDepNeeded(ctx.OtherModuleDependencyTag(dep)) && !dep.IsHideFromMake() && !dep.IsSkipInstall() {
  1670. installDeps = append(installDeps, dep.base().installFilesDepSet)
  1671. packagingSpecs = append(packagingSpecs, dep.base().packagingSpecsDepSet)
  1672. }
  1673. })
  1674. return installDeps, packagingSpecs
  1675. }
  1676. func (m *ModuleBase) FilesToInstall() InstallPaths {
  1677. return m.installFiles
  1678. }
  1679. func (m *ModuleBase) PackagingSpecs() []PackagingSpec {
  1680. return m.packagingSpecs
  1681. }
  1682. func (m *ModuleBase) TransitivePackagingSpecs() []PackagingSpec {
  1683. return m.packagingSpecsDepSet.ToList()
  1684. }
  1685. func (m *ModuleBase) NoAddressSanitizer() bool {
  1686. return m.noAddressSanitizer
  1687. }
  1688. func (m *ModuleBase) InstallInData() bool {
  1689. return false
  1690. }
  1691. func (m *ModuleBase) InstallInTestcases() bool {
  1692. return false
  1693. }
  1694. func (m *ModuleBase) InstallInSanitizerDir() bool {
  1695. return false
  1696. }
  1697. func (m *ModuleBase) InstallInRamdisk() bool {
  1698. return Bool(m.commonProperties.Ramdisk)
  1699. }
  1700. func (m *ModuleBase) InstallInVendorRamdisk() bool {
  1701. return Bool(m.commonProperties.Vendor_ramdisk)
  1702. }
  1703. func (m *ModuleBase) InstallInDebugRamdisk() bool {
  1704. return Bool(m.commonProperties.Debug_ramdisk)
  1705. }
  1706. func (m *ModuleBase) InstallInRecovery() bool {
  1707. return Bool(m.commonProperties.Recovery)
  1708. }
  1709. func (m *ModuleBase) InstallInVendor() bool {
  1710. return Bool(m.commonProperties.Vendor)
  1711. }
  1712. func (m *ModuleBase) InstallInRoot() bool {
  1713. return false
  1714. }
  1715. func (m *ModuleBase) InstallForceOS() (*OsType, *ArchType) {
  1716. return nil, nil
  1717. }
  1718. func (m *ModuleBase) Owner() string {
  1719. return String(m.commonProperties.Owner)
  1720. }
  1721. func (m *ModuleBase) setImageVariation(variant string) {
  1722. m.commonProperties.ImageVariation = variant
  1723. }
  1724. func (m *ModuleBase) ImageVariation() blueprint.Variation {
  1725. return blueprint.Variation{
  1726. Mutator: "image",
  1727. Variation: m.base().commonProperties.ImageVariation,
  1728. }
  1729. }
  1730. func (m *ModuleBase) getVariationByMutatorName(mutator string) string {
  1731. for i, v := range m.commonProperties.DebugMutators {
  1732. if v == mutator {
  1733. return m.commonProperties.DebugVariations[i]
  1734. }
  1735. }
  1736. return ""
  1737. }
  1738. func (m *ModuleBase) InRamdisk() bool {
  1739. return m.base().commonProperties.ImageVariation == RamdiskVariation
  1740. }
  1741. func (m *ModuleBase) InVendorRamdisk() bool {
  1742. return m.base().commonProperties.ImageVariation == VendorRamdiskVariation
  1743. }
  1744. func (m *ModuleBase) InDebugRamdisk() bool {
  1745. return m.base().commonProperties.ImageVariation == DebugRamdiskVariation
  1746. }
  1747. func (m *ModuleBase) InRecovery() bool {
  1748. return m.base().commonProperties.ImageVariation == RecoveryVariation
  1749. }
  1750. func (m *ModuleBase) RequiredModuleNames() []string {
  1751. return m.base().commonProperties.Required
  1752. }
  1753. func (m *ModuleBase) HostRequiredModuleNames() []string {
  1754. return m.base().commonProperties.Host_required
  1755. }
  1756. func (m *ModuleBase) TargetRequiredModuleNames() []string {
  1757. return m.base().commonProperties.Target_required
  1758. }
  1759. func (m *ModuleBase) InitRc() Paths {
  1760. return append(Paths{}, m.initRcPaths...)
  1761. }
  1762. func (m *ModuleBase) VintfFragments() Paths {
  1763. return append(Paths{}, m.vintfFragmentsPaths...)
  1764. }
  1765. func (m *ModuleBase) CompileMultilib() *string {
  1766. return m.base().commonProperties.Compile_multilib
  1767. }
  1768. // SetLicenseInstallMap stores the set of dependency module:location mappings for files in an
  1769. // apex container for use when generation the license metadata file.
  1770. func (m *ModuleBase) SetLicenseInstallMap(installMap []string) {
  1771. m.licenseInstallMap = append(m.licenseInstallMap, installMap...)
  1772. }
  1773. func (m *ModuleBase) generateModuleTarget(ctx ModuleContext) {
  1774. var allInstalledFiles InstallPaths
  1775. var allCheckbuildFiles Paths
  1776. ctx.VisitAllModuleVariants(func(module Module) {
  1777. a := module.base()
  1778. allInstalledFiles = append(allInstalledFiles, a.installFiles...)
  1779. // A module's -checkbuild phony targets should
  1780. // not be created if the module is not exported to make.
  1781. // Those could depend on the build target and fail to compile
  1782. // for the current build target.
  1783. if !ctx.Config().KatiEnabled() || !shouldSkipAndroidMkProcessing(a) {
  1784. allCheckbuildFiles = append(allCheckbuildFiles, a.checkbuildFiles...)
  1785. }
  1786. })
  1787. var deps Paths
  1788. namespacePrefix := ctx.Namespace().id
  1789. if namespacePrefix != "" {
  1790. namespacePrefix = namespacePrefix + "-"
  1791. }
  1792. if len(allInstalledFiles) > 0 {
  1793. name := namespacePrefix + ctx.ModuleName() + "-install"
  1794. ctx.Phony(name, allInstalledFiles.Paths()...)
  1795. m.installTarget = PathForPhony(ctx, name)
  1796. deps = append(deps, m.installTarget)
  1797. }
  1798. if len(allCheckbuildFiles) > 0 {
  1799. name := namespacePrefix + ctx.ModuleName() + "-checkbuild"
  1800. ctx.Phony(name, allCheckbuildFiles...)
  1801. m.checkbuildTarget = PathForPhony(ctx, name)
  1802. deps = append(deps, m.checkbuildTarget)
  1803. }
  1804. if len(deps) > 0 {
  1805. suffix := ""
  1806. if ctx.Config().KatiEnabled() {
  1807. suffix = "-soong"
  1808. }
  1809. ctx.Phony(namespacePrefix+ctx.ModuleName()+suffix, deps...)
  1810. m.blueprintDir = ctx.ModuleDir()
  1811. }
  1812. }
  1813. func determineModuleKind(m *ModuleBase, ctx blueprint.EarlyModuleContext) moduleKind {
  1814. var socSpecific = Bool(m.commonProperties.Vendor) || Bool(m.commonProperties.Proprietary) || Bool(m.commonProperties.Soc_specific)
  1815. var deviceSpecific = Bool(m.commonProperties.Device_specific)
  1816. var productSpecific = Bool(m.commonProperties.Product_specific)
  1817. var systemExtSpecific = Bool(m.commonProperties.System_ext_specific)
  1818. msg := "conflicting value set here"
  1819. if socSpecific && deviceSpecific {
  1820. ctx.PropertyErrorf("device_specific", "a module cannot be specific to SoC and device at the same time.")
  1821. if Bool(m.commonProperties.Vendor) {
  1822. ctx.PropertyErrorf("vendor", msg)
  1823. }
  1824. if Bool(m.commonProperties.Proprietary) {
  1825. ctx.PropertyErrorf("proprietary", msg)
  1826. }
  1827. if Bool(m.commonProperties.Soc_specific) {
  1828. ctx.PropertyErrorf("soc_specific", msg)
  1829. }
  1830. }
  1831. if productSpecific && systemExtSpecific {
  1832. ctx.PropertyErrorf("product_specific", "a module cannot be specific to product and system_ext at the same time.")
  1833. ctx.PropertyErrorf("system_ext_specific", msg)
  1834. }
  1835. if (socSpecific || deviceSpecific) && (productSpecific || systemExtSpecific) {
  1836. if productSpecific {
  1837. ctx.PropertyErrorf("product_specific", "a module cannot be specific to SoC or device and product at the same time.")
  1838. } else {
  1839. ctx.PropertyErrorf("system_ext_specific", "a module cannot be specific to SoC or device and system_ext at the same time.")
  1840. }
  1841. if deviceSpecific {
  1842. ctx.PropertyErrorf("device_specific", msg)
  1843. } else {
  1844. if Bool(m.commonProperties.Vendor) {
  1845. ctx.PropertyErrorf("vendor", msg)
  1846. }
  1847. if Bool(m.commonProperties.Proprietary) {
  1848. ctx.PropertyErrorf("proprietary", msg)
  1849. }
  1850. if Bool(m.commonProperties.Soc_specific) {
  1851. ctx.PropertyErrorf("soc_specific", msg)
  1852. }
  1853. }
  1854. }
  1855. if productSpecific {
  1856. return productSpecificModule
  1857. } else if systemExtSpecific {
  1858. return systemExtSpecificModule
  1859. } else if deviceSpecific {
  1860. return deviceSpecificModule
  1861. } else if socSpecific {
  1862. return socSpecificModule
  1863. } else {
  1864. return platformModule
  1865. }
  1866. }
  1867. func (m *ModuleBase) earlyModuleContextFactory(ctx blueprint.EarlyModuleContext) earlyModuleContext {
  1868. return earlyModuleContext{
  1869. EarlyModuleContext: ctx,
  1870. kind: determineModuleKind(m, ctx),
  1871. config: ctx.Config().(Config),
  1872. }
  1873. }
  1874. func (m *ModuleBase) baseModuleContextFactory(ctx blueprint.BaseModuleContext) baseModuleContext {
  1875. return baseModuleContext{
  1876. bp: ctx,
  1877. earlyModuleContext: m.earlyModuleContextFactory(ctx),
  1878. os: m.commonProperties.CompileOS,
  1879. target: m.commonProperties.CompileTarget,
  1880. targetPrimary: m.commonProperties.CompilePrimary,
  1881. multiTargets: m.commonProperties.CompileMultiTargets,
  1882. }
  1883. }
  1884. func (m *ModuleBase) GenerateBuildActions(blueprintCtx blueprint.ModuleContext) {
  1885. ctx := &moduleContext{
  1886. module: m.module,
  1887. bp: blueprintCtx,
  1888. baseModuleContext: m.baseModuleContextFactory(blueprintCtx),
  1889. variables: make(map[string]string),
  1890. }
  1891. m.licenseMetadataFile = PathForModuleOut(ctx, "meta_lic")
  1892. dependencyInstallFiles, dependencyPackagingSpecs := m.computeInstallDeps(ctx)
  1893. // set m.installFilesDepSet to only the transitive dependencies to be used as the dependencies
  1894. // of installed files of this module. It will be replaced by a depset including the installed
  1895. // files of this module at the end for use by modules that depend on this one.
  1896. m.installFilesDepSet = newInstallPathsDepSet(nil, dependencyInstallFiles)
  1897. // Temporarily continue to call blueprintCtx.GetMissingDependencies() to maintain the previous behavior of never
  1898. // reporting missing dependency errors in Blueprint when AllowMissingDependencies == true.
  1899. // TODO: This will be removed once defaults modules handle missing dependency errors
  1900. blueprintCtx.GetMissingDependencies()
  1901. // For the final GenerateAndroidBuildActions pass, require that all visited dependencies Soong modules and
  1902. // are enabled. Unless the module is a CommonOS variant which may have dependencies on disabled variants
  1903. // (because the dependencies are added before the modules are disabled). The
  1904. // GetOsSpecificVariantsOfCommonOSVariant(...) method will ensure that the disabled variants are
  1905. // ignored.
  1906. ctx.baseModuleContext.strictVisitDeps = !m.IsCommonOSVariant()
  1907. if ctx.config.captureBuild {
  1908. ctx.ruleParams = make(map[blueprint.Rule]blueprint.RuleParams)
  1909. }
  1910. desc := "//" + ctx.ModuleDir() + ":" + ctx.ModuleName() + " "
  1911. var suffix []string
  1912. if ctx.Os().Class != Device && ctx.Os().Class != Generic {
  1913. suffix = append(suffix, ctx.Os().String())
  1914. }
  1915. if !ctx.PrimaryArch() {
  1916. suffix = append(suffix, ctx.Arch().ArchType.String())
  1917. }
  1918. if apexInfo := ctx.Provider(ApexInfoProvider).(ApexInfo); !apexInfo.IsForPlatform() {
  1919. suffix = append(suffix, apexInfo.ApexVariationName)
  1920. }
  1921. ctx.Variable(pctx, "moduleDesc", desc)
  1922. s := ""
  1923. if len(suffix) > 0 {
  1924. s = " [" + strings.Join(suffix, " ") + "]"
  1925. }
  1926. ctx.Variable(pctx, "moduleDescSuffix", s)
  1927. // Some common property checks for properties that will be used later in androidmk.go
  1928. checkDistProperties(ctx, "dist", &m.distProperties.Dist)
  1929. for i := range m.distProperties.Dists {
  1930. checkDistProperties(ctx, fmt.Sprintf("dists[%d]", i), &m.distProperties.Dists[i])
  1931. }
  1932. if m.Enabled() {
  1933. // ensure all direct android.Module deps are enabled
  1934. ctx.VisitDirectDepsBlueprint(func(bm blueprint.Module) {
  1935. if m, ok := bm.(Module); ok {
  1936. ctx.validateAndroidModule(bm, ctx.OtherModuleDependencyTag(m), ctx.baseModuleContext.strictVisitDeps)
  1937. }
  1938. })
  1939. licensesPropertyFlattener(ctx)
  1940. if ctx.Failed() {
  1941. return
  1942. }
  1943. if mixedBuildMod, handled := m.isHandledByBazel(ctx); handled {
  1944. mixedBuildMod.ProcessBazelQueryResponse(ctx)
  1945. } else {
  1946. m.module.GenerateAndroidBuildActions(ctx)
  1947. }
  1948. if ctx.Failed() {
  1949. return
  1950. }
  1951. m.initRcPaths = PathsForModuleSrc(ctx, m.commonProperties.Init_rc)
  1952. rcDir := PathForModuleInstall(ctx, "etc", "init")
  1953. for _, src := range m.initRcPaths {
  1954. ctx.PackageFile(rcDir, filepath.Base(src.String()), src)
  1955. }
  1956. m.vintfFragmentsPaths = PathsForModuleSrc(ctx, m.commonProperties.Vintf_fragments)
  1957. vintfDir := PathForModuleInstall(ctx, "etc", "vintf", "manifest")
  1958. for _, src := range m.vintfFragmentsPaths {
  1959. ctx.PackageFile(vintfDir, filepath.Base(src.String()), src)
  1960. }
  1961. // Create the set of tagged dist files after calling GenerateAndroidBuildActions
  1962. // as GenerateTaggedDistFiles() calls OutputFiles(tag) and so relies on the
  1963. // output paths being set which must be done before or during
  1964. // GenerateAndroidBuildActions.
  1965. m.distFiles = m.GenerateTaggedDistFiles(ctx)
  1966. if ctx.Failed() {
  1967. return
  1968. }
  1969. m.installFiles = append(m.installFiles, ctx.installFiles...)
  1970. m.checkbuildFiles = append(m.checkbuildFiles, ctx.checkbuildFiles...)
  1971. m.packagingSpecs = append(m.packagingSpecs, ctx.packagingSpecs...)
  1972. m.katiInstalls = append(m.katiInstalls, ctx.katiInstalls...)
  1973. m.katiSymlinks = append(m.katiSymlinks, ctx.katiSymlinks...)
  1974. } else if ctx.Config().AllowMissingDependencies() {
  1975. // If the module is not enabled it will not create any build rules, nothing will call
  1976. // ctx.GetMissingDependencies(), and blueprint will consider the missing dependencies to be unhandled
  1977. // and report them as an error even when AllowMissingDependencies = true. Call
  1978. // ctx.GetMissingDependencies() here to tell blueprint not to handle them.
  1979. ctx.GetMissingDependencies()
  1980. }
  1981. if m == ctx.FinalModule().(Module).base() {
  1982. m.generateModuleTarget(ctx)
  1983. if ctx.Failed() {
  1984. return
  1985. }
  1986. }
  1987. m.installFilesDepSet = newInstallPathsDepSet(m.installFiles, dependencyInstallFiles)
  1988. m.packagingSpecsDepSet = newPackagingSpecsDepSet(m.packagingSpecs, dependencyPackagingSpecs)
  1989. buildLicenseMetadata(ctx, m.licenseMetadataFile)
  1990. m.buildParams = ctx.buildParams
  1991. m.ruleParams = ctx.ruleParams
  1992. m.variables = ctx.variables
  1993. }
  1994. func (m *ModuleBase) isHandledByBazel(ctx ModuleContext) (MixedBuildBuildable, bool) {
  1995. if !ctx.Config().BazelContext.BazelEnabled() {
  1996. return nil, false
  1997. }
  1998. if mixedBuildMod, ok := m.module.(MixedBuildBuildable); ok {
  1999. if mixedBuildMod.IsMixedBuildSupported(ctx) && MixedBuildsEnabled(ctx) {
  2000. return mixedBuildMod, true
  2001. }
  2002. }
  2003. return nil, false
  2004. }
  2005. // Check the supplied dist structure to make sure that it is valid.
  2006. //
  2007. // property - the base property, e.g. dist or dists[1], which is combined with the
  2008. // name of the nested property to produce the full property, e.g. dist.dest or
  2009. // dists[1].dir.
  2010. func checkDistProperties(ctx *moduleContext, property string, dist *Dist) {
  2011. if dist.Dest != nil {
  2012. _, err := validateSafePath(*dist.Dest)
  2013. if err != nil {
  2014. ctx.PropertyErrorf(property+".dest", "%s", err.Error())
  2015. }
  2016. }
  2017. if dist.Dir != nil {
  2018. _, err := validateSafePath(*dist.Dir)
  2019. if err != nil {
  2020. ctx.PropertyErrorf(property+".dir", "%s", err.Error())
  2021. }
  2022. }
  2023. if dist.Suffix != nil {
  2024. if strings.Contains(*dist.Suffix, "/") {
  2025. ctx.PropertyErrorf(property+".suffix", "Suffix may not contain a '/' character.")
  2026. }
  2027. }
  2028. }
  2029. type earlyModuleContext struct {
  2030. blueprint.EarlyModuleContext
  2031. kind moduleKind
  2032. config Config
  2033. }
  2034. func (e *earlyModuleContext) Glob(globPattern string, excludes []string) Paths {
  2035. return Glob(e, globPattern, excludes)
  2036. }
  2037. func (e *earlyModuleContext) GlobFiles(globPattern string, excludes []string) Paths {
  2038. return GlobFiles(e, globPattern, excludes)
  2039. }
  2040. func (e *earlyModuleContext) IsSymlink(path Path) bool {
  2041. fileInfo, err := e.config.fs.Lstat(path.String())
  2042. if err != nil {
  2043. e.ModuleErrorf("os.Lstat(%q) failed: %s", path.String(), err)
  2044. }
  2045. return fileInfo.Mode()&os.ModeSymlink == os.ModeSymlink
  2046. }
  2047. func (e *earlyModuleContext) Readlink(path Path) string {
  2048. dest, err := e.config.fs.Readlink(path.String())
  2049. if err != nil {
  2050. e.ModuleErrorf("os.Readlink(%q) failed: %s", path.String(), err)
  2051. }
  2052. return dest
  2053. }
  2054. func (e *earlyModuleContext) Module() Module {
  2055. module, _ := e.EarlyModuleContext.Module().(Module)
  2056. return module
  2057. }
  2058. func (e *earlyModuleContext) Config() Config {
  2059. return e.EarlyModuleContext.Config().(Config)
  2060. }
  2061. func (e *earlyModuleContext) AConfig() Config {
  2062. return e.config
  2063. }
  2064. func (e *earlyModuleContext) DeviceConfig() DeviceConfig {
  2065. return DeviceConfig{e.config.deviceConfig}
  2066. }
  2067. func (e *earlyModuleContext) Platform() bool {
  2068. return e.kind == platformModule
  2069. }
  2070. func (e *earlyModuleContext) DeviceSpecific() bool {
  2071. return e.kind == deviceSpecificModule
  2072. }
  2073. func (e *earlyModuleContext) SocSpecific() bool {
  2074. return e.kind == socSpecificModule
  2075. }
  2076. func (e *earlyModuleContext) ProductSpecific() bool {
  2077. return e.kind == productSpecificModule
  2078. }
  2079. func (e *earlyModuleContext) SystemExtSpecific() bool {
  2080. return e.kind == systemExtSpecificModule
  2081. }
  2082. func (e *earlyModuleContext) Namespace() *Namespace {
  2083. return e.EarlyModuleContext.Namespace().(*Namespace)
  2084. }
  2085. type baseModuleContext struct {
  2086. bp blueprint.BaseModuleContext
  2087. earlyModuleContext
  2088. os OsType
  2089. target Target
  2090. multiTargets []Target
  2091. targetPrimary bool
  2092. debug bool
  2093. walkPath []Module
  2094. tagPath []blueprint.DependencyTag
  2095. strictVisitDeps bool // If true, enforce that all dependencies are enabled
  2096. bazelConversionMode bool
  2097. }
  2098. func (b *baseModuleContext) isBazelConversionMode() bool {
  2099. return b.bazelConversionMode
  2100. }
  2101. func (b *baseModuleContext) OtherModuleName(m blueprint.Module) string {
  2102. return b.bp.OtherModuleName(m)
  2103. }
  2104. func (b *baseModuleContext) OtherModuleDir(m blueprint.Module) string { return b.bp.OtherModuleDir(m) }
  2105. func (b *baseModuleContext) OtherModuleErrorf(m blueprint.Module, fmt string, args ...interface{}) {
  2106. b.bp.OtherModuleErrorf(m, fmt, args...)
  2107. }
  2108. func (b *baseModuleContext) OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag {
  2109. return b.bp.OtherModuleDependencyTag(m)
  2110. }
  2111. func (b *baseModuleContext) OtherModuleExists(name string) bool { return b.bp.OtherModuleExists(name) }
  2112. func (b *baseModuleContext) OtherModuleDependencyVariantExists(variations []blueprint.Variation, name string) bool {
  2113. return b.bp.OtherModuleDependencyVariantExists(variations, name)
  2114. }
  2115. func (b *baseModuleContext) OtherModuleFarDependencyVariantExists(variations []blueprint.Variation, name string) bool {
  2116. return b.bp.OtherModuleFarDependencyVariantExists(variations, name)
  2117. }
  2118. func (b *baseModuleContext) OtherModuleReverseDependencyVariantExists(name string) bool {
  2119. return b.bp.OtherModuleReverseDependencyVariantExists(name)
  2120. }
  2121. func (b *baseModuleContext) OtherModuleType(m blueprint.Module) string {
  2122. return b.bp.OtherModuleType(m)
  2123. }
  2124. func (b *baseModuleContext) OtherModuleProvider(m blueprint.Module, provider blueprint.ProviderKey) interface{} {
  2125. return b.bp.OtherModuleProvider(m, provider)
  2126. }
  2127. func (b *baseModuleContext) OtherModuleHasProvider(m blueprint.Module, provider blueprint.ProviderKey) bool {
  2128. return b.bp.OtherModuleHasProvider(m, provider)
  2129. }
  2130. func (b *baseModuleContext) Provider(provider blueprint.ProviderKey) interface{} {
  2131. return b.bp.Provider(provider)
  2132. }
  2133. func (b *baseModuleContext) HasProvider(provider blueprint.ProviderKey) bool {
  2134. return b.bp.HasProvider(provider)
  2135. }
  2136. func (b *baseModuleContext) SetProvider(provider blueprint.ProviderKey, value interface{}) {
  2137. b.bp.SetProvider(provider, value)
  2138. }
  2139. func (b *baseModuleContext) GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module {
  2140. return b.bp.GetDirectDepWithTag(name, tag)
  2141. }
  2142. func (b *baseModuleContext) blueprintBaseModuleContext() blueprint.BaseModuleContext {
  2143. return b.bp
  2144. }
  2145. type moduleContext struct {
  2146. bp blueprint.ModuleContext
  2147. baseModuleContext
  2148. packagingSpecs []PackagingSpec
  2149. installFiles InstallPaths
  2150. checkbuildFiles Paths
  2151. module Module
  2152. phonies map[string]Paths
  2153. katiInstalls []katiInstall
  2154. katiSymlinks []katiInstall
  2155. // For tests
  2156. buildParams []BuildParams
  2157. ruleParams map[blueprint.Rule]blueprint.RuleParams
  2158. variables map[string]string
  2159. }
  2160. // katiInstall stores a request from Soong to Make to create an install rule.
  2161. type katiInstall struct {
  2162. from Path
  2163. to InstallPath
  2164. implicitDeps Paths
  2165. orderOnlyDeps Paths
  2166. executable bool
  2167. extraFiles *extraFilesZip
  2168. absFrom string
  2169. }
  2170. type extraFilesZip struct {
  2171. zip Path
  2172. dir InstallPath
  2173. }
  2174. type katiInstalls []katiInstall
  2175. // BuiltInstalled returns the katiInstalls in the form used by $(call copy-many-files) in Make, a
  2176. // space separated list of from:to tuples.
  2177. func (installs katiInstalls) BuiltInstalled() string {
  2178. sb := strings.Builder{}
  2179. for i, install := range installs {
  2180. if i != 0 {
  2181. sb.WriteRune(' ')
  2182. }
  2183. sb.WriteString(install.from.String())
  2184. sb.WriteRune(':')
  2185. sb.WriteString(install.to.String())
  2186. }
  2187. return sb.String()
  2188. }
  2189. // InstallPaths returns the install path of each entry.
  2190. func (installs katiInstalls) InstallPaths() InstallPaths {
  2191. paths := make(InstallPaths, 0, len(installs))
  2192. for _, install := range installs {
  2193. paths = append(paths, install.to)
  2194. }
  2195. return paths
  2196. }
  2197. func (m *moduleContext) ninjaError(params BuildParams, err error) (PackageContext, BuildParams) {
  2198. return pctx, BuildParams{
  2199. Rule: ErrorRule,
  2200. Description: params.Description,
  2201. Output: params.Output,
  2202. Outputs: params.Outputs,
  2203. ImplicitOutput: params.ImplicitOutput,
  2204. ImplicitOutputs: params.ImplicitOutputs,
  2205. Args: map[string]string{
  2206. "error": err.Error(),
  2207. },
  2208. }
  2209. }
  2210. func (m *moduleContext) ModuleBuild(pctx PackageContext, params ModuleBuildParams) {
  2211. m.Build(pctx, BuildParams(params))
  2212. }
  2213. func validateBuildParams(params blueprint.BuildParams) error {
  2214. // Validate that the symlink outputs are declared outputs or implicit outputs
  2215. allOutputs := map[string]bool{}
  2216. for _, output := range params.Outputs {
  2217. allOutputs[output] = true
  2218. }
  2219. for _, output := range params.ImplicitOutputs {
  2220. allOutputs[output] = true
  2221. }
  2222. for _, symlinkOutput := range params.SymlinkOutputs {
  2223. if !allOutputs[symlinkOutput] {
  2224. return fmt.Errorf(
  2225. "Symlink output %s is not a declared output or implicit output",
  2226. symlinkOutput)
  2227. }
  2228. }
  2229. return nil
  2230. }
  2231. // Convert build parameters from their concrete Android types into their string representations,
  2232. // and combine the singular and plural fields of the same type (e.g. Output and Outputs).
  2233. func convertBuildParams(params BuildParams) blueprint.BuildParams {
  2234. bparams := blueprint.BuildParams{
  2235. Rule: params.Rule,
  2236. Description: params.Description,
  2237. Deps: params.Deps,
  2238. Outputs: params.Outputs.Strings(),
  2239. ImplicitOutputs: params.ImplicitOutputs.Strings(),
  2240. SymlinkOutputs: params.SymlinkOutputs.Strings(),
  2241. Inputs: params.Inputs.Strings(),
  2242. Implicits: params.Implicits.Strings(),
  2243. OrderOnly: params.OrderOnly.Strings(),
  2244. Validations: params.Validations.Strings(),
  2245. Args: params.Args,
  2246. Optional: !params.Default,
  2247. }
  2248. if params.Depfile != nil {
  2249. bparams.Depfile = params.Depfile.String()
  2250. }
  2251. if params.Output != nil {
  2252. bparams.Outputs = append(bparams.Outputs, params.Output.String())
  2253. }
  2254. if params.SymlinkOutput != nil {
  2255. bparams.SymlinkOutputs = append(bparams.SymlinkOutputs, params.SymlinkOutput.String())
  2256. }
  2257. if params.ImplicitOutput != nil {
  2258. bparams.ImplicitOutputs = append(bparams.ImplicitOutputs, params.ImplicitOutput.String())
  2259. }
  2260. if params.Input != nil {
  2261. bparams.Inputs = append(bparams.Inputs, params.Input.String())
  2262. }
  2263. if params.Implicit != nil {
  2264. bparams.Implicits = append(bparams.Implicits, params.Implicit.String())
  2265. }
  2266. if params.Validation != nil {
  2267. bparams.Validations = append(bparams.Validations, params.Validation.String())
  2268. }
  2269. bparams.Outputs = proptools.NinjaEscapeList(bparams.Outputs)
  2270. bparams.ImplicitOutputs = proptools.NinjaEscapeList(bparams.ImplicitOutputs)
  2271. bparams.SymlinkOutputs = proptools.NinjaEscapeList(bparams.SymlinkOutputs)
  2272. bparams.Inputs = proptools.NinjaEscapeList(bparams.Inputs)
  2273. bparams.Implicits = proptools.NinjaEscapeList(bparams.Implicits)
  2274. bparams.OrderOnly = proptools.NinjaEscapeList(bparams.OrderOnly)
  2275. bparams.Validations = proptools.NinjaEscapeList(bparams.Validations)
  2276. bparams.Depfile = proptools.NinjaEscape(bparams.Depfile)
  2277. return bparams
  2278. }
  2279. func (m *moduleContext) Variable(pctx PackageContext, name, value string) {
  2280. if m.config.captureBuild {
  2281. m.variables[name] = value
  2282. }
  2283. m.bp.Variable(pctx.PackageContext, name, value)
  2284. }
  2285. func (m *moduleContext) Rule(pctx PackageContext, name string, params blueprint.RuleParams,
  2286. argNames ...string) blueprint.Rule {
  2287. if m.config.UseRemoteBuild() {
  2288. if params.Pool == nil {
  2289. // When USE_GOMA=true or USE_RBE=true are set and the rule is not supported by goma/RBE, restrict
  2290. // jobs to the local parallelism value
  2291. params.Pool = localPool
  2292. } else if params.Pool == remotePool {
  2293. // remotePool is a fake pool used to identify rule that are supported for remoting. If the rule's
  2294. // pool is the remotePool, replace with nil so that ninja runs it at NINJA_REMOTE_NUM_JOBS
  2295. // parallelism.
  2296. params.Pool = nil
  2297. }
  2298. }
  2299. rule := m.bp.Rule(pctx.PackageContext, name, params, argNames...)
  2300. if m.config.captureBuild {
  2301. m.ruleParams[rule] = params
  2302. }
  2303. return rule
  2304. }
  2305. func (m *moduleContext) Build(pctx PackageContext, params BuildParams) {
  2306. if params.Description != "" {
  2307. params.Description = "${moduleDesc}" + params.Description + "${moduleDescSuffix}"
  2308. }
  2309. if missingDeps := m.GetMissingDependencies(); len(missingDeps) > 0 {
  2310. pctx, params = m.ninjaError(params, fmt.Errorf("module %s missing dependencies: %s\n",
  2311. m.ModuleName(), strings.Join(missingDeps, ", ")))
  2312. }
  2313. if m.config.captureBuild {
  2314. m.buildParams = append(m.buildParams, params)
  2315. }
  2316. bparams := convertBuildParams(params)
  2317. err := validateBuildParams(bparams)
  2318. if err != nil {
  2319. m.ModuleErrorf(
  2320. "%s: build parameter validation failed: %s",
  2321. m.ModuleName(),
  2322. err.Error())
  2323. }
  2324. m.bp.Build(pctx.PackageContext, bparams)
  2325. }
  2326. func (m *moduleContext) Phony(name string, deps ...Path) {
  2327. addPhony(m.config, name, deps...)
  2328. }
  2329. func (m *moduleContext) GetMissingDependencies() []string {
  2330. var missingDeps []string
  2331. missingDeps = append(missingDeps, m.Module().base().commonProperties.MissingDeps...)
  2332. missingDeps = append(missingDeps, m.bp.GetMissingDependencies()...)
  2333. missingDeps = FirstUniqueStrings(missingDeps)
  2334. return missingDeps
  2335. }
  2336. func (b *baseModuleContext) AddMissingDependencies(deps []string) {
  2337. if deps != nil {
  2338. missingDeps := &b.Module().base().commonProperties.MissingDeps
  2339. *missingDeps = append(*missingDeps, deps...)
  2340. *missingDeps = FirstUniqueStrings(*missingDeps)
  2341. }
  2342. }
  2343. type AllowDisabledModuleDependency interface {
  2344. blueprint.DependencyTag
  2345. AllowDisabledModuleDependency(target Module) bool
  2346. }
  2347. func (b *baseModuleContext) validateAndroidModule(module blueprint.Module, tag blueprint.DependencyTag, strict bool) Module {
  2348. aModule, _ := module.(Module)
  2349. if !strict {
  2350. return aModule
  2351. }
  2352. if aModule == nil {
  2353. b.ModuleErrorf("module %q (%#v) not an android module", b.OtherModuleName(module), tag)
  2354. return nil
  2355. }
  2356. if !aModule.Enabled() {
  2357. if t, ok := tag.(AllowDisabledModuleDependency); !ok || !t.AllowDisabledModuleDependency(aModule) {
  2358. if b.Config().AllowMissingDependencies() {
  2359. b.AddMissingDependencies([]string{b.OtherModuleName(aModule)})
  2360. } else {
  2361. b.ModuleErrorf("depends on disabled module %q", b.OtherModuleName(aModule))
  2362. }
  2363. }
  2364. return nil
  2365. }
  2366. return aModule
  2367. }
  2368. type dep struct {
  2369. mod blueprint.Module
  2370. tag blueprint.DependencyTag
  2371. }
  2372. func (b *baseModuleContext) getDirectDepsInternal(name string, tag blueprint.DependencyTag) []dep {
  2373. var deps []dep
  2374. b.VisitDirectDepsBlueprint(func(module blueprint.Module) {
  2375. if aModule, _ := module.(Module); aModule != nil {
  2376. if aModule.base().BaseModuleName() == name {
  2377. returnedTag := b.bp.OtherModuleDependencyTag(aModule)
  2378. if tag == nil || returnedTag == tag {
  2379. deps = append(deps, dep{aModule, returnedTag})
  2380. }
  2381. }
  2382. } else if b.bp.OtherModuleName(module) == name {
  2383. returnedTag := b.bp.OtherModuleDependencyTag(module)
  2384. if tag == nil || returnedTag == tag {
  2385. deps = append(deps, dep{module, returnedTag})
  2386. }
  2387. }
  2388. })
  2389. return deps
  2390. }
  2391. func (b *baseModuleContext) getDirectDepInternal(name string, tag blueprint.DependencyTag) (blueprint.Module, blueprint.DependencyTag) {
  2392. deps := b.getDirectDepsInternal(name, tag)
  2393. if len(deps) == 1 {
  2394. return deps[0].mod, deps[0].tag
  2395. } else if len(deps) >= 2 {
  2396. panic(fmt.Errorf("Multiple dependencies having same BaseModuleName() %q found from %q",
  2397. name, b.ModuleName()))
  2398. } else {
  2399. return nil, nil
  2400. }
  2401. }
  2402. func (b *baseModuleContext) getDirectDepFirstTag(name string) (blueprint.Module, blueprint.DependencyTag) {
  2403. foundDeps := b.getDirectDepsInternal(name, nil)
  2404. deps := map[blueprint.Module]bool{}
  2405. for _, dep := range foundDeps {
  2406. deps[dep.mod] = true
  2407. }
  2408. if len(deps) == 1 {
  2409. return foundDeps[0].mod, foundDeps[0].tag
  2410. } else if len(deps) >= 2 {
  2411. // this could happen if two dependencies have the same name in different namespaces
  2412. // TODO(b/186554727): this should not occur if namespaces are handled within
  2413. // getDirectDepsInternal.
  2414. panic(fmt.Errorf("Multiple dependencies having same BaseModuleName() %q found from %q",
  2415. name, b.ModuleName()))
  2416. } else {
  2417. return nil, nil
  2418. }
  2419. }
  2420. func (b *baseModuleContext) GetDirectDepsWithTag(tag blueprint.DependencyTag) []Module {
  2421. var deps []Module
  2422. b.VisitDirectDepsBlueprint(func(module blueprint.Module) {
  2423. if aModule, _ := module.(Module); aModule != nil {
  2424. if b.bp.OtherModuleDependencyTag(aModule) == tag {
  2425. deps = append(deps, aModule)
  2426. }
  2427. }
  2428. })
  2429. return deps
  2430. }
  2431. func (m *moduleContext) GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module {
  2432. module, _ := m.getDirectDepInternal(name, tag)
  2433. return module
  2434. }
  2435. // GetDirectDep returns the Module and DependencyTag for the direct dependency with the specified
  2436. // name, or nil if none exists. If there are multiple dependencies on the same module it returns the
  2437. // first DependencyTag.
  2438. func (b *baseModuleContext) GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag) {
  2439. return b.getDirectDepFirstTag(name)
  2440. }
  2441. func (b *baseModuleContext) ModuleFromName(name string) (blueprint.Module, bool) {
  2442. if !b.isBazelConversionMode() {
  2443. panic("cannot call ModuleFromName if not in bazel conversion mode")
  2444. }
  2445. if moduleName, _ := SrcIsModuleWithTag(name); moduleName != "" {
  2446. return b.bp.ModuleFromName(moduleName)
  2447. } else {
  2448. return b.bp.ModuleFromName(name)
  2449. }
  2450. }
  2451. func (b *baseModuleContext) VisitDirectDepsBlueprint(visit func(blueprint.Module)) {
  2452. b.bp.VisitDirectDeps(visit)
  2453. }
  2454. func (b *baseModuleContext) VisitDirectDeps(visit func(Module)) {
  2455. b.bp.VisitDirectDeps(func(module blueprint.Module) {
  2456. if aModule := b.validateAndroidModule(module, b.bp.OtherModuleDependencyTag(module), b.strictVisitDeps); aModule != nil {
  2457. visit(aModule)
  2458. }
  2459. })
  2460. }
  2461. func (b *baseModuleContext) VisitDirectDepsWithTag(tag blueprint.DependencyTag, visit func(Module)) {
  2462. b.bp.VisitDirectDeps(func(module blueprint.Module) {
  2463. if b.bp.OtherModuleDependencyTag(module) == tag {
  2464. if aModule := b.validateAndroidModule(module, b.bp.OtherModuleDependencyTag(module), b.strictVisitDeps); aModule != nil {
  2465. visit(aModule)
  2466. }
  2467. }
  2468. })
  2469. }
  2470. func (b *baseModuleContext) VisitDirectDepsIf(pred func(Module) bool, visit func(Module)) {
  2471. b.bp.VisitDirectDepsIf(
  2472. // pred
  2473. func(module blueprint.Module) bool {
  2474. if aModule := b.validateAndroidModule(module, b.bp.OtherModuleDependencyTag(module), b.strictVisitDeps); aModule != nil {
  2475. return pred(aModule)
  2476. } else {
  2477. return false
  2478. }
  2479. },
  2480. // visit
  2481. func(module blueprint.Module) {
  2482. visit(module.(Module))
  2483. })
  2484. }
  2485. func (b *baseModuleContext) VisitDepsDepthFirst(visit func(Module)) {
  2486. b.bp.VisitDepsDepthFirst(func(module blueprint.Module) {
  2487. if aModule := b.validateAndroidModule(module, b.bp.OtherModuleDependencyTag(module), b.strictVisitDeps); aModule != nil {
  2488. visit(aModule)
  2489. }
  2490. })
  2491. }
  2492. func (b *baseModuleContext) VisitDepsDepthFirstIf(pred func(Module) bool, visit func(Module)) {
  2493. b.bp.VisitDepsDepthFirstIf(
  2494. // pred
  2495. func(module blueprint.Module) bool {
  2496. if aModule := b.validateAndroidModule(module, b.bp.OtherModuleDependencyTag(module), b.strictVisitDeps); aModule != nil {
  2497. return pred(aModule)
  2498. } else {
  2499. return false
  2500. }
  2501. },
  2502. // visit
  2503. func(module blueprint.Module) {
  2504. visit(module.(Module))
  2505. })
  2506. }
  2507. func (b *baseModuleContext) WalkDepsBlueprint(visit func(blueprint.Module, blueprint.Module) bool) {
  2508. b.bp.WalkDeps(visit)
  2509. }
  2510. func (b *baseModuleContext) WalkDeps(visit func(Module, Module) bool) {
  2511. b.walkPath = []Module{b.Module()}
  2512. b.tagPath = []blueprint.DependencyTag{}
  2513. b.bp.WalkDeps(func(child, parent blueprint.Module) bool {
  2514. childAndroidModule, _ := child.(Module)
  2515. parentAndroidModule, _ := parent.(Module)
  2516. if childAndroidModule != nil && parentAndroidModule != nil {
  2517. // record walkPath before visit
  2518. for b.walkPath[len(b.walkPath)-1] != parentAndroidModule {
  2519. b.walkPath = b.walkPath[0 : len(b.walkPath)-1]
  2520. b.tagPath = b.tagPath[0 : len(b.tagPath)-1]
  2521. }
  2522. b.walkPath = append(b.walkPath, childAndroidModule)
  2523. b.tagPath = append(b.tagPath, b.OtherModuleDependencyTag(childAndroidModule))
  2524. return visit(childAndroidModule, parentAndroidModule)
  2525. } else {
  2526. return false
  2527. }
  2528. })
  2529. }
  2530. func (b *baseModuleContext) GetWalkPath() []Module {
  2531. return b.walkPath
  2532. }
  2533. func (b *baseModuleContext) GetTagPath() []blueprint.DependencyTag {
  2534. return b.tagPath
  2535. }
  2536. func (b *baseModuleContext) VisitAllModuleVariants(visit func(Module)) {
  2537. b.bp.VisitAllModuleVariants(func(module blueprint.Module) {
  2538. visit(module.(Module))
  2539. })
  2540. }
  2541. func (b *baseModuleContext) PrimaryModule() Module {
  2542. return b.bp.PrimaryModule().(Module)
  2543. }
  2544. func (b *baseModuleContext) FinalModule() Module {
  2545. return b.bp.FinalModule().(Module)
  2546. }
  2547. // IsMetaDependencyTag returns true for cross-cutting metadata dependencies.
  2548. func IsMetaDependencyTag(tag blueprint.DependencyTag) bool {
  2549. if tag == licenseKindTag {
  2550. return true
  2551. } else if tag == licensesTag {
  2552. return true
  2553. }
  2554. return false
  2555. }
  2556. // A regexp for removing boilerplate from BaseDependencyTag from the string representation of
  2557. // a dependency tag.
  2558. var tagCleaner = regexp.MustCompile(`\QBaseDependencyTag:{}\E(, )?`)
  2559. // PrettyPrintTag returns string representation of the tag, but prefers
  2560. // custom String() method if available.
  2561. func PrettyPrintTag(tag blueprint.DependencyTag) string {
  2562. // Use tag's custom String() method if available.
  2563. if stringer, ok := tag.(fmt.Stringer); ok {
  2564. return stringer.String()
  2565. }
  2566. // Otherwise, get a default string representation of the tag's struct.
  2567. tagString := fmt.Sprintf("%T: %+v", tag, tag)
  2568. // Remove the boilerplate from BaseDependencyTag as it adds no value.
  2569. tagString = tagCleaner.ReplaceAllString(tagString, "")
  2570. return tagString
  2571. }
  2572. func (b *baseModuleContext) GetPathString(skipFirst bool) string {
  2573. sb := strings.Builder{}
  2574. tagPath := b.GetTagPath()
  2575. walkPath := b.GetWalkPath()
  2576. if !skipFirst {
  2577. sb.WriteString(walkPath[0].String())
  2578. }
  2579. for i, m := range walkPath[1:] {
  2580. sb.WriteString("\n")
  2581. sb.WriteString(fmt.Sprintf(" via tag %s\n", PrettyPrintTag(tagPath[i])))
  2582. sb.WriteString(fmt.Sprintf(" -> %s", m.String()))
  2583. }
  2584. return sb.String()
  2585. }
  2586. func (m *moduleContext) ModuleSubDir() string {
  2587. return m.bp.ModuleSubDir()
  2588. }
  2589. func (b *baseModuleContext) Target() Target {
  2590. return b.target
  2591. }
  2592. func (b *baseModuleContext) TargetPrimary() bool {
  2593. return b.targetPrimary
  2594. }
  2595. func (b *baseModuleContext) MultiTargets() []Target {
  2596. return b.multiTargets
  2597. }
  2598. func (b *baseModuleContext) Arch() Arch {
  2599. return b.target.Arch
  2600. }
  2601. func (b *baseModuleContext) Os() OsType {
  2602. return b.os
  2603. }
  2604. func (b *baseModuleContext) Host() bool {
  2605. return b.os.Class == Host
  2606. }
  2607. func (b *baseModuleContext) Device() bool {
  2608. return b.os.Class == Device
  2609. }
  2610. func (b *baseModuleContext) Darwin() bool {
  2611. return b.os == Darwin
  2612. }
  2613. func (b *baseModuleContext) Windows() bool {
  2614. return b.os == Windows
  2615. }
  2616. func (b *baseModuleContext) Debug() bool {
  2617. return b.debug
  2618. }
  2619. func (b *baseModuleContext) PrimaryArch() bool {
  2620. if len(b.config.Targets[b.target.Os]) <= 1 {
  2621. return true
  2622. }
  2623. return b.target.Arch.ArchType == b.config.Targets[b.target.Os][0].Arch.ArchType
  2624. }
  2625. // Makes this module a platform module, i.e. not specific to soc, device,
  2626. // product, or system_ext.
  2627. func (m *ModuleBase) MakeAsPlatform() {
  2628. m.commonProperties.Vendor = boolPtr(false)
  2629. m.commonProperties.Proprietary = boolPtr(false)
  2630. m.commonProperties.Soc_specific = boolPtr(false)
  2631. m.commonProperties.Product_specific = boolPtr(false)
  2632. m.commonProperties.System_ext_specific = boolPtr(false)
  2633. }
  2634. func (m *ModuleBase) MakeAsSystemExt() {
  2635. m.commonProperties.Vendor = boolPtr(false)
  2636. m.commonProperties.Proprietary = boolPtr(false)
  2637. m.commonProperties.Soc_specific = boolPtr(false)
  2638. m.commonProperties.Product_specific = boolPtr(false)
  2639. m.commonProperties.System_ext_specific = boolPtr(true)
  2640. }
  2641. // IsNativeBridgeSupported returns true if "native_bridge_supported" is explicitly set as "true"
  2642. func (m *ModuleBase) IsNativeBridgeSupported() bool {
  2643. return proptools.Bool(m.commonProperties.Native_bridge_supported)
  2644. }
  2645. func (m *moduleContext) InstallInData() bool {
  2646. return m.module.InstallInData()
  2647. }
  2648. func (m *moduleContext) InstallInTestcases() bool {
  2649. return m.module.InstallInTestcases()
  2650. }
  2651. func (m *moduleContext) InstallInSanitizerDir() bool {
  2652. return m.module.InstallInSanitizerDir()
  2653. }
  2654. func (m *moduleContext) InstallInRamdisk() bool {
  2655. return m.module.InstallInRamdisk()
  2656. }
  2657. func (m *moduleContext) InstallInVendorRamdisk() bool {
  2658. return m.module.InstallInVendorRamdisk()
  2659. }
  2660. func (m *moduleContext) InstallInDebugRamdisk() bool {
  2661. return m.module.InstallInDebugRamdisk()
  2662. }
  2663. func (m *moduleContext) InstallInRecovery() bool {
  2664. return m.module.InstallInRecovery()
  2665. }
  2666. func (m *moduleContext) InstallInRoot() bool {
  2667. return m.module.InstallInRoot()
  2668. }
  2669. func (m *moduleContext) InstallForceOS() (*OsType, *ArchType) {
  2670. return m.module.InstallForceOS()
  2671. }
  2672. func (m *moduleContext) InstallInVendor() bool {
  2673. return m.module.InstallInVendor()
  2674. }
  2675. func (m *moduleContext) skipInstall() bool {
  2676. if m.module.base().commonProperties.SkipInstall {
  2677. return true
  2678. }
  2679. if m.module.base().commonProperties.HideFromMake {
  2680. return true
  2681. }
  2682. // We'll need a solution for choosing which of modules with the same name in different
  2683. // namespaces to install. For now, reuse the list of namespaces exported to Make as the
  2684. // list of namespaces to install in a Soong-only build.
  2685. if !m.module.base().commonProperties.NamespaceExportedToMake {
  2686. return true
  2687. }
  2688. return false
  2689. }
  2690. func (m *moduleContext) InstallFile(installPath InstallPath, name string, srcPath Path,
  2691. deps ...Path) InstallPath {
  2692. return m.installFile(installPath, name, srcPath, deps, false, nil)
  2693. }
  2694. func (m *moduleContext) InstallExecutable(installPath InstallPath, name string, srcPath Path,
  2695. deps ...Path) InstallPath {
  2696. return m.installFile(installPath, name, srcPath, deps, true, nil)
  2697. }
  2698. func (m *moduleContext) InstallFileWithExtraFilesZip(installPath InstallPath, name string, srcPath Path,
  2699. extraZip Path, deps ...Path) InstallPath {
  2700. return m.installFile(installPath, name, srcPath, deps, false, &extraFilesZip{
  2701. zip: extraZip,
  2702. dir: installPath,
  2703. })
  2704. }
  2705. func (m *moduleContext) PackageFile(installPath InstallPath, name string, srcPath Path) PackagingSpec {
  2706. fullInstallPath := installPath.Join(m, name)
  2707. return m.packageFile(fullInstallPath, srcPath, false)
  2708. }
  2709. func (m *moduleContext) packageFile(fullInstallPath InstallPath, srcPath Path, executable bool) PackagingSpec {
  2710. licenseFiles := m.Module().EffectiveLicenseFiles()
  2711. spec := PackagingSpec{
  2712. relPathInPackage: Rel(m, fullInstallPath.PartitionDir(), fullInstallPath.String()),
  2713. srcPath: srcPath,
  2714. symlinkTarget: "",
  2715. executable: executable,
  2716. effectiveLicenseFiles: &licenseFiles,
  2717. partition: fullInstallPath.partition,
  2718. }
  2719. m.packagingSpecs = append(m.packagingSpecs, spec)
  2720. return spec
  2721. }
  2722. func (m *moduleContext) installFile(installPath InstallPath, name string, srcPath Path, deps []Path,
  2723. executable bool, extraZip *extraFilesZip) InstallPath {
  2724. fullInstallPath := installPath.Join(m, name)
  2725. m.module.base().hooks.runInstallHooks(m, srcPath, fullInstallPath, false)
  2726. if !m.skipInstall() {
  2727. deps = append(deps, m.module.base().installFilesDepSet.ToList().Paths()...)
  2728. var implicitDeps, orderOnlyDeps Paths
  2729. if m.Host() {
  2730. // Installed host modules might be used during the build, depend directly on their
  2731. // dependencies so their timestamp is updated whenever their dependency is updated
  2732. implicitDeps = deps
  2733. } else {
  2734. orderOnlyDeps = deps
  2735. }
  2736. if m.Config().KatiEnabled() {
  2737. // When creating the install rule in Soong but embedding in Make, write the rule to a
  2738. // makefile instead of directly to the ninja file so that main.mk can add the
  2739. // dependencies from the `required` property that are hard to resolve in Soong.
  2740. m.katiInstalls = append(m.katiInstalls, katiInstall{
  2741. from: srcPath,
  2742. to: fullInstallPath,
  2743. implicitDeps: implicitDeps,
  2744. orderOnlyDeps: orderOnlyDeps,
  2745. executable: executable,
  2746. extraFiles: extraZip,
  2747. })
  2748. } else {
  2749. rule := Cp
  2750. if executable {
  2751. rule = CpExecutable
  2752. }
  2753. extraCmds := ""
  2754. if extraZip != nil {
  2755. extraCmds += fmt.Sprintf(" && ( unzip -qDD -d '%s' '%s' 2>&1 | grep -v \"zipfile is empty\"; exit $${PIPESTATUS[0]} )",
  2756. extraZip.dir.String(), extraZip.zip.String())
  2757. extraCmds += " || ( code=$$?; if [ $$code -ne 0 -a $$code -ne 1 ]; then exit $$code; fi )"
  2758. implicitDeps = append(implicitDeps, extraZip.zip)
  2759. }
  2760. m.Build(pctx, BuildParams{
  2761. Rule: rule,
  2762. Description: "install " + fullInstallPath.Base(),
  2763. Output: fullInstallPath,
  2764. Input: srcPath,
  2765. Implicits: implicitDeps,
  2766. OrderOnly: orderOnlyDeps,
  2767. Default: !m.Config().KatiEnabled(),
  2768. Args: map[string]string{
  2769. "extraCmds": extraCmds,
  2770. },
  2771. })
  2772. }
  2773. m.installFiles = append(m.installFiles, fullInstallPath)
  2774. }
  2775. m.packageFile(fullInstallPath, srcPath, executable)
  2776. m.checkbuildFiles = append(m.checkbuildFiles, srcPath)
  2777. return fullInstallPath
  2778. }
  2779. func (m *moduleContext) InstallSymlink(installPath InstallPath, name string, srcPath InstallPath) InstallPath {
  2780. fullInstallPath := installPath.Join(m, name)
  2781. m.module.base().hooks.runInstallHooks(m, srcPath, fullInstallPath, true)
  2782. relPath, err := filepath.Rel(path.Dir(fullInstallPath.String()), srcPath.String())
  2783. if err != nil {
  2784. panic(fmt.Sprintf("Unable to generate symlink between %q and %q: %s", fullInstallPath.Base(), srcPath.Base(), err))
  2785. }
  2786. if !m.skipInstall() {
  2787. if m.Config().KatiEnabled() {
  2788. // When creating the symlink rule in Soong but embedding in Make, write the rule to a
  2789. // makefile instead of directly to the ninja file so that main.mk can add the
  2790. // dependencies from the `required` property that are hard to resolve in Soong.
  2791. m.katiSymlinks = append(m.katiSymlinks, katiInstall{
  2792. from: srcPath,
  2793. to: fullInstallPath,
  2794. })
  2795. } else {
  2796. // The symlink doesn't need updating when the target is modified, but we sometimes
  2797. // have a dependency on a symlink to a binary instead of to the binary directly, and
  2798. // the mtime of the symlink must be updated when the binary is modified, so use a
  2799. // normal dependency here instead of an order-only dependency.
  2800. m.Build(pctx, BuildParams{
  2801. Rule: Symlink,
  2802. Description: "install symlink " + fullInstallPath.Base(),
  2803. Output: fullInstallPath,
  2804. Input: srcPath,
  2805. Default: !m.Config().KatiEnabled(),
  2806. Args: map[string]string{
  2807. "fromPath": relPath,
  2808. },
  2809. })
  2810. }
  2811. m.installFiles = append(m.installFiles, fullInstallPath)
  2812. m.checkbuildFiles = append(m.checkbuildFiles, srcPath)
  2813. }
  2814. m.packagingSpecs = append(m.packagingSpecs, PackagingSpec{
  2815. relPathInPackage: Rel(m, fullInstallPath.PartitionDir(), fullInstallPath.String()),
  2816. srcPath: nil,
  2817. symlinkTarget: relPath,
  2818. executable: false,
  2819. partition: fullInstallPath.partition,
  2820. })
  2821. return fullInstallPath
  2822. }
  2823. // installPath/name -> absPath where absPath might be a path that is available only at runtime
  2824. // (e.g. /apex/...)
  2825. func (m *moduleContext) InstallAbsoluteSymlink(installPath InstallPath, name string, absPath string) InstallPath {
  2826. fullInstallPath := installPath.Join(m, name)
  2827. m.module.base().hooks.runInstallHooks(m, nil, fullInstallPath, true)
  2828. if !m.skipInstall() {
  2829. if m.Config().KatiEnabled() {
  2830. // When creating the symlink rule in Soong but embedding in Make, write the rule to a
  2831. // makefile instead of directly to the ninja file so that main.mk can add the
  2832. // dependencies from the `required` property that are hard to resolve in Soong.
  2833. m.katiSymlinks = append(m.katiSymlinks, katiInstall{
  2834. absFrom: absPath,
  2835. to: fullInstallPath,
  2836. })
  2837. } else {
  2838. m.Build(pctx, BuildParams{
  2839. Rule: Symlink,
  2840. Description: "install symlink " + fullInstallPath.Base() + " -> " + absPath,
  2841. Output: fullInstallPath,
  2842. Default: !m.Config().KatiEnabled(),
  2843. Args: map[string]string{
  2844. "fromPath": absPath,
  2845. },
  2846. })
  2847. }
  2848. m.installFiles = append(m.installFiles, fullInstallPath)
  2849. }
  2850. m.packagingSpecs = append(m.packagingSpecs, PackagingSpec{
  2851. relPathInPackage: Rel(m, fullInstallPath.PartitionDir(), fullInstallPath.String()),
  2852. srcPath: nil,
  2853. symlinkTarget: absPath,
  2854. executable: false,
  2855. partition: fullInstallPath.partition,
  2856. })
  2857. return fullInstallPath
  2858. }
  2859. func (m *moduleContext) CheckbuildFile(srcPath Path) {
  2860. m.checkbuildFiles = append(m.checkbuildFiles, srcPath)
  2861. }
  2862. func (m *moduleContext) blueprintModuleContext() blueprint.ModuleContext {
  2863. return m.bp
  2864. }
  2865. func (m *moduleContext) LicenseMetadataFile() Path {
  2866. return m.module.base().licenseMetadataFile
  2867. }
  2868. // SrcIsModule decodes module references in the format ":unqualified-name" or "//namespace:name"
  2869. // into the module name, or empty string if the input was not a module reference.
  2870. func SrcIsModule(s string) (module string) {
  2871. if len(s) > 1 {
  2872. if s[0] == ':' {
  2873. module = s[1:]
  2874. if !isUnqualifiedModuleName(module) {
  2875. // The module name should be unqualified but is not so do not treat it as a module.
  2876. module = ""
  2877. }
  2878. } else if s[0] == '/' && s[1] == '/' {
  2879. module = s
  2880. }
  2881. }
  2882. return module
  2883. }
  2884. // SrcIsModuleWithTag decodes module references in the format ":unqualified-name{.tag}" or
  2885. // "//namespace:name{.tag}" into the module name and tag, ":unqualified-name" or "//namespace:name"
  2886. // into the module name and an empty string for the tag, or empty strings if the input was not a
  2887. // module reference.
  2888. func SrcIsModuleWithTag(s string) (module, tag string) {
  2889. if len(s) > 1 {
  2890. if s[0] == ':' {
  2891. module = s[1:]
  2892. } else if s[0] == '/' && s[1] == '/' {
  2893. module = s
  2894. }
  2895. if module != "" {
  2896. if tagStart := strings.IndexByte(module, '{'); tagStart > 0 {
  2897. if module[len(module)-1] == '}' {
  2898. tag = module[tagStart+1 : len(module)-1]
  2899. module = module[:tagStart]
  2900. }
  2901. }
  2902. if s[0] == ':' && !isUnqualifiedModuleName(module) {
  2903. // The module name should be unqualified but is not so do not treat it as a module.
  2904. module = ""
  2905. tag = ""
  2906. }
  2907. }
  2908. }
  2909. return module, tag
  2910. }
  2911. // isUnqualifiedModuleName makes sure that the supplied module is an unqualified module name, i.e.
  2912. // does not contain any /.
  2913. func isUnqualifiedModuleName(module string) bool {
  2914. return strings.IndexByte(module, '/') == -1
  2915. }
  2916. // sourceOrOutputDependencyTag is the dependency tag added automatically by pathDepsMutator for any
  2917. // module reference in a property annotated with `android:"path"` or passed to ExtractSourceDeps
  2918. // or ExtractSourcesDeps.
  2919. //
  2920. // If uniquely identifies the dependency that was added as it contains both the module name used to
  2921. // add the dependency as well as the tag. That makes it very simple to find the matching dependency
  2922. // in GetModuleFromPathDep as all it needs to do is find the dependency whose tag matches the tag
  2923. // used to add it. It does not need to check that the module name as returned by one of
  2924. // Module.Name(), BaseModuleContext.OtherModuleName() or ModuleBase.BaseModuleName() matches the
  2925. // name supplied in the tag. That means it does not need to handle differences in module names
  2926. // caused by prebuilt_ prefix, or fully qualified module names.
  2927. type sourceOrOutputDependencyTag struct {
  2928. blueprint.BaseDependencyTag
  2929. // The name of the module.
  2930. moduleName string
  2931. // The tag that will be passed to the module's OutputFileProducer.OutputFiles(tag) method.
  2932. tag string
  2933. }
  2934. func sourceOrOutputDepTag(moduleName, tag string) blueprint.DependencyTag {
  2935. return sourceOrOutputDependencyTag{moduleName: moduleName, tag: tag}
  2936. }
  2937. // IsSourceDepTagWithOutputTag returns true if the supplied blueprint.DependencyTag is one that was
  2938. // used to add dependencies by either ExtractSourceDeps, ExtractSourcesDeps or automatically for
  2939. // properties tagged with `android:"path"` AND it was added using a module reference of
  2940. // :moduleName{outputTag}.
  2941. func IsSourceDepTagWithOutputTag(depTag blueprint.DependencyTag, outputTag string) bool {
  2942. t, ok := depTag.(sourceOrOutputDependencyTag)
  2943. return ok && t.tag == outputTag
  2944. }
  2945. // Adds necessary dependencies to satisfy filegroup or generated sources modules listed in srcFiles
  2946. // using ":module" syntax, if any.
  2947. //
  2948. // Deprecated: tag the property with `android:"path"` instead.
  2949. func ExtractSourcesDeps(ctx BottomUpMutatorContext, srcFiles []string) {
  2950. set := make(map[string]bool)
  2951. for _, s := range srcFiles {
  2952. if m, t := SrcIsModuleWithTag(s); m != "" {
  2953. if _, found := set[s]; found {
  2954. ctx.ModuleErrorf("found source dependency duplicate: %q!", s)
  2955. } else {
  2956. set[s] = true
  2957. ctx.AddDependency(ctx.Module(), sourceOrOutputDepTag(m, t), m)
  2958. }
  2959. }
  2960. }
  2961. }
  2962. // Adds necessary dependencies to satisfy filegroup or generated sources modules specified in s
  2963. // using ":module" syntax, if any.
  2964. //
  2965. // Deprecated: tag the property with `android:"path"` instead.
  2966. func ExtractSourceDeps(ctx BottomUpMutatorContext, s *string) {
  2967. if s != nil {
  2968. if m, t := SrcIsModuleWithTag(*s); m != "" {
  2969. ctx.AddDependency(ctx.Module(), sourceOrOutputDepTag(m, t), m)
  2970. }
  2971. }
  2972. }
  2973. // A module that implements SourceFileProducer can be referenced from any property that is tagged with `android:"path"`
  2974. // using the ":module" syntax and provides a list of paths to be used as if they were listed in the property.
  2975. type SourceFileProducer interface {
  2976. Srcs() Paths
  2977. }
  2978. // A module that implements OutputFileProducer can be referenced from any property that is tagged with `android:"path"`
  2979. // using the ":module" syntax or ":module{.tag}" syntax and provides a list of output files to be used as if they were
  2980. // listed in the property.
  2981. type OutputFileProducer interface {
  2982. OutputFiles(tag string) (Paths, error)
  2983. }
  2984. // OutputFilesForModule returns the paths from an OutputFileProducer with the given tag. On error, including if the
  2985. // module produced zero paths, it reports errors to the ctx and returns nil.
  2986. func OutputFilesForModule(ctx PathContext, module blueprint.Module, tag string) Paths {
  2987. paths, err := outputFilesForModule(ctx, module, tag)
  2988. if err != nil {
  2989. reportPathError(ctx, err)
  2990. return nil
  2991. }
  2992. return paths
  2993. }
  2994. // OutputFileForModule returns the path from an OutputFileProducer with the given tag. On error, including if the
  2995. // module produced zero or multiple paths, it reports errors to the ctx and returns nil.
  2996. func OutputFileForModule(ctx PathContext, module blueprint.Module, tag string) Path {
  2997. paths, err := outputFilesForModule(ctx, module, tag)
  2998. if err != nil {
  2999. reportPathError(ctx, err)
  3000. return nil
  3001. }
  3002. if len(paths) > 1 {
  3003. ReportPathErrorf(ctx, "got multiple output files from module %q, expected exactly one",
  3004. pathContextName(ctx, module))
  3005. return nil
  3006. }
  3007. return paths[0]
  3008. }
  3009. func outputFilesForModule(ctx PathContext, module blueprint.Module, tag string) (Paths, error) {
  3010. if outputFileProducer, ok := module.(OutputFileProducer); ok {
  3011. paths, err := outputFileProducer.OutputFiles(tag)
  3012. if err != nil {
  3013. return nil, fmt.Errorf("failed to get output file from module %q: %s",
  3014. pathContextName(ctx, module), err.Error())
  3015. }
  3016. if len(paths) == 0 {
  3017. return nil, fmt.Errorf("failed to get output files from module %q", pathContextName(ctx, module))
  3018. }
  3019. return paths, nil
  3020. } else if sourceFileProducer, ok := module.(SourceFileProducer); ok {
  3021. if tag != "" {
  3022. return nil, fmt.Errorf("module %q is a SourceFileProducer, not an OutputFileProducer, and so does not support tag %q", pathContextName(ctx, module), tag)
  3023. }
  3024. paths := sourceFileProducer.Srcs()
  3025. if len(paths) == 0 {
  3026. return nil, fmt.Errorf("failed to get output files from module %q", pathContextName(ctx, module))
  3027. }
  3028. return paths, nil
  3029. } else {
  3030. return nil, fmt.Errorf("module %q is not an OutputFileProducer", pathContextName(ctx, module))
  3031. }
  3032. }
  3033. // Modules can implement HostToolProvider and return a valid OptionalPath from HostToolPath() to
  3034. // specify that they can be used as a tool by a genrule module.
  3035. type HostToolProvider interface {
  3036. Module
  3037. // HostToolPath returns the path to the host tool for the module if it is one, or an invalid
  3038. // OptionalPath.
  3039. HostToolPath() OptionalPath
  3040. }
  3041. // Returns a list of paths expanded from globs and modules referenced using ":module" syntax. The property must
  3042. // be tagged with `android:"path" to support automatic source module dependency resolution.
  3043. //
  3044. // Deprecated: use PathsForModuleSrc or PathsForModuleSrcExcludes instead.
  3045. func (m *moduleContext) ExpandSources(srcFiles, excludes []string) Paths {
  3046. return PathsForModuleSrcExcludes(m, srcFiles, excludes)
  3047. }
  3048. // Returns a single path expanded from globs and modules referenced using ":module" syntax. The property must
  3049. // be tagged with `android:"path" to support automatic source module dependency resolution.
  3050. //
  3051. // Deprecated: use PathForModuleSrc instead.
  3052. func (m *moduleContext) ExpandSource(srcFile, _ string) Path {
  3053. return PathForModuleSrc(m, srcFile)
  3054. }
  3055. // Returns an optional single path expanded from globs and modules referenced using ":module" syntax if
  3056. // the srcFile is non-nil. The property must be tagged with `android:"path" to support automatic source module
  3057. // dependency resolution.
  3058. func (m *moduleContext) ExpandOptionalSource(srcFile *string, _ string) OptionalPath {
  3059. if srcFile != nil {
  3060. return OptionalPathForPath(PathForModuleSrc(m, *srcFile))
  3061. }
  3062. return OptionalPath{}
  3063. }
  3064. func (m *moduleContext) RequiredModuleNames() []string {
  3065. return m.module.RequiredModuleNames()
  3066. }
  3067. func (m *moduleContext) HostRequiredModuleNames() []string {
  3068. return m.module.HostRequiredModuleNames()
  3069. }
  3070. func (m *moduleContext) TargetRequiredModuleNames() []string {
  3071. return m.module.TargetRequiredModuleNames()
  3072. }
  3073. func init() {
  3074. RegisterSingletonType("buildtarget", BuildTargetSingleton)
  3075. }
  3076. func BuildTargetSingleton() Singleton {
  3077. return &buildTargetSingleton{}
  3078. }
  3079. func parentDir(dir string) string {
  3080. dir, _ = filepath.Split(dir)
  3081. return filepath.Clean(dir)
  3082. }
  3083. type buildTargetSingleton struct{}
  3084. func AddAncestors(ctx SingletonContext, dirMap map[string]Paths, mmName func(string) string) ([]string, []string) {
  3085. // Ensure ancestor directories are in dirMap
  3086. // Make directories build their direct subdirectories
  3087. // Returns a slice of all directories and a slice of top-level directories.
  3088. dirs := SortedStringKeys(dirMap)
  3089. for _, dir := range dirs {
  3090. dir := parentDir(dir)
  3091. for dir != "." && dir != "/" {
  3092. if _, exists := dirMap[dir]; exists {
  3093. break
  3094. }
  3095. dirMap[dir] = nil
  3096. dir = parentDir(dir)
  3097. }
  3098. }
  3099. dirs = SortedStringKeys(dirMap)
  3100. var topDirs []string
  3101. for _, dir := range dirs {
  3102. p := parentDir(dir)
  3103. if p != "." && p != "/" {
  3104. dirMap[p] = append(dirMap[p], PathForPhony(ctx, mmName(dir)))
  3105. } else if dir != "." && dir != "/" && dir != "" {
  3106. topDirs = append(topDirs, dir)
  3107. }
  3108. }
  3109. return SortedStringKeys(dirMap), topDirs
  3110. }
  3111. func (c *buildTargetSingleton) GenerateBuildActions(ctx SingletonContext) {
  3112. var checkbuildDeps Paths
  3113. mmTarget := func(dir string) string {
  3114. return "MODULES-IN-" + strings.Replace(filepath.Clean(dir), "/", "-", -1)
  3115. }
  3116. modulesInDir := make(map[string]Paths)
  3117. ctx.VisitAllModules(func(module Module) {
  3118. blueprintDir := module.base().blueprintDir
  3119. installTarget := module.base().installTarget
  3120. checkbuildTarget := module.base().checkbuildTarget
  3121. if checkbuildTarget != nil {
  3122. checkbuildDeps = append(checkbuildDeps, checkbuildTarget)
  3123. modulesInDir[blueprintDir] = append(modulesInDir[blueprintDir], checkbuildTarget)
  3124. }
  3125. if installTarget != nil {
  3126. modulesInDir[blueprintDir] = append(modulesInDir[blueprintDir], installTarget)
  3127. }
  3128. })
  3129. suffix := ""
  3130. if ctx.Config().KatiEnabled() {
  3131. suffix = "-soong"
  3132. }
  3133. // Create a top-level checkbuild target that depends on all modules
  3134. ctx.Phony("checkbuild"+suffix, checkbuildDeps...)
  3135. // Make will generate the MODULES-IN-* targets
  3136. if ctx.Config().KatiEnabled() {
  3137. return
  3138. }
  3139. dirs, _ := AddAncestors(ctx, modulesInDir, mmTarget)
  3140. // Create a MODULES-IN-<directory> target that depends on all modules in a directory, and
  3141. // depends on the MODULES-IN-* targets of all of its subdirectories that contain Android.bp
  3142. // files.
  3143. for _, dir := range dirs {
  3144. ctx.Phony(mmTarget(dir), modulesInDir[dir]...)
  3145. }
  3146. // Create (host|host-cross|target)-<OS> phony rules to build a reduced checkbuild.
  3147. type osAndCross struct {
  3148. os OsType
  3149. hostCross bool
  3150. }
  3151. osDeps := map[osAndCross]Paths{}
  3152. ctx.VisitAllModules(func(module Module) {
  3153. if module.Enabled() {
  3154. key := osAndCross{os: module.Target().Os, hostCross: module.Target().HostCross}
  3155. osDeps[key] = append(osDeps[key], module.base().checkbuildFiles...)
  3156. }
  3157. })
  3158. osClass := make(map[string]Paths)
  3159. for key, deps := range osDeps {
  3160. var className string
  3161. switch key.os.Class {
  3162. case Host:
  3163. if key.hostCross {
  3164. className = "host-cross"
  3165. } else {
  3166. className = "host"
  3167. }
  3168. case Device:
  3169. className = "target"
  3170. default:
  3171. continue
  3172. }
  3173. name := className + "-" + key.os.Name
  3174. osClass[className] = append(osClass[className], PathForPhony(ctx, name))
  3175. ctx.Phony(name, deps...)
  3176. }
  3177. // Wrap those into host|host-cross|target phony rules
  3178. for _, class := range SortedStringKeys(osClass) {
  3179. ctx.Phony(class, osClass[class]...)
  3180. }
  3181. }
  3182. // Collect information for opening IDE project files in java/jdeps.go.
  3183. type IDEInfo interface {
  3184. IDEInfo(ideInfo *IdeInfo)
  3185. BaseModuleName() string
  3186. }
  3187. // Extract the base module name from the Import name.
  3188. // Often the Import name has a prefix "prebuilt_".
  3189. // Remove the prefix explicitly if needed
  3190. // until we find a better solution to get the Import name.
  3191. type IDECustomizedModuleName interface {
  3192. IDECustomizedModuleName() string
  3193. }
  3194. type IdeInfo struct {
  3195. Deps []string `json:"dependencies,omitempty"`
  3196. Srcs []string `json:"srcs,omitempty"`
  3197. Aidl_include_dirs []string `json:"aidl_include_dirs,omitempty"`
  3198. Jarjar_rules []string `json:"jarjar_rules,omitempty"`
  3199. Jars []string `json:"jars,omitempty"`
  3200. Classes []string `json:"class,omitempty"`
  3201. Installed_paths []string `json:"installed,omitempty"`
  3202. SrcJars []string `json:"srcjars,omitempty"`
  3203. Paths []string `json:"path,omitempty"`
  3204. Static_libs []string `json:"static_libs,omitempty"`
  3205. Libs []string `json:"libs,omitempty"`
  3206. }
  3207. func CheckBlueprintSyntax(ctx BaseModuleContext, filename string, contents string) []error {
  3208. bpctx := ctx.blueprintBaseModuleContext()
  3209. return blueprint.CheckBlueprintSyntax(bpctx.ModuleFactories(), filename, contents)
  3210. }
  3211. // installPathsDepSet is a thin type-safe wrapper around the generic depSet. It always uses
  3212. // topological order.
  3213. type installPathsDepSet struct {
  3214. depSet
  3215. }
  3216. // newInstallPathsDepSet returns an immutable packagingSpecsDepSet with the given direct and
  3217. // transitive contents.
  3218. func newInstallPathsDepSet(direct InstallPaths, transitive []*installPathsDepSet) *installPathsDepSet {
  3219. return &installPathsDepSet{*newDepSet(TOPOLOGICAL, direct, transitive)}
  3220. }
  3221. // ToList returns the installPathsDepSet flattened to a list in topological order.
  3222. func (d *installPathsDepSet) ToList() InstallPaths {
  3223. if d == nil {
  3224. return nil
  3225. }
  3226. return d.depSet.ToList().(InstallPaths)
  3227. }