module.go 145 KB

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