1""" This module contains functions used by the test cases to hide the
2architecture and/or the platform dependent nature of the tests. """
3
4from __future__ import absolute_import
5
6# System modules
7import itertools
8import re
9import subprocess
10import sys
11import os
12
13# Third-party modules
14import six
15from six.moves.urllib import parse as urlparse
16
17# LLDB modules
18from . import configuration
19import use_lldb_suite
20import lldb
21
22
23def check_first_register_readable(test_case):
24    arch = test_case.getArchitecture()
25
26    if arch in ['x86_64', 'i386']:
27        test_case.expect("register read eax", substrs=['eax = 0x'])
28    elif arch in ['arm', 'armv7', 'armv7k']:
29        test_case.expect("register read r0", substrs=['r0 = 0x'])
30    elif arch in ['aarch64', 'arm64']:
31        test_case.expect("register read x0", substrs=['x0 = 0x'])
32    elif re.match("mips", arch):
33        test_case.expect("register read zero", substrs=['zero = 0x'])
34    elif arch in ['s390x']:
35        test_case.expect("register read r0", substrs=['r0 = 0x'])
36    else:
37        # TODO: Add check for other architectures
38        test_case.fail(
39            "Unsupported architecture for test case (arch: %s)" %
40            test_case.getArchitecture())
41
42
43def _run_adb_command(cmd, device_id):
44    device_id_args = []
45    if device_id:
46        device_id_args = ["-s", device_id]
47    full_cmd = ["adb"] + device_id_args + cmd
48    p = subprocess.Popen(
49        full_cmd,
50        stdout=subprocess.PIPE,
51        stderr=subprocess.PIPE)
52    stdout, stderr = p.communicate()
53    return p.returncode, stdout, stderr
54
55
56def target_is_android():
57    if not hasattr(target_is_android, 'result'):
58        triple = lldb.DBG.GetSelectedPlatform().GetTriple()
59        match = re.match(".*-.*-.*-android", triple)
60        target_is_android.result = match is not None
61    return target_is_android.result
62
63
64def android_device_api():
65    if not hasattr(android_device_api, 'result'):
66        assert configuration.lldb_platform_url is not None
67        device_id = None
68        parsed_url = urlparse.urlparse(configuration.lldb_platform_url)
69        host_name = parsed_url.netloc.split(":")[0]
70        if host_name != 'localhost':
71            device_id = host_name
72            if device_id.startswith('[') and device_id.endswith(']'):
73                device_id = device_id[1:-1]
74        retcode, stdout, stderr = _run_adb_command(
75            ["shell", "getprop", "ro.build.version.sdk"], device_id)
76        if retcode == 0:
77            android_device_api.result = int(stdout)
78        else:
79            raise LookupError(
80                ">>> Unable to determine the API level of the Android device.\n"
81                ">>> stdout:\n%s\n"
82                ">>> stderr:\n%s\n" %
83                (stdout, stderr))
84    return android_device_api.result
85
86
87def match_android_device(device_arch, valid_archs=None, valid_api_levels=None):
88    if not target_is_android():
89        return False
90    if valid_archs is not None and device_arch not in valid_archs:
91        return False
92    if valid_api_levels is not None and android_device_api() not in valid_api_levels:
93        return False
94
95    return True
96
97
98def finalize_build_dictionary(dictionary):
99    if target_is_android():
100        if dictionary is None:
101            dictionary = {}
102        dictionary["OS"] = "Android"
103        dictionary["PIE"] = 1
104    return dictionary
105
106
107def getHostPlatform():
108    """Returns the host platform running the test suite."""
109    # Attempts to return a platform name matching a target Triple platform.
110    if sys.platform.startswith('linux'):
111        return 'linux'
112    elif sys.platform.startswith('win32') or sys.platform.startswith('cygwin'):
113        return 'windows'
114    elif sys.platform.startswith('darwin'):
115        return 'darwin'
116    elif sys.platform.startswith('freebsd'):
117        return 'freebsd'
118    elif sys.platform.startswith('netbsd'):
119        return 'netbsd'
120    else:
121        return sys.platform
122
123
124def getDarwinOSTriples():
125    return ['darwin', 'macosx', 'ios', 'watchos', 'tvos', 'bridgeos']
126
127
128def getPlatform():
129    """Returns the target platform which the tests are running on."""
130    platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2]
131    if platform.startswith('freebsd'):
132        platform = 'freebsd'
133    elif platform.startswith('netbsd'):
134        platform = 'netbsd'
135    return platform
136
137
138def platformIsDarwin():
139    """Returns true if the OS triple for the selected platform is any valid apple OS"""
140    return getPlatform() in getDarwinOSTriples()
141
142
143def findMainThreadCheckerDylib():
144    if not platformIsDarwin():
145        return ""
146
147    with os.popen('xcode-select -p') as output:
148        xcode_developer_path = output.read().strip()
149        mtc_dylib_path = '%s/usr/lib/libMainThreadChecker.dylib' % xcode_developer_path
150        if os.path.isfile(mtc_dylib_path):
151            return mtc_dylib_path
152
153    return ""
154
155
156class _PlatformContext(object):
157    """Value object class which contains platform-specific options."""
158
159    def __init__(self, shlib_environment_var, shlib_prefix, shlib_extension):
160        self.shlib_environment_var = shlib_environment_var
161        self.shlib_prefix = shlib_prefix
162        self.shlib_extension = shlib_extension
163
164
165def createPlatformContext():
166    if platformIsDarwin():
167        return _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib')
168    elif getPlatform() in ("freebsd", "linux", "netbsd"):
169        return _PlatformContext('LD_LIBRARY_PATH', 'lib', 'so')
170    else:
171        return None
172
173
174def hasChattyStderr(test_case):
175    """Some targets produce garbage on the standard error output. This utility function
176    determines whether the tests can be strict about the expected stderr contents."""
177    if match_android_device(test_case.getArchitecture(), ['aarch64'], range(22, 25+1)):
178        return True  # The dynamic linker on the device will complain about unknown DT entries
179    return False
180