1*e3723e1fSApple OSS Distributions## 2*e3723e1fSApple OSS Distributions# Copyright (c) 2023 Apple Inc. All rights reserved. 3*e3723e1fSApple OSS Distributions# 4*e3723e1fSApple OSS Distributions# @APPLE_OSREFERENCE_LICENSE_HEADER_START@ 5*e3723e1fSApple OSS Distributions# 6*e3723e1fSApple OSS Distributions# This file contains Original Code and/or Modifications of Original Code 7*e3723e1fSApple OSS Distributions# as defined in and that are subject to the Apple Public Source License 8*e3723e1fSApple OSS Distributions# Version 2.0 (the 'License'). You may not use this file except in 9*e3723e1fSApple OSS Distributions# compliance with the License. The rights granted to you under the License 10*e3723e1fSApple OSS Distributions# may not be used to create, or enable the creation or redistribution of, 11*e3723e1fSApple OSS Distributions# unlawful or unlicensed copies of an Apple operating system, or to 12*e3723e1fSApple OSS Distributions# circumvent, violate, or enable the circumvention or violation of, any 13*e3723e1fSApple OSS Distributions# terms of an Apple operating system software license agreement. 14*e3723e1fSApple OSS Distributions# 15*e3723e1fSApple OSS Distributions# Please obtain a copy of the License at 16*e3723e1fSApple OSS Distributions# http://www.opensource.apple.com/apsl/ and read it before using this file. 17*e3723e1fSApple OSS Distributions# 18*e3723e1fSApple OSS Distributions# The Original Code and all software distributed under the License are 19*e3723e1fSApple OSS Distributions# distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER 20*e3723e1fSApple OSS Distributions# EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, 21*e3723e1fSApple OSS Distributions# INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, 22*e3723e1fSApple OSS Distributions# FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. 23*e3723e1fSApple OSS Distributions# Please see the License for the specific language governing rights and 24*e3723e1fSApple OSS Distributions# limitations under the License. 25*e3723e1fSApple OSS Distributions# 26*e3723e1fSApple OSS Distributions# @APPLE_OSREFERENCE_LICENSE_HEADER_END@ 27*e3723e1fSApple OSS Distributions## 28*e3723e1fSApple OSS Distributions 29*e3723e1fSApple OSS Distributions""" LLDB Scripted Process designed for unit-testing mock support. """ 30*e3723e1fSApple OSS Distributions 31*e3723e1fSApple OSS Distributionsimport unittest 32*e3723e1fSApple OSS Distributionsimport sys 33*e3723e1fSApple OSS Distributionsimport logging 34*e3723e1fSApple OSS Distributionsfrom collections import namedtuple 35*e3723e1fSApple OSS Distributionsfrom pathlib import Path 36*e3723e1fSApple OSS Distributions 37*e3723e1fSApple OSS Distributionsimport lldb 38*e3723e1fSApple OSS Distributionsimport lldbmock.memorymock 39*e3723e1fSApple OSS Distributionsfrom lldb.plugins.scripted_process import ScriptedProcess, ScriptedThread 40*e3723e1fSApple OSS Distributionsfrom lldbtest.unittest import LLDBTextTestRunner, LLDBJSONTestRunner 41*e3723e1fSApple OSS Distributionsfrom lldbtest.coverage import CoverageContext 42*e3723e1fSApple OSS Distributions 43*e3723e1fSApple OSS Distributions# location of this script 44*e3723e1fSApple OSS DistributionsSCRIPT_PATH = Path(__file__).parent 45*e3723e1fSApple OSS Distributions 46*e3723e1fSApple OSS Distributions# Configure logging. 47*e3723e1fSApple OSS Distributions# This script is loaded first so we can share root logger with other files. 48*e3723e1fSApple OSS Distributions 49*e3723e1fSApple OSS Distributionslogging.root.setLevel(logging.INFO) 50*e3723e1fSApple OSS Distributionslogging.basicConfig(level=logging.INFO) 51*e3723e1fSApple OSS Distributionslldb.test_logger = logging.getLogger("UnitTest") 52*e3723e1fSApple OSS Distributionslldb.test_logger.getChild("ScriptedProcess").info("Log initialized.") 53*e3723e1fSApple OSS Distributions 54*e3723e1fSApple OSS Distributions 55*e3723e1fSApple OSS Distributionsclass TestThread(ScriptedThread): 56*e3723e1fSApple OSS Distributions """ Scripted thread that represents custom thread state. """ 57*e3723e1fSApple OSS Distributions 58*e3723e1fSApple OSS Distributions 59*e3723e1fSApple OSS Distributionsclass TestProcess(ScriptedProcess): 60*e3723e1fSApple OSS Distributions """ Scripted process that represents target's memory. """ 61*e3723e1fSApple OSS Distributions 62*e3723e1fSApple OSS Distributions LOG = lldb.test_logger.getChild("ScriptedProcess") 63*e3723e1fSApple OSS Distributions 64*e3723e1fSApple OSS Distributions MockElem = namedtuple('MockElem', ['addr', 'mock']) 65*e3723e1fSApple OSS Distributions 66*e3723e1fSApple OSS Distributions def __init__(self, ctx: lldb.SBExecutionContext, args: lldb.SBStructuredData): 67*e3723e1fSApple OSS Distributions super().__init__(ctx, args) 68*e3723e1fSApple OSS Distributions 69*e3723e1fSApple OSS Distributions self.verbose = args.GetValueForKey("verbose").GetBooleanValue() 70*e3723e1fSApple OSS Distributions self.debug = args.GetValueForKey("debug").GetBooleanValue() 71*e3723e1fSApple OSS Distributions self.json = args.GetValueForKey("json").GetStringValue(256) 72*e3723e1fSApple OSS Distributions print(self.json) 73*e3723e1fSApple OSS Distributions self._mocks = [] 74*e3723e1fSApple OSS Distributions 75*e3723e1fSApple OSS Distributions # 76*e3723e1fSApple OSS Distributions # Testing framework API 77*e3723e1fSApple OSS Distributions # 78*e3723e1fSApple OSS Distributions 79*e3723e1fSApple OSS Distributions def add_mock(self, addr: int, mock: lldbmock.memorymock.BaseMock): 80*e3723e1fSApple OSS Distributions # Do not allow overlaping mocks to keep logic simple. 81*e3723e1fSApple OSS Distributions if any(me for me in self._mocks 82*e3723e1fSApple OSS Distributions if me.addr <= addr < (me.addr + me.mock.size)): 83*e3723e1fSApple OSS Distributions raise ValueError("Overlaping mock with") 84*e3723e1fSApple OSS Distributions 85*e3723e1fSApple OSS Distributions self._mocks.append(TestProcess.MockElem(addr, mock)) 86*e3723e1fSApple OSS Distributions 87*e3723e1fSApple OSS Distributions def remove_mock(self, mock: lldbmock.memorymock.BaseMock): 88*e3723e1fSApple OSS Distributions raise NotImplementedError("Mock removal not implemented yet") 89*e3723e1fSApple OSS Distributions 90*e3723e1fSApple OSS Distributions def reset_mocks(self): 91*e3723e1fSApple OSS Distributions """ Remove all mocks. """ 92*e3723e1fSApple OSS Distributions self._mocks = [] 93*e3723e1fSApple OSS Distributions 94*e3723e1fSApple OSS Distributions # 95*e3723e1fSApple OSS Distributions # LLDB Scripted Process Implementation 96*e3723e1fSApple OSS Distributions # 97*e3723e1fSApple OSS Distributions 98*e3723e1fSApple OSS Distributions def get_memory_region_containing_address( 99*e3723e1fSApple OSS Distributions self, 100*e3723e1fSApple OSS Distributions addr: int 101*e3723e1fSApple OSS Distributions ) -> lldb.SBMemoryRegionInfo: 102*e3723e1fSApple OSS Distributions # A generic answer should work in our case 103*e3723e1fSApple OSS Distributions return lldb.SBMemoryRegionInfo() 104*e3723e1fSApple OSS Distributions 105*e3723e1fSApple OSS Distributions def read_memory_at_address( 106*e3723e1fSApple OSS Distributions self, 107*e3723e1fSApple OSS Distributions addr: int, 108*e3723e1fSApple OSS Distributions size: int, 109*e3723e1fSApple OSS Distributions error: lldb.SBError = lldb.SBError() 110*e3723e1fSApple OSS Distributions ) -> lldb.SBData: 111*e3723e1fSApple OSS Distributions """ Performs I/O read on top of set of mock structures. 112*e3723e1fSApple OSS Distributions Undefined regions are set to 0. 113*e3723e1fSApple OSS Distributions """ 114*e3723e1fSApple OSS Distributions data = lldb.SBData() 115*e3723e1fSApple OSS Distributions rawdata = bytearray(size) 116*e3723e1fSApple OSS Distributions 117*e3723e1fSApple OSS Distributions # Avoid delegating reads back to SBTarget. That leads to infinite 118*e3723e1fSApple OSS Distributions # recursion as SBTarget calls to read from SBProcess instance. 119*e3723e1fSApple OSS Distributions 120*e3723e1fSApple OSS Distributions # Overlay mocks on top of the I/O. 121*e3723e1fSApple OSS Distributions for maddr, mock in ( 122*e3723e1fSApple OSS Distributions (me.addr, me.mock) for me 123*e3723e1fSApple OSS Distributions in self._mocks): 124*e3723e1fSApple OSS Distributions 125*e3723e1fSApple OSS Distributions # check for overlap 126*e3723e1fSApple OSS Distributions start_addr = max(addr, maddr) 127*e3723e1fSApple OSS Distributions end_addr = min(addr + size, maddr + mock.size) 128*e3723e1fSApple OSS Distributions 129*e3723e1fSApple OSS Distributions if end_addr < start_addr: 130*e3723e1fSApple OSS Distributions # no intersection of I/O and mock entry 131*e3723e1fSApple OSS Distributions continue 132*e3723e1fSApple OSS Distributions 133*e3723e1fSApple OSS Distributions offs = start_addr - maddr # In the mock space 134*e3723e1fSApple OSS Distributions boffs = start_addr - addr # In mbuffer space 135*e3723e1fSApple OSS Distributions sz = end_addr - start_addr # size to read 136*e3723e1fSApple OSS Distributions 137*e3723e1fSApple OSS Distributions self.LOG.debug("overlap: %x +%d", offs, sz) 138*e3723e1fSApple OSS Distributions self.LOG.debug("raw read %x +%d", addr, size) 139*e3723e1fSApple OSS Distributions self.LOG.debug("final read %x +%d", start_addr - addr, sz) 140*e3723e1fSApple OSS Distributions #self.LOG.debug("data: %s", mock.getData()[offs: offs + sz]) 141*e3723e1fSApple OSS Distributions 142*e3723e1fSApple OSS Distributions # Merge mock data into I/O buffer. 143*e3723e1fSApple OSS Distributions rawdata[boffs: boffs + sz] = mock.getData()[offs:offs+sz] 144*e3723e1fSApple OSS Distributions 145*e3723e1fSApple OSS Distributions data.SetDataWithOwnership( 146*e3723e1fSApple OSS Distributions error, 147*e3723e1fSApple OSS Distributions rawdata, 148*e3723e1fSApple OSS Distributions lldb.eByteOrderLittle, 149*e3723e1fSApple OSS Distributions 8 150*e3723e1fSApple OSS Distributions ) 151*e3723e1fSApple OSS Distributions 152*e3723e1fSApple OSS Distributions return data 153*e3723e1fSApple OSS Distributions 154*e3723e1fSApple OSS Distributions def get_loaded_images(self) -> list: 155*e3723e1fSApple OSS Distributions return self.loaded_images 156*e3723e1fSApple OSS Distributions 157*e3723e1fSApple OSS Distributions def get_process_id(self) -> int: 158*e3723e1fSApple OSS Distributions return 0 159*e3723e1fSApple OSS Distributions 160*e3723e1fSApple OSS Distributions def is_alive(self) -> bool: 161*e3723e1fSApple OSS Distributions return True 162*e3723e1fSApple OSS Distributions 163*e3723e1fSApple OSS Distributions def get_scripted_thread_plugin(self) -> str: 164*e3723e1fSApple OSS Distributions return __class__.__module__ + '.' + TestThread.__name__ 165*e3723e1fSApple OSS Distributions 166*e3723e1fSApple OSS Distributions 167*e3723e1fSApple OSS Distributionsdef run_unit_tests(debugger, _command, _exe_ctx, _result, _internal_dict): 168*e3723e1fSApple OSS Distributions """ Runs standart Python unit tests inside LLDB. """ 169*e3723e1fSApple OSS Distributions 170*e3723e1fSApple OSS Distributions # Obtain current plugin instance 171*e3723e1fSApple OSS Distributions sp = debugger.GetSelectedTarget().GetProcess().GetScriptedImplementation() 172*e3723e1fSApple OSS Distributions 173*e3723e1fSApple OSS Distributions # Enable debugging 174*e3723e1fSApple OSS Distributions if sp.debug: 175*e3723e1fSApple OSS Distributions logging.root.setLevel(logging.DEBUG) 176*e3723e1fSApple OSS Distributions logging.basicConfig(level=logging.DEBUG) 177*e3723e1fSApple OSS Distributions 178*e3723e1fSApple OSS Distributions log = logging.getLogger("ScriptedProcess") 179*e3723e1fSApple OSS Distributions log.info("Running tests") 180*e3723e1fSApple OSS Distributions log.info("Using path: %s", SCRIPT_PATH / "lldb_tests") 181*e3723e1fSApple OSS Distributions tests = unittest.TestLoader().discover(SCRIPT_PATH / "lldb_tests") 182*e3723e1fSApple OSS Distributions 183*e3723e1fSApple OSS Distributions # Select runner class 184*e3723e1fSApple OSS Distributions RunnerClass = LLDBJSONTestRunner if sp.json else LLDBTextTestRunner 185*e3723e1fSApple OSS Distributions 186*e3723e1fSApple OSS Distributions # Open output file if requested 187*e3723e1fSApple OSS Distributions if sp.json: 188*e3723e1fSApple OSS Distributions with open(f"{sp.json}-lldb.json", 'wt') as outfile: 189*e3723e1fSApple OSS Distributions runner = RunnerClass(verbosity=2 if sp.verbose else 1, debug=sp.debug, 190*e3723e1fSApple OSS Distributions stream=outfile) 191*e3723e1fSApple OSS Distributions runner.run(tests) 192*e3723e1fSApple OSS Distributions else: 193*e3723e1fSApple OSS Distributions runner = RunnerClass(stream=sys.stderr, verbosity=2 if sp.verbose else 1, 194*e3723e1fSApple OSS Distributions debug=sp.debug) 195*e3723e1fSApple OSS Distributions runner.run(tests) 196*e3723e1fSApple OSS Distributions 197*e3723e1fSApple OSS Distributionsdef __lldb_init_module(_debugger, _internal_dict): 198*e3723e1fSApple OSS Distributions """ LLDB entry point """ 199*e3723e1fSApple OSS Distributions 200*e3723e1fSApple OSS Distributions # XNU has really bad import structure and it is easy to create circular 201*e3723e1fSApple OSS Distributions # dependencies. Forcibly import XNU before tests are ran so the final 202*e3723e1fSApple OSS Distributions # result is close to what imports from a dSYM would end up with. 203*e3723e1fSApple OSS Distributions with CoverageContext(): 204*e3723e1fSApple OSS Distributions lldb.debugger.HandleCommand( 205*e3723e1fSApple OSS Distributions f"command script import {SCRIPT_PATH / '../xnu.py'}") 206*e3723e1fSApple OSS Distributions 207*e3723e1fSApple OSS Distributions logging.getLogger("ScriptedProcess").info("Running LLDB module init.") 208*e3723e1fSApple OSS Distributions lldb.debugger.HandleCommand(f"command script add " 209*e3723e1fSApple OSS Distributions f"-f {__name__}.{run_unit_tests.__name__}" 210*e3723e1fSApple OSS Distributions f" run-unit-tests") 211