blob: 7af8d9d185b421669a1cf3fc95469811236121a1 [file] [log] [blame]
Nan Zhangdb0b9a32017-02-27 10:12:13 -08001// 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
15package python
16
17// This file contains the "Base" module type for building Python program.
18
19import (
20 "fmt"
21 "path/filepath"
22 "regexp"
Brett Brotherton8c7c65e2025-03-12 20:56:07 -070023 "sort"
Nan Zhangdb0b9a32017-02-27 10:12:13 -080024 "strings"
25
Yu Liue98f7062025-01-17 22:52:43 +000026 "android/soong/cc"
Cole Faustd85c6772025-01-31 10:54:46 -080027
Nan Zhangdb0b9a32017-02-27 10:12:13 -080028 "github.com/google/blueprint"
Brett Brotherton8c7c65e2025-03-12 20:56:07 -070029 "github.com/google/blueprint/depset"
Nan Zhangd4e641b2017-07-12 12:55:28 -070030 "github.com/google/blueprint/proptools"
Nan Zhangdb0b9a32017-02-27 10:12:13 -080031
32 "android/soong/android"
33)
34
Yu Liue98f7062025-01-17 22:52:43 +000035type PythonLibraryInfo struct {
36 SrcsPathMappings []pathMapping
37 DataPathMappings []pathMapping
38 SrcsZip android.Path
39 PrecompiledSrcsZip android.Path
40 PkgPath string
Brett Brotherton8c7c65e2025-03-12 20:56:07 -070041 BundleSharedLibs android.Paths
Yu Liue98f7062025-01-17 22:52:43 +000042}
43
44var PythonLibraryInfoProvider = blueprint.NewProvider[PythonLibraryInfo]()
45
Liz Kammerd737d022020-11-16 15:42:51 -080046// the version-specific properties that apply to python modules.
Nan Zhangd4e641b2017-07-12 12:55:28 -070047type VersionProperties struct {
Liz Kammerd737d022020-11-16 15:42:51 -080048 // whether the module is required to be built with this version.
49 // Defaults to true for Python 3, and false otherwise.
Liz Kammer59c0eae2021-09-17 17:48:05 -040050 Enabled *bool
Nan Zhangdb0b9a32017-02-27 10:12:13 -080051
Liz Kammerd737d022020-11-16 15:42:51 -080052 // list of source files specific to this Python version.
53 // Using the syntax ":module", srcs may reference the outputs of other modules that produce source files,
54 // e.g. genrule or filegroup.
Colin Cross27b922f2019-03-04 22:35:41 -080055 Srcs []string `android:"path,arch_variant"`
Nan Zhangd4e641b2017-07-12 12:55:28 -070056
Liz Kammerd737d022020-11-16 15:42:51 -080057 // list of source files that should not be used to build the Python module for this version.
58 // This is most useful to remove files that are not common to all Python versions.
Colin Cross27b922f2019-03-04 22:35:41 -080059 Exclude_srcs []string `android:"path,arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080060
Liz Kammerd737d022020-11-16 15:42:51 -080061 // list of the Python libraries used only for this Python version.
Nan Zhangd4e641b2017-07-12 12:55:28 -070062 Libs []string `android:"arch_variant"`
63
Cole Faustf09101e2024-04-18 18:33:15 +000064 // whether the binary is required to be built with embedded launcher for this version, defaults to true.
Liz Kammer59c0eae2021-09-17 17:48:05 -040065 Embedded_launcher *bool // TODO(b/174041232): Remove this property
Nan Zhangdb0b9a32017-02-27 10:12:13 -080066}
67
Liz Kammerd737d022020-11-16 15:42:51 -080068// properties that apply to all python modules
Nan Zhangd4e641b2017-07-12 12:55:28 -070069type BaseProperties struct {
Nan Zhangdb0b9a32017-02-27 10:12:13 -080070 // the package path prefix within the output artifact at which to place the source/data
71 // files of the current module.
72 // eg. Pkg_path = "a/b/c"; Other packages can reference this module by using
73 // (from a.b.c import ...) statement.
Nan Zhangbea09752018-05-31 12:49:33 -070074 // if left unspecified, all the source/data files path is unchanged within zip file.
Liz Kammer59c0eae2021-09-17 17:48:05 -040075 Pkg_path *string
Nan Zhangd4e641b2017-07-12 12:55:28 -070076
77 // true, if the Python module is used internally, eg, Python std libs.
Liz Kammer59c0eae2021-09-17 17:48:05 -040078 Is_internal *bool
Nan Zhangdb0b9a32017-02-27 10:12:13 -080079
80 // list of source (.py) files compatible both with Python2 and Python3 used to compile the
81 // Python module.
82 // srcs may reference the outputs of other modules that produce source files like genrule
83 // or filegroup using the syntax ":module".
84 // Srcs has to be non-empty.
Colin Cross27b922f2019-03-04 22:35:41 -080085 Srcs []string `android:"path,arch_variant"`
Nan Zhangd4e641b2017-07-12 12:55:28 -070086
87 // list of source files that should not be used to build the C/C++ module.
88 // This is most useful in the arch/multilib variants to remove non-common files
Colin Cross27b922f2019-03-04 22:35:41 -080089 Exclude_srcs []string `android:"path,arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080090
91 // list of files or filegroup modules that provide data that should be installed alongside
92 // the test. the file extension can be arbitrary except for (.py).
Colin Cross27b922f2019-03-04 22:35:41 -080093 Data []string `android:"path,arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080094
Cole Faust65cb40a2024-10-21 15:41:42 -070095 // Same as data, but will add dependencies on modules using the device's os variation and
96 // the common arch variation. Useful for a host test that wants to embed a module built for
97 // device.
98 Device_common_data []string `android:"path_device_common"`
99
Inseob Kim25f5ae42025-01-07 22:27:58 +0900100 // Same as data, but will add dependencies on modules via a device os variation and the
101 // device's first supported arch's variation. Useful for a host test that wants to embed a
102 // module built for device.
103 Device_first_data []string `android:"path_device_first"`
104
Colin Cross1bc63932020-11-22 20:12:45 -0800105 // list of java modules that provide data that should be installed alongside the test.
106 Java_data []string
107
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800108 // list of the Python libraries compatible both with Python2 and Python3.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700109 Libs []string `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800110
Brett Brotherton8c7c65e2025-03-12 20:56:07 -0700111 // list of shared libraries that should be packaged with the python code for this module.
112 Shared_libs []string `android:"arch_variant"`
113
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800114 Version struct {
Liz Kammerd737d022020-11-16 15:42:51 -0800115 // Python2-specific properties, including whether Python2 is supported for this module
116 // and version-specific sources, exclusions and dependencies.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700117 Py2 VersionProperties `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800118
Liz Kammerd737d022020-11-16 15:42:51 -0800119 // Python3-specific properties, including whether Python3 is supported for this module
120 // and version-specific sources, exclusions and dependencies.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700121 Py3 VersionProperties `android:"arch_variant"`
122 } `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800123
Cole Faustd85c6772025-01-31 10:54:46 -0800124 // This enabled property is to accept the collapsed enabled property from the VersionProperties.
125 // It is unused now, as all builds should be python3.
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700126 Enabled *bool `blueprint:"mutated"`
127
Cole Faustd85c6772025-01-31 10:54:46 -0800128 // whether the binary is required to be built with an embedded python interpreter, defaults to
129 // true. This allows taking the resulting binary outside of the build and running it on machines
130 // that don't have python installed or may have an older version of python.
131 Embedded_launcher *bool
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800132}
133
Liz Kammerd737d022020-11-16 15:42:51 -0800134// Used to store files of current module after expanding dependencies
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800135type pathMapping struct {
136 dest string
137 src android.Path
138}
139
Cole Faust4d247e62023-01-23 10:14:58 -0800140type PythonLibraryModule struct {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800141 android.ModuleBase
Nan Zhanga3fc4ba2017-07-20 17:43:37 -0700142 android.DefaultableModuleBase
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800143
Nan Zhangb8fa1972017-12-22 16:12:00 -0800144 properties BaseProperties
145 protoProperties android.ProtoProperties
Nan Zhangd4e641b2017-07-12 12:55:28 -0700146
147 // initialize before calling Init
148 hod android.HostOrDeviceSupported
149 multilib android.Multilib
150
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800151 // the Python files of current module after expanding source dependencies.
152 // pathMapping: <dest: runfile_path, src: source_path>
153 srcsPathMappings []pathMapping
154
155 // the data files of current module after expanding source dependencies.
156 // pathMapping: <dest: runfile_path, src: source_path>
157 dataPathMappings []pathMapping
158
Cole Faust5c503d12023-01-24 11:48:08 -0800159 // The zip file containing the current module's source/data files.
Nan Zhang1db85402017-12-18 13:20:23 -0800160 srcsZip android.Path
Cole Faust5c503d12023-01-24 11:48:08 -0800161
162 // The zip file containing the current module's source/data files, with the
163 // source files precompiled.
164 precompiledSrcsZip android.Path
Ronald Braunsteinc4cd7a12024-04-16 16:39:48 -0700165
166 sourceProperties android.SourceProperties
Brett Brotherton8c7c65e2025-03-12 20:56:07 -0700167
168 // The shared libraries that should be bundled with the python code for
169 // any standalone python binaries that depend on this module.
170 bundleSharedLibs android.Paths
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800171}
172
Liz Kammerd737d022020-11-16 15:42:51 -0800173// newModule generates new Python base module
Cole Faust4d247e62023-01-23 10:14:58 -0800174func newModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *PythonLibraryModule {
175 return &PythonLibraryModule{
Nan Zhangd4e641b2017-07-12 12:55:28 -0700176 hod: hod,
177 multilib: multilib,
178 }
179}
180
Liz Kammerd737d022020-11-16 15:42:51 -0800181// getSrcsPathMappings gets this module's path mapping of src source path : runfiles destination
Cole Faust4d247e62023-01-23 10:14:58 -0800182func (p *PythonLibraryModule) getSrcsPathMappings() []pathMapping {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800183 return p.srcsPathMappings
184}
185
Liz Kammerd737d022020-11-16 15:42:51 -0800186// getSrcsPathMappings gets this module's path mapping of data source path : runfiles destination
Cole Faust4d247e62023-01-23 10:14:58 -0800187func (p *PythonLibraryModule) getDataPathMappings() []pathMapping {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800188 return p.dataPathMappings
189}
190
Liz Kammerd737d022020-11-16 15:42:51 -0800191// getSrcsZip returns the filepath where the current module's source/data files are zipped.
Cole Faust4d247e62023-01-23 10:14:58 -0800192func (p *PythonLibraryModule) getSrcsZip() android.Path {
Nan Zhang1db85402017-12-18 13:20:23 -0800193 return p.srcsZip
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800194}
195
Cole Faust5c503d12023-01-24 11:48:08 -0800196// getSrcsZip returns the filepath where the current module's source/data files are zipped.
197func (p *PythonLibraryModule) getPrecompiledSrcsZip() android.Path {
198 return p.precompiledSrcsZip
199}
200
Dan Willemsen339a63f2023-08-15 22:17:03 -0400201// getPkgPath returns the pkg_path value
202func (p *PythonLibraryModule) getPkgPath() string {
203 return String(p.properties.Pkg_path)
204}
205
Cole Faust4d247e62023-01-23 10:14:58 -0800206func (p *PythonLibraryModule) getBaseProperties() *BaseProperties {
207 return &p.properties
208}
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800209
Brett Brotherton8c7c65e2025-03-12 20:56:07 -0700210func (p *PythonLibraryModule) getBundleSharedLibs() android.Paths {
211 return p.bundleSharedLibs
212}
213
Cole Faust4d247e62023-01-23 10:14:58 -0800214func (p *PythonLibraryModule) init() android.Module {
Ronald Braunsteinc4cd7a12024-04-16 16:39:48 -0700215 p.AddProperties(&p.properties, &p.protoProperties, &p.sourceProperties)
Nan Zhangd4e641b2017-07-12 12:55:28 -0700216 android.InitAndroidArchModule(p, p.hod, p.multilib)
Nan Zhanga3fc4ba2017-07-20 17:43:37 -0700217 android.InitDefaultableModule(p)
Nan Zhangd4e641b2017-07-12 12:55:28 -0700218 return p
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800219}
220
Liz Kammerd737d022020-11-16 15:42:51 -0800221// Python-specific tag to transfer information on the purpose of a dependency.
222// This is used when adding a dependency on a module, which can later be accessed when visiting
223// dependencies.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700224type dependencyTag struct {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800225 blueprint.BaseDependencyTag
Nan Zhangd4e641b2017-07-12 12:55:28 -0700226 name string
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800227}
228
Liz Kammerd737d022020-11-16 15:42:51 -0800229// Python-specific tag that indicates that installed files of this module should depend on installed
230// files of the dependency
Colin Crosse9fe2942020-11-10 18:12:15 -0800231type installDependencyTag struct {
232 blueprint.BaseDependencyTag
Liz Kammerd737d022020-11-16 15:42:51 -0800233 // embedding this struct provides the installation dependency requirement
Colin Crosse9fe2942020-11-10 18:12:15 -0800234 android.InstallAlwaysNeededDependencyTag
235 name string
236}
237
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800238var (
Cole Faust5c503d12023-01-24 11:48:08 -0800239 pythonLibTag = dependencyTag{name: "pythonLib"}
240 javaDataTag = dependencyTag{name: "javaData"}
Brett Brotherton8c7c65e2025-03-12 20:56:07 -0700241 sharedLibTag = dependencyTag{name: "sharedLib"}
Cole Faust5c503d12023-01-24 11:48:08 -0800242 // The python interpreter, with soong module name "py3-launcher" or "py3-launcher-autorun".
Cole Faust909d2372023-02-13 23:17:40 +0000243 launcherTag = dependencyTag{name: "launcher"}
244 launcherSharedLibTag = installDependencyTag{name: "launcherSharedLib"}
Cole Faust5c503d12023-01-24 11:48:08 -0800245 // The python interpreter built for host so that we can precompile python sources.
246 // This only works because the precompiled sources don't vary by architecture.
247 // The soong module name is "py3-launcher".
Cole Faust909d2372023-02-13 23:17:40 +0000248 hostLauncherTag = dependencyTag{name: "hostLauncher"}
249 hostlauncherSharedLibTag = dependencyTag{name: "hostlauncherSharedLib"}
250 hostStdLibTag = dependencyTag{name: "hostStdLib"}
251 pathComponentRegexp = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`)
252 pyExt = ".py"
253 protoExt = ".proto"
Cole Faust909d2372023-02-13 23:17:40 +0000254 internalPath = "internal"
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800255)
256
Cole Faust4d247e62023-01-23 10:14:58 -0800257type basePropertiesProvider interface {
258 getBaseProperties() *BaseProperties
259}
260
Liz Kammerd737d022020-11-16 15:42:51 -0800261func anyHasExt(paths []string, ext string) bool {
262 for _, p := range paths {
263 if filepath.Ext(p) == ext {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800264 return true
265 }
266 }
267
268 return false
269}
270
Cole Faust4d247e62023-01-23 10:14:58 -0800271func (p *PythonLibraryModule) anySrcHasExt(ctx android.BottomUpMutatorContext, ext string) bool {
Liz Kammerd737d022020-11-16 15:42:51 -0800272 return anyHasExt(p.properties.Srcs, ext)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800273}
274
Liz Kammerd737d022020-11-16 15:42:51 -0800275// DepsMutator mutates dependencies for this module:
Colin Crossd079e0b2022-08-16 10:27:33 -0700276// - handles proto dependencies,
277// - if required, specifies launcher and adds launcher dependencies,
278// - applies python version mutations to Python dependencies
Cole Faust4d247e62023-01-23 10:14:58 -0800279func (p *PythonLibraryModule) DepsMutator(ctx android.BottomUpMutatorContext) {
Cole Faustd85c6772025-01-31 10:54:46 -0800280 // Flatten the version.py3 props down into the main property struct. Leftover from when
281 // there was both python2 and 3 in the build, and properties could be different between them.
282 if base, ok := ctx.Module().(basePropertiesProvider); ok {
283 props := base.getBaseProperties()
Colin Crossfe17f6f2019-03-28 19:30:56 -0700284
Cole Faustd85c6772025-01-31 10:54:46 -0800285 err := proptools.AppendMatchingProperties([]interface{}{props}, &props.Version.Py3, nil)
286 if err != nil {
287 panic(err)
288 }
Nan Zhangb8fa1972017-12-22 16:12:00 -0800289 }
Colin Crosse20113d2020-11-22 19:37:44 -0800290
Cole Faustd85c6772025-01-31 10:54:46 -0800291 android.ProtoDeps(ctx, &p.protoProperties)
292
Liz Kammerd737d022020-11-16 15:42:51 -0800293 // If sources contain a proto file, add dependency on libprotobuf-python
294 if p.anySrcHasExt(ctx, protoExt) && p.Name() != "libprotobuf-python" {
Cole Faustd85c6772025-01-31 10:54:46 -0800295 ctx.AddDependency(ctx.Module(), pythonLibTag, "libprotobuf-python")
Colin Crosse20113d2020-11-22 19:37:44 -0800296 }
Liz Kammerd737d022020-11-16 15:42:51 -0800297
298 // Add python library dependencies for this python version variation
Cole Faustd85c6772025-01-31 10:54:46 -0800299 ctx.AddDependency(ctx.Module(), pythonLibTag, android.LastUniqueStrings(p.properties.Libs)...)
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700300
Colin Cross1bc63932020-11-22 20:12:45 -0800301 // Emulate the data property for java_data but with the arch variation overridden to "common"
302 // so that it can point to java modules.
303 javaDataVariation := []blueprint.Variation{{"arch", android.Common.String()}}
304 ctx.AddVariationDependencies(javaDataVariation, javaDataTag, p.properties.Java_data...)
Cole Faust5c503d12023-01-24 11:48:08 -0800305
Brett Brotherton8c7c65e2025-03-12 20:56:07 -0700306 if ctx.Host() {
307 ctx.AddVariationDependencies(ctx.Config().BuildOSTarget.Variations(), sharedLibTag, p.properties.Shared_libs...)
308 } else if len(p.properties.Shared_libs) > 0 {
309 ctx.PropertyErrorf("shared_libs", "shared_libs is not supported for device builds")
310 }
311
Cole Faust909d2372023-02-13 23:17:40 +0000312 p.AddDepsOnPythonLauncherAndStdlib(ctx, hostStdLibTag, hostLauncherTag, hostlauncherSharedLibTag, false, ctx.Config().BuildOSTarget)
Cole Faust5c503d12023-01-24 11:48:08 -0800313}
314
Cole Faust909d2372023-02-13 23:17:40 +0000315// AddDepsOnPythonLauncherAndStdlib will make the current module depend on the python stdlib,
316// launcher (interpreter), and the launcher's shared libraries. If autorun is true, it will use
317// the autorun launcher instead of the regular one. This function acceps a targetForDeps argument
318// as the target to use for these dependencies. For embedded launcher python binaries, the launcher
319// that will be embedded will be under the same target as the python module itself. But when
320// precompiling python code, we need to get the python launcher built for host, even if we're
321// compiling the python module for device, so we pass a different target to this function.
Cole Faust5c503d12023-01-24 11:48:08 -0800322func (p *PythonLibraryModule) AddDepsOnPythonLauncherAndStdlib(ctx android.BottomUpMutatorContext,
Cole Faust909d2372023-02-13 23:17:40 +0000323 stdLibTag, launcherTag, launcherSharedLibTag blueprint.DependencyTag,
Cole Faust5c503d12023-01-24 11:48:08 -0800324 autorun bool, targetForDeps android.Target) {
325 var stdLib string
326 var launcherModule string
Cole Faust909d2372023-02-13 23:17:40 +0000327 // Add launcher shared lib dependencies. Ideally, these should be
328 // derived from the `shared_libs` property of the launcher. TODO: read these from
329 // the python launcher itself using ctx.OtherModuleProvider() or similar on the result
330 // of ctx.AddFarVariationDependencies()
331 launcherSharedLibDeps := []string{
332 "libsqlite",
333 }
334 // Add launcher-specific dependencies for bionic
335 if targetForDeps.Os.Bionic() {
336 launcherSharedLibDeps = append(launcherSharedLibDeps, "libc", "libdl", "libm")
337 }
338 if targetForDeps.Os == android.LinuxMusl && !ctx.Config().HostStaticBinaries() {
339 launcherSharedLibDeps = append(launcherSharedLibDeps, "libc_musl")
340 }
Cole Faust5c503d12023-01-24 11:48:08 -0800341
Cole Faustd85c6772025-01-31 10:54:46 -0800342 var prebuiltStdLib bool
343 if targetForDeps.Os.Bionic() {
344 prebuiltStdLib = false
345 } else if ctx.Config().VendorConfig("cpython3").Bool("force_build_host") {
346 prebuiltStdLib = false
347 } else {
348 prebuiltStdLib = true
Cole Faust5c503d12023-01-24 11:48:08 -0800349 }
Cole Faustd85c6772025-01-31 10:54:46 -0800350
351 if prebuiltStdLib {
352 stdLib = "py3-stdlib-prebuilt"
353 } else {
354 stdLib = "py3-stdlib"
355 }
356
357 launcherModule = "py3-launcher"
358 if autorun {
359 launcherModule = "py3-launcher-autorun"
360 }
361 if ctx.Config().HostStaticBinaries() && targetForDeps.Os == android.LinuxMusl {
362 launcherModule += "-static"
363 }
364 if ctx.Device() {
365 launcherSharedLibDeps = append(launcherSharedLibDeps, "liblog")
366 }
367
Cole Faust5c503d12023-01-24 11:48:08 -0800368 targetVariations := targetForDeps.Variations()
369 if ctx.ModuleName() != stdLib {
Cole Faust5c503d12023-01-24 11:48:08 -0800370 // Using AddFarVariationDependencies for all of these because they can be for a different
371 // platform, like if the python module itself was being compiled for device, we may want
372 // the python interpreter built for host so that we can precompile python sources.
Cole Faustd85c6772025-01-31 10:54:46 -0800373 ctx.AddFarVariationDependencies(targetVariations, stdLibTag, stdLib)
Cole Faust5c503d12023-01-24 11:48:08 -0800374 }
375 ctx.AddFarVariationDependencies(targetVariations, launcherTag, launcherModule)
Cole Faust909d2372023-02-13 23:17:40 +0000376 ctx.AddFarVariationDependencies(targetVariations, launcherSharedLibTag, launcherSharedLibDeps...)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800377}
378
Cole Faust4d247e62023-01-23 10:14:58 -0800379// GenerateAndroidBuildActions performs build actions common to all Python modules
380func (p *PythonLibraryModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Cole Faustd85c6772025-01-31 10:54:46 -0800381 if proptools.BoolDefault(p.properties.Version.Py2.Enabled, false) {
382 ctx.PropertyErrorf("version.py2.enabled", "Python 2 is no longer supported, please convert to python 3.")
383 }
Liz Kammerd737d022020-11-16 15:42:51 -0800384 expandedSrcs := android.PathsForModuleSrcExcludes(ctx, p.properties.Srcs, p.properties.Exclude_srcs)
Ronald Braunsteinc4cd7a12024-04-16 16:39:48 -0700385 // Keep before any early returns.
386 android.SetProvider(ctx, android.TestOnlyProviderKey, android.TestModuleInformation{
387 TestOnly: Bool(p.sourceProperties.Test_only),
388 TopLevelTarget: p.sourceProperties.Top_level_test_target,
389 })
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800390
391 // expand data files from "data" property.
Colin Cross8a497952019-03-05 22:25:09 -0800392 expandedData := android.PathsForModuleSrc(ctx, p.properties.Data)
Cole Faust65cb40a2024-10-21 15:41:42 -0700393 expandedData = append(expandedData, android.PathsForModuleSrc(ctx, p.properties.Device_common_data)...)
Inseob Kim25f5ae42025-01-07 22:27:58 +0900394 expandedData = append(expandedData, android.PathsForModuleSrc(ctx, p.properties.Device_first_data)...)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800395
Colin Cross1bc63932020-11-22 20:12:45 -0800396 // Emulate the data property for java_data dependencies.
Yu Liue98f7062025-01-17 22:52:43 +0000397 for _, javaData := range ctx.GetDirectDepsProxyWithTag(javaDataTag) {
Colin Cross1bc63932020-11-22 20:12:45 -0800398 expandedData = append(expandedData, android.OutputFilesForModule(ctx, javaData, "")...)
399 }
400
Brett Brotherton8c7c65e2025-03-12 20:56:07 -0700401 var directImplementationDeps android.Paths
402 var transitiveImplementationDeps []depset.DepSet[android.Path]
403 ctx.VisitDirectDepsProxyWithTag(sharedLibTag, func(dep android.ModuleProxy) {
404 sharedLibInfo, _ := android.OtherModuleProvider(ctx, dep, cc.SharedLibraryInfoProvider)
405 if sharedLibInfo.SharedLibrary != nil {
406 expandedData = append(expandedData, android.OutputFilesForModule(ctx, dep, "")...)
407 directImplementationDeps = append(directImplementationDeps, android.OutputFilesForModule(ctx, dep, "")...)
408 if info, ok := android.OtherModuleProvider(ctx, dep, cc.ImplementationDepInfoProvider); ok {
409 transitiveImplementationDeps = append(transitiveImplementationDeps, info.ImplementationDeps)
410 p.bundleSharedLibs = append(p.bundleSharedLibs, info.ImplementationDeps.ToList()...)
411 }
412 } else {
413 ctx.PropertyErrorf("shared_libs", "%q of type %q is not supported", dep.Name(), ctx.OtherModuleType(dep))
414 }
415 })
416 android.SetProvider(ctx, cc.ImplementationDepInfoProvider, &cc.ImplementationDepInfo{
417 ImplementationDeps: depset.New(depset.PREORDER, directImplementationDeps, transitiveImplementationDeps),
418 })
419
Liz Kammerd737d022020-11-16 15:42:51 -0800420 // Validate pkg_path property
Nan Zhang1db85402017-12-18 13:20:23 -0800421 pkgPath := String(p.properties.Pkg_path)
422 if pkgPath != "" {
Liz Kammerd737d022020-11-16 15:42:51 -0800423 // TODO: export validation from android/paths.go handling to replace this duplicated functionality
Nan Zhang1db85402017-12-18 13:20:23 -0800424 pkgPath = filepath.Clean(String(p.properties.Pkg_path))
425 if pkgPath == ".." || strings.HasPrefix(pkgPath, "../") ||
426 strings.HasPrefix(pkgPath, "/") {
Nan Zhangd4e641b2017-07-12 12:55:28 -0700427 ctx.PropertyErrorf("pkg_path",
428 "%q must be a relative path contained in par file.",
Nan Zhangea568a42017-11-08 21:20:04 -0800429 String(p.properties.Pkg_path))
Nan Zhangd4e641b2017-07-12 12:55:28 -0700430 return
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800431 }
Liz Kammerd737d022020-11-16 15:42:51 -0800432 }
433 // If property Is_internal is set, prepend pkgPath with internalPath
434 if proptools.BoolDefault(p.properties.Is_internal, false) {
435 pkgPath = filepath.Join(internalPath, pkgPath)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800436 }
437
Liz Kammerd737d022020-11-16 15:42:51 -0800438 // generate src:destination path mappings for this module
Nan Zhang1db85402017-12-18 13:20:23 -0800439 p.genModulePathMappings(ctx, pkgPath, expandedSrcs, expandedData)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800440
Liz Kammerd737d022020-11-16 15:42:51 -0800441 // generate the zipfile of all source and data files
Nan Zhang1db85402017-12-18 13:20:23 -0800442 p.srcsZip = p.createSrcsZip(ctx, pkgPath)
Dan Willemsen7b90bcd2025-02-11 13:11:23 -0500443 p.precompiledSrcsZip = p.precompileSrcs(ctx)
Yu Liue98f7062025-01-17 22:52:43 +0000444
445 android.SetProvider(ctx, PythonLibraryInfoProvider, PythonLibraryInfo{
446 SrcsPathMappings: p.getSrcsPathMappings(),
447 DataPathMappings: p.getDataPathMappings(),
448 SrcsZip: p.getSrcsZip(),
449 PkgPath: p.getPkgPath(),
450 PrecompiledSrcsZip: p.getPrecompiledSrcsZip(),
Brett Brotherton8c7c65e2025-03-12 20:56:07 -0700451 BundleSharedLibs: p.getBundleSharedLibs(),
Yu Liue98f7062025-01-17 22:52:43 +0000452 })
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800453}
454
Liz Kammerd737d022020-11-16 15:42:51 -0800455func isValidPythonPath(path string) error {
456 identifiers := strings.Split(strings.TrimSuffix(path, filepath.Ext(path)), "/")
457 for _, token := range identifiers {
458 if !pathComponentRegexp.MatchString(token) {
459 return fmt.Errorf("the path %q contains invalid subpath %q. "+
460 "Subpaths must be at least one character long. "+
461 "The first character must an underscore or letter. "+
462 "Following characters may be any of: letter, digit, underscore, hyphen.",
463 path, token)
464 }
465 }
466 return nil
467}
468
469// For this module, generate unique pathMappings: <dest: runfiles_path, src: source_path>
470// for python/data files expanded from properties.
Cole Faust4d247e62023-01-23 10:14:58 -0800471func (p *PythonLibraryModule) genModulePathMappings(ctx android.ModuleContext, pkgPath string,
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800472 expandedSrcs, expandedData android.Paths) {
473 // fetch <runfiles_path, source_path> pairs from "src" and "data" properties to
Nan Zhangb8fa1972017-12-22 16:12:00 -0800474 // check current module duplicates.
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800475 destToPySrcs := make(map[string]string)
476 destToPyData := make(map[string]string)
477
Dan Willemsen339a63f2023-08-15 22:17:03 -0400478 // Disable path checks for the stdlib, as it includes a "." in the version string
479 isInternal := proptools.BoolDefault(p.properties.Is_internal, false)
480
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800481 for _, s := range expandedSrcs {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800482 if s.Ext() != pyExt && s.Ext() != protoExt {
483 ctx.PropertyErrorf("srcs", "found non (.py|.proto) file: %q!", s.String())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800484 continue
485 }
Nan Zhang1db85402017-12-18 13:20:23 -0800486 runfilesPath := filepath.Join(pkgPath, s.Rel())
Dan Willemsen339a63f2023-08-15 22:17:03 -0400487 if !isInternal {
488 if err := isValidPythonPath(runfilesPath); err != nil {
489 ctx.PropertyErrorf("srcs", err.Error())
490 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800491 }
Liz Kammerd737d022020-11-16 15:42:51 -0800492 if !checkForDuplicateOutputPath(ctx, destToPySrcs, runfilesPath, s.String(), p.Name(), p.Name()) {
493 p.srcsPathMappings = append(p.srcsPathMappings, pathMapping{dest: runfilesPath, src: s})
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800494 }
495 }
496
497 for _, d := range expandedData {
Raphael Blistein59858462024-05-08 16:15:53 +0000498 if d.Ext() == pyExt {
499 ctx.PropertyErrorf("data", "found (.py) file: %q!", d.String())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800500 continue
501 }
Nan Zhang1db85402017-12-18 13:20:23 -0800502 runfilesPath := filepath.Join(pkgPath, d.Rel())
Liz Kammerd737d022020-11-16 15:42:51 -0800503 if !checkForDuplicateOutputPath(ctx, destToPyData, runfilesPath, d.String(), p.Name(), p.Name()) {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800504 p.dataPathMappings = append(p.dataPathMappings,
505 pathMapping{dest: runfilesPath, src: d})
506 }
507 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800508}
509
Liz Kammerd737d022020-11-16 15:42:51 -0800510// createSrcsZip registers build actions to zip current module's sources and data.
Cole Faust4d247e62023-01-23 10:14:58 -0800511func (p *PythonLibraryModule) createSrcsZip(ctx android.ModuleContext, pkgPath string) android.Path {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800512 relativeRootMap := make(map[string]android.Paths)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800513 var protoSrcs android.Paths
Cole Faust5c503d12023-01-24 11:48:08 -0800514 addPathMapping := func(path pathMapping) {
Raphael Blistein59858462024-05-08 16:15:53 +0000515 relativeRoot := strings.TrimSuffix(path.src.String(), path.src.Rel())
516 relativeRootMap[relativeRoot] = append(relativeRootMap[relativeRoot], path.src)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800517 }
Cole Faust5c503d12023-01-24 11:48:08 -0800518
519 // "srcs" or "data" properties may contain filegroups so it might happen that
520 // the root directory for each source path is different.
521 for _, path := range p.srcsPathMappings {
Raphael Blistein59858462024-05-08 16:15:53 +0000522 // handle proto sources separately
523 if path.src.Ext() == protoExt {
524 protoSrcs = append(protoSrcs, path.src)
525 } else {
526 addPathMapping(path)
527 }
Cole Faust5c503d12023-01-24 11:48:08 -0800528 }
529 for _, path := range p.dataPathMappings {
530 addPathMapping(path)
531 }
532
Nan Zhangb8fa1972017-12-22 16:12:00 -0800533 var zips android.Paths
534 if len(protoSrcs) > 0 {
Colin Cross19878da2019-03-28 14:45:07 -0700535 protoFlags := android.GetProtoFlags(ctx, &p.protoProperties)
536 protoFlags.OutTypeFlag = "--python_out"
537
Cole Faustcaf766b2022-10-21 16:07:56 -0700538 if pkgPath != "" {
Cole Faust43ac21f2022-09-19 11:19:52 -0700539 pkgPathStagingDir := android.PathForModuleGen(ctx, "protos_staged_for_pkg_path")
540 rule := android.NewRuleBuilder(pctx, ctx)
541 var stagedProtoSrcs android.Paths
542 for _, srcFile := range protoSrcs {
543 stagedProtoSrc := pkgPathStagingDir.Join(ctx, pkgPath, srcFile.Rel())
Cole Faust43ac21f2022-09-19 11:19:52 -0700544 rule.Command().Text("cp -f").Input(srcFile).Output(stagedProtoSrc)
545 stagedProtoSrcs = append(stagedProtoSrcs, stagedProtoSrc)
546 }
547 rule.Build("stage_protos_for_pkg_path", "Stage protos for pkg_path")
548 protoSrcs = stagedProtoSrcs
Cole Faust43ac21f2022-09-19 11:19:52 -0700549 }
550
Nan Zhangb8fa1972017-12-22 16:12:00 -0800551 for _, srcFile := range protoSrcs {
Cole Faustcaf766b2022-10-21 16:07:56 -0700552 zip := genProto(ctx, srcFile, protoFlags)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800553 zips = append(zips, zip)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800554 }
555 }
556
Nan Zhangb8fa1972017-12-22 16:12:00 -0800557 if len(relativeRootMap) > 0 {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800558 // in order to keep stable order of soong_zip params, we sort the keys here.
Cole Faust18994c72023-02-28 16:02:16 -0800559 roots := android.SortedKeys(relativeRootMap)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800560
Cole Faust01243362022-06-02 12:11:12 -0700561 // Use -symlinks=false so that the symlinks in the bazel output directory are followed
562 parArgs := []string{"-symlinks=false"}
Nan Zhangf0c4e432018-05-22 14:50:18 -0700563 if pkgPath != "" {
Liz Kammerd737d022020-11-16 15:42:51 -0800564 // use package path as path prefix
Nan Zhangf0c4e432018-05-22 14:50:18 -0700565 parArgs = append(parArgs, `-P `+pkgPath)
566 }
Liz Kammerd737d022020-11-16 15:42:51 -0800567 paths := android.Paths{}
568 for _, root := range roots {
569 // specify relative root of file in following -f arguments
570 parArgs = append(parArgs, `-C `+root)
571 for _, path := range relativeRootMap[root] {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800572 parArgs = append(parArgs, `-f `+path.String())
Liz Kammerd737d022020-11-16 15:42:51 -0800573 paths = append(paths, path)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800574 }
575 }
576
577 origSrcsZip := android.PathForModuleOut(ctx, ctx.ModuleName()+".py.srcszip")
578 ctx.Build(pctx, android.BuildParams{
579 Rule: zip,
580 Description: "python library archive",
581 Output: origSrcsZip,
Liz Kammerd737d022020-11-16 15:42:51 -0800582 // as zip rule does not use $in, there is no real need to distinguish between Inputs and Implicits
583 Implicits: paths,
Nan Zhangb8fa1972017-12-22 16:12:00 -0800584 Args: map[string]string{
585 "args": strings.Join(parArgs, " "),
586 },
587 })
588 zips = append(zips, origSrcsZip)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800589 }
Liz Kammerd737d022020-11-16 15:42:51 -0800590 // we may have multiple zips due to separate handling of proto source files
Nan Zhangb8fa1972017-12-22 16:12:00 -0800591 if len(zips) == 1 {
592 return zips[0]
593 } else {
594 combinedSrcsZip := android.PathForModuleOut(ctx, ctx.ModuleName()+".srcszip")
595 ctx.Build(pctx, android.BuildParams{
596 Rule: combineZip,
597 Description: "combine python library archive",
598 Output: combinedSrcsZip,
599 Inputs: zips,
600 })
601 return combinedSrcsZip
602 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800603}
604
Cole Faust5c503d12023-01-24 11:48:08 -0800605func (p *PythonLibraryModule) precompileSrcs(ctx android.ModuleContext) android.Path {
606 // To precompile the python sources, we need a python interpreter and stdlib built
607 // for host. We then use those to compile the python sources, which may be used on either
608 // host of device. Python bytecode is architecture agnostic, so we're essentially
609 // "cross compiling" for device here purely by virtue of host and device python bytecode
610 // being the same.
611 var stdLib android.Path
Dan Willemsen339a63f2023-08-15 22:17:03 -0400612 var stdLibPkg string
Cole Faust5c503d12023-01-24 11:48:08 -0800613 var launcher android.Path
Dan Willemsen339a63f2023-08-15 22:17:03 -0400614 if proptools.BoolDefault(p.properties.Is_internal, false) {
Cole Faust5c503d12023-01-24 11:48:08 -0800615 stdLib = p.srcsZip
Dan Willemsen339a63f2023-08-15 22:17:03 -0400616 stdLibPkg = p.getPkgPath()
Cole Faust5c503d12023-01-24 11:48:08 -0800617 } else {
Yu Liue98f7062025-01-17 22:52:43 +0000618 ctx.VisitDirectDepsProxyWithTag(hostStdLibTag, func(module android.ModuleProxy) {
619 if dep, ok := android.OtherModuleProvider(ctx, module, PythonLibraryInfoProvider); ok {
620 stdLib = dep.PrecompiledSrcsZip
621 stdLibPkg = dep.PkgPath
Cole Faust5c503d12023-01-24 11:48:08 -0800622 }
623 })
624 }
Yu Liue98f7062025-01-17 22:52:43 +0000625 ctx.VisitDirectDepsProxyWithTag(hostLauncherTag, func(module android.ModuleProxy) {
626 if dep, ok := android.OtherModuleProvider(ctx, module, cc.LinkableInfoProvider); ok {
627 optionalLauncher := dep.OutputFile
Cole Faust5c503d12023-01-24 11:48:08 -0800628 if optionalLauncher.Valid() {
629 launcher = optionalLauncher.Path()
630 }
Cole Faust909d2372023-02-13 23:17:40 +0000631 }
632 })
633 var launcherSharedLibs android.Paths
634 var ldLibraryPath []string
Yu Liue98f7062025-01-17 22:52:43 +0000635 ctx.VisitDirectDepsProxyWithTag(hostlauncherSharedLibTag, func(module android.ModuleProxy) {
636 if dep, ok := android.OtherModuleProvider(ctx, module, cc.LinkableInfoProvider); ok {
637 optionalPath := dep.OutputFile
Cole Faust909d2372023-02-13 23:17:40 +0000638 if optionalPath.Valid() {
639 launcherSharedLibs = append(launcherSharedLibs, optionalPath.Path())
640 ldLibraryPath = append(ldLibraryPath, filepath.Dir(optionalPath.Path().String()))
Cole Faust5c503d12023-01-24 11:48:08 -0800641 }
642 }
643 })
644
645 out := android.PathForModuleOut(ctx, ctx.ModuleName()+".srcszipprecompiled")
646 if stdLib == nil || launcher == nil {
647 // This shouldn't happen in a real build because we'll error out when adding dependencies
648 // on the stdlib and launcher if they don't exist. But some tests set
649 // AllowMissingDependencies.
650 return out
651 }
652 ctx.Build(pctx, android.BuildParams{
653 Rule: precompile,
654 Input: p.srcsZip,
655 Output: out,
656 Implicits: launcherSharedLibs,
657 Description: "Precompile the python sources of " + ctx.ModuleName(),
658 Args: map[string]string{
659 "stdlibZip": stdLib.String(),
Dan Willemsen339a63f2023-08-15 22:17:03 -0400660 "stdlibPkg": stdLibPkg,
Cole Faust5c503d12023-01-24 11:48:08 -0800661 "launcher": launcher.String(),
662 "ldLibraryPath": strings.Join(ldLibraryPath, ":"),
663 },
664 })
665 return out
666}
667
Liz Kammerd737d022020-11-16 15:42:51 -0800668// collectPathsFromTransitiveDeps checks for source/data files for duplicate paths
669// for module and its transitive dependencies and collects list of data/source file
670// zips for transitive dependencies.
Cole Faust5c503d12023-01-24 11:48:08 -0800671func (p *PythonLibraryModule) collectPathsFromTransitiveDeps(ctx android.ModuleContext, precompiled bool) android.Paths {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800672 // fetch <runfiles_path, source_path> pairs from "src" and "data" properties to
673 // check duplicates.
674 destToPySrcs := make(map[string]string)
675 destToPyData := make(map[string]string)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800676 for _, path := range p.srcsPathMappings {
677 destToPySrcs[path.dest] = path.src.String()
678 }
679 for _, path := range p.dataPathMappings {
680 destToPyData[path.dest] = path.src.String()
681 }
682
Colin Cross0ff74572025-04-03 19:48:48 -0700683 seen := make(map[android.ModuleProxy]bool)
Colin Cross6b753602018-06-21 13:03:07 -0700684
Cole Faust4d247e62023-01-23 10:14:58 -0800685 var result android.Paths
686
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800687 // visit all its dependencies in depth first.
Yu Liue98f7062025-01-17 22:52:43 +0000688 ctx.WalkDepsProxy(func(child, _ android.ModuleProxy) bool {
Liz Kammerd737d022020-11-16 15:42:51 -0800689 // we only collect dependencies tagged as python library deps
Colin Cross6b753602018-06-21 13:03:07 -0700690 if ctx.OtherModuleDependencyTag(child) != pythonLibTag {
691 return false
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800692 }
Colin Cross6b753602018-06-21 13:03:07 -0700693 if seen[child] {
694 return false
695 }
696 seen[child] = true
Nan Zhangb8fa1972017-12-22 16:12:00 -0800697 // Python modules only can depend on Python libraries.
Yu Liue98f7062025-01-17 22:52:43 +0000698 dep, isLibrary := android.OtherModuleProvider(ctx, child, PythonLibraryInfoProvider)
699 _, isBinary := android.OtherModuleProvider(ctx, child, PythonBinaryInfoProvider)
700 if !isLibrary || isBinary {
Liz Kammerd737d022020-11-16 15:42:51 -0800701 ctx.PropertyErrorf("libs",
Nan Zhangd4e641b2017-07-12 12:55:28 -0700702 "the dependency %q of module %q is not Python library!",
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxd75507f2021-08-20 21:02:43 +0000703 ctx.OtherModuleName(child), ctx.ModuleName())
Nan Zhangd4e641b2017-07-12 12:55:28 -0700704 }
Liz Kammerd737d022020-11-16 15:42:51 -0800705 // collect source and data paths, checking that there are no duplicate output file conflicts
Yu Liue98f7062025-01-17 22:52:43 +0000706 if isLibrary {
707 srcs := dep.SrcsPathMappings
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800708 for _, path := range srcs {
Liz Kammerd737d022020-11-16 15:42:51 -0800709 checkForDuplicateOutputPath(ctx, destToPySrcs,
Colin Cross6b753602018-06-21 13:03:07 -0700710 path.dest, path.src.String(), ctx.ModuleName(), ctx.OtherModuleName(child))
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800711 }
Yu Liue98f7062025-01-17 22:52:43 +0000712 data := dep.DataPathMappings
Liz Kammerd737d022020-11-16 15:42:51 -0800713 for _, path := range data {
714 checkForDuplicateOutputPath(ctx, destToPyData,
715 path.dest, path.src.String(), ctx.ModuleName(), ctx.OtherModuleName(child))
716 }
Cole Faust5c503d12023-01-24 11:48:08 -0800717 if precompiled {
Yu Liue98f7062025-01-17 22:52:43 +0000718 result = append(result, dep.PrecompiledSrcsZip)
Cole Faust5c503d12023-01-24 11:48:08 -0800719 } else {
Yu Liue98f7062025-01-17 22:52:43 +0000720 result = append(result, dep.SrcsZip)
Cole Faust5c503d12023-01-24 11:48:08 -0800721 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800722 }
Colin Cross6b753602018-06-21 13:03:07 -0700723 return true
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800724 })
Cole Faust4d247e62023-01-23 10:14:58 -0800725 return result
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800726}
727
Brett Brotherton8c7c65e2025-03-12 20:56:07 -0700728func (p *PythonLibraryModule) collectSharedLibDeps(ctx android.ModuleContext) android.Paths {
Colin Cross0ff74572025-04-03 19:48:48 -0700729 seen := make(map[android.ModuleProxy]bool)
Brett Brotherton8c7c65e2025-03-12 20:56:07 -0700730
731 var result android.Paths
732
733 ctx.WalkDepsProxy(func(child, _ android.ModuleProxy) bool {
734 // we only collect dependencies tagged as python library deps
735 if ctx.OtherModuleDependencyTag(child) != pythonLibTag {
736 return false
737 }
738 if seen[child] {
739 return false
740 }
741 seen[child] = true
742 dep, isLibrary := android.OtherModuleProvider(ctx, child, PythonLibraryInfoProvider)
743 if isLibrary {
744 result = append(result, dep.BundleSharedLibs...)
745 }
746 return true
747 })
748 return result
749}
750
751func (p *PythonLibraryModule) zipSharedLibs(ctx android.ModuleContext, bundleSharedLibs android.Paths) android.Path {
752 // sort the paths to keep the output deterministic
753 sort.Slice(bundleSharedLibs, func(i, j int) bool {
754 return bundleSharedLibs[i].String() < bundleSharedLibs[j].String()
755 })
756
757 parArgs := []string{"-symlinks=false", "-P lib64"}
758 paths := android.Paths{}
759 for _, path := range bundleSharedLibs {
760 // specify relative root of file in following -f arguments
761 parArgs = append(parArgs, `-C `+filepath.Dir(path.String()))
762 parArgs = append(parArgs, `-f `+path.String())
763 paths = append(paths, path)
764 }
765 srcsZip := android.PathForModuleOut(ctx, ctx.ModuleName()+".sharedlibs.srcszip")
766 ctx.Build(pctx, android.BuildParams{
767 Rule: zip,
768 Description: "bundle shared libraries for python binary",
769 Output: srcsZip,
Spandan Das8ed07762025-03-14 21:52:09 +0000770 Implicits: paths,
Brett Brotherton8c7c65e2025-03-12 20:56:07 -0700771 Args: map[string]string{
772 "args": strings.Join(parArgs, " "),
773 },
774 })
775 return srcsZip
776}
777
Liz Kammerd737d022020-11-16 15:42:51 -0800778// chckForDuplicateOutputPath checks whether outputPath has already been included in map m, which
779// would result in two files being placed in the same location.
780// If there is a duplicate path, an error is thrown and true is returned
781// Otherwise, outputPath: srcPath is added to m and returns false
782func checkForDuplicateOutputPath(ctx android.ModuleContext, m map[string]string, outputPath, srcPath, curModule, otherModule string) bool {
783 if oldSrcPath, found := m[outputPath]; found {
Nan Zhangbea09752018-05-31 12:49:33 -0700784 ctx.ModuleErrorf("found two files to be placed at the same location within zip %q."+
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800785 " First file: in module %s at path %q."+
786 " Second file: in module %s at path %q.",
Liz Kammerd737d022020-11-16 15:42:51 -0800787 outputPath, curModule, oldSrcPath, otherModule, srcPath)
788 return true
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800789 }
Liz Kammerd737d022020-11-16 15:42:51 -0800790 m[outputPath] = srcPath
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800791
Liz Kammerd737d022020-11-16 15:42:51 -0800792 return false
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800793}
Nan Zhangea568a42017-11-08 21:20:04 -0800794
Liz Kammerd737d022020-11-16 15:42:51 -0800795// InstallInData returns true as Python is not supported in the system partition
Cole Faust4d247e62023-01-23 10:14:58 -0800796func (p *PythonLibraryModule) InstallInData() bool {
Nan Zhangd9ec5e72017-12-01 20:00:31 +0000797 return true
798}
799
Nan Zhangea568a42017-11-08 21:20:04 -0800800var Bool = proptools.Bool
Dan Willemsen6ca390f2019-02-14 23:17:08 -0800801var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -0800802var String = proptools.String