blob: 10c11ada0267a966034e4352bb2d3fc5adc920a6 [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 Willemsen7b90bcd2025-02-11 13:11:23 -0500403 p.precompiledSrcsZip = p.precompileSrcs(ctx)
Yu Liue98f7062025-01-17 22:52:43 +0000404
405 android.SetProvider(ctx, PythonLibraryInfoProvider, PythonLibraryInfo{
406 SrcsPathMappings: p.getSrcsPathMappings(),
407 DataPathMappings: p.getDataPathMappings(),
408 SrcsZip: p.getSrcsZip(),
409 PkgPath: p.getPkgPath(),
410 PrecompiledSrcsZip: p.getPrecompiledSrcsZip(),
411 })
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800412}
413
Liz Kammerd737d022020-11-16 15:42:51 -0800414func isValidPythonPath(path string) error {
415 identifiers := strings.Split(strings.TrimSuffix(path, filepath.Ext(path)), "/")
416 for _, token := range identifiers {
417 if !pathComponentRegexp.MatchString(token) {
418 return fmt.Errorf("the path %q contains invalid subpath %q. "+
419 "Subpaths must be at least one character long. "+
420 "The first character must an underscore or letter. "+
421 "Following characters may be any of: letter, digit, underscore, hyphen.",
422 path, token)
423 }
424 }
425 return nil
426}
427
428// For this module, generate unique pathMappings: <dest: runfiles_path, src: source_path>
429// for python/data files expanded from properties.
Cole Faust4d247e62023-01-23 10:14:58 -0800430func (p *PythonLibraryModule) genModulePathMappings(ctx android.ModuleContext, pkgPath string,
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800431 expandedSrcs, expandedData android.Paths) {
432 // fetch <runfiles_path, source_path> pairs from "src" and "data" properties to
Nan Zhangb8fa1972017-12-22 16:12:00 -0800433 // check current module duplicates.
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800434 destToPySrcs := make(map[string]string)
435 destToPyData := make(map[string]string)
436
Dan Willemsen339a63f2023-08-15 22:17:03 -0400437 // Disable path checks for the stdlib, as it includes a "." in the version string
438 isInternal := proptools.BoolDefault(p.properties.Is_internal, false)
439
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800440 for _, s := range expandedSrcs {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800441 if s.Ext() != pyExt && s.Ext() != protoExt {
442 ctx.PropertyErrorf("srcs", "found non (.py|.proto) file: %q!", s.String())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800443 continue
444 }
Nan Zhang1db85402017-12-18 13:20:23 -0800445 runfilesPath := filepath.Join(pkgPath, s.Rel())
Dan Willemsen339a63f2023-08-15 22:17:03 -0400446 if !isInternal {
447 if err := isValidPythonPath(runfilesPath); err != nil {
448 ctx.PropertyErrorf("srcs", err.Error())
449 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800450 }
Liz Kammerd737d022020-11-16 15:42:51 -0800451 if !checkForDuplicateOutputPath(ctx, destToPySrcs, runfilesPath, s.String(), p.Name(), p.Name()) {
452 p.srcsPathMappings = append(p.srcsPathMappings, pathMapping{dest: runfilesPath, src: s})
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800453 }
454 }
455
456 for _, d := range expandedData {
Raphael Blistein59858462024-05-08 16:15:53 +0000457 if d.Ext() == pyExt {
458 ctx.PropertyErrorf("data", "found (.py) file: %q!", d.String())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800459 continue
460 }
Nan Zhang1db85402017-12-18 13:20:23 -0800461 runfilesPath := filepath.Join(pkgPath, d.Rel())
Liz Kammerd737d022020-11-16 15:42:51 -0800462 if !checkForDuplicateOutputPath(ctx, destToPyData, runfilesPath, d.String(), p.Name(), p.Name()) {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800463 p.dataPathMappings = append(p.dataPathMappings,
464 pathMapping{dest: runfilesPath, src: d})
465 }
466 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800467}
468
Liz Kammerd737d022020-11-16 15:42:51 -0800469// createSrcsZip registers build actions to zip current module's sources and data.
Cole Faust4d247e62023-01-23 10:14:58 -0800470func (p *PythonLibraryModule) createSrcsZip(ctx android.ModuleContext, pkgPath string) android.Path {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800471 relativeRootMap := make(map[string]android.Paths)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800472 var protoSrcs android.Paths
Cole Faust5c503d12023-01-24 11:48:08 -0800473 addPathMapping := func(path pathMapping) {
Raphael Blistein59858462024-05-08 16:15:53 +0000474 relativeRoot := strings.TrimSuffix(path.src.String(), path.src.Rel())
475 relativeRootMap[relativeRoot] = append(relativeRootMap[relativeRoot], path.src)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800476 }
Cole Faust5c503d12023-01-24 11:48:08 -0800477
478 // "srcs" or "data" properties may contain filegroups so it might happen that
479 // the root directory for each source path is different.
480 for _, path := range p.srcsPathMappings {
Raphael Blistein59858462024-05-08 16:15:53 +0000481 // handle proto sources separately
482 if path.src.Ext() == protoExt {
483 protoSrcs = append(protoSrcs, path.src)
484 } else {
485 addPathMapping(path)
486 }
Cole Faust5c503d12023-01-24 11:48:08 -0800487 }
488 for _, path := range p.dataPathMappings {
489 addPathMapping(path)
490 }
491
Nan Zhangb8fa1972017-12-22 16:12:00 -0800492 var zips android.Paths
493 if len(protoSrcs) > 0 {
Colin Cross19878da2019-03-28 14:45:07 -0700494 protoFlags := android.GetProtoFlags(ctx, &p.protoProperties)
495 protoFlags.OutTypeFlag = "--python_out"
496
Cole Faustcaf766b2022-10-21 16:07:56 -0700497 if pkgPath != "" {
Cole Faust43ac21f2022-09-19 11:19:52 -0700498 pkgPathStagingDir := android.PathForModuleGen(ctx, "protos_staged_for_pkg_path")
499 rule := android.NewRuleBuilder(pctx, ctx)
500 var stagedProtoSrcs android.Paths
501 for _, srcFile := range protoSrcs {
502 stagedProtoSrc := pkgPathStagingDir.Join(ctx, pkgPath, srcFile.Rel())
Cole Faust43ac21f2022-09-19 11:19:52 -0700503 rule.Command().Text("cp -f").Input(srcFile).Output(stagedProtoSrc)
504 stagedProtoSrcs = append(stagedProtoSrcs, stagedProtoSrc)
505 }
506 rule.Build("stage_protos_for_pkg_path", "Stage protos for pkg_path")
507 protoSrcs = stagedProtoSrcs
Cole Faust43ac21f2022-09-19 11:19:52 -0700508 }
509
Nan Zhangb8fa1972017-12-22 16:12:00 -0800510 for _, srcFile := range protoSrcs {
Cole Faustcaf766b2022-10-21 16:07:56 -0700511 zip := genProto(ctx, srcFile, protoFlags)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800512 zips = append(zips, zip)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800513 }
514 }
515
Nan Zhangb8fa1972017-12-22 16:12:00 -0800516 if len(relativeRootMap) > 0 {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800517 // in order to keep stable order of soong_zip params, we sort the keys here.
Cole Faust18994c72023-02-28 16:02:16 -0800518 roots := android.SortedKeys(relativeRootMap)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800519
Cole Faust01243362022-06-02 12:11:12 -0700520 // Use -symlinks=false so that the symlinks in the bazel output directory are followed
521 parArgs := []string{"-symlinks=false"}
Nan Zhangf0c4e432018-05-22 14:50:18 -0700522 if pkgPath != "" {
Liz Kammerd737d022020-11-16 15:42:51 -0800523 // use package path as path prefix
Nan Zhangf0c4e432018-05-22 14:50:18 -0700524 parArgs = append(parArgs, `-P `+pkgPath)
525 }
Liz Kammerd737d022020-11-16 15:42:51 -0800526 paths := android.Paths{}
527 for _, root := range roots {
528 // specify relative root of file in following -f arguments
529 parArgs = append(parArgs, `-C `+root)
530 for _, path := range relativeRootMap[root] {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800531 parArgs = append(parArgs, `-f `+path.String())
Liz Kammerd737d022020-11-16 15:42:51 -0800532 paths = append(paths, path)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800533 }
534 }
535
536 origSrcsZip := android.PathForModuleOut(ctx, ctx.ModuleName()+".py.srcszip")
537 ctx.Build(pctx, android.BuildParams{
538 Rule: zip,
539 Description: "python library archive",
540 Output: origSrcsZip,
Liz Kammerd737d022020-11-16 15:42:51 -0800541 // as zip rule does not use $in, there is no real need to distinguish between Inputs and Implicits
542 Implicits: paths,
Nan Zhangb8fa1972017-12-22 16:12:00 -0800543 Args: map[string]string{
544 "args": strings.Join(parArgs, " "),
545 },
546 })
547 zips = append(zips, origSrcsZip)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800548 }
Liz Kammerd737d022020-11-16 15:42:51 -0800549 // we may have multiple zips due to separate handling of proto source files
Nan Zhangb8fa1972017-12-22 16:12:00 -0800550 if len(zips) == 1 {
551 return zips[0]
552 } else {
553 combinedSrcsZip := android.PathForModuleOut(ctx, ctx.ModuleName()+".srcszip")
554 ctx.Build(pctx, android.BuildParams{
555 Rule: combineZip,
556 Description: "combine python library archive",
557 Output: combinedSrcsZip,
558 Inputs: zips,
559 })
560 return combinedSrcsZip
561 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800562}
563
Cole Faust5c503d12023-01-24 11:48:08 -0800564func (p *PythonLibraryModule) precompileSrcs(ctx android.ModuleContext) android.Path {
565 // To precompile the python sources, we need a python interpreter and stdlib built
566 // for host. We then use those to compile the python sources, which may be used on either
567 // host of device. Python bytecode is architecture agnostic, so we're essentially
568 // "cross compiling" for device here purely by virtue of host and device python bytecode
569 // being the same.
570 var stdLib android.Path
Dan Willemsen339a63f2023-08-15 22:17:03 -0400571 var stdLibPkg string
Cole Faust5c503d12023-01-24 11:48:08 -0800572 var launcher android.Path
Dan Willemsen339a63f2023-08-15 22:17:03 -0400573 if proptools.BoolDefault(p.properties.Is_internal, false) {
Cole Faust5c503d12023-01-24 11:48:08 -0800574 stdLib = p.srcsZip
Dan Willemsen339a63f2023-08-15 22:17:03 -0400575 stdLibPkg = p.getPkgPath()
Cole Faust5c503d12023-01-24 11:48:08 -0800576 } else {
Yu Liue98f7062025-01-17 22:52:43 +0000577 ctx.VisitDirectDepsProxyWithTag(hostStdLibTag, func(module android.ModuleProxy) {
578 if dep, ok := android.OtherModuleProvider(ctx, module, PythonLibraryInfoProvider); ok {
579 stdLib = dep.PrecompiledSrcsZip
580 stdLibPkg = dep.PkgPath
Cole Faust5c503d12023-01-24 11:48:08 -0800581 }
582 })
583 }
Yu Liue98f7062025-01-17 22:52:43 +0000584 ctx.VisitDirectDepsProxyWithTag(hostLauncherTag, func(module android.ModuleProxy) {
585 if dep, ok := android.OtherModuleProvider(ctx, module, cc.LinkableInfoProvider); ok {
586 optionalLauncher := dep.OutputFile
Cole Faust5c503d12023-01-24 11:48:08 -0800587 if optionalLauncher.Valid() {
588 launcher = optionalLauncher.Path()
589 }
Cole Faust909d2372023-02-13 23:17:40 +0000590 }
591 })
592 var launcherSharedLibs android.Paths
593 var ldLibraryPath []string
Yu Liue98f7062025-01-17 22:52:43 +0000594 ctx.VisitDirectDepsProxyWithTag(hostlauncherSharedLibTag, func(module android.ModuleProxy) {
595 if dep, ok := android.OtherModuleProvider(ctx, module, cc.LinkableInfoProvider); ok {
596 optionalPath := dep.OutputFile
Cole Faust909d2372023-02-13 23:17:40 +0000597 if optionalPath.Valid() {
598 launcherSharedLibs = append(launcherSharedLibs, optionalPath.Path())
599 ldLibraryPath = append(ldLibraryPath, filepath.Dir(optionalPath.Path().String()))
Cole Faust5c503d12023-01-24 11:48:08 -0800600 }
601 }
602 })
603
604 out := android.PathForModuleOut(ctx, ctx.ModuleName()+".srcszipprecompiled")
605 if stdLib == nil || launcher == nil {
606 // This shouldn't happen in a real build because we'll error out when adding dependencies
607 // on the stdlib and launcher if they don't exist. But some tests set
608 // AllowMissingDependencies.
609 return out
610 }
611 ctx.Build(pctx, android.BuildParams{
612 Rule: precompile,
613 Input: p.srcsZip,
614 Output: out,
615 Implicits: launcherSharedLibs,
616 Description: "Precompile the python sources of " + ctx.ModuleName(),
617 Args: map[string]string{
618 "stdlibZip": stdLib.String(),
Dan Willemsen339a63f2023-08-15 22:17:03 -0400619 "stdlibPkg": stdLibPkg,
Cole Faust5c503d12023-01-24 11:48:08 -0800620 "launcher": launcher.String(),
621 "ldLibraryPath": strings.Join(ldLibraryPath, ":"),
622 },
623 })
624 return out
625}
626
Liz Kammerd737d022020-11-16 15:42:51 -0800627// collectPathsFromTransitiveDeps checks for source/data files for duplicate paths
628// for module and its transitive dependencies and collects list of data/source file
629// zips for transitive dependencies.
Cole Faust5c503d12023-01-24 11:48:08 -0800630func (p *PythonLibraryModule) collectPathsFromTransitiveDeps(ctx android.ModuleContext, precompiled bool) android.Paths {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800631 // fetch <runfiles_path, source_path> pairs from "src" and "data" properties to
632 // check duplicates.
633 destToPySrcs := make(map[string]string)
634 destToPyData := make(map[string]string)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800635 for _, path := range p.srcsPathMappings {
636 destToPySrcs[path.dest] = path.src.String()
637 }
638 for _, path := range p.dataPathMappings {
639 destToPyData[path.dest] = path.src.String()
640 }
641
Colin Cross6b753602018-06-21 13:03:07 -0700642 seen := make(map[android.Module]bool)
643
Cole Faust4d247e62023-01-23 10:14:58 -0800644 var result android.Paths
645
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800646 // visit all its dependencies in depth first.
Yu Liue98f7062025-01-17 22:52:43 +0000647 ctx.WalkDepsProxy(func(child, _ android.ModuleProxy) bool {
Liz Kammerd737d022020-11-16 15:42:51 -0800648 // we only collect dependencies tagged as python library deps
Colin Cross6b753602018-06-21 13:03:07 -0700649 if ctx.OtherModuleDependencyTag(child) != pythonLibTag {
650 return false
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800651 }
Colin Cross6b753602018-06-21 13:03:07 -0700652 if seen[child] {
653 return false
654 }
655 seen[child] = true
Nan Zhangb8fa1972017-12-22 16:12:00 -0800656 // Python modules only can depend on Python libraries.
Yu Liue98f7062025-01-17 22:52:43 +0000657 dep, isLibrary := android.OtherModuleProvider(ctx, child, PythonLibraryInfoProvider)
658 _, isBinary := android.OtherModuleProvider(ctx, child, PythonBinaryInfoProvider)
659 if !isLibrary || isBinary {
Liz Kammerd737d022020-11-16 15:42:51 -0800660 ctx.PropertyErrorf("libs",
Nan Zhangd4e641b2017-07-12 12:55:28 -0700661 "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 +0000662 ctx.OtherModuleName(child), ctx.ModuleName())
Nan Zhangd4e641b2017-07-12 12:55:28 -0700663 }
Liz Kammerd737d022020-11-16 15:42:51 -0800664 // collect source and data paths, checking that there are no duplicate output file conflicts
Yu Liue98f7062025-01-17 22:52:43 +0000665 if isLibrary {
666 srcs := dep.SrcsPathMappings
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800667 for _, path := range srcs {
Liz Kammerd737d022020-11-16 15:42:51 -0800668 checkForDuplicateOutputPath(ctx, destToPySrcs,
Colin Cross6b753602018-06-21 13:03:07 -0700669 path.dest, path.src.String(), ctx.ModuleName(), ctx.OtherModuleName(child))
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800670 }
Yu Liue98f7062025-01-17 22:52:43 +0000671 data := dep.DataPathMappings
Liz Kammerd737d022020-11-16 15:42:51 -0800672 for _, path := range data {
673 checkForDuplicateOutputPath(ctx, destToPyData,
674 path.dest, path.src.String(), ctx.ModuleName(), ctx.OtherModuleName(child))
675 }
Cole Faust5c503d12023-01-24 11:48:08 -0800676 if precompiled {
Yu Liue98f7062025-01-17 22:52:43 +0000677 result = append(result, dep.PrecompiledSrcsZip)
Cole Faust5c503d12023-01-24 11:48:08 -0800678 } else {
Yu Liue98f7062025-01-17 22:52:43 +0000679 result = append(result, dep.SrcsZip)
Cole Faust5c503d12023-01-24 11:48:08 -0800680 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800681 }
Colin Cross6b753602018-06-21 13:03:07 -0700682 return true
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800683 })
Cole Faust4d247e62023-01-23 10:14:58 -0800684 return result
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800685}
686
Liz Kammerd737d022020-11-16 15:42:51 -0800687// chckForDuplicateOutputPath checks whether outputPath has already been included in map m, which
688// would result in two files being placed in the same location.
689// If there is a duplicate path, an error is thrown and true is returned
690// Otherwise, outputPath: srcPath is added to m and returns false
691func checkForDuplicateOutputPath(ctx android.ModuleContext, m map[string]string, outputPath, srcPath, curModule, otherModule string) bool {
692 if oldSrcPath, found := m[outputPath]; found {
Nan Zhangbea09752018-05-31 12:49:33 -0700693 ctx.ModuleErrorf("found two files to be placed at the same location within zip %q."+
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800694 " First file: in module %s at path %q."+
695 " Second file: in module %s at path %q.",
Liz Kammerd737d022020-11-16 15:42:51 -0800696 outputPath, curModule, oldSrcPath, otherModule, srcPath)
697 return true
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800698 }
Liz Kammerd737d022020-11-16 15:42:51 -0800699 m[outputPath] = srcPath
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800700
Liz Kammerd737d022020-11-16 15:42:51 -0800701 return false
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800702}
Nan Zhangea568a42017-11-08 21:20:04 -0800703
Liz Kammerd737d022020-11-16 15:42:51 -0800704// InstallInData returns true as Python is not supported in the system partition
Cole Faust4d247e62023-01-23 10:14:58 -0800705func (p *PythonLibraryModule) InstallInData() bool {
Nan Zhangd9ec5e72017-12-01 20:00:31 +0000706 return true
707}
708
Nan Zhangea568a42017-11-08 21:20:04 -0800709var Bool = proptools.Bool
Dan Willemsen6ca390f2019-02-14 23:17:08 -0800710var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -0800711var String = proptools.String