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