1""" This module contains functions used by the test cases to hide the 2architecture and/or the platform dependent nature of the tests. """ 3 4# System modules 5import itertools 6import json 7import re 8import subprocess 9import sys 10import os 11from packaging import version 12from urllib.parse import urlparse 13 14# LLDB modules 15import lldb 16from . import configuration 17from . import lldbtest_config 18import lldbsuite.test.lldbplatform as lldbplatform 19from lldbsuite.test.builders import get_builder 20from lldbsuite.test.lldbutil import is_exe 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", "armv8l", "armv7l"]: 29 test_case.expect("register read r0", substrs=["r0 = 0x"]) 30 elif arch in ["aarch64", "arm64", "arm64e", "arm64_32"]: 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 elif arch in ["powerpc64le"]: 37 test_case.expect("register read r0", substrs=["r0 = 0x"]) 38 elif re.match("^rv(32|64)", arch): 39 test_case.expect("register read zero", substrs=["zero = 0x"]) 40 else: 41 # TODO: Add check for other architectures 42 test_case.fail( 43 "Unsupported architecture for test case (arch: %s)" 44 % test_case.getArchitecture() 45 ) 46 47 48def _run_adb_command(cmd, device_id): 49 device_id_args = [] 50 if device_id: 51 device_id_args = ["-s", device_id] 52 full_cmd = ["adb"] + device_id_args + cmd 53 p = subprocess.Popen(full_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 54 stdout, stderr = p.communicate() 55 return p.returncode, stdout, stderr 56 57 58def target_is_android(): 59 return configuration.lldb_platform_name == "remote-android" 60 61 62def android_device_api(): 63 if not hasattr(android_device_api, "result"): 64 assert configuration.lldb_platform_url is not None 65 device_id = None 66 parsed_url = urlparse(configuration.lldb_platform_url) 67 host_name = parsed_url.netloc.split(":")[0] 68 if host_name != "localhost": 69 device_id = host_name 70 if device_id.startswith("[") and device_id.endswith("]"): 71 device_id = device_id[1:-1] 72 retcode, stdout, stderr = _run_adb_command( 73 ["shell", "getprop", "ro.build.version.sdk"], device_id 74 ) 75 if retcode == 0: 76 android_device_api.result = int(stdout) 77 else: 78 raise LookupError( 79 ">>> Unable to determine the API level of the Android device.\n" 80 ">>> stdout:\n%s\n" 81 ">>> stderr:\n%s\n" % (stdout, stderr) 82 ) 83 return android_device_api.result 84 85 86def match_android_device(device_arch, valid_archs=None, valid_api_levels=None): 87 if not target_is_android(): 88 return False 89 if valid_archs is not None and device_arch not in valid_archs: 90 return False 91 if valid_api_levels is not None and android_device_api() not in valid_api_levels: 92 return False 93 94 return True 95 96 97def finalize_build_dictionary(dictionary): 98 # Provide uname-like platform name 99 platform_name_to_uname = { 100 "linux": "Linux", 101 "netbsd": "NetBSD", 102 "freebsd": "FreeBSD", 103 "windows": "Windows_NT", 104 "macosx": "Darwin", 105 "darwin": "Darwin", 106 } 107 108 if dictionary is None: 109 dictionary = {} 110 if target_is_android(): 111 dictionary["OS"] = "Android" 112 dictionary["PIE"] = 1 113 elif platformIsDarwin(): 114 dictionary["OS"] = "Darwin" 115 else: 116 dictionary["OS"] = platform_name_to_uname[getPlatform()] 117 118 dictionary["HOST_OS"] = platform_name_to_uname[getHostPlatform()] 119 120 return dictionary 121 122 123def _get_platform_os(p): 124 # Use the triple to determine the platform if set. 125 triple = p.GetTriple() 126 if triple: 127 platform = triple.split("-")[2] 128 if platform.startswith("freebsd"): 129 platform = "freebsd" 130 elif platform.startswith("netbsd"): 131 platform = "netbsd" 132 elif platform.startswith("openbsd"): 133 platform = "openbsd" 134 return platform 135 136 return "" 137 138 139def getHostPlatform(): 140 """Returns the host platform running the test suite.""" 141 return _get_platform_os(lldb.SBPlatform("host")) 142 143 144def getDarwinOSTriples(): 145 return lldbplatform.translate(lldbplatform.darwin_all) 146 147 148def getPlatform(): 149 """Returns the target platform which the tests are running on.""" 150 # Use the Apple SDK to determine the platform if set. 151 if configuration.apple_sdk: 152 platform = configuration.apple_sdk 153 dot = platform.find(".") 154 if dot != -1: 155 platform = platform[:dot] 156 if platform == "iphoneos": 157 platform = "ios" 158 return platform 159 160 return _get_platform_os(lldb.selected_platform) 161 162 163def platformIsDarwin(): 164 """Returns true if the OS triple for the selected platform is any valid apple OS""" 165 return getPlatform() in getDarwinOSTriples() 166 167 168def findMainThreadCheckerDylib(): 169 if not platformIsDarwin(): 170 return "" 171 172 if getPlatform() in lldbplatform.translate(lldbplatform.darwin_embedded): 173 return "/Developer/usr/lib/libMainThreadChecker.dylib" 174 175 with os.popen("xcode-select -p") as output: 176 xcode_developer_path = output.read().strip() 177 mtc_dylib_path = "%s/usr/lib/libMainThreadChecker.dylib" % xcode_developer_path 178 if os.path.isfile(mtc_dylib_path): 179 return mtc_dylib_path 180 181 return "" 182 183 184class _PlatformContext(object): 185 """Value object class which contains platform-specific options.""" 186 187 def __init__( 188 self, shlib_environment_var, shlib_path_separator, shlib_prefix, shlib_extension 189 ): 190 self.shlib_environment_var = shlib_environment_var 191 self.shlib_path_separator = shlib_path_separator 192 self.shlib_prefix = shlib_prefix 193 self.shlib_extension = shlib_extension 194 195 196def createPlatformContext(): 197 if platformIsDarwin(): 198 return _PlatformContext("DYLD_LIBRARY_PATH", ":", "lib", "dylib") 199 elif getPlatform() in ("linux", "freebsd", "netbsd", "openbsd"): 200 return _PlatformContext("LD_LIBRARY_PATH", ":", "lib", "so") 201 else: 202 return _PlatformContext("PATH", ";", "", "dll") 203 204 205def hasChattyStderr(test_case): 206 """Some targets produce garbage on the standard error output. This utility function 207 determines whether the tests can be strict about the expected stderr contents.""" 208 if match_android_device( 209 test_case.getArchitecture(), ["aarch64"], range(22, 25 + 1) 210 ): 211 return True # The dynamic linker on the device will complain about unknown DT entries 212 return False 213 214 215def builder_module(): 216 return get_builder(sys.platform) 217 218 219def getArchitecture(): 220 """Returns the architecture in effect the test suite is running with.""" 221 module = builder_module() 222 arch = module.getArchitecture() 223 if arch == "amd64": 224 arch = "x86_64" 225 if arch in ["armv7l", "armv8l"]: 226 arch = "arm" 227 return arch 228 229 230lldbArchitecture = None 231 232 233def getLLDBArchitecture(): 234 """Returns the architecture of the lldb binary.""" 235 global lldbArchitecture 236 if not lldbArchitecture: 237 # These two target settings prevent lldb from doing setup that does 238 # nothing but slow down the end goal of printing the architecture. 239 command = [ 240 lldbtest_config.lldbExec, 241 "-x", 242 "-b", 243 "-o", 244 "settings set target.preload-symbols false", 245 "-o", 246 "settings set target.load-script-from-symbol-file false", 247 "-o", 248 "file " + lldbtest_config.lldbExec, 249 ] 250 251 output = subprocess.check_output(command) 252 str = output.decode() 253 254 for line in str.splitlines(): 255 m = re.search(r"Current executable set to '.*' \((.*)\)\.", line) 256 if m: 257 lldbArchitecture = m.group(1) 258 break 259 260 return lldbArchitecture 261 262 263def getCompiler(): 264 """Returns the compiler in effect the test suite is running with.""" 265 module = builder_module() 266 return module.getCompiler() 267 268 269def getCompilerBinary(): 270 """Returns the compiler binary the test suite is running with.""" 271 return getCompiler().split()[0] 272 273 274def getCompilerVersion(): 275 """Returns a string that represents the compiler version. 276 Supports: llvm, clang. 277 """ 278 compiler = getCompilerBinary() 279 version_output = subprocess.check_output([compiler, "--version"], errors="replace") 280 m = re.search("version ([0-9.]+)", version_output) 281 if m: 282 return m.group(1) 283 return "unknown" 284 285 286def getDwarfVersion(): 287 """Returns the dwarf version generated by clang or '0'.""" 288 if configuration.dwarf_version: 289 return str(configuration.dwarf_version) 290 if "clang" in getCompiler(): 291 try: 292 triple = builder_module().getTriple(getArchitecture()) 293 target = ["-target", triple] if triple else [] 294 driver_output = subprocess.check_output( 295 [getCompiler()] + target + "-g -c -x c - -o - -###".split(), 296 stderr=subprocess.STDOUT, 297 ) 298 driver_output = driver_output.decode("utf-8") 299 for line in driver_output.split(os.linesep): 300 m = re.search("dwarf-version=([0-9])", line) 301 if m: 302 return m.group(1) 303 except subprocess.CalledProcessError: 304 pass 305 return "0" 306 307 308def expectedCompilerVersion(compiler_version): 309 """Returns True iff compiler_version[1] matches the current compiler version. 310 Use compiler_version[0] to specify the operator used to determine if a match has occurred. 311 Any operator other than the following defaults to an equality test: 312 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not' 313 314 If the current compiler version cannot be determined, we assume it is close to the top 315 of trunk, so any less-than or equal-to comparisons will return False, and any 316 greater-than or not-equal-to comparisons will return True. 317 """ 318 if compiler_version is None: 319 return True 320 operator = str(compiler_version[0]) 321 version_str = str(compiler_version[1]) 322 323 if not version_str: 324 return True 325 326 test_compiler_version_str = getCompilerVersion() 327 if test_compiler_version_str == "unknown": 328 # Assume the compiler version is at or near the top of trunk. 329 return operator in [">", ">=", "!", "!=", "not"] 330 331 actual_version = version.parse(version_str) 332 test_compiler_version = version.parse(test_compiler_version_str) 333 334 if operator == ">": 335 return test_compiler_version > actual_version 336 if operator == ">=" or operator == "=>": 337 return test_compiler_version >= actual_version 338 if operator == "<": 339 return test_compiler_version < actual_version 340 if operator == "<=" or operator == "=<": 341 return test_compiler_version <= actual_version 342 if operator == "!=" or operator == "!" or operator == "not": 343 return version_str not in test_compiler_version_str 344 return version_str in test_compiler_version_str 345 346 347def expectedCompiler(compilers): 348 """Returns True iff any element of compilers is a sub-string of the current compiler.""" 349 if compilers is None: 350 return True 351 352 for compiler in compilers: 353 if compiler in getCompiler(): 354 return True 355 356 return False 357 358 359# This is a helper function to determine if a specific version of Xcode's linker 360# contains a TLS bug. We want to skip TLS tests if they contain this bug, but 361# adding a linker/linker_version conditions to a decorator is challenging due to 362# the number of ways linkers can enter the build process. 363def xcode15LinkerBug(): 364 """Returns true iff a test is running on a darwin platform and the host linker is between versions 1000 and 1109.""" 365 darwin_platforms = lldbplatform.translate(lldbplatform.darwin_all) 366 if getPlatform() not in darwin_platforms: 367 return False 368 369 try: 370 raw_version_details = subprocess.check_output( 371 ("xcrun", "ld", "-version_details") 372 ) 373 version_details = json.loads(raw_version_details) 374 version = version_details.get("version", "0") 375 version_tuple = tuple(int(x) for x in version.split(".")) 376 if (1000,) <= version_tuple <= (1109,): 377 return True 378 except: 379 pass 380 381 return False 382