python.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. // Copyright 2017 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 python
  15. // This file contains the "Base" module type for building Python program.
  16. import (
  17. "fmt"
  18. "path/filepath"
  19. "regexp"
  20. "strings"
  21. "github.com/google/blueprint"
  22. "github.com/google/blueprint/proptools"
  23. "android/soong/android"
  24. )
  25. func init() {
  26. registerPythonMutators(android.InitRegistrationContext)
  27. }
  28. func registerPythonMutators(ctx android.RegistrationContext) {
  29. ctx.PreDepsMutators(RegisterPythonPreDepsMutators)
  30. }
  31. // Exported to support other packages using Python modules in tests.
  32. func RegisterPythonPreDepsMutators(ctx android.RegisterMutatorsContext) {
  33. ctx.BottomUp("python_version", versionSplitMutator()).Parallel()
  34. }
  35. // the version-specific properties that apply to python modules.
  36. type VersionProperties struct {
  37. // whether the module is required to be built with this version.
  38. // Defaults to true for Python 3, and false otherwise.
  39. Enabled *bool
  40. // list of source files specific to this Python version.
  41. // Using the syntax ":module", srcs may reference the outputs of other modules that produce source files,
  42. // e.g. genrule or filegroup.
  43. Srcs []string `android:"path,arch_variant"`
  44. // list of source files that should not be used to build the Python module for this version.
  45. // This is most useful to remove files that are not common to all Python versions.
  46. Exclude_srcs []string `android:"path,arch_variant"`
  47. // list of the Python libraries used only for this Python version.
  48. Libs []string `android:"arch_variant"`
  49. // whether the binary is required to be built with embedded launcher for this version, defaults to false.
  50. Embedded_launcher *bool // TODO(b/174041232): Remove this property
  51. }
  52. // properties that apply to all python modules
  53. type BaseProperties struct {
  54. // the package path prefix within the output artifact at which to place the source/data
  55. // files of the current module.
  56. // eg. Pkg_path = "a/b/c"; Other packages can reference this module by using
  57. // (from a.b.c import ...) statement.
  58. // if left unspecified, all the source/data files path is unchanged within zip file.
  59. Pkg_path *string
  60. // true, if the Python module is used internally, eg, Python std libs.
  61. Is_internal *bool
  62. // list of source (.py) files compatible both with Python2 and Python3 used to compile the
  63. // Python module.
  64. // srcs may reference the outputs of other modules that produce source files like genrule
  65. // or filegroup using the syntax ":module".
  66. // Srcs has to be non-empty.
  67. Srcs []string `android:"path,arch_variant"`
  68. // list of source files that should not be used to build the C/C++ module.
  69. // This is most useful in the arch/multilib variants to remove non-common files
  70. Exclude_srcs []string `android:"path,arch_variant"`
  71. // list of files or filegroup modules that provide data that should be installed alongside
  72. // the test. the file extension can be arbitrary except for (.py).
  73. Data []string `android:"path,arch_variant"`
  74. // list of java modules that provide data that should be installed alongside the test.
  75. Java_data []string
  76. // list of the Python libraries compatible both with Python2 and Python3.
  77. Libs []string `android:"arch_variant"`
  78. Version struct {
  79. // Python2-specific properties, including whether Python2 is supported for this module
  80. // and version-specific sources, exclusions and dependencies.
  81. Py2 VersionProperties `android:"arch_variant"`
  82. // Python3-specific properties, including whether Python3 is supported for this module
  83. // and version-specific sources, exclusions and dependencies.
  84. Py3 VersionProperties `android:"arch_variant"`
  85. } `android:"arch_variant"`
  86. // the actual version each module uses after variations created.
  87. // this property name is hidden from users' perspectives, and soong will populate it during
  88. // runtime.
  89. Actual_version string `blueprint:"mutated"`
  90. // whether the module is required to be built with actual_version.
  91. // this is set by the python version mutator based on version-specific properties
  92. Enabled *bool `blueprint:"mutated"`
  93. // whether the binary is required to be built with embedded launcher for this actual_version.
  94. // this is set by the python version mutator based on version-specific properties
  95. Embedded_launcher *bool `blueprint:"mutated"`
  96. }
  97. // Used to store files of current module after expanding dependencies
  98. type pathMapping struct {
  99. dest string
  100. src android.Path
  101. }
  102. type PythonLibraryModule struct {
  103. android.ModuleBase
  104. android.DefaultableModuleBase
  105. android.BazelModuleBase
  106. properties BaseProperties
  107. protoProperties android.ProtoProperties
  108. // initialize before calling Init
  109. hod android.HostOrDeviceSupported
  110. multilib android.Multilib
  111. // the Python files of current module after expanding source dependencies.
  112. // pathMapping: <dest: runfile_path, src: source_path>
  113. srcsPathMappings []pathMapping
  114. // the data files of current module after expanding source dependencies.
  115. // pathMapping: <dest: runfile_path, src: source_path>
  116. dataPathMappings []pathMapping
  117. // The zip file containing the current module's source/data files.
  118. srcsZip android.Path
  119. // The zip file containing the current module's source/data files, with the
  120. // source files precompiled.
  121. precompiledSrcsZip android.Path
  122. }
  123. // newModule generates new Python base module
  124. func newModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *PythonLibraryModule {
  125. return &PythonLibraryModule{
  126. hod: hod,
  127. multilib: multilib,
  128. }
  129. }
  130. // interface implemented by Python modules to provide source and data mappings and zip to python
  131. // modules that depend on it
  132. type pythonDependency interface {
  133. getSrcsPathMappings() []pathMapping
  134. getDataPathMappings() []pathMapping
  135. getSrcsZip() android.Path
  136. getPrecompiledSrcsZip() android.Path
  137. }
  138. // getSrcsPathMappings gets this module's path mapping of src source path : runfiles destination
  139. func (p *PythonLibraryModule) getSrcsPathMappings() []pathMapping {
  140. return p.srcsPathMappings
  141. }
  142. // getSrcsPathMappings gets this module's path mapping of data source path : runfiles destination
  143. func (p *PythonLibraryModule) getDataPathMappings() []pathMapping {
  144. return p.dataPathMappings
  145. }
  146. // getSrcsZip returns the filepath where the current module's source/data files are zipped.
  147. func (p *PythonLibraryModule) getSrcsZip() android.Path {
  148. return p.srcsZip
  149. }
  150. // getSrcsZip returns the filepath where the current module's source/data files are zipped.
  151. func (p *PythonLibraryModule) getPrecompiledSrcsZip() android.Path {
  152. return p.precompiledSrcsZip
  153. }
  154. func (p *PythonLibraryModule) getBaseProperties() *BaseProperties {
  155. return &p.properties
  156. }
  157. var _ pythonDependency = (*PythonLibraryModule)(nil)
  158. func (p *PythonLibraryModule) init() android.Module {
  159. p.AddProperties(&p.properties, &p.protoProperties)
  160. android.InitAndroidArchModule(p, p.hod, p.multilib)
  161. android.InitDefaultableModule(p)
  162. android.InitBazelModule(p)
  163. return p
  164. }
  165. // Python-specific tag to transfer information on the purpose of a dependency.
  166. // This is used when adding a dependency on a module, which can later be accessed when visiting
  167. // dependencies.
  168. type dependencyTag struct {
  169. blueprint.BaseDependencyTag
  170. name string
  171. }
  172. // Python-specific tag that indicates that installed files of this module should depend on installed
  173. // files of the dependency
  174. type installDependencyTag struct {
  175. blueprint.BaseDependencyTag
  176. // embedding this struct provides the installation dependency requirement
  177. android.InstallAlwaysNeededDependencyTag
  178. name string
  179. }
  180. var (
  181. pythonLibTag = dependencyTag{name: "pythonLib"}
  182. javaDataTag = dependencyTag{name: "javaData"}
  183. // The python interpreter, with soong module name "py3-launcher" or "py3-launcher-autorun".
  184. launcherTag = dependencyTag{name: "launcher"}
  185. launcherSharedLibTag = installDependencyTag{name: "launcherSharedLib"}
  186. // The python interpreter built for host so that we can precompile python sources.
  187. // This only works because the precompiled sources don't vary by architecture.
  188. // The soong module name is "py3-launcher".
  189. hostLauncherTag = dependencyTag{name: "hostLauncher"}
  190. hostlauncherSharedLibTag = dependencyTag{name: "hostlauncherSharedLib"}
  191. hostStdLibTag = dependencyTag{name: "hostStdLib"}
  192. pathComponentRegexp = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`)
  193. pyExt = ".py"
  194. protoExt = ".proto"
  195. pyVersion2 = "PY2"
  196. pyVersion3 = "PY3"
  197. internalPath = "internal"
  198. )
  199. type basePropertiesProvider interface {
  200. getBaseProperties() *BaseProperties
  201. }
  202. // versionSplitMutator creates version variants for modules and appends the version-specific
  203. // properties for a given variant to the properties in the variant module
  204. func versionSplitMutator() func(android.BottomUpMutatorContext) {
  205. return func(mctx android.BottomUpMutatorContext) {
  206. if base, ok := mctx.Module().(basePropertiesProvider); ok {
  207. props := base.getBaseProperties()
  208. var versionNames []string
  209. // collect version specific properties, so that we can merge version-specific properties
  210. // into the module's overall properties
  211. var versionProps []VersionProperties
  212. // PY3 is first so that we alias the PY3 variant rather than PY2 if both
  213. // are available
  214. if proptools.BoolDefault(props.Version.Py3.Enabled, true) {
  215. versionNames = append(versionNames, pyVersion3)
  216. versionProps = append(versionProps, props.Version.Py3)
  217. }
  218. if proptools.BoolDefault(props.Version.Py2.Enabled, false) {
  219. versionNames = append(versionNames, pyVersion2)
  220. versionProps = append(versionProps, props.Version.Py2)
  221. }
  222. modules := mctx.CreateLocalVariations(versionNames...)
  223. // Alias module to the first variant
  224. if len(versionNames) > 0 {
  225. mctx.AliasVariation(versionNames[0])
  226. }
  227. for i, v := range versionNames {
  228. // set the actual version for Python module.
  229. newProps := modules[i].(basePropertiesProvider).getBaseProperties()
  230. newProps.Actual_version = v
  231. // append versioned properties for the Python module to the overall properties
  232. err := proptools.AppendMatchingProperties([]interface{}{newProps}, &versionProps[i], nil)
  233. if err != nil {
  234. panic(err)
  235. }
  236. }
  237. }
  238. }
  239. }
  240. func anyHasExt(paths []string, ext string) bool {
  241. for _, p := range paths {
  242. if filepath.Ext(p) == ext {
  243. return true
  244. }
  245. }
  246. return false
  247. }
  248. func (p *PythonLibraryModule) anySrcHasExt(ctx android.BottomUpMutatorContext, ext string) bool {
  249. return anyHasExt(p.properties.Srcs, ext)
  250. }
  251. // DepsMutator mutates dependencies for this module:
  252. // - handles proto dependencies,
  253. // - if required, specifies launcher and adds launcher dependencies,
  254. // - applies python version mutations to Python dependencies
  255. func (p *PythonLibraryModule) DepsMutator(ctx android.BottomUpMutatorContext) {
  256. android.ProtoDeps(ctx, &p.protoProperties)
  257. versionVariation := []blueprint.Variation{
  258. {"python_version", p.properties.Actual_version},
  259. }
  260. // If sources contain a proto file, add dependency on libprotobuf-python
  261. if p.anySrcHasExt(ctx, protoExt) && p.Name() != "libprotobuf-python" {
  262. ctx.AddVariationDependencies(versionVariation, pythonLibTag, "libprotobuf-python")
  263. }
  264. // Add python library dependencies for this python version variation
  265. ctx.AddVariationDependencies(versionVariation, pythonLibTag, android.LastUniqueStrings(p.properties.Libs)...)
  266. // Emulate the data property for java_data but with the arch variation overridden to "common"
  267. // so that it can point to java modules.
  268. javaDataVariation := []blueprint.Variation{{"arch", android.Common.String()}}
  269. ctx.AddVariationDependencies(javaDataVariation, javaDataTag, p.properties.Java_data...)
  270. p.AddDepsOnPythonLauncherAndStdlib(ctx, hostStdLibTag, hostLauncherTag, hostlauncherSharedLibTag, false, ctx.Config().BuildOSTarget)
  271. }
  272. // AddDepsOnPythonLauncherAndStdlib will make the current module depend on the python stdlib,
  273. // launcher (interpreter), and the launcher's shared libraries. If autorun is true, it will use
  274. // the autorun launcher instead of the regular one. This function acceps a targetForDeps argument
  275. // as the target to use for these dependencies. For embedded launcher python binaries, the launcher
  276. // that will be embedded will be under the same target as the python module itself. But when
  277. // precompiling python code, we need to get the python launcher built for host, even if we're
  278. // compiling the python module for device, so we pass a different target to this function.
  279. func (p *PythonLibraryModule) AddDepsOnPythonLauncherAndStdlib(ctx android.BottomUpMutatorContext,
  280. stdLibTag, launcherTag, launcherSharedLibTag blueprint.DependencyTag,
  281. autorun bool, targetForDeps android.Target) {
  282. var stdLib string
  283. var launcherModule string
  284. // Add launcher shared lib dependencies. Ideally, these should be
  285. // derived from the `shared_libs` property of the launcher. TODO: read these from
  286. // the python launcher itself using ctx.OtherModuleProvider() or similar on the result
  287. // of ctx.AddFarVariationDependencies()
  288. launcherSharedLibDeps := []string{
  289. "libsqlite",
  290. }
  291. // Add launcher-specific dependencies for bionic
  292. if targetForDeps.Os.Bionic() {
  293. launcherSharedLibDeps = append(launcherSharedLibDeps, "libc", "libdl", "libm")
  294. }
  295. if targetForDeps.Os == android.LinuxMusl && !ctx.Config().HostStaticBinaries() {
  296. launcherSharedLibDeps = append(launcherSharedLibDeps, "libc_musl")
  297. }
  298. switch p.properties.Actual_version {
  299. case pyVersion2:
  300. stdLib = "py2-stdlib"
  301. launcherModule = "py2-launcher"
  302. if autorun {
  303. launcherModule = "py2-launcher-autorun"
  304. }
  305. launcherSharedLibDeps = append(launcherSharedLibDeps, "libc++")
  306. case pyVersion3:
  307. stdLib = "py3-stdlib"
  308. launcherModule = "py3-launcher"
  309. if autorun {
  310. launcherModule = "py3-launcher-autorun"
  311. }
  312. if ctx.Config().HostStaticBinaries() && targetForDeps.Os == android.LinuxMusl {
  313. launcherModule += "-static"
  314. }
  315. if ctx.Device() {
  316. launcherSharedLibDeps = append(launcherSharedLibDeps, "liblog")
  317. }
  318. default:
  319. panic(fmt.Errorf("unknown Python Actual_version: %q for module: %q.",
  320. p.properties.Actual_version, ctx.ModuleName()))
  321. }
  322. targetVariations := targetForDeps.Variations()
  323. if ctx.ModuleName() != stdLib {
  324. stdLibVariations := make([]blueprint.Variation, 0, len(targetVariations)+1)
  325. stdLibVariations = append(stdLibVariations, blueprint.Variation{Mutator: "python_version", Variation: p.properties.Actual_version})
  326. stdLibVariations = append(stdLibVariations, targetVariations...)
  327. // Using AddFarVariationDependencies for all of these because they can be for a different
  328. // platform, like if the python module itself was being compiled for device, we may want
  329. // the python interpreter built for host so that we can precompile python sources.
  330. ctx.AddFarVariationDependencies(stdLibVariations, stdLibTag, stdLib)
  331. }
  332. ctx.AddFarVariationDependencies(targetVariations, launcherTag, launcherModule)
  333. ctx.AddFarVariationDependencies(targetVariations, launcherSharedLibTag, launcherSharedLibDeps...)
  334. }
  335. // GenerateAndroidBuildActions performs build actions common to all Python modules
  336. func (p *PythonLibraryModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
  337. expandedSrcs := android.PathsForModuleSrcExcludes(ctx, p.properties.Srcs, p.properties.Exclude_srcs)
  338. // expand data files from "data" property.
  339. expandedData := android.PathsForModuleSrc(ctx, p.properties.Data)
  340. // Emulate the data property for java_data dependencies.
  341. for _, javaData := range ctx.GetDirectDepsWithTag(javaDataTag) {
  342. expandedData = append(expandedData, android.OutputFilesForModule(ctx, javaData, "")...)
  343. }
  344. // Validate pkg_path property
  345. pkgPath := String(p.properties.Pkg_path)
  346. if pkgPath != "" {
  347. // TODO: export validation from android/paths.go handling to replace this duplicated functionality
  348. pkgPath = filepath.Clean(String(p.properties.Pkg_path))
  349. if pkgPath == ".." || strings.HasPrefix(pkgPath, "../") ||
  350. strings.HasPrefix(pkgPath, "/") {
  351. ctx.PropertyErrorf("pkg_path",
  352. "%q must be a relative path contained in par file.",
  353. String(p.properties.Pkg_path))
  354. return
  355. }
  356. }
  357. // If property Is_internal is set, prepend pkgPath with internalPath
  358. if proptools.BoolDefault(p.properties.Is_internal, false) {
  359. pkgPath = filepath.Join(internalPath, pkgPath)
  360. }
  361. // generate src:destination path mappings for this module
  362. p.genModulePathMappings(ctx, pkgPath, expandedSrcs, expandedData)
  363. // generate the zipfile of all source and data files
  364. p.srcsZip = p.createSrcsZip(ctx, pkgPath)
  365. p.precompiledSrcsZip = p.precompileSrcs(ctx)
  366. }
  367. func isValidPythonPath(path string) error {
  368. identifiers := strings.Split(strings.TrimSuffix(path, filepath.Ext(path)), "/")
  369. for _, token := range identifiers {
  370. if !pathComponentRegexp.MatchString(token) {
  371. return fmt.Errorf("the path %q contains invalid subpath %q. "+
  372. "Subpaths must be at least one character long. "+
  373. "The first character must an underscore or letter. "+
  374. "Following characters may be any of: letter, digit, underscore, hyphen.",
  375. path, token)
  376. }
  377. }
  378. return nil
  379. }
  380. // For this module, generate unique pathMappings: <dest: runfiles_path, src: source_path>
  381. // for python/data files expanded from properties.
  382. func (p *PythonLibraryModule) genModulePathMappings(ctx android.ModuleContext, pkgPath string,
  383. expandedSrcs, expandedData android.Paths) {
  384. // fetch <runfiles_path, source_path> pairs from "src" and "data" properties to
  385. // check current module duplicates.
  386. destToPySrcs := make(map[string]string)
  387. destToPyData := make(map[string]string)
  388. for _, s := range expandedSrcs {
  389. if s.Ext() != pyExt && s.Ext() != protoExt {
  390. ctx.PropertyErrorf("srcs", "found non (.py|.proto) file: %q!", s.String())
  391. continue
  392. }
  393. runfilesPath := filepath.Join(pkgPath, s.Rel())
  394. if err := isValidPythonPath(runfilesPath); err != nil {
  395. ctx.PropertyErrorf("srcs", err.Error())
  396. }
  397. if !checkForDuplicateOutputPath(ctx, destToPySrcs, runfilesPath, s.String(), p.Name(), p.Name()) {
  398. p.srcsPathMappings = append(p.srcsPathMappings, pathMapping{dest: runfilesPath, src: s})
  399. }
  400. }
  401. for _, d := range expandedData {
  402. if d.Ext() == pyExt || d.Ext() == protoExt {
  403. ctx.PropertyErrorf("data", "found (.py|.proto) file: %q!", d.String())
  404. continue
  405. }
  406. runfilesPath := filepath.Join(pkgPath, d.Rel())
  407. if !checkForDuplicateOutputPath(ctx, destToPyData, runfilesPath, d.String(), p.Name(), p.Name()) {
  408. p.dataPathMappings = append(p.dataPathMappings,
  409. pathMapping{dest: runfilesPath, src: d})
  410. }
  411. }
  412. }
  413. // createSrcsZip registers build actions to zip current module's sources and data.
  414. func (p *PythonLibraryModule) createSrcsZip(ctx android.ModuleContext, pkgPath string) android.Path {
  415. relativeRootMap := make(map[string]android.Paths)
  416. var protoSrcs android.Paths
  417. addPathMapping := func(path pathMapping) {
  418. // handle proto sources separately
  419. if path.src.Ext() == protoExt {
  420. protoSrcs = append(protoSrcs, path.src)
  421. } else {
  422. relativeRoot := strings.TrimSuffix(path.src.String(), path.src.Rel())
  423. relativeRootMap[relativeRoot] = append(relativeRootMap[relativeRoot], path.src)
  424. }
  425. }
  426. // "srcs" or "data" properties may contain filegroups so it might happen that
  427. // the root directory for each source path is different.
  428. for _, path := range p.srcsPathMappings {
  429. addPathMapping(path)
  430. }
  431. for _, path := range p.dataPathMappings {
  432. addPathMapping(path)
  433. }
  434. var zips android.Paths
  435. if len(protoSrcs) > 0 {
  436. protoFlags := android.GetProtoFlags(ctx, &p.protoProperties)
  437. protoFlags.OutTypeFlag = "--python_out"
  438. if pkgPath != "" {
  439. pkgPathStagingDir := android.PathForModuleGen(ctx, "protos_staged_for_pkg_path")
  440. rule := android.NewRuleBuilder(pctx, ctx)
  441. var stagedProtoSrcs android.Paths
  442. for _, srcFile := range protoSrcs {
  443. stagedProtoSrc := pkgPathStagingDir.Join(ctx, pkgPath, srcFile.Rel())
  444. rule.Command().Text("mkdir -p").Flag(filepath.Base(stagedProtoSrc.String()))
  445. rule.Command().Text("cp -f").Input(srcFile).Output(stagedProtoSrc)
  446. stagedProtoSrcs = append(stagedProtoSrcs, stagedProtoSrc)
  447. }
  448. rule.Build("stage_protos_for_pkg_path", "Stage protos for pkg_path")
  449. protoSrcs = stagedProtoSrcs
  450. }
  451. for _, srcFile := range protoSrcs {
  452. zip := genProto(ctx, srcFile, protoFlags)
  453. zips = append(zips, zip)
  454. }
  455. }
  456. if len(relativeRootMap) > 0 {
  457. // in order to keep stable order of soong_zip params, we sort the keys here.
  458. roots := android.SortedStringKeys(relativeRootMap)
  459. // Use -symlinks=false so that the symlinks in the bazel output directory are followed
  460. parArgs := []string{"-symlinks=false"}
  461. if pkgPath != "" {
  462. // use package path as path prefix
  463. parArgs = append(parArgs, `-P `+pkgPath)
  464. }
  465. paths := android.Paths{}
  466. for _, root := range roots {
  467. // specify relative root of file in following -f arguments
  468. parArgs = append(parArgs, `-C `+root)
  469. for _, path := range relativeRootMap[root] {
  470. parArgs = append(parArgs, `-f `+path.String())
  471. paths = append(paths, path)
  472. }
  473. }
  474. origSrcsZip := android.PathForModuleOut(ctx, ctx.ModuleName()+".py.srcszip")
  475. ctx.Build(pctx, android.BuildParams{
  476. Rule: zip,
  477. Description: "python library archive",
  478. Output: origSrcsZip,
  479. // as zip rule does not use $in, there is no real need to distinguish between Inputs and Implicits
  480. Implicits: paths,
  481. Args: map[string]string{
  482. "args": strings.Join(parArgs, " "),
  483. },
  484. })
  485. zips = append(zips, origSrcsZip)
  486. }
  487. // we may have multiple zips due to separate handling of proto source files
  488. if len(zips) == 1 {
  489. return zips[0]
  490. } else {
  491. combinedSrcsZip := android.PathForModuleOut(ctx, ctx.ModuleName()+".srcszip")
  492. ctx.Build(pctx, android.BuildParams{
  493. Rule: combineZip,
  494. Description: "combine python library archive",
  495. Output: combinedSrcsZip,
  496. Inputs: zips,
  497. })
  498. return combinedSrcsZip
  499. }
  500. }
  501. func (p *PythonLibraryModule) precompileSrcs(ctx android.ModuleContext) android.Path {
  502. // To precompile the python sources, we need a python interpreter and stdlib built
  503. // for host. We then use those to compile the python sources, which may be used on either
  504. // host of device. Python bytecode is architecture agnostic, so we're essentially
  505. // "cross compiling" for device here purely by virtue of host and device python bytecode
  506. // being the same.
  507. var stdLib android.Path
  508. var launcher android.Path
  509. if ctx.ModuleName() == "py3-stdlib" || ctx.ModuleName() == "py2-stdlib" {
  510. stdLib = p.srcsZip
  511. } else {
  512. ctx.VisitDirectDepsWithTag(hostStdLibTag, func(module android.Module) {
  513. if dep, ok := module.(pythonDependency); ok {
  514. stdLib = dep.getPrecompiledSrcsZip()
  515. }
  516. })
  517. }
  518. ctx.VisitDirectDepsWithTag(hostLauncherTag, func(module android.Module) {
  519. if dep, ok := module.(IntermPathProvider); ok {
  520. optionalLauncher := dep.IntermPathForModuleOut()
  521. if optionalLauncher.Valid() {
  522. launcher = optionalLauncher.Path()
  523. }
  524. }
  525. })
  526. var launcherSharedLibs android.Paths
  527. var ldLibraryPath []string
  528. ctx.VisitDirectDepsWithTag(hostlauncherSharedLibTag, func(module android.Module) {
  529. if dep, ok := module.(IntermPathProvider); ok {
  530. optionalPath := dep.IntermPathForModuleOut()
  531. if optionalPath.Valid() {
  532. launcherSharedLibs = append(launcherSharedLibs, optionalPath.Path())
  533. ldLibraryPath = append(ldLibraryPath, filepath.Dir(optionalPath.Path().String()))
  534. }
  535. }
  536. })
  537. out := android.PathForModuleOut(ctx, ctx.ModuleName()+".srcszipprecompiled")
  538. if stdLib == nil || launcher == nil {
  539. // This shouldn't happen in a real build because we'll error out when adding dependencies
  540. // on the stdlib and launcher if they don't exist. But some tests set
  541. // AllowMissingDependencies.
  542. return out
  543. }
  544. ctx.Build(pctx, android.BuildParams{
  545. Rule: precompile,
  546. Input: p.srcsZip,
  547. Output: out,
  548. Implicits: launcherSharedLibs,
  549. Description: "Precompile the python sources of " + ctx.ModuleName(),
  550. Args: map[string]string{
  551. "stdlibZip": stdLib.String(),
  552. "launcher": launcher.String(),
  553. "ldLibraryPath": strings.Join(ldLibraryPath, ":"),
  554. },
  555. })
  556. return out
  557. }
  558. // isPythonLibModule returns whether the given module is a Python library PythonLibraryModule or not
  559. func isPythonLibModule(module blueprint.Module) bool {
  560. if _, ok := module.(*PythonLibraryModule); ok {
  561. if _, ok := module.(*PythonBinaryModule); !ok {
  562. return true
  563. }
  564. }
  565. return false
  566. }
  567. // collectPathsFromTransitiveDeps checks for source/data files for duplicate paths
  568. // for module and its transitive dependencies and collects list of data/source file
  569. // zips for transitive dependencies.
  570. func (p *PythonLibraryModule) collectPathsFromTransitiveDeps(ctx android.ModuleContext, precompiled bool) android.Paths {
  571. // fetch <runfiles_path, source_path> pairs from "src" and "data" properties to
  572. // check duplicates.
  573. destToPySrcs := make(map[string]string)
  574. destToPyData := make(map[string]string)
  575. for _, path := range p.srcsPathMappings {
  576. destToPySrcs[path.dest] = path.src.String()
  577. }
  578. for _, path := range p.dataPathMappings {
  579. destToPyData[path.dest] = path.src.String()
  580. }
  581. seen := make(map[android.Module]bool)
  582. var result android.Paths
  583. // visit all its dependencies in depth first.
  584. ctx.WalkDeps(func(child, parent android.Module) bool {
  585. // we only collect dependencies tagged as python library deps
  586. if ctx.OtherModuleDependencyTag(child) != pythonLibTag {
  587. return false
  588. }
  589. if seen[child] {
  590. return false
  591. }
  592. seen[child] = true
  593. // Python modules only can depend on Python libraries.
  594. if !isPythonLibModule(child) {
  595. ctx.PropertyErrorf("libs",
  596. "the dependency %q of module %q is not Python library!",
  597. ctx.OtherModuleName(child), ctx.ModuleName())
  598. }
  599. // collect source and data paths, checking that there are no duplicate output file conflicts
  600. if dep, ok := child.(pythonDependency); ok {
  601. srcs := dep.getSrcsPathMappings()
  602. for _, path := range srcs {
  603. checkForDuplicateOutputPath(ctx, destToPySrcs,
  604. path.dest, path.src.String(), ctx.ModuleName(), ctx.OtherModuleName(child))
  605. }
  606. data := dep.getDataPathMappings()
  607. for _, path := range data {
  608. checkForDuplicateOutputPath(ctx, destToPyData,
  609. path.dest, path.src.String(), ctx.ModuleName(), ctx.OtherModuleName(child))
  610. }
  611. if precompiled {
  612. result = append(result, dep.getPrecompiledSrcsZip())
  613. } else {
  614. result = append(result, dep.getSrcsZip())
  615. }
  616. }
  617. return true
  618. })
  619. return result
  620. }
  621. // chckForDuplicateOutputPath checks whether outputPath has already been included in map m, which
  622. // would result in two files being placed in the same location.
  623. // If there is a duplicate path, an error is thrown and true is returned
  624. // Otherwise, outputPath: srcPath is added to m and returns false
  625. func checkForDuplicateOutputPath(ctx android.ModuleContext, m map[string]string, outputPath, srcPath, curModule, otherModule string) bool {
  626. if oldSrcPath, found := m[outputPath]; found {
  627. ctx.ModuleErrorf("found two files to be placed at the same location within zip %q."+
  628. " First file: in module %s at path %q."+
  629. " Second file: in module %s at path %q.",
  630. outputPath, curModule, oldSrcPath, otherModule, srcPath)
  631. return true
  632. }
  633. m[outputPath] = srcPath
  634. return false
  635. }
  636. // InstallInData returns true as Python is not supported in the system partition
  637. func (p *PythonLibraryModule) InstallInData() bool {
  638. return true
  639. }
  640. var Bool = proptools.Bool
  641. var BoolDefault = proptools.BoolDefault
  642. var String = proptools.String