module.go 130 KB

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