blob: f8f41658f4c1cedc618d777b34ddd711f5bca046 [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"
Nan Zhangdb0b9a32017-02-27 10:12:13 -080023 "strings"
24
Yu Liue98f7062025-01-17 22:52:43 +000025 "android/soong/cc"
Cole Faustd85c6772025-01-31 10:54:46 -080026
Nan Zhangdb0b9a32017-02-27 10:12:13 -080027 "github.com/google/blueprint"
Nan Zhangd4e641b2017-07-12 12:55:28 -070028 "github.com/google/blueprint/proptools"
Nan Zhangdb0b9a32017-02-27 10:12:13 -080029
30 "android/soong/android"
31)
32
Yu Liue98f7062025-01-17 22:52:43 +000033type PythonLibraryInfo struct {
34 SrcsPathMappings []pathMapping
35 DataPathMappings []pathMapping
36 SrcsZip android.Path
37 PrecompiledSrcsZip android.Path
38 PkgPath string
39}
40
41var PythonLibraryInfoProvider = blueprint.NewProvider[PythonLibraryInfo]()
42
Liz Kammerd737d022020-11-16 15:42:51 -080043// the version-specific properties that apply to python modules.
Nan Zhangd4e641b2017-07-12 12:55:28 -070044type VersionProperties struct {
Liz Kammerd737d022020-11-16 15:42:51 -080045 // whether the module is required to be built with this version.
46 // Defaults to true for Python 3, and false otherwise.
Liz Kammer59c0eae2021-09-17 17:48:05 -040047 Enabled *bool
Nan Zhangdb0b9a32017-02-27 10:12:13 -080048
Liz Kammerd737d022020-11-16 15:42:51 -080049 // list of source files specific to this Python version.
50 // Using the syntax ":module", srcs may reference the outputs of other modules that produce source files,
51 // e.g. genrule or filegroup.
Colin Cross27b922f2019-03-04 22:35:41 -080052 Srcs []string `android:"path,arch_variant"`
Nan Zhangd4e641b2017-07-12 12:55:28 -070053
Liz Kammerd737d022020-11-16 15:42:51 -080054 // list of source files that should not be used to build the Python module for this version.
55 // This is most useful to remove files that are not common to all Python versions.
Colin Cross27b922f2019-03-04 22:35:41 -080056 Exclude_srcs []string `android:"path,arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080057
Liz Kammerd737d022020-11-16 15:42:51 -080058 // list of the Python libraries used only for this Python version.
Nan Zhangd4e641b2017-07-12 12:55:28 -070059 Libs []string `android:"arch_variant"`
60
Cole Faustf09101e2024-04-18 18:33:15 +000061 // whether the binary is required to be built with embedded launcher for this version, defaults to true.
Liz Kammer59c0eae2021-09-17 17:48:05 -040062 Embedded_launcher *bool // TODO(b/174041232): Remove this property
Nan Zhangdb0b9a32017-02-27 10:12:13 -080063}
64
Liz Kammerd737d022020-11-16 15:42:51 -080065// properties that apply to all python modules
Nan Zhangd4e641b2017-07-12 12:55:28 -070066type BaseProperties struct {
Nan Zhangdb0b9a32017-02-27 10:12:13 -080067 // the package path prefix within the output artifact at which to place the source/data
68 // files of the current module.
69 // eg. Pkg_path = "a/b/c"; Other packages can reference this module by using
70 // (from a.b.c import ...) statement.
Nan Zhangbea09752018-05-31 12:49:33 -070071 // if left unspecified, all the source/data files path is unchanged within zip file.
Liz Kammer59c0eae2021-09-17 17:48:05 -040072 Pkg_path *string
Nan Zhangd4e641b2017-07-12 12:55:28 -070073
74 // true, if the Python module is used internally, eg, Python std libs.
Liz Kammer59c0eae2021-09-17 17:48:05 -040075 Is_internal *bool
Nan Zhangdb0b9a32017-02-27 10:12:13 -080076
77 // list of source (.py) files compatible both with Python2 and Python3 used to compile the
78 // Python module.
79 // srcs may reference the outputs of other modules that produce source files like genrule
80 // or filegroup using the syntax ":module".
81 // Srcs has to be non-empty.
Colin Cross27b922f2019-03-04 22:35:41 -080082 Srcs []string `android:"path,arch_variant"`
Nan Zhangd4e641b2017-07-12 12:55:28 -070083
84 // list of source files that should not be used to build the C/C++ module.
85 // This is most useful in the arch/multilib variants to remove non-common files
Colin Cross27b922f2019-03-04 22:35:41 -080086 Exclude_srcs []string `android:"path,arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080087
88 // list of files or filegroup modules that provide data that should be installed alongside
89 // the test. the file extension can be arbitrary except for (.py).
Colin Cross27b922f2019-03-04 22:35:41 -080090 Data []string `android:"path,arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080091
Cole Faust65cb40a2024-10-21 15:41:42 -070092 // Same as data, but will add dependencies on modules using the device's os variation and
93 // the common arch variation. Useful for a host test that wants to embed a module built for
94 // device.
95 Device_common_data []string `android:"path_device_common"`
96
Inseob Kim25f5ae42025-01-07 22:27:58 +090097 // Same as data, but will add dependencies on modules via a device os variation and the
98 // device's first supported arch's variation. Useful for a host test that wants to embed a
99 // module built for device.
100 Device_first_data []string `android:"path_device_first"`
101
Colin Cross1bc63932020-11-22 20:12:45 -0800102 // list of java modules that provide data that should be installed alongside the test.
103 Java_data []string
104
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800105 // list of the Python libraries compatible both with Python2 and Python3.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700106 Libs []string `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800107
108 Version struct {
Liz Kammerd737d022020-11-16 15:42:51 -0800109 // Python2-specific properties, including whether Python2 is supported for this module
110 // and version-specific sources, exclusions and dependencies.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700111 Py2 VersionProperties `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800112
Liz Kammerd737d022020-11-16 15:42:51 -0800113 // Python3-specific properties, including whether Python3 is supported for this module
114 // and version-specific sources, exclusions and dependencies.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700115 Py3 VersionProperties `android:"arch_variant"`
116 } `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800117
Cole Faustd85c6772025-01-31 10:54:46 -0800118 // This enabled property is to accept the collapsed enabled property from the VersionProperties.
119 // It is unused now, as all builds should be python3.
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700120 Enabled *bool `blueprint:"mutated"`
121
Cole Faustd85c6772025-01-31 10:54:46 -0800122 // whether the binary is required to be built with an embedded python interpreter, defaults to
123 // true. This allows taking the resulting binary outside of the build and running it on machines
124 // that don't have python installed or may have an older version of python.
125 Embedded_launcher *bool
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800126}
127
Liz Kammerd737d022020-11-16 15:42:51 -0800128// Used to store files of current module after expanding dependencies
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800129type pathMapping struct {
130 dest string
131 src android.Path
132}
133
Cole Faust4d247e62023-01-23 10:14:58 -0800134type PythonLibraryModule struct {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800135 android.ModuleBase
Nan Zhanga3fc4ba2017-07-20 17:43:37 -0700136 android.DefaultableModuleBase
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800137
Nan Zhangb8fa1972017-12-22 16:12:00 -0800138 properties BaseProperties
139 protoProperties android.ProtoProperties
Nan Zhangd4e641b2017-07-12 12:55:28 -0700140
141 // initialize before calling Init
142 hod android.HostOrDeviceSupported
143 multilib android.Multilib
144
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800145 // the Python files of current module after expanding source dependencies.
146 // pathMapping: <dest: runfile_path, src: source_path>
147 srcsPathMappings []pathMapping
148
149 // the data files of current module after expanding source dependencies.
150 // pathMapping: <dest: runfile_path, src: source_path>
151 dataPathMappings []pathMapping
152
Cole Faust5c503d12023-01-24 11:48:08 -0800153 // The zip file containing the current module's source/data files.
Nan Zhang1db85402017-12-18 13:20:23 -0800154 srcsZip android.Path
Cole Faust5c503d12023-01-24 11:48:08 -0800155
156 // The zip file containing the current module's source/data files, with the
157 // source files precompiled.
158 precompiledSrcsZip android.Path
Ronald Braunsteinc4cd7a12024-04-16 16:39:48 -0700159
160 sourceProperties android.SourceProperties
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800161}
162
Liz Kammerd737d022020-11-16 15:42:51 -0800163// newModule generates new Python base module
Cole Faust4d247e62023-01-23 10:14:58 -0800164func newModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *PythonLibraryModule {
165 return &PythonLibraryModule{
Nan Zhangd4e641b2017-07-12 12:55:28 -0700166 hod: hod,
167 multilib: multilib,
168 }
169}
170
Liz Kammerd737d022020-11-16 15:42:51 -0800171// getSrcsPathMappings gets this module's path mapping of src source path : runfiles destination
Cole Faust4d247e62023-01-23 10:14:58 -0800172func (p *PythonLibraryModule) getSrcsPathMappings() []pathMapping {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800173 return p.srcsPathMappings
174}
175
Liz Kammerd737d022020-11-16 15:42:51 -0800176// getSrcsPathMappings gets this module's path mapping of data source path : runfiles destination
Cole Faust4d247e62023-01-23 10:14:58 -0800177func (p *PythonLibraryModule) getDataPathMappings() []pathMapping {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800178 return p.dataPathMappings
179}
180
Liz Kammerd737d022020-11-16 15:42:51 -0800181// getSrcsZip returns the filepath where the current module's source/data files are zipped.
Cole Faust4d247e62023-01-23 10:14:58 -0800182func (p *PythonLibraryModule) getSrcsZip() android.Path {
Nan Zhang1db85402017-12-18 13:20:23 -0800183 return p.srcsZip
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800184}
185
Cole Faust5c503d12023-01-24 11:48:08 -0800186// getSrcsZip returns the filepath where the current module's source/data files are zipped.
187func (p *PythonLibraryModule) getPrecompiledSrcsZip() android.Path {
188 return p.precompiledSrcsZip
189}
190
Dan Willemsen339a63f2023-08-15 22:17:03 -0400191// getPkgPath returns the pkg_path value
192func (p *PythonLibraryModule) getPkgPath() string {
193 return String(p.properties.Pkg_path)
194}
195
Cole Faust4d247e62023-01-23 10:14:58 -0800196func (p *PythonLibraryModule) getBaseProperties() *BaseProperties {
197 return &p.properties
198}
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800199
Cole Faust4d247e62023-01-23 10:14:58 -0800200func (p *PythonLibraryModule) init() android.Module {
Ronald Braunsteinc4cd7a12024-04-16 16:39:48 -0700201 p.AddProperties(&p.properties, &p.protoProperties, &p.sourceProperties)
Nan Zhangd4e641b2017-07-12 12:55:28 -0700202 android.InitAndroidArchModule(p, p.hod, p.multilib)
Nan Zhanga3fc4ba2017-07-20 17:43:37 -0700203 android.InitDefaultableModule(p)
Nan Zhangd4e641b2017-07-12 12:55:28 -0700204 return p
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800205}
206
Liz Kammerd737d022020-11-16 15:42:51 -0800207// Python-specific tag to transfer information on the purpose of a dependency.
208// This is used when adding a dependency on a module, which can later be accessed when visiting
209// dependencies.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700210type dependencyTag struct {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800211 blueprint.BaseDependencyTag
Nan Zhangd4e641b2017-07-12 12:55:28 -0700212 name string
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800213}
214
Liz Kammerd737d022020-11-16 15:42:51 -0800215// Python-specific tag that indicates that installed files of this module should depend on installed
216// files of the dependency
Colin Crosse9fe2942020-11-10 18:12:15 -0800217type installDependencyTag struct {
218 blueprint.BaseDependencyTag
Liz Kammerd737d022020-11-16 15:42:51 -0800219 // embedding this struct provides the installation dependency requirement
Colin Crosse9fe2942020-11-10 18:12:15 -0800220 android.InstallAlwaysNeededDependencyTag
221 name string
222}
223
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800224var (
Cole Faust5c503d12023-01-24 11:48:08 -0800225 pythonLibTag = dependencyTag{name: "pythonLib"}
226 javaDataTag = dependencyTag{name: "javaData"}
227 // The python interpreter, with soong module name "py3-launcher" or "py3-launcher-autorun".
Cole Faust909d2372023-02-13 23:17:40 +0000228 launcherTag = dependencyTag{name: "launcher"}
229 launcherSharedLibTag = installDependencyTag{name: "launcherSharedLib"}
Cole Faust5c503d12023-01-24 11:48:08 -0800230 // The python interpreter built for host so that we can precompile python sources.
231 // This only works because the precompiled sources don't vary by architecture.
232 // The soong module name is "py3-launcher".
Cole Faust909d2372023-02-13 23:17:40 +0000233 hostLauncherTag = dependencyTag{name: "hostLauncher"}
234 hostlauncherSharedLibTag = dependencyTag{name: "hostlauncherSharedLib"}
235 hostStdLibTag = dependencyTag{name: "hostStdLib"}
236 pathComponentRegexp = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`)
237 pyExt = ".py"
238 protoExt = ".proto"
Cole Faust909d2372023-02-13 23:17:40 +0000239 internalPath = "internal"
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800240)
241
Cole Faust4d247e62023-01-23 10:14:58 -0800242type basePropertiesProvider interface {
243 getBaseProperties() *BaseProperties
244}
245
Liz Kammerd737d022020-11-16 15:42:51 -0800246func anyHasExt(paths []string, ext string) bool {
247 for _, p := range paths {
248 if filepath.Ext(p) == ext {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800249 return true
250 }
251 }
252
253 return false
254}
255
Cole Faust4d247e62023-01-23 10:14:58 -0800256func (p *PythonLibraryModule) anySrcHasExt(ctx android.BottomUpMutatorContext, ext string) bool {
Liz Kammerd737d022020-11-16 15:42:51 -0800257 return anyHasExt(p.properties.Srcs, ext)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800258}
259
Liz Kammerd737d022020-11-16 15:42:51 -0800260// DepsMutator mutates dependencies for this module:
Colin Crossd079e0b2022-08-16 10:27:33 -0700261// - handles proto dependencies,
262// - if required, specifies launcher and adds launcher dependencies,
263// - applies python version mutations to Python dependencies
Cole Faust4d247e62023-01-23 10:14:58 -0800264func (p *PythonLibraryModule) DepsMutator(ctx android.BottomUpMutatorContext) {
Cole Faustd85c6772025-01-31 10:54:46 -0800265 // Flatten the version.py3 props down into the main property struct. Leftover from when
266 // there was both python2 and 3 in the build, and properties could be different between them.
267 if base, ok := ctx.Module().(basePropertiesProvider); ok {
268 props := base.getBaseProperties()
Colin Crossfe17f6f2019-03-28 19:30:56 -0700269
Cole Faustd85c6772025-01-31 10:54:46 -0800270 err := proptools.AppendMatchingProperties([]interface{}{props}, &props.Version.Py3, nil)
271 if err != nil {
272 panic(err)
273 }
Nan Zhangb8fa1972017-12-22 16:12:00 -0800274 }
Colin Crosse20113d2020-11-22 19:37:44 -0800275
Cole Faustd85c6772025-01-31 10:54:46 -0800276 android.ProtoDeps(ctx, &p.protoProperties)
277
Liz Kammerd737d022020-11-16 15:42:51 -0800278 // If sources contain a proto file, add dependency on libprotobuf-python
279 if p.anySrcHasExt(ctx, protoExt) && p.Name() != "libprotobuf-python" {
Cole Faustd85c6772025-01-31 10:54:46 -0800280 ctx.AddDependency(ctx.Module(), pythonLibTag, "libprotobuf-python")
Colin Crosse20113d2020-11-22 19:37:44 -0800281 }
Liz Kammerd737d022020-11-16 15:42:51 -0800282
283 // Add python library dependencies for this python version variation
Cole Faustd85c6772025-01-31 10:54:46 -0800284 ctx.AddDependency(ctx.Module(), pythonLibTag, android.LastUniqueStrings(p.properties.Libs)...)
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700285
Colin Cross1bc63932020-11-22 20:12:45 -0800286 // Emulate the data property for java_data but with the arch variation overridden to "common"
287 // so that it can point to java modules.
288 javaDataVariation := []blueprint.Variation{{"arch", android.Common.String()}}
289 ctx.AddVariationDependencies(javaDataVariation, javaDataTag, p.properties.Java_data...)
Cole Faust5c503d12023-01-24 11:48:08 -0800290
Cole Faust909d2372023-02-13 23:17:40 +0000291 p.AddDepsOnPythonLauncherAndStdlib(ctx, hostStdLibTag, hostLauncherTag, hostlauncherSharedLibTag, false, ctx.Config().BuildOSTarget)
Cole Faust5c503d12023-01-24 11:48:08 -0800292}
293
Cole Faust909d2372023-02-13 23:17:40 +0000294// AddDepsOnPythonLauncherAndStdlib will make the current module depend on the python stdlib,
295// launcher (interpreter), and the launcher's shared libraries. If autorun is true, it will use
296// the autorun launcher instead of the regular one. This function acceps a targetForDeps argument
297// as the target to use for these dependencies. For embedded launcher python binaries, the launcher
298// that will be embedded will be under the same target as the python module itself. But when
299// precompiling python code, we need to get the python launcher built for host, even if we're
300// compiling the python module for device, so we pass a different target to this function.
Cole Faust5c503d12023-01-24 11:48:08 -0800301func (p *PythonLibraryModule) AddDepsOnPythonLauncherAndStdlib(ctx android.BottomUpMutatorContext,
Cole Faust909d2372023-02-13 23:17:40 +0000302 stdLibTag, launcherTag, launcherSharedLibTag blueprint.DependencyTag,
Cole Faust5c503d12023-01-24 11:48:08 -0800303 autorun bool, targetForDeps android.Target) {
304 var stdLib string
305 var launcherModule string
Cole Faust909d2372023-02-13 23:17:40 +0000306 // Add launcher shared lib dependencies. Ideally, these should be
307 // derived from the `shared_libs` property of the launcher. TODO: read these from
308 // the python launcher itself using ctx.OtherModuleProvider() or similar on the result
309 // of ctx.AddFarVariationDependencies()
310 launcherSharedLibDeps := []string{
311 "libsqlite",
312 }
313 // Add launcher-specific dependencies for bionic
314 if targetForDeps.Os.Bionic() {
315 launcherSharedLibDeps = append(launcherSharedLibDeps, "libc", "libdl", "libm")
316 }
317 if targetForDeps.Os == android.LinuxMusl && !ctx.Config().HostStaticBinaries() {
318 launcherSharedLibDeps = append(launcherSharedLibDeps, "libc_musl")
319 }
Cole Faust5c503d12023-01-24 11:48:08 -0800320
Cole Faustd85c6772025-01-31 10:54:46 -0800321 var prebuiltStdLib bool
322 if targetForDeps.Os.Bionic() {
323 prebuiltStdLib = false
324 } else if ctx.Config().VendorConfig("cpython3").Bool("force_build_host") {
325 prebuiltStdLib = false
326 } else {
327 prebuiltStdLib = true
Cole Faust5c503d12023-01-24 11:48:08 -0800328 }
Cole Faustd85c6772025-01-31 10:54:46 -0800329
330 if prebuiltStdLib {
331 stdLib = "py3-stdlib-prebuilt"
332 } else {
333 stdLib = "py3-stdlib"
334 }
335
336 launcherModule = "py3-launcher"
337 if autorun {
338 launcherModule = "py3-launcher-autorun"
339 }
340 if ctx.Config().HostStaticBinaries() && targetForDeps.Os == android.LinuxMusl {
341 launcherModule += "-static"
342 }
343 if ctx.Device() {
344 launcherSharedLibDeps = append(launcherSharedLibDeps, "liblog")
345 }
346
Cole Faust5c503d12023-01-24 11:48:08 -0800347 targetVariations := targetForDeps.Variations()
348 if ctx.ModuleName() != stdLib {
Cole Faust5c503d12023-01-24 11:48:08 -0800349 // Using AddFarVariationDependencies for all of these because they can be for a different
350 // platform, like if the python module itself was being compiled for device, we may want
351 // the python interpreter built for host so that we can precompile python sources.
Cole Faustd85c6772025-01-31 10:54:46 -0800352 ctx.AddFarVariationDependencies(targetVariations, stdLibTag, stdLib)
Cole Faust5c503d12023-01-24 11:48:08 -0800353 }
354 ctx.AddFarVariationDependencies(targetVariations, launcherTag, launcherModule)
Cole Faust909d2372023-02-13 23:17:40 +0000355 ctx.AddFarVariationDependencies(targetVariations, launcherSharedLibTag, launcherSharedLibDeps...)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800356}
357
Cole Faust4d247e62023-01-23 10:14:58 -0800358// GenerateAndroidBuildActions performs build actions common to all Python modules
359func (p *PythonLibraryModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Cole Faustd85c6772025-01-31 10:54:46 -0800360 if proptools.BoolDefault(p.properties.Version.Py2.Enabled, false) {
361 ctx.PropertyErrorf("version.py2.enabled", "Python 2 is no longer supported, please convert to python 3.")
362 }
Liz Kammerd737d022020-11-16 15:42:51 -0800363 expandedSrcs := android.PathsForModuleSrcExcludes(ctx, p.properties.Srcs, p.properties.Exclude_srcs)
Ronald Braunsteinc4cd7a12024-04-16 16:39:48 -0700364 // Keep before any early returns.
365 android.SetProvider(ctx, android.TestOnlyProviderKey, android.TestModuleInformation{
366 TestOnly: Bool(p.sourceProperties.Test_only),
367 TopLevelTarget: p.sourceProperties.Top_level_test_target,
368 })
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800369
370 // expand data files from "data" property.
Colin Cross8a497952019-03-05 22:25:09 -0800371 expandedData := android.PathsForModuleSrc(ctx, p.properties.Data)
Cole Faust65cb40a2024-10-21 15:41:42 -0700372 expandedData = append(expandedData, android.PathsForModuleSrc(ctx, p.properties.Device_common_data)...)
Inseob Kim25f5ae42025-01-07 22:27:58 +0900373 expandedData = append(expandedData, android.PathsForModuleSrc(ctx, p.properties.Device_first_data)...)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800374
Colin Cross1bc63932020-11-22 20:12:45 -0800375 // Emulate the data property for java_data dependencies.
Yu Liue98f7062025-01-17 22:52:43 +0000376 for _, javaData := range ctx.GetDirectDepsProxyWithTag(javaDataTag) {
Colin Cross1bc63932020-11-22 20:12:45 -0800377 expandedData = append(expandedData, android.OutputFilesForModule(ctx, javaData, "")...)
378 }
379
Liz Kammerd737d022020-11-16 15:42:51 -0800380 // Validate pkg_path property
Nan Zhang1db85402017-12-18 13:20:23 -0800381 pkgPath := String(p.properties.Pkg_path)
382 if pkgPath != "" {
Liz Kammerd737d022020-11-16 15:42:51 -0800383 // TODO: export validation from android/paths.go handling to replace this duplicated functionality
Nan Zhang1db85402017-12-18 13:20:23 -0800384 pkgPath = filepath.Clean(String(p.properties.Pkg_path))
385 if pkgPath == ".." || strings.HasPrefix(pkgPath, "../") ||
386 strings.HasPrefix(pkgPath, "/") {
Nan Zhangd4e641b2017-07-12 12:55:28 -0700387 ctx.PropertyErrorf("pkg_path",
388 "%q must be a relative path contained in par file.",
Nan Zhangea568a42017-11-08 21:20:04 -0800389 String(p.properties.Pkg_path))
Nan Zhangd4e641b2017-07-12 12:55:28 -0700390 return
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800391 }
Liz Kammerd737d022020-11-16 15:42:51 -0800392 }
393 // If property Is_internal is set, prepend pkgPath with internalPath
394 if proptools.BoolDefault(p.properties.Is_internal, false) {
395 pkgPath = filepath.Join(internalPath, pkgPath)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800396 }
397
Liz Kammerd737d022020-11-16 15:42:51 -0800398 // generate src:destination path mappings for this module
Nan Zhang1db85402017-12-18 13:20:23 -0800399 p.genModulePathMappings(ctx, pkgPath, expandedSrcs, expandedData)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800400
Liz Kammerd737d022020-11-16 15:42:51 -0800401 // generate the zipfile of all source and data files
Nan Zhang1db85402017-12-18 13:20:23 -0800402 p.srcsZip = p.createSrcsZip(ctx, pkgPath)
Dan Willemsen7ca4d102025-01-07 20:14:25 -0500403 // TODO(b/388344853): precompilation temporarily disabled for python3.13 upgrade
404 p.precompiledSrcsZip = p.srcsZip //p.precompileSrcs(ctx)
Yu Liue98f7062025-01-17 22:52:43 +0000405
406 android.SetProvider(ctx, PythonLibraryInfoProvider, PythonLibraryInfo{
407 SrcsPathMappings: p.getSrcsPathMappings(),
408 DataPathMappings: p.getDataPathMappings(),
409 SrcsZip: p.getSrcsZip(),
410 PkgPath: p.getPkgPath(),
411 PrecompiledSrcsZip: p.getPrecompiledSrcsZip(),
412 })
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800413}
414
Liz Kammerd737d022020-11-16 15:42:51 -0800415func isValidPythonPath(path string) error {
416 identifiers := strings.Split(strings.TrimSuffix(path, filepath.Ext(path)), "/")
417 for _, token := range identifiers {
418 if !pathComponentRegexp.MatchString(token) {
419 return fmt.Errorf("the path %q contains invalid subpath %q. "+
420 "Subpaths must be at least one character long. "+
421 "The first character must an underscore or letter. "+
422 "Following characters may be any of: letter, digit, underscore, hyphen.",
423 path, token)
424 }
425 }
426 return nil
427}
428
429// For this module, generate unique pathMappings: <dest: runfiles_path, src: source_path>
430// for python/data files expanded from properties.
Cole Faust4d247e62023-01-23 10:14:58 -0800431func (p *PythonLibraryModule) genModulePathMappings(ctx android.ModuleContext, pkgPath string,
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800432 expandedSrcs, expandedData android.Paths) {
433 // fetch <runfiles_path, source_path> pairs from "src" and "data" properties to
Nan Zhangb8fa1972017-12-22 16:12:00 -0800434 // check current module duplicates.
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800435 destToPySrcs := make(map[string]string)
436 destToPyData := make(map[string]string)
437
Dan Willemsen339a63f2023-08-15 22:17:03 -0400438 // Disable path checks for the stdlib, as it includes a "." in the version string
439 isInternal := proptools.BoolDefault(p.properties.Is_internal, false)
440
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800441 for _, s := range expandedSrcs {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800442 if s.Ext() != pyExt && s.Ext() != protoExt {
443 ctx.PropertyErrorf("srcs", "found non (.py|.proto) file: %q!", s.String())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800444 continue
445 }
Nan Zhang1db85402017-12-18 13:20:23 -0800446 runfilesPath := filepath.Join(pkgPath, s.Rel())
Dan Willemsen339a63f2023-08-15 22:17:03 -0400447 if !isInternal {
448 if err := isValidPythonPath(runfilesPath); err != nil {
449 ctx.PropertyErrorf("srcs", err.Error())
450 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800451 }
Liz Kammerd737d022020-11-16 15:42:51 -0800452 if !checkForDuplicateOutputPath(ctx, destToPySrcs, runfilesPath, s.String(), p.Name(), p.Name()) {
453 p.srcsPathMappings = append(p.srcsPathMappings, pathMapping{dest: runfilesPath, src: s})
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800454 }
455 }
456
457 for _, d := range expandedData {
Raphael Blistein59858462024-05-08 16:15:53 +0000458 if d.Ext() == pyExt {
459 ctx.PropertyErrorf("data", "found (.py) file: %q!", d.String())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800460 continue
461 }
Nan Zhang1db85402017-12-18 13:20:23 -0800462 runfilesPath := filepath.Join(pkgPath, d.Rel())
Liz Kammerd737d022020-11-16 15:42:51 -0800463 if !checkForDuplicateOutputPath(ctx, destToPyData, runfilesPath, d.String(), p.Name(), p.Name()) {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800464 p.dataPathMappings = append(p.dataPathMappings,
465 pathMapping{dest: runfilesPath, src: d})
466 }
467 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800468}
469
Liz Kammerd737d022020-11-16 15:42:51 -0800470// createSrcsZip registers build actions to zip current module's sources and data.
Cole Faust4d247e62023-01-23 10:14:58 -0800471func (p *PythonLibraryModule) createSrcsZip(ctx android.ModuleContext, pkgPath string) android.Path {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800472 relativeRootMap := make(map[string]android.Paths)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800473 var protoSrcs android.Paths
Cole Faust5c503d12023-01-24 11:48:08 -0800474 addPathMapping := func(path pathMapping) {
Raphael Blistein59858462024-05-08 16:15:53 +0000475 relativeRoot := strings.TrimSuffix(path.src.String(), path.src.Rel())
476 relativeRootMap[relativeRoot] = append(relativeRootMap[relativeRoot], path.src)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800477 }
Cole Faust5c503d12023-01-24 11:48:08 -0800478
479 // "srcs" or "data" properties may contain filegroups so it might happen that
480 // the root directory for each source path is different.
481 for _, path := range p.srcsPathMappings {
Raphael Blistein59858462024-05-08 16:15:53 +0000482 // handle proto sources separately
483 if path.src.Ext() == protoExt {
484 protoSrcs = append(protoSrcs, path.src)
485 } else {
486 addPathMapping(path)
487 }
Cole Faust5c503d12023-01-24 11:48:08 -0800488 }
489 for _, path := range p.dataPathMappings {
490 addPathMapping(path)
491 }
492
Nan Zhangb8fa1972017-12-22 16:12:00 -0800493 var zips android.Paths
494 if len(protoSrcs) > 0 {
Colin Cross19878da2019-03-28 14:45:07 -0700495 protoFlags := android.GetProtoFlags(ctx, &p.protoProperties)
496 protoFlags.OutTypeFlag = "--python_out"
497
Cole Faustcaf766b2022-10-21 16:07:56 -0700498 if pkgPath != "" {
Cole Faust43ac21f2022-09-19 11:19:52 -0700499 pkgPathStagingDir := android.PathForModuleGen(ctx, "protos_staged_for_pkg_path")
500 rule := android.NewRuleBuilder(pctx, ctx)
501 var stagedProtoSrcs android.Paths
502 for _, srcFile := range protoSrcs {
503 stagedProtoSrc := pkgPathStagingDir.Join(ctx, pkgPath, srcFile.Rel())
Cole Faust43ac21f2022-09-19 11:19:52 -0700504 rule.Command().Text("cp -f").Input(srcFile).Output(stagedProtoSrc)
505 stagedProtoSrcs = append(stagedProtoSrcs, stagedProtoSrc)
506 }
507 rule.Build("stage_protos_for_pkg_path", "Stage protos for pkg_path")
508 protoSrcs = stagedProtoSrcs
Cole Faust43ac21f2022-09-19 11:19:52 -0700509 }
510
Nan Zhangb8fa1972017-12-22 16:12:00 -0800511 for _, srcFile := range protoSrcs {
Cole Faustcaf766b2022-10-21 16:07:56 -0700512 zip := genProto(ctx, srcFile, protoFlags)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800513 zips = append(zips, zip)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800514 }
515 }
516
Nan Zhangb8fa1972017-12-22 16:12:00 -0800517 if len(relativeRootMap) > 0 {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800518 // in order to keep stable order of soong_zip params, we sort the keys here.
Cole Faust18994c72023-02-28 16:02:16 -0800519 roots := android.SortedKeys(relativeRootMap)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800520
Cole Faust01243362022-06-02 12:11:12 -0700521 // Use -symlinks=false so that the symlinks in the bazel output directory are followed
522 parArgs := []string{"-symlinks=false"}
Nan Zhangf0c4e432018-05-22 14:50:18 -0700523 if pkgPath != "" {
Liz Kammerd737d022020-11-16 15:42:51 -0800524 // use package path as path prefix
Nan Zhangf0c4e432018-05-22 14:50:18 -0700525 parArgs = append(parArgs, `-P `+pkgPath)
526 }
Liz Kammerd737d022020-11-16 15:42:51 -0800527 paths := android.Paths{}
528 for _, root := range roots {
529 // specify relative root of file in following -f arguments
530 parArgs = append(parArgs, `-C `+root)
531 for _, path := range relativeRootMap[root] {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800532 parArgs = append(parArgs, `-f `+path.String())
Liz Kammerd737d022020-11-16 15:42:51 -0800533 paths = append(paths, path)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800534 }
535 }
536
537 origSrcsZip := android.PathForModuleOut(ctx, ctx.ModuleName()+".py.srcszip")
538 ctx.Build(pctx, android.BuildParams{
539 Rule: zip,
540 Description: "python library archive",
541 Output: origSrcsZip,
Liz Kammerd737d022020-11-16 15:42:51 -0800542 // as zip rule does not use $in, there is no real need to distinguish between Inputs and Implicits
543 Implicits: paths,
Nan Zhangb8fa1972017-12-22 16:12:00 -0800544 Args: map[string]string{
545 "args": strings.Join(parArgs, " "),
546 },
547 })
548 zips = append(zips, origSrcsZip)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800549 }
Liz Kammerd737d022020-11-16 15:42:51 -0800550 // we may have multiple zips due to separate handling of proto source files
Nan Zhangb8fa1972017-12-22 16:12:00 -0800551 if len(zips) == 1 {
552 return zips[0]
553 } else {
554 combinedSrcsZip := android.PathForModuleOut(ctx, ctx.ModuleName()+".srcszip")
555 ctx.Build(pctx, android.BuildParams{
556 Rule: combineZip,
557 Description: "combine python library archive",
558 Output: combinedSrcsZip,
559 Inputs: zips,
560 })
561 return combinedSrcsZip
562 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800563}
564
Cole Faust5c503d12023-01-24 11:48:08 -0800565func (p *PythonLibraryModule) precompileSrcs(ctx android.ModuleContext) android.Path {
566 // To precompile the python sources, we need a python interpreter and stdlib built
567 // for host. We then use those to compile the python sources, which may be used on either
568 // host of device. Python bytecode is architecture agnostic, so we're essentially
569 // "cross compiling" for device here purely by virtue of host and device python bytecode
570 // being the same.
571 var stdLib android.Path
Dan Willemsen339a63f2023-08-15 22:17:03 -0400572 var stdLibPkg string
Cole Faust5c503d12023-01-24 11:48:08 -0800573 var launcher android.Path
Dan Willemsen339a63f2023-08-15 22:17:03 -0400574 if proptools.BoolDefault(p.properties.Is_internal, false) {
Cole Faust5c503d12023-01-24 11:48:08 -0800575 stdLib = p.srcsZip
Dan Willemsen339a63f2023-08-15 22:17:03 -0400576 stdLibPkg = p.getPkgPath()
Cole Faust5c503d12023-01-24 11:48:08 -0800577 } else {
Yu Liue98f7062025-01-17 22:52:43 +0000578 ctx.VisitDirectDepsProxyWithTag(hostStdLibTag, func(module android.ModuleProxy) {
579 if dep, ok := android.OtherModuleProvider(ctx, module, PythonLibraryInfoProvider); ok {
580 stdLib = dep.PrecompiledSrcsZip
581 stdLibPkg = dep.PkgPath
Cole Faust5c503d12023-01-24 11:48:08 -0800582 }
583 })
584 }
Yu Liue98f7062025-01-17 22:52:43 +0000585 ctx.VisitDirectDepsProxyWithTag(hostLauncherTag, func(module android.ModuleProxy) {
586 if dep, ok := android.OtherModuleProvider(ctx, module, cc.LinkableInfoProvider); ok {
587 optionalLauncher := dep.OutputFile
Cole Faust5c503d12023-01-24 11:48:08 -0800588 if optionalLauncher.Valid() {
589 launcher = optionalLauncher.Path()
590 }
Cole Faust909d2372023-02-13 23:17:40 +0000591 }
592 })
593 var launcherSharedLibs android.Paths
594 var ldLibraryPath []string
Yu Liue98f7062025-01-17 22:52:43 +0000595 ctx.VisitDirectDepsProxyWithTag(hostlauncherSharedLibTag, func(module android.ModuleProxy) {
596 if dep, ok := android.OtherModuleProvider(ctx, module, cc.LinkableInfoProvider); ok {
597 optionalPath := dep.OutputFile
Cole Faust909d2372023-02-13 23:17:40 +0000598 if optionalPath.Valid() {
599 launcherSharedLibs = append(launcherSharedLibs, optionalPath.Path())
600 ldLibraryPath = append(ldLibraryPath, filepath.Dir(optionalPath.Path().String()))
Cole Faust5c503d12023-01-24 11:48:08 -0800601 }
602 }
603 })
604
605 out := android.PathForModuleOut(ctx, ctx.ModuleName()+".srcszipprecompiled")
606 if stdLib == nil || launcher == nil {
607 // This shouldn't happen in a real build because we'll error out when adding dependencies
608 // on the stdlib and launcher if they don't exist. But some tests set
609 // AllowMissingDependencies.
610 return out
611 }
612 ctx.Build(pctx, android.BuildParams{
613 Rule: precompile,
614 Input: p.srcsZip,
615 Output: out,
616 Implicits: launcherSharedLibs,
617 Description: "Precompile the python sources of " + ctx.ModuleName(),
618 Args: map[string]string{
619 "stdlibZip": stdLib.String(),
Dan Willemsen339a63f2023-08-15 22:17:03 -0400620 "stdlibPkg": stdLibPkg,
Cole Faust5c503d12023-01-24 11:48:08 -0800621 "launcher": launcher.String(),
622 "ldLibraryPath": strings.Join(ldLibraryPath, ":"),
623 },
624 })
625 return out
626}
627
Liz Kammerd737d022020-11-16 15:42:51 -0800628// collectPathsFromTransitiveDeps checks for source/data files for duplicate paths
629// for module and its transitive dependencies and collects list of data/source file
630// zips for transitive dependencies.
Cole Faust5c503d12023-01-24 11:48:08 -0800631func (p *PythonLibraryModule) collectPathsFromTransitiveDeps(ctx android.ModuleContext, precompiled bool) android.Paths {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800632 // fetch <runfiles_path, source_path> pairs from "src" and "data" properties to
633 // check duplicates.
634 destToPySrcs := make(map[string]string)
635 destToPyData := make(map[string]string)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800636 for _, path := range p.srcsPathMappings {
637 destToPySrcs[path.dest] = path.src.String()
638 }
639 for _, path := range p.dataPathMappings {
640 destToPyData[path.dest] = path.src.String()
641 }
642
Colin Cross6b753602018-06-21 13:03:07 -0700643 seen := make(map[android.Module]bool)
644
Cole Faust4d247e62023-01-23 10:14:58 -0800645 var result android.Paths
646
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800647 // visit all its dependencies in depth first.
Yu Liue98f7062025-01-17 22:52:43 +0000648 ctx.WalkDepsProxy(func(child, _ android.ModuleProxy) bool {
Liz Kammerd737d022020-11-16 15:42:51 -0800649 // we only collect dependencies tagged as python library deps
Colin Cross6b753602018-06-21 13:03:07 -0700650 if ctx.OtherModuleDependencyTag(child) != pythonLibTag {
651 return false
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800652 }
Colin Cross6b753602018-06-21 13:03:07 -0700653 if seen[child] {
654 return false
655 }
656 seen[child] = true
Nan Zhangb8fa1972017-12-22 16:12:00 -0800657 // Python modules only can depend on Python libraries.
Yu Liue98f7062025-01-17 22:52:43 +0000658 dep, isLibrary := android.OtherModuleProvider(ctx, child, PythonLibraryInfoProvider)
659 _, isBinary := android.OtherModuleProvider(ctx, child, PythonBinaryInfoProvider)
660 if !isLibrary || isBinary {
Liz Kammerd737d022020-11-16 15:42:51 -0800661 ctx.PropertyErrorf("libs",
Nan Zhangd4e641b2017-07-12 12:55:28 -0700662 "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 +0000663 ctx.OtherModuleName(child), ctx.ModuleName())
Nan Zhangd4e641b2017-07-12 12:55:28 -0700664 }
Liz Kammerd737d022020-11-16 15:42:51 -0800665 // collect source and data paths, checking that there are no duplicate output file conflicts
Yu Liue98f7062025-01-17 22:52:43 +0000666 if isLibrary {
667 srcs := dep.SrcsPathMappings
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800668 for _, path := range srcs {
Liz Kammerd737d022020-11-16 15:42:51 -0800669 checkForDuplicateOutputPath(ctx, destToPySrcs,
Colin Cross6b753602018-06-21 13:03:07 -0700670 path.dest, path.src.String(), ctx.ModuleName(), ctx.OtherModuleName(child))
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800671 }
Yu Liue98f7062025-01-17 22:52:43 +0000672 data := dep.DataPathMappings
Liz Kammerd737d022020-11-16 15:42:51 -0800673 for _, path := range data {
674 checkForDuplicateOutputPath(ctx, destToPyData,
675 path.dest, path.src.String(), ctx.ModuleName(), ctx.OtherModuleName(child))
676 }
Cole Faust5c503d12023-01-24 11:48:08 -0800677 if precompiled {
Yu Liue98f7062025-01-17 22:52:43 +0000678 result = append(result, dep.PrecompiledSrcsZip)
Cole Faust5c503d12023-01-24 11:48:08 -0800679 } else {
Yu Liue98f7062025-01-17 22:52:43 +0000680 result = append(result, dep.SrcsZip)
Cole Faust5c503d12023-01-24 11:48:08 -0800681 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800682 }
Colin Cross6b753602018-06-21 13:03:07 -0700683 return true
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800684 })
Cole Faust4d247e62023-01-23 10:14:58 -0800685 return result
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800686}
687
Liz Kammerd737d022020-11-16 15:42:51 -0800688// chckForDuplicateOutputPath checks whether outputPath has already been included in map m, which
689// would result in two files being placed in the same location.
690// If there is a duplicate path, an error is thrown and true is returned
691// Otherwise, outputPath: srcPath is added to m and returns false
692func checkForDuplicateOutputPath(ctx android.ModuleContext, m map[string]string, outputPath, srcPath, curModule, otherModule string) bool {
693 if oldSrcPath, found := m[outputPath]; found {
Nan Zhangbea09752018-05-31 12:49:33 -0700694 ctx.ModuleErrorf("found two files to be placed at the same location within zip %q."+
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800695 " First file: in module %s at path %q."+
696 " Second file: in module %s at path %q.",
Liz Kammerd737d022020-11-16 15:42:51 -0800697 outputPath, curModule, oldSrcPath, otherModule, srcPath)
698 return true
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800699 }
Liz Kammerd737d022020-11-16 15:42:51 -0800700 m[outputPath] = srcPath
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800701
Liz Kammerd737d022020-11-16 15:42:51 -0800702 return false
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800703}
Nan Zhangea568a42017-11-08 21:20:04 -0800704
Liz Kammerd737d022020-11-16 15:42:51 -0800705// InstallInData returns true as Python is not supported in the system partition
Cole Faust4d247e62023-01-23 10:14:58 -0800706func (p *PythonLibraryModule) InstallInData() bool {
Nan Zhangd9ec5e72017-12-01 20:00:31 +0000707 return true
708}
709
Nan Zhangea568a42017-11-08 21:20:04 -0800710var Bool = proptools.Bool
Dan Willemsen6ca390f2019-02-14 23:17:08 -0800711var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -0800712var String = proptools.String