module.go 119 KB

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