module.go 138 KB

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