• 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 androidmk
16
17import (
18	"fmt"
19	"sort"
20	"strconv"
21	"strings"
22
23	mkparser "android/soong/androidmk/parser"
24
25	bpparser "github.com/google/blueprint/parser"
26)
27
28const (
29	clearVarsPath      = "__android_mk_clear_vars"
30	includeIgnoredPath = "__android_mk_include_ignored"
31)
32
33type bpVariable struct {
34	name         string
35	variableType bpparser.Type
36}
37
38type variableAssignmentContext struct {
39	file    *bpFile
40	prefix  string
41	mkvalue *mkparser.MakeString
42	append  bool
43}
44
45var trueValue = &bpparser.Bool{
46	Value: true,
47}
48
49var rewriteProperties = map[string](func(variableAssignmentContext) error){
50	// custom functions
51	"LOCAL_32_BIT_ONLY":                    local32BitOnly,
52	"LOCAL_AIDL_INCLUDES":                  localAidlIncludes,
53	"LOCAL_ASSET_DIR":                      localizePathList("asset_dirs"),
54	"LOCAL_C_INCLUDES":                     localIncludeDirs,
55	"LOCAL_EXPORT_C_INCLUDE_DIRS":          exportIncludeDirs,
56	"LOCAL_JARJAR_RULES":                   localizePath("jarjar_rules"),
57	"LOCAL_LDFLAGS":                        ldflags,
58	"LOCAL_MODULE_CLASS":                   prebuiltClass,
59	"LOCAL_MODULE_STEM":                    stem,
60	"LOCAL_MODULE_HOST_OS":                 hostOs,
61	"LOCAL_RESOURCE_DIR":                   localizePathList("resource_dirs"),
62	"LOCAL_NOTICE_FILE":                    localizePathList("android_license_files"),
63	"LOCAL_SANITIZE":                       sanitize(""),
64	"LOCAL_SANITIZE_DIAG":                  sanitize("diag."),
65	"LOCAL_STRIP_MODULE":                   strip(),
66	"LOCAL_CFLAGS":                         cflags,
67	"LOCAL_UNINSTALLABLE_MODULE":           invert("installable"),
68	"LOCAL_PROGUARD_ENABLED":               proguardEnabled,
69	"LOCAL_MODULE_PATH":                    prebuiltModulePath,
70	"LOCAL_REPLACE_PREBUILT_APK_INSTALLED": prebuiltPreprocessed,
71
72	"LOCAL_DISABLE_AUTO_GENERATE_TEST_CONFIG": invert("auto_gen_config"),
73
74	// composite functions
75	"LOCAL_MODULE_TAGS": includeVariableIf(bpVariable{"tags", bpparser.ListType}, not(valueDumpEquals("optional"))),
76
77	// skip functions
78	"LOCAL_ADDITIONAL_DEPENDENCIES": skip, // TODO: check for only .mk files?
79	"LOCAL_CPP_EXTENSION":           skip,
80	"LOCAL_MODULE_SUFFIX":           skip, // TODO
81	"LOCAL_PATH":                    skip, // Nothing to do, except maybe avoid the "./" in paths?
82	"LOCAL_PRELINK_MODULE":          skip, // Already phased out
83	"LOCAL_BUILT_MODULE_STEM":       skip,
84	"LOCAL_USE_AAPT2":               skip, // Always enabled in Soong
85	"LOCAL_JAR_EXCLUDE_FILES":       skip, // Soong never excludes files from jars
86
87	"LOCAL_ANNOTATION_PROCESSOR_CLASSES": skip, // Soong gets the processor classes from the plugin
88	"LOCAL_CTS_TEST_PACKAGE":             skip, // Obsolete
89	"LOCAL_JACK_ENABLED":                 skip, // Obselete
90	"LOCAL_JACK_FLAGS":                   skip, // Obselete
91}
92
93// adds a group of properties all having the same type
94func addStandardProperties(propertyType bpparser.Type, properties map[string]string) {
95	for key, val := range properties {
96		rewriteProperties[key] = includeVariable(bpVariable{val, propertyType})
97	}
98}
99
100func init() {
101	addStandardProperties(bpparser.StringType,
102		map[string]string{
103			"LOCAL_MODULE":                  "name",
104			"LOCAL_CXX_STL":                 "stl",
105			"LOCAL_MULTILIB":                "compile_multilib",
106			"LOCAL_ARM_MODE_HACK":           "instruction_set",
107			"LOCAL_SDK_VERSION":             "sdk_version",
108			"LOCAL_MIN_SDK_VERSION":         "min_sdk_version",
109			"LOCAL_NDK_STL_VARIANT":         "stl",
110			"LOCAL_JAR_MANIFEST":            "manifest",
111			"LOCAL_CERTIFICATE":             "certificate",
112			"LOCAL_CERTIFICATE_LINEAGE":     "lineage",
113			"LOCAL_PACKAGE_NAME":            "name",
114			"LOCAL_MODULE_RELATIVE_PATH":    "relative_install_path",
115			"LOCAL_PROTOC_OPTIMIZE_TYPE":    "proto.type",
116			"LOCAL_MODULE_OWNER":            "owner",
117			"LOCAL_RENDERSCRIPT_TARGET_API": "renderscript.target_api",
118			"LOCAL_JAVA_LANGUAGE_VERSION":   "java_version",
119			"LOCAL_INSTRUMENTATION_FOR":     "instrumentation_for",
120			"LOCAL_MANIFEST_FILE":           "manifest",
121
122			"LOCAL_DEX_PREOPT_PROFILE_CLASS_LISTING": "dex_preopt.profile",
123			"LOCAL_TEST_CONFIG":                      "test_config",
124			"LOCAL_RRO_THEME":                        "theme",
125		})
126	addStandardProperties(bpparser.ListType,
127		map[string]string{
128			"LOCAL_SRC_FILES":                     "srcs",
129			"LOCAL_SRC_FILES_EXCLUDE":             "exclude_srcs",
130			"LOCAL_HEADER_LIBRARIES":              "header_libs",
131			"LOCAL_SHARED_LIBRARIES":              "shared_libs",
132			"LOCAL_STATIC_LIBRARIES":              "static_libs",
133			"LOCAL_WHOLE_STATIC_LIBRARIES":        "whole_static_libs",
134			"LOCAL_SYSTEM_SHARED_LIBRARIES":       "system_shared_libs",
135			"LOCAL_USES_LIBRARIES":                "uses_libs",
136			"LOCAL_OPTIONAL_USES_LIBRARIES":       "optional_uses_libs",
137			"LOCAL_ASFLAGS":                       "asflags",
138			"LOCAL_CLANG_ASFLAGS":                 "clang_asflags",
139			"LOCAL_COMPATIBILITY_SUPPORT_FILES":   "data",
140			"LOCAL_CONLYFLAGS":                    "conlyflags",
141			"LOCAL_CPPFLAGS":                      "cppflags",
142			"LOCAL_REQUIRED_MODULES":              "required",
143			"LOCAL_HOST_REQUIRED_MODULES":         "host_required",
144			"LOCAL_TARGET_REQUIRED_MODULES":       "target_required",
145			"LOCAL_OVERRIDES_MODULES":             "overrides",
146			"LOCAL_LDLIBS":                        "host_ldlibs",
147			"LOCAL_CLANG_CFLAGS":                  "clang_cflags",
148			"LOCAL_YACCFLAGS":                     "yacc.flags",
149			"LOCAL_SANITIZE_RECOVER":              "sanitize.recover",
150			"LOCAL_LOGTAGS_FILES":                 "logtags",
151			"LOCAL_EXPORT_HEADER_LIBRARY_HEADERS": "export_header_lib_headers",
152			"LOCAL_EXPORT_SHARED_LIBRARY_HEADERS": "export_shared_lib_headers",
153			"LOCAL_EXPORT_STATIC_LIBRARY_HEADERS": "export_static_lib_headers",
154			"LOCAL_INIT_RC":                       "init_rc",
155			"LOCAL_VINTF_FRAGMENTS":               "vintf_fragments",
156			"LOCAL_TIDY_FLAGS":                    "tidy_flags",
157			// TODO: This is comma-separated, not space-separated
158			"LOCAL_TIDY_CHECKS":           "tidy_checks",
159			"LOCAL_RENDERSCRIPT_INCLUDES": "renderscript.include_dirs",
160			"LOCAL_RENDERSCRIPT_FLAGS":    "renderscript.flags",
161
162			"LOCAL_JAVA_RESOURCE_DIRS":    "java_resource_dirs",
163			"LOCAL_JAVA_RESOURCE_FILES":   "java_resources",
164			"LOCAL_JAVACFLAGS":            "javacflags",
165			"LOCAL_ERROR_PRONE_FLAGS":     "errorprone.javacflags",
166			"LOCAL_DX_FLAGS":              "dxflags",
167			"LOCAL_JAVA_LIBRARIES":        "libs",
168			"LOCAL_STATIC_JAVA_LIBRARIES": "static_libs",
169			"LOCAL_JNI_SHARED_LIBRARIES":  "jni_libs",
170			"LOCAL_AAPT_FLAGS":            "aaptflags",
171			"LOCAL_PACKAGE_SPLITS":        "package_splits",
172			"LOCAL_COMPATIBILITY_SUITE":   "test_suites",
173			"LOCAL_OVERRIDES_PACKAGES":    "overrides",
174
175			"LOCAL_ANNOTATION_PROCESSORS": "plugins",
176
177			"LOCAL_PROGUARD_FLAGS":      "optimize.proguard_flags",
178			"LOCAL_PROGUARD_FLAG_FILES": "optimize.proguard_flags_files",
179
180			// These will be rewritten to libs/static_libs by bpfix, after their presence is used to convert
181			// java_library_static to android_library.
182			"LOCAL_SHARED_ANDROID_LIBRARIES": "android_libs",
183			"LOCAL_STATIC_ANDROID_LIBRARIES": "android_static_libs",
184			"LOCAL_ADDITIONAL_CERTIFICATES":  "additional_certificates",
185
186			// Jacoco filters:
187			"LOCAL_JACK_COVERAGE_INCLUDE_FILTER": "jacoco.include_filter",
188			"LOCAL_JACK_COVERAGE_EXCLUDE_FILTER": "jacoco.exclude_filter",
189
190			"LOCAL_FULL_LIBS_MANIFEST_FILES": "additional_manifests",
191
192			// will be rewrite later to "license_kinds:" by byfix
193			"LOCAL_LICENSE_KINDS": "android_license_kinds",
194			// will be removed later by byfix
195			// TODO: does this property matter in the license module?
196			"LOCAL_LICENSE_CONDITIONS": "android_license_conditions",
197			"LOCAL_GENERATED_SOURCES":  "generated_sources",
198		})
199
200	addStandardProperties(bpparser.BoolType,
201		map[string]string{
202			// Bool properties
203			"LOCAL_IS_HOST_MODULE":             "host",
204			"LOCAL_CLANG":                      "clang",
205			"LOCAL_FORCE_STATIC_EXECUTABLE":    "static_executable",
206			"LOCAL_NATIVE_COVERAGE":            "native_coverage",
207			"LOCAL_NO_CRT":                     "nocrt",
208			"LOCAL_ALLOW_UNDEFINED_SYMBOLS":    "allow_undefined_symbols",
209			"LOCAL_RTTI_FLAG":                  "rtti",
210			"LOCAL_PACK_MODULE_RELOCATIONS":    "pack_relocations",
211			"LOCAL_TIDY":                       "tidy",
212			"LOCAL_USE_CLANG_LLD":              "use_clang_lld",
213			"LOCAL_PROPRIETARY_MODULE":         "proprietary",
214			"LOCAL_VENDOR_MODULE":              "vendor",
215			"LOCAL_ODM_MODULE":                 "device_specific",
216			"LOCAL_PRODUCT_MODULE":             "product_specific",
217			"LOCAL_PRODUCT_SERVICES_MODULE":    "product_specific",
218			"LOCAL_SYSTEM_EXT_MODULE":          "system_ext_specific",
219			"LOCAL_EXPORT_PACKAGE_RESOURCES":   "export_package_resources",
220			"LOCAL_PRIVILEGED_MODULE":          "privileged",
221			"LOCAL_AAPT_INCLUDE_ALL_RESOURCES": "aapt_include_all_resources",
222			"LOCAL_DONT_MERGE_MANIFESTS":       "dont_merge_manifests",
223			"LOCAL_USE_EMBEDDED_NATIVE_LIBS":   "use_embedded_native_libs",
224			"LOCAL_USE_EMBEDDED_DEX":           "use_embedded_dex",
225
226			"LOCAL_DEX_PREOPT":                  "dex_preopt.enabled",
227			"LOCAL_DEX_PREOPT_APP_IMAGE":        "dex_preopt.app_image",
228			"LOCAL_DEX_PREOPT_GENERATE_PROFILE": "dex_preopt.profile_guided",
229
230			"LOCAL_PRIVATE_PLATFORM_APIS": "platform_apis",
231			"LOCAL_JETIFIER_ENABLED":      "jetifier",
232
233			"LOCAL_IS_UNIT_TEST": "unit_test",
234
235			"LOCAL_ENFORCE_USES_LIBRARIES": "enforce_uses_libs",
236
237			"LOCAL_CHECK_ELF_FILES": "check_elf_files",
238		})
239}
240
241type listSplitFunc func(bpparser.Expression) (string, bpparser.Expression, error)
242
243func emptyList(value bpparser.Expression) bool {
244	if list, ok := value.(*bpparser.List); ok {
245		return len(list.Values) == 0
246	}
247	return false
248}
249
250func splitBpList(val bpparser.Expression, keyFunc listSplitFunc) (lists map[string]bpparser.Expression, err error) {
251	lists = make(map[string]bpparser.Expression)
252
253	switch val := val.(type) {
254	case *bpparser.Operator:
255		listsA, err := splitBpList(val.Args[0], keyFunc)
256		if err != nil {
257			return nil, err
258		}
259
260		listsB, err := splitBpList(val.Args[1], keyFunc)
261		if err != nil {
262			return nil, err
263		}
264
265		for k, v := range listsA {
266			if !emptyList(v) {
267				lists[k] = v
268			}
269		}
270
271		for k, vB := range listsB {
272			if emptyList(vB) {
273				continue
274			}
275
276			if vA, ok := lists[k]; ok {
277				expression := val.Copy().(*bpparser.Operator)
278				expression.Args = [2]bpparser.Expression{vA, vB}
279				lists[k] = expression
280			} else {
281				lists[k] = vB
282			}
283		}
284	case *bpparser.Variable:
285		key, value, err := keyFunc(val)
286		if err != nil {
287			return nil, err
288		}
289		if value.Type() == bpparser.ListType {
290			lists[key] = value
291		} else {
292			lists[key] = &bpparser.List{
293				Values: []bpparser.Expression{value},
294			}
295		}
296	case *bpparser.List:
297		for _, v := range val.Values {
298			key, value, err := keyFunc(v)
299			if err != nil {
300				return nil, err
301			}
302			l := lists[key]
303			if l == nil {
304				l = &bpparser.List{}
305			}
306			l.(*bpparser.List).Values = append(l.(*bpparser.List).Values, value)
307			lists[key] = l
308		}
309	default:
310		panic(fmt.Errorf("unexpected type %t", val))
311	}
312
313	return lists, nil
314}
315
316// classifyLocalOrGlobalPath tells whether a file path should be interpreted relative to the current module (local)
317// or relative to the root of the source checkout (global)
318func classifyLocalOrGlobalPath(value bpparser.Expression) (string, bpparser.Expression, error) {
319	switch v := value.(type) {
320	case *bpparser.Variable:
321		if v.Name == "LOCAL_PATH" {
322			return "local", &bpparser.String{
323				Value: ".",
324			}, nil
325		} else {
326			// TODO: Should we split variables?
327			return "global", value, nil
328		}
329	case *bpparser.Operator:
330		if v.Type() != bpparser.StringType {
331			return "", nil, fmt.Errorf("classifyLocalOrGlobalPath expected a string, got %s", v.Type())
332		}
333
334		if v.Operator != '+' {
335			return "global", value, nil
336		}
337
338		firstOperand := v.Args[0]
339		secondOperand := v.Args[1]
340		if firstOperand.Type() != bpparser.StringType {
341			return "global", value, nil
342		}
343
344		if _, ok := firstOperand.(*bpparser.Operator); ok {
345			return "global", value, nil
346		}
347
348		if variable, ok := firstOperand.(*bpparser.Variable); !ok || variable.Name != "LOCAL_PATH" {
349			return "global", value, nil
350		}
351
352		local := secondOperand
353		if s, ok := secondOperand.(*bpparser.String); ok {
354			if strings.HasPrefix(s.Value, "/") {
355				s.Value = s.Value[1:]
356			}
357		}
358		return "local", local, nil
359	case *bpparser.String:
360		return "global", value, nil
361	default:
362		return "", nil, fmt.Errorf("classifyLocalOrGlobalPath expected a string, got %s", v.Type())
363
364	}
365}
366
367// splitAndAssign splits a Make list into components and then
368// creates the corresponding variable assignments.
369func splitAndAssign(ctx variableAssignmentContext, splitFunc listSplitFunc, namesByClassification map[string]string) error {
370	val, err := makeVariableToBlueprint(ctx.file, ctx.mkvalue, bpparser.ListType)
371	if err != nil {
372		return err
373	}
374
375	lists, err := splitBpList(val, splitFunc)
376	if err != nil {
377		return err
378	}
379
380	var classifications []string
381	for classification := range namesByClassification {
382		classifications = append(classifications, classification)
383	}
384	sort.Strings(classifications)
385
386	for _, nameClassification := range classifications {
387		name := namesByClassification[nameClassification]
388		if component, ok := lists[nameClassification]; ok && !emptyList(component) {
389			err = setVariable(ctx.file, ctx.append, ctx.prefix, name, component, true)
390			if err != nil {
391				return err
392			}
393		}
394	}
395	return nil
396}
397
398func localIncludeDirs(ctx variableAssignmentContext) error {
399	return splitAndAssign(ctx, classifyLocalOrGlobalPath, map[string]string{"global": "include_dirs", "local": "local_include_dirs"})
400}
401
402func exportIncludeDirs(ctx variableAssignmentContext) error {
403	// Add any paths that could not be converted to local relative paths to export_include_dirs
404	// anyways, they will cause an error if they don't exist and can be fixed manually.
405	return splitAndAssign(ctx, classifyLocalOrGlobalPath, map[string]string{"global": "export_include_dirs", "local": "export_include_dirs"})
406}
407
408func local32BitOnly(ctx variableAssignmentContext) error {
409	val, err := makeVariableToBlueprint(ctx.file, ctx.mkvalue, bpparser.BoolType)
410	if err != nil {
411		return err
412	}
413	boolValue, ok := val.(*bpparser.Bool)
414	if !ok {
415		return fmt.Errorf("value should evaluate to boolean literal")
416	}
417	if boolValue.Value {
418		thirtyTwo := &bpparser.String{
419			Value: "32",
420		}
421		return setVariable(ctx.file, false, ctx.prefix, "compile_multilib", thirtyTwo, true)
422	}
423	return nil
424}
425
426func localAidlIncludes(ctx variableAssignmentContext) error {
427	return splitAndAssign(ctx, classifyLocalOrGlobalPath, map[string]string{"global": "aidl.include_dirs", "local": "aidl.local_include_dirs"})
428}
429
430func localizePathList(attribute string) func(ctx variableAssignmentContext) error {
431	return func(ctx variableAssignmentContext) error {
432		paths, err := localizePaths(ctx)
433		if err == nil {
434			err = setVariable(ctx.file, ctx.append, ctx.prefix, attribute, paths, true)
435		}
436		return err
437	}
438}
439
440func localizePath(attribute string) func(ctx variableAssignmentContext) error {
441	return func(ctx variableAssignmentContext) error {
442		paths, err := localizePaths(ctx)
443		if err == nil {
444			pathList, ok := paths.(*bpparser.List)
445			if !ok {
446				panic("Expected list")
447			}
448			switch len(pathList.Values) {
449			case 0:
450				err = setVariable(ctx.file, ctx.append, ctx.prefix, attribute, &bpparser.List{}, true)
451			case 1:
452				err = setVariable(ctx.file, ctx.append, ctx.prefix, attribute, pathList.Values[0], true)
453			default:
454				err = fmt.Errorf("Expected single value for %s", attribute)
455			}
456		}
457		return err
458	}
459}
460
461// Convert the "full" paths (that is, from the top of the source tree) to the relative one
462// (from the directory containing the blueprint file) and set given attribute to it.
463// This is needed for some of makefile variables (e.g., LOCAL_RESOURCE_DIR).
464// At the moment only the paths of the `$(LOCAL_PATH)/foo/bar` format can be converted
465// (to `foo/bar` in this case) as we cannot convert a literal path without
466// knowing makefiles's location in the source tree. We just issue a warning in the latter case.
467func localizePaths(ctx variableAssignmentContext) (bpparser.Expression, error) {
468	bpvalue, err := makeVariableToBlueprint(ctx.file, ctx.mkvalue, bpparser.ListType)
469	var result bpparser.Expression
470	if err != nil {
471		return result, err
472	}
473	classifiedPaths, err := splitBpList(bpvalue, classifyLocalOrGlobalPath)
474	if err != nil {
475		return result, err
476	}
477	for pathClass, path := range classifiedPaths {
478		switch pathClass {
479		case "local":
480			result = path
481		default:
482			err = fmt.Errorf("Only $(LOCAL_PATH)/.. values are allowed")
483		}
484	}
485	return result, err
486}
487
488func stem(ctx variableAssignmentContext) error {
489	val, err := makeVariableToBlueprint(ctx.file, ctx.mkvalue, bpparser.StringType)
490	if err != nil {
491		return err
492	}
493	varName := "stem"
494
495	if exp, ok := val.(*bpparser.Operator); ok && exp.Operator == '+' {
496		if variable, ok := exp.Args[0].(*bpparser.Variable); ok && variable.Name == "LOCAL_MODULE" {
497			varName = "suffix"
498			val = exp.Args[1]
499		}
500	}
501
502	return setVariable(ctx.file, ctx.append, ctx.prefix, varName, val, true)
503}
504
505func hostOs(ctx variableAssignmentContext) error {
506	val, err := makeVariableToBlueprint(ctx.file, ctx.mkvalue, bpparser.ListType)
507	if err != nil {
508		return err
509	}
510
511	inList := func(s string) bool {
512		for _, v := range val.(*bpparser.List).Values {
513			if v.(*bpparser.String).Value == s {
514				return true
515			}
516		}
517		return false
518	}
519
520	falseValue := &bpparser.Bool{
521		Value: false,
522	}
523
524	if inList("windows") {
525		err = setVariable(ctx.file, ctx.append, "target.windows", "enabled", trueValue, true)
526	}
527
528	if !inList("linux") && err == nil {
529		err = setVariable(ctx.file, ctx.append, "target.linux_glibc", "enabled", falseValue, true)
530	}
531
532	if !inList("darwin") && err == nil {
533		err = setVariable(ctx.file, ctx.append, "target.darwin", "enabled", falseValue, true)
534	}
535
536	return err
537}
538
539func sanitize(sub string) func(ctx variableAssignmentContext) error {
540	return func(ctx variableAssignmentContext) error {
541		val, err := makeVariableToBlueprint(ctx.file, ctx.mkvalue, bpparser.ListType)
542		if err != nil {
543			return err
544		}
545
546		if _, ok := val.(*bpparser.List); !ok {
547			return fmt.Errorf("unsupported sanitize expression")
548		}
549
550		misc := &bpparser.List{}
551
552		for _, v := range val.(*bpparser.List).Values {
553			switch v := v.(type) {
554			case *bpparser.Variable, *bpparser.Operator:
555				ctx.file.errorf(ctx.mkvalue, "unsupported sanitize expression")
556			case *bpparser.String:
557				switch v.Value {
558				case "never", "address", "fuzzer", "thread", "undefined", "cfi":
559					bpTrue := &bpparser.Bool{
560						Value: true,
561					}
562					err = setVariable(ctx.file, false, ctx.prefix, "sanitize."+sub+v.Value, bpTrue, true)
563					if err != nil {
564						return err
565					}
566				default:
567					misc.Values = append(misc.Values, v)
568				}
569			default:
570				return fmt.Errorf("sanitize expected a string, got %s", v.Type())
571			}
572		}
573
574		if len(misc.Values) > 0 {
575			err = setVariable(ctx.file, false, ctx.prefix, "sanitize."+sub+"misc_undefined", misc, true)
576			if err != nil {
577				return err
578			}
579		}
580
581		return err
582	}
583}
584
585func strip() func(ctx variableAssignmentContext) error {
586	return func(ctx variableAssignmentContext) error {
587		val, err := makeVariableToBlueprint(ctx.file, ctx.mkvalue, bpparser.StringType)
588		if err != nil {
589			return err
590		}
591
592		if _, ok := val.(*bpparser.String); !ok {
593			return fmt.Errorf("unsupported strip expression")
594		}
595
596		bpTrue := &bpparser.Bool{
597			Value: true,
598		}
599		v := val.(*bpparser.String).Value
600		sub := (map[string]string{"false": "none", "true": "all", "keep_symbols": "keep_symbols"})[v]
601		if sub == "" {
602			return fmt.Errorf("unexpected strip option: %s", v)
603		}
604		return setVariable(ctx.file, false, ctx.prefix, "strip."+sub, bpTrue, true)
605	}
606}
607
608func prebuiltClass(ctx variableAssignmentContext) error {
609	class := ctx.mkvalue.Value(ctx.file.scope)
610	if _, ok := prebuiltTypes[class]; ok {
611		ctx.file.scope.Set("BUILD_PREBUILT", class)
612	} else {
613		// reset to default
614		ctx.file.scope.Set("BUILD_PREBUILT", "prebuilt")
615	}
616	return nil
617}
618
619func makeBlueprintStringAssignment(file *bpFile, prefix string, suffix string, value string) error {
620	val, err := makeVariableToBlueprint(file, mkparser.SimpleMakeString(value, mkparser.NoPos), bpparser.StringType)
621	if err == nil {
622		err = setVariable(file, false, prefix, suffix, val, true)
623	}
624	return err
625}
626
627// Assigns a given boolean value to a given variable in the result bp file. See
628// setVariable documentation for more information about prefix and name.
629func makeBlueprintBoolAssignment(ctx variableAssignmentContext, prefix, name string, value bool) error {
630	expressionValue, err := stringToBoolValue(strconv.FormatBool(value))
631	if err == nil {
632		err = setVariable(ctx.file, false, prefix, name, expressionValue, true)
633	}
634	return err
635}
636
637// If variable is a literal variable name, return the name, otherwise return ""
638func varLiteralName(variable mkparser.Variable) string {
639	if len(variable.Name.Variables) == 0 {
640		return variable.Name.Strings[0]
641	}
642	return ""
643}
644
645func prebuiltModulePath(ctx variableAssignmentContext) error {
646	// Cannot handle appending
647	if ctx.append {
648		return fmt.Errorf("Cannot handle appending to LOCAL_MODULE_PATH")
649	}
650	// Analyze value in order to set the correct values for the 'device_specific',
651	// 'product_specific', 'system_ext_specific' 'vendor'/'soc_specific',
652	// 'system_ext_specific' attribute. Two cases are allowed:
653	//   $(VAR)/<literal-value>
654	//   $(PRODUCT_OUT)/$(TARGET_COPY_OUT_VENDOR)/<literal-value>
655	// The last case is equivalent to $(TARGET_OUT_VENDOR)/<literal-value>
656	// Map the variable name if present to `local_module_path_var`
657	// Map literal-path to local_module_path_fixed
658	varname := ""
659	fixed := ""
660	val := ctx.mkvalue
661
662	if len(val.Variables) == 1 && varLiteralName(val.Variables[0]) != "" && len(val.Strings) == 2 && val.Strings[0] == "" {
663		if varLiteralName(val.Variables[0]) == "PRODUCT_OUT" && val.Strings[1] == "/system/priv-app" {
664			return makeBlueprintBoolAssignment(ctx, "", "privileged", true)
665		}
666		fixed = val.Strings[1]
667		varname = val.Variables[0].Name.Strings[0]
668		// TARGET_OUT_OPTIONAL_EXECUTABLES puts the artifact in xbin, which is
669		// deprecated. TARGET_OUT_DATA_APPS install location will be handled
670		// automatically by Soong
671		if varname == "TARGET_OUT_OPTIONAL_EXECUTABLES" || varname == "TARGET_OUT_DATA_APPS" {
672			return nil
673		}
674	} else if len(val.Variables) == 2 && varLiteralName(val.Variables[0]) == "PRODUCT_OUT" && varLiteralName(val.Variables[1]) == "TARGET_COPY_OUT_VENDOR" &&
675		len(val.Strings) == 3 && val.Strings[0] == "" && val.Strings[1] == "/" {
676		fixed = val.Strings[2]
677		varname = "TARGET_OUT_VENDOR"
678	} else {
679		return fmt.Errorf("LOCAL_MODULE_PATH value should start with $(<some-varaible>)/ or $(PRODUCT_OUT)/$(TARGET_COPY_VENDOR)/")
680	}
681	err := makeBlueprintStringAssignment(ctx.file, "local_module_path", "var", varname)
682	if err == nil && fixed != "" {
683		err = makeBlueprintStringAssignment(ctx.file, "local_module_path", "fixed", fixed)
684	}
685	return err
686}
687
688func ldflags(ctx variableAssignmentContext) error {
689	val, err := makeVariableToBlueprint(ctx.file, ctx.mkvalue, bpparser.ListType)
690	if err != nil {
691		return err
692	}
693
694	lists, err := splitBpList(val, func(value bpparser.Expression) (string, bpparser.Expression, error) {
695		// Anything other than "-Wl,--version_script," + LOCAL_PATH + "<path>" matches ldflags
696		exp1, ok := value.(*bpparser.Operator)
697		if !ok {
698			return "ldflags", value, nil
699		}
700
701		exp2, ok := exp1.Args[0].(*bpparser.Operator)
702		if !ok {
703			return "ldflags", value, nil
704		}
705
706		if s, ok := exp2.Args[0].(*bpparser.String); !ok || s.Value != "-Wl,--version-script," {
707			return "ldflags", value, nil
708		}
709
710		if v, ok := exp2.Args[1].(*bpparser.Variable); !ok || v.Name != "LOCAL_PATH" {
711			ctx.file.errorf(ctx.mkvalue, "Unrecognized version-script")
712			return "ldflags", value, nil
713		}
714
715		s, ok := exp1.Args[1].(*bpparser.String)
716		if !ok {
717			ctx.file.errorf(ctx.mkvalue, "Unrecognized version-script")
718			return "ldflags", value, nil
719		}
720
721		s.Value = strings.TrimPrefix(s.Value, "/")
722
723		return "version", s, nil
724	})
725	if err != nil {
726		return err
727	}
728
729	if ldflags, ok := lists["ldflags"]; ok && !emptyList(ldflags) {
730		err = setVariable(ctx.file, ctx.append, ctx.prefix, "ldflags", ldflags, true)
731		if err != nil {
732			return err
733		}
734	}
735
736	if version_script, ok := lists["version"]; ok && !emptyList(version_script) {
737		if len(version_script.(*bpparser.List).Values) > 1 {
738			ctx.file.errorf(ctx.mkvalue, "multiple version scripts found?")
739		}
740		err = setVariable(ctx.file, false, ctx.prefix, "version_script", version_script.(*bpparser.List).Values[0], true)
741		if err != nil {
742			return err
743		}
744	}
745
746	return nil
747}
748
749func prebuiltPreprocessed(ctx variableAssignmentContext) error {
750	ctx.mkvalue = ctx.mkvalue.Clone()
751	return setVariable(ctx.file, false, ctx.prefix, "preprocessed", trueValue, true)
752}
753
754func cflags(ctx variableAssignmentContext) error {
755	// The Soong replacement for CFLAGS doesn't need the same extra escaped quotes that were present in Make
756	ctx.mkvalue = ctx.mkvalue.Clone()
757	ctx.mkvalue.ReplaceLiteral(`\"`, `"`)
758	return includeVariableNow(bpVariable{"cflags", bpparser.ListType}, ctx)
759}
760
761func proguardEnabled(ctx variableAssignmentContext) error {
762	val, err := makeVariableToBlueprint(ctx.file, ctx.mkvalue, bpparser.ListType)
763	if err != nil {
764		return err
765	}
766
767	list, ok := val.(*bpparser.List)
768	if !ok {
769		return fmt.Errorf("unsupported proguard expression")
770	}
771
772	set := func(prop string, value bool) {
773		bpValue := &bpparser.Bool{
774			Value: value,
775		}
776		setVariable(ctx.file, false, ctx.prefix, prop, bpValue, true)
777	}
778
779	enable := false
780
781	for _, v := range list.Values {
782		s, ok := v.(*bpparser.String)
783		if !ok {
784			return fmt.Errorf("unsupported proguard expression")
785		}
786
787		switch s.Value {
788		case "disabled":
789			set("optimize.enabled", false)
790		case "obfuscation":
791			enable = true
792			set("optimize.obfuscate", true)
793		case "optimization":
794			enable = true
795			set("optimize.optimize", true)
796		case "full":
797			enable = true
798		case "custom":
799			set("optimize.no_aapt_flags", true)
800			enable = true
801		default:
802			return fmt.Errorf("unsupported proguard value %q", s)
803		}
804	}
805
806	if enable {
807		// This is only necessary for libraries which default to false, but we can't
808		// tell the difference between a library and an app here.
809		set("optimize.enabled", true)
810	}
811
812	return nil
813}
814
815func invert(name string) func(ctx variableAssignmentContext) error {
816	return func(ctx variableAssignmentContext) error {
817		val, err := makeVariableToBlueprint(ctx.file, ctx.mkvalue, bpparser.BoolType)
818		if err != nil {
819			return err
820		}
821
822		val.(*bpparser.Bool).Value = !val.(*bpparser.Bool).Value
823
824		return setVariable(ctx.file, ctx.append, ctx.prefix, name, val, true)
825	}
826}
827
828// given a conditional, returns a function that will insert a variable assignment or not, based on the conditional
829func includeVariableIf(bpVar bpVariable, conditional func(ctx variableAssignmentContext) bool) func(ctx variableAssignmentContext) error {
830	return func(ctx variableAssignmentContext) error {
831		var err error
832		if conditional(ctx) {
833			err = includeVariableNow(bpVar, ctx)
834		}
835		return err
836	}
837}
838
839// given a variable, returns a function that will always insert a variable assignment
840func includeVariable(bpVar bpVariable) func(ctx variableAssignmentContext) error {
841	return includeVariableIf(bpVar, always)
842}
843
844func includeVariableNow(bpVar bpVariable, ctx variableAssignmentContext) error {
845	var val bpparser.Expression
846	var err error
847	val, err = makeVariableToBlueprint(ctx.file, ctx.mkvalue, bpVar.variableType)
848	if err == nil {
849		err = setVariable(ctx.file, ctx.append, ctx.prefix, bpVar.name, val, true)
850	}
851	return err
852}
853
854// given a function that returns a bool, returns a function that returns the opposite
855func not(conditional func(ctx variableAssignmentContext) bool) func(ctx variableAssignmentContext) bool {
856	return func(ctx variableAssignmentContext) bool {
857		return !conditional(ctx)
858	}
859}
860
861// returns a function that tells whether mkvalue.Dump equals the given query string
862func valueDumpEquals(textToMatch string) func(ctx variableAssignmentContext) bool {
863	return func(ctx variableAssignmentContext) bool {
864		return (ctx.mkvalue.Dump() == textToMatch)
865	}
866}
867
868func always(ctx variableAssignmentContext) bool {
869	return true
870}
871
872func skip(ctx variableAssignmentContext) error {
873	return nil
874}
875
876// Shorter suffixes of other suffixes must be at the end of the list
877var propertyPrefixes = []struct{ mk, bp string }{
878	{"arm", "arch.arm"},
879	{"arm64", "arch.arm64"},
880	{"x86", "arch.x86"},
881	{"x86_64", "arch.x86_64"},
882	{"32", "multilib.lib32"},
883	// 64 must be after x86_64
884	{"64", "multilib.lib64"},
885	{"darwin", "target.darwin"},
886	{"linux", "target.linux_glibc"},
887	{"windows", "target.windows"},
888}
889
890var conditionalTranslations = map[string]map[bool]string{
891	"($(HOST_OS),darwin)": {
892		true:  "target.darwin",
893		false: "target.not_darwin"},
894	"($(HOST_OS), darwin)": {
895		true:  "target.darwin",
896		false: "target.not_darwin"},
897	"($(HOST_OS),windows)": {
898		true:  "target.windows",
899		false: "target.not_windows"},
900	"($(HOST_OS), windows)": {
901		true:  "target.windows",
902		false: "target.not_windows"},
903	"($(HOST_OS),linux)": {
904		true:  "target.linux_glibc",
905		false: "target.not_linux_glibc"},
906	"($(HOST_OS), linux)": {
907		true:  "target.linux_glibc",
908		false: "target.not_linux_glibc"},
909	"($(BUILD_OS),darwin)": {
910		true:  "target.darwin",
911		false: "target.not_darwin"},
912	"($(BUILD_OS), darwin)": {
913		true:  "target.darwin",
914		false: "target.not_darwin"},
915	"($(BUILD_OS),linux)": {
916		true:  "target.linux_glibc",
917		false: "target.not_linux_glibc"},
918	"($(BUILD_OS), linux)": {
919		true:  "target.linux_glibc",
920		false: "target.not_linux_glibc"},
921	"(,$(TARGET_BUILD_APPS))": {
922		false: "product_variables.unbundled_build"},
923	"($(TARGET_BUILD_APPS),)": {
924		false: "product_variables.unbundled_build"},
925	"($(TARGET_BUILD_PDK),true)": {
926		true: "product_variables.pdk"},
927	"($(TARGET_BUILD_PDK), true)": {
928		true: "product_variables.pdk"},
929}
930
931func mydir(args []string) []string {
932	return []string{"."}
933}
934
935func allFilesUnder(wildcard string) func(args []string) []string {
936	return func(args []string) []string {
937		dirs := []string{""}
938		if len(args) > 0 {
939			dirs = strings.Fields(args[0])
940		}
941
942		paths := make([]string, len(dirs))
943		for i := range paths {
944			paths[i] = fmt.Sprintf("%s/**/"+wildcard, dirs[i])
945		}
946		return paths
947	}
948}
949
950func allSubdirJavaFiles(args []string) []string {
951	return []string{"**/*.java"}
952}
953
954func includeIgnored(args []string) []string {
955	return []string{includeIgnoredPath}
956}
957
958var moduleTypes = map[string]string{
959	"BUILD_SHARED_LIBRARY":        "cc_library_shared",
960	"BUILD_STATIC_LIBRARY":        "cc_library_static",
961	"BUILD_HOST_SHARED_LIBRARY":   "cc_library_host_shared",
962	"BUILD_HOST_STATIC_LIBRARY":   "cc_library_host_static",
963	"BUILD_HEADER_LIBRARY":        "cc_library_headers",
964	"BUILD_EXECUTABLE":            "cc_binary",
965	"BUILD_HOST_EXECUTABLE":       "cc_binary_host",
966	"BUILD_NATIVE_TEST":           "cc_test",
967	"BUILD_HOST_NATIVE_TEST":      "cc_test_host",
968	"BUILD_NATIVE_BENCHMARK":      "cc_benchmark",
969	"BUILD_HOST_NATIVE_BENCHMARK": "cc_benchmark_host",
970
971	"BUILD_JAVA_LIBRARY":             "java_library_installable", // will be rewritten to java_library by bpfix
972	"BUILD_STATIC_JAVA_LIBRARY":      "java_library",
973	"BUILD_HOST_JAVA_LIBRARY":        "java_library_host",
974	"BUILD_HOST_DALVIK_JAVA_LIBRARY": "java_library_host_dalvik",
975	"BUILD_PACKAGE":                  "android_app",
976	"BUILD_RRO_PACKAGE":              "runtime_resource_overlay",
977
978	"BUILD_CTS_EXECUTABLE":          "cc_binary",               // will be further massaged by bpfix depending on the output path
979	"BUILD_CTS_SUPPORT_PACKAGE":     "cts_support_package",     // will be rewritten to android_test by bpfix
980	"BUILD_CTS_PACKAGE":             "cts_package",             // will be rewritten to android_test by bpfix
981	"BUILD_CTS_TARGET_JAVA_LIBRARY": "cts_target_java_library", // will be rewritten to java_library by bpfix
982	"BUILD_CTS_HOST_JAVA_LIBRARY":   "cts_host_java_library",   // will be rewritten to java_library_host by bpfix
983}
984
985var prebuiltTypes = map[string]string{
986	"SHARED_LIBRARIES": "cc_prebuilt_library_shared",
987	"STATIC_LIBRARIES": "cc_prebuilt_library_static",
988	"EXECUTABLES":      "cc_prebuilt_binary",
989	"JAVA_LIBRARIES":   "java_import",
990	"APPS":             "android_app_import",
991	"ETC":              "prebuilt_etc",
992}
993
994var soongModuleTypes = map[string]bool{}
995
996var includePathToModule = map[string]string{
997	// The content will be populated dynamically in androidScope below
998}
999
1000func mapIncludePath(path string) (string, bool) {
1001	if path == clearVarsPath || path == includeIgnoredPath {
1002		return path, true
1003	}
1004	module, ok := includePathToModule[path]
1005	return module, ok
1006}
1007
1008func androidScope() mkparser.Scope {
1009	globalScope := mkparser.NewScope(nil)
1010	globalScope.Set("CLEAR_VARS", clearVarsPath)
1011	globalScope.SetFunc("my-dir", mydir)
1012	globalScope.SetFunc("all-java-files-under", allFilesUnder("*.java"))
1013	globalScope.SetFunc("all-proto-files-under", allFilesUnder("*.proto"))
1014	globalScope.SetFunc("all-aidl-files-under", allFilesUnder("*.aidl"))
1015	globalScope.SetFunc("all-Iaidl-files-under", allFilesUnder("I*.aidl"))
1016	globalScope.SetFunc("all-logtags-files-under", allFilesUnder("*.logtags"))
1017	globalScope.SetFunc("all-subdir-java-files", allSubdirJavaFiles)
1018	globalScope.SetFunc("all-makefiles-under", includeIgnored)
1019	globalScope.SetFunc("first-makefiles-under", includeIgnored)
1020	globalScope.SetFunc("all-named-subdir-makefiles", includeIgnored)
1021	globalScope.SetFunc("all-subdir-makefiles", includeIgnored)
1022
1023	// The scope maps each known variable to a path, and then includePathToModule maps a path
1024	// to a module. We don't care what the actual path value is so long as the value in scope
1025	// is mapped, so we might as well use variable name as key, too.
1026	for varName, moduleName := range moduleTypes {
1027		path := varName
1028		globalScope.Set(varName, path)
1029		includePathToModule[path] = moduleName
1030	}
1031	for varName, moduleName := range prebuiltTypes {
1032		includePathToModule[varName] = moduleName
1033	}
1034
1035	return globalScope
1036}
1037