module.go 139 KB

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