module.go 134 KB

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