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