1""" 2Defines a class value which encapsulates the basic lldb Scripting Bridge APIs. This provides an easy 3wrapper to extract information from C based constructs. 4 5 |------- core.value------------| 6 | |--lldb Scripting Bridge--| | 7 | | |--lldb core--| | | 8 | |-------------------------| | 9 |------------------------------| 10 11Use the member function GetSBValue() to access the base Scripting Bridge value. 12""" 13from __future__ import absolute_import, division, print_function 14 15# The value class is designed to be Python 2/3 compatible. Pulling in more 16# builtins classes may break it. 17from builtins import range 18import numbers 19 20# Override int with valueint so we get the desired behavior. 21from .compat import valueint as int 22 23from past.utils import old_div 24import lldb 25import re 26from .caching import ( 27 cache_statically, 28) 29import six 30from .pointer import PointerPolicy 31 32_CSTRING_REX = re.compile(r"((?:\s*|const\s+)\s*char(?:\s+\*|\s+[A-Za-z_0-9]*\s*\[|)\s*)", re.MULTILINE | re.DOTALL) 33 34 35# pragma pylint: disable=hex-method, div-method, rdiv-method, idiv-method, oct-method, nonzero-method 36class value(object): 37 """A class designed to wrap lldb.SBValue() objects so the resulting object 38 can be used as a variable would be in code. So if you have a Point structure 39 variable in your code in the current frame named "pt", you can initialize an instance 40 of this class with it: 41 42 pt = lldb.value(lldb.frame.FindVariable("pt")) 43 print pt 44 print pt.x 45 print pt.y 46 47 pt = lldb.value(lldb.frame.FindVariable("rectangle_array")) 48 print rectangle_array[12] 49 print rectangle_array[5].origin.x 50 """ 51 52 __slots__ = ('__sbval', '__ptr') 53 54 def __init__(self, sbvalue, usePtrPolicy=True): 55 # Using a double `__` means this will be hidden from getattr() 56 # and can't conflict with C/C++ type field names. 57 self.__sbval = sbvalue 58 self.__ptr = PointerPolicy.match(sbvalue) if usePtrPolicy else None 59 60 @property 61 def sbvalue(self): 62 """backward compability for the old .sbvalue property""" 63 return self.GetSBValue() 64 65 @property 66 def ptrpolicy(self): 67 return self.__ptr 68 69 @ptrpolicy.setter 70 def ptrpolicy(self, policy): 71 self.__ptr = policy 72 73 def __bool__(self): 74 return self.__sbval.__bool__() and self._GetValueAsUnsigned() != 0 75 76 def __nonzero__(self): 77 return self.__sbval.__nonzero__() and self._GetValueAsUnsigned() != 0 78 79 def __repr__(self): 80 return self.__sbval.__str__() 81 82 # 83 # Compare operators 84 # 85 86 def __eq__(self, other): 87 self_val = self._GetValueAsUnsigned() 88 if isinstance(other, value): 89 other_val = other._GetValueAsUnsigned() 90 return self_val == other_val 91 if isinstance(other, numbers.Integral): 92 return int(self) == other 93 raise TypeError("EQ operator is not defined for this type.") 94 95 def __ne__(self, other): 96 return not self == other 97 98 def __lt__(self, other): 99 self_val = self._GetValueAsUnsigned() 100 if isinstance(other, value): 101 other_val = other._GetValueAsUnsigned() 102 return self_val < other_val 103 if isinstance(other, numbers.Integral): 104 return int(self) < int(other) 105 raise TypeError("LT operator is not defined for this type") 106 107 def __le__(self, other): 108 return self < other or self == other 109 110 def __gt__(self, other): 111 return not self <= other 112 113 def __ge__(self, other): 114 return not self < other 115 116 def __str__(self): 117 global _CSTRING_REX 118 sbv = self.__sbval 119 type_name = sbv.GetType().GetCanonicalType().GetName() 120 if len(_CSTRING_REX.findall(type_name)) > 0: 121 return self._GetValueAsString() 122 summary = sbv.GetSummary() 123 if summary: 124 return summary.strip('"') 125 return sbv.__str__() 126 127 def __getitem__(self, key): 128 # Allow array access if this value has children... 129 if type(key) is slice: 130 _start = int(key.start) 131 _end = int(key.stop) 132 _step = 1 133 if key.step is not None: 134 _step = int(key.step) 135 retval = [] 136 while _start < _end: 137 retval.append(self[_start]) 138 _start += _step 139 return retval 140 if type(key) is value: 141 key = int(key) 142 if isinstance(key, numbers.Integral): 143 sbv = self.__sbval 144 if self.__ptr: 145 sbv = self.__ptr.GetPointerSBValue(sbv) 146 child_sbvalue = sbv.GetValueForExpressionPath("[%i]" % key) 147 if child_sbvalue and child_sbvalue.IsValid(): 148 return value(child_sbvalue) 149 raise IndexError("Index '%d' is out of range" % key) 150 raise TypeError("Cannot fetch array item for key of type {}".format(str(type(key)))) 151 152 def __getattr__(self, name): 153 sbv = self.__sbval 154 if self.__ptr: 155 sbv = self.__ptr.GetPointerSBValue(sbv) 156 child_sbvalue = sbv.GetChildMemberWithName(name) 157 if child_sbvalue and child_sbvalue.IsValid(): 158 return value(child_sbvalue) 159 raise AttributeError("No field by name: " + name) 160 161 def __add__(self, other): 162 return int(self) + int(other) 163 164 def __radd__(self, other): 165 return int(self) + int(other) 166 167 def __sub__(self, other): 168 return int(self) - int(other) 169 170 def __rsub__(self, other): 171 return int(other) - int(self) 172 173 def __mul__(self, other): 174 return int(self) * int(other) 175 176 def __rmul__(self, other): 177 return int(self) * int(other) 178 179 def __floordiv__(self, other): 180 return int(self) // int(other) 181 182 def __rfloordiv__(self, other): 183 return int(other) // int(self) 184 185 def __mod__(self, other): 186 return int(self) % int(other) 187 188 def __rmod__(self, other): 189 return int(other) % int(self) 190 191 def __divmod__(self, other): 192 return divmod(int(self), int(other)) 193 194 def __rdivmod__(self, other): 195 return divmod(int(other), int(self)) 196 197 def __pow__(self, other): 198 return int(self) ** int(other) 199 200 def __lshift__(self, other): 201 return int(self) << int(other) 202 203 def __rshift__(self, other): 204 return int(self) >> int(other) 205 206 def __and__(self, other): 207 return int(self) & int(other) 208 209 def __rand__(self, other): 210 return int(other) & int(self) 211 212 def __xor__(self, other): 213 return int(self) ^ int(other) 214 215 def __or__(self, other): 216 return int(self) | int(other) 217 218 def __div__(self, other): 219 return old_div(int(self), int(other)) 220 221 def __rdiv__(self, other): 222 return old_div(int(other), int(self)) 223 224 def __truediv__(self, other): 225 return int(self) / int(other) 226 227 def __rtruediv__(self, other): 228 return int(other) / int(self) 229 230 def __iadd__(self, other): 231 result = self.__add__(other) 232 self.__sbval.SetValueFromCString(str(result)) 233 return result 234 235 def __isub__(self, other): 236 result = self.__sub__(other) 237 self.__sbval.SetValueFromCString(str(result)) 238 return result 239 240 def __imul__(self, other): 241 result = self.__mul__(other) 242 self.__sbval.SetValueFromCString(str(result)) 243 return result 244 245 def __idiv__(self, other): 246 result = self.__div__(other) 247 self.__sbval.SetValueFromCString(str(result)) 248 return result 249 250 def __itruediv__(self, other): 251 result = self.__truediv__(other) 252 self.__sbval.SetValueFromCString(str(result)) 253 return result 254 255 def __ifloordiv__(self, other): 256 result = self.__floordiv__(other) 257 self.__sbval.SetValueFromCString(str(result)) 258 return result 259 260 def __imod__(self, other): 261 result = self.__mod__(other) 262 self.__sbval.SetValueFromCString(str(result)) 263 return result 264 265 def __ipow__(self, other): 266 result = self.__pow__(other) 267 self.__sbval.SetValueFromCString(str(result)) 268 return result 269 270 def __ilshift__(self, other): 271 result = self.__lshift__(other) 272 self.__sbval.SetValueFromCString(str(result)) 273 return result 274 275 def __irshift__(self, other): 276 result = self.__rshift__(other) 277 self.__sbval.SetValueFromCString(str(result)) 278 return result 279 280 def __iand__(self, other): 281 result = self.__and__(other) 282 self.__sbval.SetValueFromCString(str(result)) 283 return result 284 285 def __ixor__(self, other): 286 result = self.__xor__(other) 287 self.__sbval.SetValueFromCString(str(result)) 288 return result 289 290 def __ior__(self, other): 291 result = self.__or__(other) 292 self.__sbval.SetValueFromCString(str(result)) 293 return result 294 295 def __neg__(self): 296 return -int(self) 297 298 def __pos__(self): 299 return +int(self) 300 301 def __abs__(self): 302 return abs(int(self)) 303 304 def __invert__(self): 305 return ~int(self) 306 307 def __complex__(self): 308 return complex(int(self)) 309 310 def __int__(self): 311 sbv = self.__sbval 312 if self.__ptr: 313 sbv = self.__ptr.GetPointerSBValue(sbv) 314 315 flags = sbv.GetType().GetTypeFlags() 316 if flags & lldb.eTypeIsPointer: 317 return sbv.GetValueAsAddress() 318 if not flags & lldb.eTypeIsSigned: 319 return self._GetValueAsUnsigned() 320 321 return sbv.GetValueAsSigned() 322 323 # Python 3 conversion to int calls this. 324 def __index__(self): 325 return self.__int__() 326 327 def __long__(self): 328 sbv = self.__sbval 329 if self.__ptr: 330 sbv = self.__ptr.GetPointerSBValue(sbv) 331 332 flags = sbv.GetType().GetTypeFlags() 333 if flags & lldb.eTypeIsPointer: 334 return sbv.GetValueAsAddress() 335 if not flags & lldb.eTypeIsSigned: 336 return self._GetValueAsUnsigned() 337 338 return sbv.GetValueAsSigned() 339 340 def __float__(self): 341 return float(self.__sbval.GetValueAsSigned()) 342 343 # Python 2 must return native string. 344 def __oct__(self): 345 return '0%o' % self._GetValueAsUnsigned() 346 347 # Python 2 must return native string. 348 def __hex__(self): 349 return '0x%x' % self._GetValueAsUnsigned() 350 351 def __hash__(self): 352 return hash(self.__sbval) 353 354 def GetSBValue(self): 355 sbv = self.__sbval 356 if self.__ptr: 357 sbv = self.__ptr.GetPointerSBValue(sbv) 358 359 return sbv 360 361 def __getstate__(self): 362 err = lldb.SBError() 363 sbv = self.__sbval 364 if self.__ptr: 365 sbv = self.__ptr.GetPointerSBValue(sbv) 366 addr = sbv.GetValueAsAddress() 367 size = sbv.GetType().GetPointeeType().GetByteSize() 368 else: 369 addr = sbv.GetLoadAddress() 370 size = sbv.GetType().GetByteSize() 371 372 content = sbv.GetProcess().ReadMemory(addr, size, err) 373 if err.fail: 374 content = '' 375 return content 376 377 def _GetValueAsSigned(self): 378 sbv = self.__sbval 379 if self.__ptr: 380 print("ERROR: You cannot get 'int' from pointer type %s, please use unsigned(obj) for such purposes." % sbv.GetType().GetDisplayTypeName()) 381 raise ValueError("Cannot get signed int for pointer data.") 382 serr = lldb.SBError() 383 retval = sbv.GetValueAsSigned(serr) 384 if serr.success: 385 return retval 386 raise ValueError("Failed to read signed data. {} (type = {}) Error description: {}".format( 387 str(sbv), sbv.GetType().GetDisplayTypeName(), serr.GetCString())) 388 389 def _GetValueAsCast(self, dest_type): 390 if not isinstance(dest_type, lldb.SBType): 391 raise ValueError("Invalid type for dest_type: {}".format(type(dest_type))) 392 addr = self._GetValueAsUnsigned() 393 sbval = self.__sbval.target.CreateValueFromExpression("newname", "(void *)"+str(addr)) 394 val = value(sbval.Cast(dest_type)) 395 return val 396 397 def _GetValueAsUnsigned(self): 398 sbv = self.__sbval 399 if self.__ptr: 400 sbv = self.__ptr.GetPointerSBValue(sbv) 401 return sbv.GetValueAsAddress() 402 serr = lldb.SBError() 403 retval = sbv.GetValueAsUnsigned(serr) 404 if serr.success: 405 return retval 406 raise ValueError("Failed to read unsigned data. {} (type = {}) Error description: {}".format( 407 str(sbv), sbv.GetType().GetDisplayTypeName(), serr.GetCString())) 408 409 def _GetValueAsString(self, offset=0, maxlen=1024): 410 sbv = self.__sbval 411 serr = lldb.SBError() 412 sbdata = None 413 if self.__ptr: 414 sbv = self.__ptr.GetPointerSBValue(sbv) 415 sbdata = sbv.GetPointeeData(offset, maxlen) 416 else: 417 sbdata = sbv.GetData() 418 419 retval = '' 420 bytesize = sbdata.GetByteSize() 421 if bytesize == 0: 422 # raise ValueError('Unable to read value as string') 423 return '' 424 for i in range(0, bytesize): 425 serr.Clear() 426 ch = chr(sbdata.GetUnsignedInt8(serr, i)) 427 if serr.fail: 428 raise ValueError("Unable to read string data: " + serr.GetCString()) 429 if ch == '\0': 430 break 431 retval += ch 432 return retval 433 434 def __format__(self, format_spec): 435 # typechar is last char. see http://www.python.org/dev/peps/pep-3101/ 436 typechar = format_spec[-1] if len(format_spec) else '' 437 438 if typechar in 'bcdoxX': # requires integral conversion 439 return format(int(self), format_spec) 440 441 if typechar in 'eEfFgG%': # requires float conversion 442 return format(float(self), format_spec) 443 444 if typechar in 's': # requires string conversion 445 return format(str(self), format_spec) 446 447 # 'n' or '' mean "whatever you got for me" 448 flags = self.__sbval.GetType().GetTypeFlags() 449 if flags & lldb.eTypeIsFloat: 450 return format(float(self), format_spec) 451 elif flags & lldb.eTypeIsScalar: 452 return format(int(self), format_spec) 453 else: 454 return format(str(self), format_spec) 455 456def unsigned(val): 457 """ Helper function to get unsigned value from core.value 458 params: val - value (see value class above) representation of an integer type 459 returns: int which is unsigned. 460 raises : ValueError if the type cannot be represented as unsigned int. 461 """ 462 if type(val) is value: 463 return int(val._GetValueAsUnsigned()) 464 return int(val) 465 466 467def signed(val): 468 """ Helper function to get signed value from core.value 469 params: val - value (see value class above) representation of an integer type 470 returns: int which is signed. 471 raises: ValueError if the type cannot be represented as signed int. 472 """ 473 if type(val) is value: 474 return val.GetSBValue().GetValueAsSigned() 475 return int(val) 476 477 478def sizeof(t): 479 """ Find the byte size of a type. 480 params: t - str : ex 'time_spec' returns equivalent of sizeof(time_spec) in C 481 t - value: ex a value object. returns size of the object 482 returns: int - byte size length 483 """ 484 if type(t) is value: 485 return t.GetSBValue().GetByteSize() 486 if isinstance(t, six.string_types): 487 return gettype(t).GetByteSize() 488 raise ValueError("Cannot get sizeof. Invalid argument") 489 490 491def dereference(val): 492 """ Get a dereferenced obj for a pointer type obj 493 params: val - value object representing a pointer type C construct in lldb 494 returns: value - value 495 ex. val = dereference(ptr_obj) #python 496 is same as 497 obj_ptr = (int *)0x1234 #C 498 val = *obj_ptr #C 499 """ 500 if type(val) is value: 501 sbv = val.GetSBValue() 502 if val.ptrpolicy: 503 sbv = val.ptrpolicy.GetPointerSBValue(sbv) 504 return value(sbv.Dereference()) 505 raise TypeError('Cannot dereference this type.') 506 507 508def wrapped(val): 509 """ Get original pointer value without aplying pointer policy. 510 param: val - value object representing a pointer 511 returns: value - value 512 """ 513 if isinstance(val, value): 514 policy = val.ptrpolicy 515 val.ptrpolicy = None 516 newval = value(val.GetSBValue(), False) 517 val.ptrpolicy = policy 518 return newval 519 raise TypeError("Cannot do wrapped for non-value type objects") 520 521 522def addressof(val): 523 """ Get address of a core.value object. 524 params: val - value object representing a C construct in lldb 525 returns: value - value object referring to 'type(val) *' type 526 ex. addr = addressof(hello_obj) #python 527 is same as 528 uintptr_t addr = (uintptr_t)&hello_obj #C 529 """ 530 if type(val) is value: 531 return value(val.GetSBValue().AddressOf()) 532 raise TypeError("Cannot do addressof for non-value type objects") 533 534 535def cast(obj, target_type): 536 """ Type cast an object to another C type. 537 params: 538 obj - core.value object representing some C construct in lldb 539 target_type - str : ex 'char *' 540 - lldb.SBType : 541 """ 542 dest_type = target_type 543 if isinstance(target_type, six.string_types): 544 dest_type = gettype(target_type) 545 elif type(target_type) is value: 546 dest_type = target_type.GetSBValue().GetType() 547 548 if type(obj) is value: 549 return obj._GetValueAsCast(dest_type) 550 elif type(obj) is int: 551 print("ERROR: You cannot cast an 'int' to %s, please use kern.GetValueFromAddress() for such purposes." % str(target_type)) 552 raise TypeError("object of type %s cannot be casted to %s" % (str(type(obj)), str(target_type))) 553 554 555def containerof(obj, target_type, field_name): 556 """ Type cast an object to another C type from a pointer to a field. 557 params: 558 obj - core.value object representing some C construct in lldb 559 target_type - str : ex 'struct thread' 560 - lldb.SBType : 561 field_name - the field name within the target_type obj is a pointer to 562 """ 563 addr = int(obj) - getfieldoffset(target_type, field_name) 564 sbv = obj.GetSBValue() 565 sbv = sbv.chkCreateValueFromAddress(None, addr, gettype(target_type)) 566 return value(sbv.AddressOf()) 567 568 569@cache_statically 570def gettype(target_type, target=None): 571 """ Returns lldb.SBType of the given target_type 572 params: 573 target_type - str, ex. 'char', 'uint32_t' etc 574 returns: 575 lldb.SBType - SBType corresponding to the given target_type 576 raises: 577 NameError - Incase the type is not identified 578 """ 579 580 # 581 # If the type was qualified with a `struct` or `class`, ... 582 # make sure we pick up the proper definition in case of clashes. 583 # 584 want = 0 585 name = str(target_type).strip() 586 587 if name.startswith("struct"): 588 want = lldb.eTypeClassStruct 589 elif name.startswith("union"): 590 want = lldb.eTypeClassUnion 591 elif name.startswith("class"): 592 want = lldb.eTypeClassClass 593 elif name.startswith("enum"): 594 want = lldb.eTypeClassEnumeration 595 elif name.startswith("typedef"): 596 want = lldb.eTypeClassTypedef 597 598 # 599 # Now remove constness and speficiers, and pointers 600 # 601 tmpname = re.sub(r'\bconst\b', '', name).strip(" ") 602 tmpname = re.sub(r'^(struct|class|union|enum|typedef) ', '', tmpname) 603 basename = tmpname.rstrip(" *") 604 ptrlevel = tmpname.count('*', len(basename)) 605 606 # After the sort, the struct type with more fields will be at index [0]. 607 # This heuristic helps selecting struct type with more fields 608 # compared to ones with "opaque" members 609 type_lst = target.chkFindTypes(basename) 610 type_arr = [type_lst.GetTypeAtIndex(i) for i in range(len(type_lst))] 611 type_arr.sort(reverse=True, key=lambda x: x.GetNumberOfFields()) 612 613 for tyobj in type_arr: 614 if want and tyobj.GetTypeClass() != want: 615 continue 616 617 for i in range(ptrlevel): 618 tyobj = tyobj.GetPointerType() 619 620 return tyobj 621 622 raise NameError('Unable to find type {}'.format(target_type)) 623 624 625@cache_statically 626def getfieldoffset(struct_type, field_name_or_path, target=None): 627 """ Returns the byte offset of a field inside a given struct 628 Understands anonymous unions and field names in sub-structs 629 params: 630 field_name_or_path - str, name or path to the field inside the struct ex. 'ip_messages' 631 returns: 632 int - byte offset of the field_name inside the struct_type 633 """ 634 635 return gettype(struct_type).xGetFieldOffset(field_name_or_path) 636 637 638def islong(x): 639 """ Returns True if a string represents a long integer, False otherwise 640 """ 641 try: 642 int(x, 16) 643 except ValueError: 644 try: 645 int(x) 646 except ValueError: 647 return False 648 return True 649 650 651def readmemory(val): 652 """ Returns a string of hex data that is referenced by the value. 653 params: val - a value object. 654 return: str - string of hex bytes. 655 raises: TypeError if val is not a valid type 656 """ 657 if not type(val) is value: 658 raise TypeError('%s is not of type value' % str(type(val))) 659 return val.__getstate__() 660 661 662def getOSPtr(cpp_obj): 663 """ Returns a core.value created from an intrusive_shared_ptr or itself, cpp_obj 664 params: cpp_obj - core.value object representing a C construct in lldb 665 return: core.value - newly created core.value or cpp_obj 666 """ 667 child = cpp_obj.GetSBValue().GetChildAtIndex(0) 668 if 'intrusive_shared_ptr' in str(child): 669 return value(child.GetChildMemberWithName('ptr_')) 670 return cpp_obj 671