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