blob: 770ea4d14273202db36c428f4f879af38aa3a4be [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"
23 "sort"
24 "strings"
25
26 "github.com/google/blueprint"
Nan Zhangd4e641b2017-07-12 12:55:28 -070027 "github.com/google/blueprint/proptools"
Nan Zhangdb0b9a32017-02-27 10:12:13 -080028
29 "android/soong/android"
30)
31
32func init() {
Liz Kammerdd849a82020-06-12 16:38:45 -070033 android.PreDepsMutators(RegisterPythonPreDepsMutators)
34}
35
36func RegisterPythonPreDepsMutators(ctx android.RegisterMutatorsContext) {
Colin Crosse20113d2020-11-22 19:37:44 -080037 ctx.BottomUp("python_version", versionSplitMutator()).Parallel()
Nan Zhangdb0b9a32017-02-27 10:12:13 -080038}
39
40// the version properties that apply to python libraries and binaries.
Nan Zhangd4e641b2017-07-12 12:55:28 -070041type VersionProperties struct {
Nan Zhangdb0b9a32017-02-27 10:12:13 -080042 // true, if the module is required to be built with this version.
Nan Zhangd4e641b2017-07-12 12:55:28 -070043 Enabled *bool `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080044
45 // non-empty list of .py files under this strict Python version.
46 // srcs may reference the outputs of other modules that produce source files like genrule
47 // or filegroup using the syntax ":module".
Colin Cross27b922f2019-03-04 22:35:41 -080048 Srcs []string `android:"path,arch_variant"`
Nan Zhangd4e641b2017-07-12 12:55:28 -070049
50 // list of source files that should not be used to build the Python module.
51 // This is most useful in the arch/multilib variants to remove non-common files
Colin Cross27b922f2019-03-04 22:35:41 -080052 Exclude_srcs []string `android:"path,arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080053
54 // list of the Python libraries under this Python version.
Nan Zhangd4e641b2017-07-12 12:55:28 -070055 Libs []string `android:"arch_variant"`
56
57 // true, if the binary is required to be built with embedded launcher.
58 // TODO(nanzhang): Remove this flag when embedded Python3 is supported later.
59 Embedded_launcher *bool `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080060}
61
62// properties that apply to python libraries and binaries.
Nan Zhangd4e641b2017-07-12 12:55:28 -070063type BaseProperties struct {
Nan Zhangdb0b9a32017-02-27 10:12:13 -080064 // the package path prefix within the output artifact at which to place the source/data
65 // files of the current module.
66 // eg. Pkg_path = "a/b/c"; Other packages can reference this module by using
67 // (from a.b.c import ...) statement.
Nan Zhangbea09752018-05-31 12:49:33 -070068 // if left unspecified, all the source/data files path is unchanged within zip file.
Nan Zhangea568a42017-11-08 21:20:04 -080069 Pkg_path *string `android:"arch_variant"`
Nan Zhangd4e641b2017-07-12 12:55:28 -070070
71 // true, if the Python module is used internally, eg, Python std libs.
72 Is_internal *bool `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080073
74 // list of source (.py) files compatible both with Python2 and Python3 used to compile the
75 // Python module.
76 // srcs may reference the outputs of other modules that produce source files like genrule
77 // or filegroup using the syntax ":module".
78 // Srcs has to be non-empty.
Colin Cross27b922f2019-03-04 22:35:41 -080079 Srcs []string `android:"path,arch_variant"`
Nan Zhangd4e641b2017-07-12 12:55:28 -070080
81 // list of source files that should not be used to build the C/C++ module.
82 // This is most useful in the arch/multilib variants to remove non-common files
Colin Cross27b922f2019-03-04 22:35:41 -080083 Exclude_srcs []string `android:"path,arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080084
85 // list of files or filegroup modules that provide data that should be installed alongside
86 // the test. the file extension can be arbitrary except for (.py).
Colin Cross27b922f2019-03-04 22:35:41 -080087 Data []string `android:"path,arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080088
89 // list of the Python libraries compatible both with Python2 and Python3.
Nan Zhangd4e641b2017-07-12 12:55:28 -070090 Libs []string `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080091
92 Version struct {
93 // all the "srcs" or Python dependencies that are to be used only for Python2.
Nan Zhangd4e641b2017-07-12 12:55:28 -070094 Py2 VersionProperties `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080095
96 // all the "srcs" or Python dependencies that are to be used only for Python3.
Nan Zhangd4e641b2017-07-12 12:55:28 -070097 Py3 VersionProperties `android:"arch_variant"`
98 } `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080099
100 // the actual version each module uses after variations created.
101 // this property name is hidden from users' perspectives, and soong will populate it during
102 // runtime.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700103 Actual_version string `blueprint:"mutated"`
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700104
105 // true, if the module is required to be built with actual_version.
106 Enabled *bool `blueprint:"mutated"`
107
108 // true, if the binary is required to be built with embedded launcher.
109 // TODO(nanzhang): Remove this flag when embedded Python3 is supported later.
110 Embedded_launcher *bool `blueprint:"mutated"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800111}
112
113type pathMapping struct {
114 dest string
115 src android.Path
116}
117
Nan Zhangd4e641b2017-07-12 12:55:28 -0700118type Module struct {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800119 android.ModuleBase
Nan Zhanga3fc4ba2017-07-20 17:43:37 -0700120 android.DefaultableModuleBase
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800121
Nan Zhangb8fa1972017-12-22 16:12:00 -0800122 properties BaseProperties
123 protoProperties android.ProtoProperties
Nan Zhangd4e641b2017-07-12 12:55:28 -0700124
125 // initialize before calling Init
126 hod android.HostOrDeviceSupported
127 multilib android.Multilib
128
129 // the bootstrapper is used to bootstrap .par executable.
130 // bootstrapper might be nil (Python library module).
131 bootstrapper bootstrapper
132
133 // the installer might be nil.
134 installer installer
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800135
136 // the Python files of current module after expanding source dependencies.
137 // pathMapping: <dest: runfile_path, src: source_path>
138 srcsPathMappings []pathMapping
139
140 // the data files of current module after expanding source dependencies.
141 // pathMapping: <dest: runfile_path, src: source_path>
142 dataPathMappings []pathMapping
143
Nan Zhang1db85402017-12-18 13:20:23 -0800144 // the zip filepath for zipping current module source/data files.
145 srcsZip android.Path
Nan Zhangd4e641b2017-07-12 12:55:28 -0700146
Nan Zhang1db85402017-12-18 13:20:23 -0800147 // dependency modules' zip filepath for zipping current module source/data files.
148 depsSrcsZips android.Paths
Nan Zhangd4e641b2017-07-12 12:55:28 -0700149
150 // (.intermediate) module output path as installation source.
151 installSource android.OptionalPath
152
Nan Zhang5323f8e2017-05-10 13:37:54 -0700153 subAndroidMkOnce map[subAndroidMkProvider]bool
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800154}
155
Nan Zhangd4e641b2017-07-12 12:55:28 -0700156func newModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
157 return &Module{
158 hod: hod,
159 multilib: multilib,
160 }
161}
162
163type bootstrapper interface {
164 bootstrapperProps() []interface{}
Nan Zhang1db85402017-12-18 13:20:23 -0800165 bootstrap(ctx android.ModuleContext, ActualVersion string, embeddedLauncher bool,
166 srcsPathMappings []pathMapping, srcsZip android.Path,
167 depsSrcsZips android.Paths) android.OptionalPath
Dan Willemsen6ca390f2019-02-14 23:17:08 -0800168
169 autorun() bool
Nan Zhangd4e641b2017-07-12 12:55:28 -0700170}
171
172type installer interface {
173 install(ctx android.ModuleContext, path android.Path)
Logan Chien02880e42018-11-06 17:30:35 +0800174 setAndroidMkSharedLibs(sharedLibs []string)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800175}
176
177type PythonDependency interface {
178 GetSrcsPathMappings() []pathMapping
179 GetDataPathMappings() []pathMapping
Nan Zhang1db85402017-12-18 13:20:23 -0800180 GetSrcsZip() android.Path
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800181}
182
Nan Zhangd4e641b2017-07-12 12:55:28 -0700183func (p *Module) GetSrcsPathMappings() []pathMapping {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800184 return p.srcsPathMappings
185}
186
Nan Zhangd4e641b2017-07-12 12:55:28 -0700187func (p *Module) GetDataPathMappings() []pathMapping {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800188 return p.dataPathMappings
189}
190
Nan Zhang1db85402017-12-18 13:20:23 -0800191func (p *Module) GetSrcsZip() android.Path {
192 return p.srcsZip
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800193}
194
Nan Zhangd4e641b2017-07-12 12:55:28 -0700195var _ PythonDependency = (*Module)(nil)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800196
Nan Zhangd4e641b2017-07-12 12:55:28 -0700197var _ android.AndroidMkDataProvider = (*Module)(nil)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800198
Nan Zhangd4e641b2017-07-12 12:55:28 -0700199func (p *Module) Init() android.Module {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800200
Nan Zhangb8fa1972017-12-22 16:12:00 -0800201 p.AddProperties(&p.properties, &p.protoProperties)
Nan Zhangd4e641b2017-07-12 12:55:28 -0700202 if p.bootstrapper != nil {
203 p.AddProperties(p.bootstrapper.bootstrapperProps()...)
204 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800205
Nan Zhangd4e641b2017-07-12 12:55:28 -0700206 android.InitAndroidArchModule(p, p.hod, p.multilib)
Nan Zhanga3fc4ba2017-07-20 17:43:37 -0700207 android.InitDefaultableModule(p)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800208
Nan Zhangd4e641b2017-07-12 12:55:28 -0700209 return p
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800210}
211
Nan Zhangd4e641b2017-07-12 12:55:28 -0700212type dependencyTag struct {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800213 blueprint.BaseDependencyTag
Nan Zhangd4e641b2017-07-12 12:55:28 -0700214 name string
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800215}
216
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800217var (
Logan Chien02880e42018-11-06 17:30:35 +0800218 pythonLibTag = dependencyTag{name: "pythonLib"}
219 launcherTag = dependencyTag{name: "launcher"}
220 launcherSharedLibTag = dependencyTag{name: "launcherSharedLib"}
221 pyIdentifierRegexp = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`)
222 pyExt = ".py"
223 protoExt = ".proto"
224 pyVersion2 = "PY2"
225 pyVersion3 = "PY3"
226 initFileName = "__init__.py"
227 mainFileName = "__main__.py"
228 entryPointFile = "entry_point.txt"
229 parFileExt = ".zip"
230 internal = "internal"
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800231)
232
233// create version variants for modules.
234func versionSplitMutator() func(android.BottomUpMutatorContext) {
235 return func(mctx android.BottomUpMutatorContext) {
Nan Zhangd4e641b2017-07-12 12:55:28 -0700236 if base, ok := mctx.Module().(*Module); ok {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800237 versionNames := []string{}
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700238 versionProps := []VersionProperties{}
Liz Kammerdd849a82020-06-12 16:38:45 -0700239 // PY3 is first so that we alias the PY3 variant rather than PY2 if both
240 // are available
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800241 if !(base.properties.Version.Py3.Enabled != nil &&
242 *(base.properties.Version.Py3.Enabled) == false) {
243 versionNames = append(versionNames, pyVersion3)
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700244 versionProps = append(versionProps, base.properties.Version.Py3)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800245 }
Liz Kammerdd849a82020-06-12 16:38:45 -0700246 if base.properties.Version.Py2.Enabled != nil &&
247 *(base.properties.Version.Py2.Enabled) == true {
248 versionNames = append(versionNames, pyVersion2)
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700249 versionProps = append(versionProps, base.properties.Version.Py2)
Liz Kammerdd849a82020-06-12 16:38:45 -0700250 }
Colin Crosse20113d2020-11-22 19:37:44 -0800251 modules := mctx.CreateLocalVariations(versionNames...)
Liz Kammerdd849a82020-06-12 16:38:45 -0700252 if len(versionNames) > 0 {
253 mctx.AliasVariation(versionNames[0])
254 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800255 for i, v := range versionNames {
256 // set the actual version for Python module.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700257 modules[i].(*Module).properties.Actual_version = v
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700258 // append versioned properties for the Python module
259 err := proptools.AppendMatchingProperties([]interface{}{&modules[i].(*Module).properties}, &versionProps[i], nil)
260 if err != nil {
261 panic(err)
262 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800263 }
264 }
265 }
266}
267
Nan Zhangb8bdacf2017-12-06 15:13:10 -0800268func (p *Module) HostToolPath() android.OptionalPath {
269 if p.installer == nil {
270 // python_library is just meta module, and doesn't have any installer.
271 return android.OptionalPath{}
272 }
273 return android.OptionalPathForPath(p.installer.(*binaryDecorator).path)
274}
275
Liz Kammere0070ee2020-06-22 11:52:59 -0700276func (p *Module) OutputFiles(tag string) (android.Paths, error) {
277 switch tag {
278 case "":
279 if outputFile := p.installSource; outputFile.Valid() {
280 return android.Paths{outputFile.Path()}, nil
281 }
282 return android.Paths{}, nil
283 default:
284 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
285 }
286}
287
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700288func (p *Module) isEmbeddedLauncherEnabled() bool {
289 return Bool(p.properties.Embedded_launcher)
Nan Zhangd4e641b2017-07-12 12:55:28 -0700290}
291
Nan Zhangb8fa1972017-12-22 16:12:00 -0800292func hasSrcExt(srcs []string, ext string) bool {
293 for _, src := range srcs {
294 if filepath.Ext(src) == ext {
295 return true
296 }
297 }
298
299 return false
300}
301
302func (p *Module) hasSrcExt(ctx android.BottomUpMutatorContext, ext string) bool {
Liz Kammer3dfd3ce2020-11-16 11:30:55 -0800303 return hasSrcExt(p.properties.Srcs, ext)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800304}
305
Nan Zhangd4e641b2017-07-12 12:55:28 -0700306func (p *Module) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Crossfe17f6f2019-03-28 19:30:56 -0700307 android.ProtoDeps(ctx, &p.protoProperties)
308
Colin Crosse20113d2020-11-22 19:37:44 -0800309 versionVariation := []blueprint.Variation{
310 {"python_version", p.properties.Actual_version},
Nan Zhangb8fa1972017-12-22 16:12:00 -0800311 }
Colin Crosse20113d2020-11-22 19:37:44 -0800312
313 if p.hasSrcExt(ctx, protoExt) && p.Name() != "libprotobuf-python" {
314 ctx.AddVariationDependencies(versionVariation, pythonLibTag, "libprotobuf-python")
315 }
316 ctx.AddVariationDependencies(versionVariation, pythonLibTag, android.LastUniqueStrings(p.properties.Libs)...)
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700317
Nan Zhangd4e641b2017-07-12 12:55:28 -0700318 switch p.properties.Actual_version {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800319 case pyVersion2:
Nan Zhangd4e641b2017-07-12 12:55:28 -0700320
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700321 if p.bootstrapper != nil && p.isEmbeddedLauncherEnabled() {
Colin Crosse20113d2020-11-22 19:37:44 -0800322 ctx.AddVariationDependencies(versionVariation, pythonLibTag, "py2-stdlib")
Dan Willemsen6ca390f2019-02-14 23:17:08 -0800323
324 launcherModule := "py2-launcher"
325 if p.bootstrapper.autorun() {
326 launcherModule = "py2-launcher-autorun"
327 }
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700328 ctx.AddFarVariationDependencies(ctx.Target().Variations(), launcherTag, launcherModule)
Logan Chien02880e42018-11-06 17:30:35 +0800329
330 // Add py2-launcher shared lib dependencies. Ideally, these should be
331 // derived from the `shared_libs` property of "py2-launcher". However, we
332 // cannot read the property at this stage and it will be too late to add
333 // dependencies later.
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700334 ctx.AddFarVariationDependencies(ctx.Target().Variations(), launcherSharedLibTag, "libsqlite")
Logan Chien02880e42018-11-06 17:30:35 +0800335
336 if ctx.Target().Os.Bionic() {
Colin Cross0f7d2ef2019-10-16 11:03:10 -0700337 ctx.AddFarVariationDependencies(ctx.Target().Variations(), launcherSharedLibTag,
338 "libc", "libdl", "libm")
Logan Chien02880e42018-11-06 17:30:35 +0800339 }
Nan Zhangd4e641b2017-07-12 12:55:28 -0700340 }
341
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800342 case pyVersion3:
Nan Zhangd4e641b2017-07-12 12:55:28 -0700343
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700344 if p.bootstrapper != nil && p.isEmbeddedLauncherEnabled() {
Colin Crosse20113d2020-11-22 19:37:44 -0800345 ctx.AddVariationDependencies(versionVariation, pythonLibTag, "py3-stdlib")
Dan Willemsen8d4d7be2019-11-04 19:21:04 -0800346
347 launcherModule := "py3-launcher"
348 if p.bootstrapper.autorun() {
349 launcherModule = "py3-launcher-autorun"
350 }
351 ctx.AddFarVariationDependencies(ctx.Target().Variations(), launcherTag, launcherModule)
352
353 // Add py3-launcher shared lib dependencies. Ideally, these should be
354 // derived from the `shared_libs` property of "py3-launcher". However, we
355 // cannot read the property at this stage and it will be too late to add
356 // dependencies later.
357 ctx.AddFarVariationDependencies(ctx.Target().Variations(), launcherSharedLibTag, "libsqlite")
358
Dan Willemsend7a1dee2020-01-20 22:08:20 -0800359 if ctx.Device() {
360 ctx.AddFarVariationDependencies(ctx.Target().Variations(), launcherSharedLibTag,
361 "liblog")
362 }
363
Dan Willemsen8d4d7be2019-11-04 19:21:04 -0800364 if ctx.Target().Os.Bionic() {
365 ctx.AddFarVariationDependencies(ctx.Target().Variations(), launcherSharedLibTag,
366 "libc", "libdl", "libm")
367 }
Nan Zhangd4e641b2017-07-12 12:55:28 -0700368 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800369 default:
Nan Zhangd4e641b2017-07-12 12:55:28 -0700370 panic(fmt.Errorf("unknown Python Actual_version: %q for module: %q.",
371 p.properties.Actual_version, ctx.ModuleName()))
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800372 }
373}
374
Nan Zhangd4e641b2017-07-12 12:55:28 -0700375func (p *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
376 p.GeneratePythonBuildActions(ctx)
Nan Zhang5323f8e2017-05-10 13:37:54 -0700377
Nan Zhangb8fa1972017-12-22 16:12:00 -0800378 // Only Python binaries and test has non-empty bootstrapper.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700379 if p.bootstrapper != nil {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800380 p.walkTransitiveDeps(ctx)
Nan Zhang1db85402017-12-18 13:20:23 -0800381 embeddedLauncher := false
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700382 embeddedLauncher = p.isEmbeddedLauncherEnabled()
Nan Zhangd4e641b2017-07-12 12:55:28 -0700383 p.installSource = p.bootstrapper.bootstrap(ctx, p.properties.Actual_version,
Nan Zhang1db85402017-12-18 13:20:23 -0800384 embeddedLauncher, p.srcsPathMappings, p.srcsZip, p.depsSrcsZips)
Nan Zhang5323f8e2017-05-10 13:37:54 -0700385 }
Nan Zhangd4e641b2017-07-12 12:55:28 -0700386
Logan Chien02880e42018-11-06 17:30:35 +0800387 if p.installer != nil {
388 var sharedLibs []string
389 ctx.VisitDirectDeps(func(dep android.Module) {
390 if ctx.OtherModuleDependencyTag(dep) == launcherSharedLibTag {
391 sharedLibs = append(sharedLibs, ctx.OtherModuleName(dep))
392 }
393 })
394 p.installer.setAndroidMkSharedLibs(sharedLibs)
395
396 if p.installSource.Valid() {
397 p.installer.install(ctx, p.installSource.Path())
398 }
Nan Zhangd4e641b2017-07-12 12:55:28 -0700399 }
400
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800401}
402
Nan Zhangd4e641b2017-07-12 12:55:28 -0700403func (p *Module) GeneratePythonBuildActions(ctx android.ModuleContext) {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800404 // expand python files from "srcs" property.
405 srcs := p.properties.Srcs
Nan Zhangd4e641b2017-07-12 12:55:28 -0700406 exclude_srcs := p.properties.Exclude_srcs
Colin Cross8a497952019-03-05 22:25:09 -0800407 expandedSrcs := android.PathsForModuleSrcExcludes(ctx, srcs, exclude_srcs)
Dan Willemsen6ca390f2019-02-14 23:17:08 -0800408 requiresSrcs := true
409 if p.bootstrapper != nil && !p.bootstrapper.autorun() {
410 requiresSrcs = false
411 }
412 if len(expandedSrcs) == 0 && requiresSrcs {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800413 ctx.ModuleErrorf("doesn't have any source files!")
414 }
415
416 // expand data files from "data" property.
Colin Cross8a497952019-03-05 22:25:09 -0800417 expandedData := android.PathsForModuleSrc(ctx, p.properties.Data)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800418
419 // sanitize pkg_path.
Nan Zhang1db85402017-12-18 13:20:23 -0800420 pkgPath := String(p.properties.Pkg_path)
421 if pkgPath != "" {
422 pkgPath = filepath.Clean(String(p.properties.Pkg_path))
423 if pkgPath == ".." || strings.HasPrefix(pkgPath, "../") ||
424 strings.HasPrefix(pkgPath, "/") {
Nan Zhangd4e641b2017-07-12 12:55:28 -0700425 ctx.PropertyErrorf("pkg_path",
426 "%q must be a relative path contained in par file.",
Nan Zhangea568a42017-11-08 21:20:04 -0800427 String(p.properties.Pkg_path))
Nan Zhangd4e641b2017-07-12 12:55:28 -0700428 return
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800429 }
Nan Zhangd4e641b2017-07-12 12:55:28 -0700430 if p.properties.Is_internal != nil && *p.properties.Is_internal {
Nan Zhang1db85402017-12-18 13:20:23 -0800431 pkgPath = filepath.Join(internal, pkgPath)
Nan Zhangd4e641b2017-07-12 12:55:28 -0700432 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800433 } else {
Nan Zhangd4e641b2017-07-12 12:55:28 -0700434 if p.properties.Is_internal != nil && *p.properties.Is_internal {
Nan Zhang1db85402017-12-18 13:20:23 -0800435 pkgPath = internal
Nan Zhangd4e641b2017-07-12 12:55:28 -0700436 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800437 }
438
Nan Zhang1db85402017-12-18 13:20:23 -0800439 p.genModulePathMappings(ctx, pkgPath, expandedSrcs, expandedData)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800440
Nan Zhang1db85402017-12-18 13:20:23 -0800441 p.srcsZip = p.createSrcsZip(ctx, pkgPath)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800442}
443
444// generate current module unique pathMappings: <dest: runfiles_path, src: source_path>
445// for python/data files.
Nan Zhang1db85402017-12-18 13:20:23 -0800446func (p *Module) genModulePathMappings(ctx android.ModuleContext, pkgPath string,
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800447 expandedSrcs, expandedData android.Paths) {
448 // fetch <runfiles_path, source_path> pairs from "src" and "data" properties to
Nan Zhangb8fa1972017-12-22 16:12:00 -0800449 // check current module duplicates.
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800450 destToPySrcs := make(map[string]string)
451 destToPyData := make(map[string]string)
452
453 for _, s := range expandedSrcs {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800454 if s.Ext() != pyExt && s.Ext() != protoExt {
455 ctx.PropertyErrorf("srcs", "found non (.py|.proto) file: %q!", s.String())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800456 continue
457 }
Nan Zhang1db85402017-12-18 13:20:23 -0800458 runfilesPath := filepath.Join(pkgPath, s.Rel())
Nan Zhangb8fa1972017-12-22 16:12:00 -0800459 identifiers := strings.Split(strings.TrimSuffix(runfilesPath,
460 filepath.Ext(runfilesPath)), "/")
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800461 for _, token := range identifiers {
462 if !pyIdentifierRegexp.MatchString(token) {
463 ctx.PropertyErrorf("srcs", "the path %q contains invalid token %q.",
464 runfilesPath, token)
465 }
466 }
467 if fillInMap(ctx, destToPySrcs, runfilesPath, s.String(), p.Name(), p.Name()) {
468 p.srcsPathMappings = append(p.srcsPathMappings,
469 pathMapping{dest: runfilesPath, src: s})
470 }
471 }
472
473 for _, d := range expandedData {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800474 if d.Ext() == pyExt || d.Ext() == protoExt {
475 ctx.PropertyErrorf("data", "found (.py|.proto) file: %q!", d.String())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800476 continue
477 }
Nan Zhang1db85402017-12-18 13:20:23 -0800478 runfilesPath := filepath.Join(pkgPath, d.Rel())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800479 if fillInMap(ctx, destToPyData, runfilesPath, d.String(), p.Name(), p.Name()) {
480 p.dataPathMappings = append(p.dataPathMappings,
481 pathMapping{dest: runfilesPath, src: d})
482 }
483 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800484}
485
Nan Zhang1db85402017-12-18 13:20:23 -0800486// register build actions to zip current module's sources.
487func (p *Module) createSrcsZip(ctx android.ModuleContext, pkgPath string) android.Path {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800488 relativeRootMap := make(map[string]android.Paths)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800489 pathMappings := append(p.srcsPathMappings, p.dataPathMappings...)
490
Nan Zhangb8fa1972017-12-22 16:12:00 -0800491 var protoSrcs android.Paths
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800492 // "srcs" or "data" properties may have filegroup so it might happen that
493 // the relative root for each source path is different.
494 for _, path := range pathMappings {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800495 if path.src.Ext() == protoExt {
496 protoSrcs = append(protoSrcs, path.src)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800497 } else {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800498 var relativeRoot string
499 relativeRoot = strings.TrimSuffix(path.src.String(), path.src.Rel())
500 if v, found := relativeRootMap[relativeRoot]; found {
501 relativeRootMap[relativeRoot] = append(v, path.src)
502 } else {
503 relativeRootMap[relativeRoot] = android.Paths{path.src}
504 }
505 }
506 }
507 var zips android.Paths
508 if len(protoSrcs) > 0 {
Colin Cross19878da2019-03-28 14:45:07 -0700509 protoFlags := android.GetProtoFlags(ctx, &p.protoProperties)
510 protoFlags.OutTypeFlag = "--python_out"
511
Nan Zhangb8fa1972017-12-22 16:12:00 -0800512 for _, srcFile := range protoSrcs {
Colin Cross19878da2019-03-28 14:45:07 -0700513 zip := genProto(ctx, srcFile, protoFlags, pkgPath)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800514 zips = append(zips, zip)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800515 }
516 }
517
Nan Zhangb8fa1972017-12-22 16:12:00 -0800518 if len(relativeRootMap) > 0 {
519 var keys []string
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800520
Nan Zhangb8fa1972017-12-22 16:12:00 -0800521 // in order to keep stable order of soong_zip params, we sort the keys here.
522 for k := range relativeRootMap {
523 keys = append(keys, k)
Nan Zhang1db85402017-12-18 13:20:23 -0800524 }
Nan Zhangb8fa1972017-12-22 16:12:00 -0800525 sort.Strings(keys)
526
527 parArgs := []string{}
Nan Zhangf0c4e432018-05-22 14:50:18 -0700528 if pkgPath != "" {
529 parArgs = append(parArgs, `-P `+pkgPath)
530 }
Nan Zhangb8fa1972017-12-22 16:12:00 -0800531 implicits := android.Paths{}
532 for _, k := range keys {
533 parArgs = append(parArgs, `-C `+k)
534 for _, path := range relativeRootMap[k] {
535 parArgs = append(parArgs, `-f `+path.String())
536 implicits = append(implicits, path)
537 }
538 }
539
540 origSrcsZip := android.PathForModuleOut(ctx, ctx.ModuleName()+".py.srcszip")
541 ctx.Build(pctx, android.BuildParams{
542 Rule: zip,
543 Description: "python library archive",
544 Output: origSrcsZip,
545 Implicits: implicits,
546 Args: map[string]string{
547 "args": strings.Join(parArgs, " "),
548 },
549 })
550 zips = append(zips, origSrcsZip)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800551 }
Nan Zhangb8fa1972017-12-22 16:12:00 -0800552 if len(zips) == 1 {
553 return zips[0]
554 } else {
555 combinedSrcsZip := android.PathForModuleOut(ctx, ctx.ModuleName()+".srcszip")
556 ctx.Build(pctx, android.BuildParams{
557 Rule: combineZip,
558 Description: "combine python library archive",
559 Output: combinedSrcsZip,
560 Inputs: zips,
561 })
562 return combinedSrcsZip
563 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800564}
565
Nan Zhangd4e641b2017-07-12 12:55:28 -0700566func isPythonLibModule(module blueprint.Module) bool {
567 if m, ok := module.(*Module); ok {
568 // Python library has no bootstrapper or installer.
569 if m.bootstrapper != nil || m.installer != nil {
570 return false
571 }
572 return true
573 }
574 return false
575}
576
Nan Zhangb8fa1972017-12-22 16:12:00 -0800577// check Python source/data files duplicates for whole runfiles tree since Python binary/test
578// need collect and zip all srcs of whole transitive dependencies to a final par file.
579func (p *Module) walkTransitiveDeps(ctx android.ModuleContext) {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800580 // fetch <runfiles_path, source_path> pairs from "src" and "data" properties to
581 // check duplicates.
582 destToPySrcs := make(map[string]string)
583 destToPyData := make(map[string]string)
584
585 for _, path := range p.srcsPathMappings {
586 destToPySrcs[path.dest] = path.src.String()
587 }
588 for _, path := range p.dataPathMappings {
589 destToPyData[path.dest] = path.src.String()
590 }
591
Colin Cross6b753602018-06-21 13:03:07 -0700592 seen := make(map[android.Module]bool)
593
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800594 // visit all its dependencies in depth first.
Colin Cross6b753602018-06-21 13:03:07 -0700595 ctx.WalkDeps(func(child, parent android.Module) bool {
596 if ctx.OtherModuleDependencyTag(child) != pythonLibTag {
597 return false
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800598 }
Colin Cross6b753602018-06-21 13:03:07 -0700599 if seen[child] {
600 return false
601 }
602 seen[child] = true
Nan Zhangb8fa1972017-12-22 16:12:00 -0800603 // Python modules only can depend on Python libraries.
Colin Cross6b753602018-06-21 13:03:07 -0700604 if !isPythonLibModule(child) {
Nan Zhangd4e641b2017-07-12 12:55:28 -0700605 panic(fmt.Errorf(
606 "the dependency %q of module %q is not Python library!",
Colin Cross6b753602018-06-21 13:03:07 -0700607 ctx.ModuleName(), ctx.OtherModuleName(child)))
Nan Zhangd4e641b2017-07-12 12:55:28 -0700608 }
Colin Cross6b753602018-06-21 13:03:07 -0700609 if dep, ok := child.(PythonDependency); ok {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800610 srcs := dep.GetSrcsPathMappings()
611 for _, path := range srcs {
612 if !fillInMap(ctx, destToPySrcs,
Colin Cross6b753602018-06-21 13:03:07 -0700613 path.dest, path.src.String(), ctx.ModuleName(), ctx.OtherModuleName(child)) {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800614 continue
615 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800616 }
617 data := dep.GetDataPathMappings()
618 for _, path := range data {
619 fillInMap(ctx, destToPyData,
Colin Cross6b753602018-06-21 13:03:07 -0700620 path.dest, path.src.String(), ctx.ModuleName(), ctx.OtherModuleName(child))
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800621 }
Nan Zhang1db85402017-12-18 13:20:23 -0800622 p.depsSrcsZips = append(p.depsSrcsZips, dep.GetSrcsZip())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800623 }
Colin Cross6b753602018-06-21 13:03:07 -0700624 return true
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800625 })
626}
627
628func fillInMap(ctx android.ModuleContext, m map[string]string,
629 key, value, curModule, otherModule string) bool {
630 if oldValue, found := m[key]; found {
Nan Zhangbea09752018-05-31 12:49:33 -0700631 ctx.ModuleErrorf("found two files to be placed at the same location within zip %q."+
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800632 " First file: in module %s at path %q."+
633 " Second file: in module %s at path %q.",
634 key, curModule, oldValue, otherModule, value)
635 return false
636 } else {
637 m[key] = value
638 }
639
640 return true
641}
Nan Zhangea568a42017-11-08 21:20:04 -0800642
Nan Zhangd9ec5e72017-12-01 20:00:31 +0000643func (p *Module) InstallInData() bool {
644 return true
645}
646
Nan Zhangea568a42017-11-08 21:20:04 -0800647var Bool = proptools.Bool
Dan Willemsen6ca390f2019-02-14 23:17:08 -0800648var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -0800649var String = proptools.String