module.go 144 KB

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