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