module.go 145 KB

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