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 getCompilerVersion(): 270 """Returns a string that represents the compiler version. 271 Supports: llvm, clang. 272 """ 273 version_output = subprocess.check_output( 274 [getCompiler(), "--version"], errors="replace" 275 ) 276 m = re.search("version ([0-9.]+)", version_output) 277 if m: 278 return m.group(1) 279 return "unknown" 280 281 282def getDwarfVersion(): 283 """Returns the dwarf version generated by clang or '0'.""" 284 if configuration.dwarf_version: 285 return str(configuration.dwarf_version) 286 if "clang" in getCompiler(): 287 try: 288 triple = builder_module().getTriple(getArchitecture()) 289 target = ["-target", triple] if triple else [] 290 driver_output = subprocess.check_output( 291 [getCompiler()] + target + "-g -c -x c - -o - -###".split(), 292 stderr=subprocess.STDOUT, 293 ) 294 driver_output = driver_output.decode("utf-8") 295 for line in driver_output.split(os.linesep): 296 m = re.search("dwarf-version=([0-9])", line) 297 if m: 298 return m.group(1) 299 except subprocess.CalledProcessError: 300 pass 301 return "0" 302 303 304def expectedCompilerVersion(compiler_version): 305 """Returns True iff compiler_version[1] matches the current compiler version. 306 Use compiler_version[0] to specify the operator used to determine if a match has occurred. 307 Any operator other than the following defaults to an equality test: 308 '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not' 309 310 If the current compiler version cannot be determined, we assume it is close to the top 311 of trunk, so any less-than or equal-to comparisons will return False, and any 312 greater-than or not-equal-to comparisons will return True. 313 """ 314 if compiler_version is None: 315 return True 316 operator = str(compiler_version[0]) 317 version_str = str(compiler_version[1]) 318 319 if not version_str: 320 return True 321 322 test_compiler_version_str = getCompilerVersion() 323 if test_compiler_version_str == "unknown": 324 # Assume the compiler version is at or near the top of trunk. 325 return operator in [">", ">=", "!", "!=", "not"] 326 327 actual_version = version.parse(version_str) 328 test_compiler_version = version.parse(test_compiler_version_str) 329 330 if operator == ">": 331 return test_compiler_version > actual_version 332 if operator == ">=" or operator == "=>": 333 return test_compiler_version >= actual_version 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 == "!=" or operator == "!" or operator == "not": 339 return version_str not in test_compiler_version_str 340 return version_str in test_compiler_version_str 341 342 343def expectedCompiler(compilers): 344 """Returns True iff any element of compilers is a sub-string of the current compiler.""" 345 if compilers is None: 346 return True 347 348 for compiler in compilers: 349 if compiler in getCompiler(): 350 return True 351 352 return False 353 354 355# This is a helper function to determine if a specific version of Xcode's linker 356# contains a TLS bug. We want to skip TLS tests if they contain this bug, but 357# adding a linker/linker_version conditions to a decorator is challenging due to 358# the number of ways linkers can enter the build process. 359def xcode15LinkerBug(): 360 """Returns true iff a test is running on a darwin platform and the host linker is between versions 1000 and 1109.""" 361 darwin_platforms = lldbplatform.translate(lldbplatform.darwin_all) 362 if getPlatform() not in darwin_platforms: 363 return False 364 365 try: 366 raw_version_details = subprocess.check_output( 367 ("xcrun", "ld", "-version_details") 368 ) 369 version_details = json.loads(raw_version_details) 370 version = version_details.get("version", "0") 371 version_tuple = tuple(int(x) for x in version.split(".")) 372 if (1000,) <= version_tuple <= (1109,): 373 return True 374 except: 375 pass 376 377 return False 378