module.go 111 KB

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