module.go 124 KB

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