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