diff options
author | Tobias Hieta <tobias@hieta.se> | 2023-05-15 11:02:42 +0200 |
---|---|---|
committer | Tobias Hieta <tobias@hieta.se> | 2023-05-17 10:48:52 +0200 |
commit | b71edfaa4ec3c998aadb35255ce2f60bba2940b0 (patch) | |
tree | e79a8adc4e62ac9e50d889b5cf9a248ceccc65de /llvm/bindings | |
parent | 7beb2ca8fa2aed594bb150c4c5734931d6ea4348 (diff) | |
download | llvm-b71edfaa4ec3c998aadb35255ce2f60bba2940b0.zip llvm-b71edfaa4ec3c998aadb35255ce2f60bba2940b0.tar.gz llvm-b71edfaa4ec3c998aadb35255ce2f60bba2940b0.tar.bz2 |
[NFC][Py Reformat] Reformat python files in llvm
This is the first commit in a series that will reformat
all the python files in the LLVM repository.
Reformatting is done with `black`.
See more information here:
https://discourse.llvm.org/t/rfc-document-and-standardize-python-code-style
Reviewed By: jhenderson, JDevlieghere, MatzeB
Differential Revision: https://reviews.llvm.org/D150545
Diffstat (limited to 'llvm/bindings')
-rw-r--r-- | llvm/bindings/python/llvm/bit_reader.py | 9 | ||||
-rw-r--r-- | llvm/bindings/python/llvm/common.py | 33 | ||||
-rw-r--r-- | llvm/bindings/python/llvm/core.py | 99 | ||||
-rw-r--r-- | llvm/bindings/python/llvm/disassembler.py | 80 | ||||
-rw-r--r-- | llvm/bindings/python/llvm/enumerations.py | 328 | ||||
-rw-r--r-- | llvm/bindings/python/llvm/object.py | 68 | ||||
-rw-r--r-- | llvm/bindings/python/llvm/tests/base.py | 18 | ||||
-rw-r--r-- | llvm/bindings/python/llvm/tests/test_bitreader.py | 2 | ||||
-rw-r--r-- | llvm/bindings/python/llvm/tests/test_core.py | 16 | ||||
-rw-r--r-- | llvm/bindings/python/llvm/tests/test_disassembler.py | 27 | ||||
-rw-r--r-- | llvm/bindings/python/llvm/tests/test_object.py | 1 |
11 files changed, 375 insertions, 306 deletions
diff --git a/llvm/bindings/python/llvm/bit_reader.py b/llvm/bindings/python/llvm/bit_reader.py index 33b8211..8d1c6d5 100644 --- a/llvm/bindings/python/llvm/bit_reader.py +++ b/llvm/bindings/python/llvm/bit_reader.py @@ -1,4 +1,3 @@ - from .common import LLVMObject from .common import c_object_p from .common import get_library @@ -10,21 +9,25 @@ from ctypes import POINTER from ctypes import byref from ctypes import c_char_p from ctypes import cast -__all__ = ['parse_bitcode'] + +__all__ = ["parse_bitcode"] lib = get_library() + def parse_bitcode(mem_buffer): """Input is .core.MemoryBuffer""" module = c_object_p() result = lib.LLVMParseBitcode2(mem_buffer, byref(module)) if result: - raise RuntimeError('LLVM Error') + raise RuntimeError("LLVM Error") m = Module(module) m.take_ownership(mem_buffer) return m + def register_library(library): library.LLVMParseBitcode2.argtypes = [MemoryBuffer, POINTER(c_object_p)] library.LLVMParseBitcode2.restype = bool + register_library(lib) diff --git a/llvm/bindings/python/llvm/common.py b/llvm/bindings/python/llvm/common.py index 9c6c6d4..4f8912a 100644 --- a/llvm/bindings/python/llvm/common.py +++ b/llvm/bindings/python/llvm/common.py @@ -1,10 +1,10 @@ -#===- common.py - Python LLVM Bindings -----------------------*- python -*--===# +# ===- common.py - Python LLVM Bindings -----------------------*- python -*--===# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # -#===------------------------------------------------------------------------===# +# ===------------------------------------------------------------------------===# from ctypes import POINTER from ctypes import c_void_p @@ -15,20 +15,22 @@ import platform # LLVM_VERSION: sync with PACKAGE_VERSION in CMakeLists.txt # but leave out the 'svn' suffix. -LLVM_VERSION = '10.0.0' +LLVM_VERSION = "10.0.0" __all__ = [ - 'c_object_p', - 'get_library', + "c_object_p", + "get_library", ] c_object_p = POINTER(c_void_p) + class LLVMObject(object): """Base class for objects that are backed by an LLVM data structure. This class should never be instantiated outside of this package. """ + def __init__(self, ptr, ownable=True, disposer=None): assert isinstance(ptr, c_object_p) @@ -61,12 +63,13 @@ class LLVMObject(object): return self._as_parameter_ def __del__(self): - if not hasattr(self, '_self_owned') or not hasattr(self, '_disposer'): + if not hasattr(self, "_self_owned") or not hasattr(self, "_disposer"): return if self._self_owned and self._disposer: self._disposer(self) + class CachedProperty(object): """Decorator that caches the result of a property lookup. @@ -74,11 +77,12 @@ class CachedProperty(object): decorator on properties that invoke C API calls for which the result of the call will be idempotent. """ + def __init__(self, wrapped): self.wrapped = wrapped try: self.__doc__ = wrapped.__doc__ - except: # pragma: no cover + except: # pragma: no cover pass def __get__(self, instance, instance_type=None): @@ -90,6 +94,7 @@ class CachedProperty(object): return value + def get_library(): """Obtain a reference to the llvm library.""" @@ -101,14 +106,14 @@ def get_library(): # library into a default linker search path. Always Try ctypes.cdll.LoadLibrary() # with all possible library names first, then try ctypes.util.find_library(). - names = ['LLVM-' + LLVM_VERSION, 'LLVM-' + LLVM_VERSION + 'svn'] + names = ["LLVM-" + LLVM_VERSION, "LLVM-" + LLVM_VERSION + "svn"] t = platform.system() - if t == 'Darwin': - pfx, ext = 'lib', '.dylib' - elif t == 'Windows': - pfx, ext = '', '.dll' + if t == "Darwin": + pfx, ext = "lib", ".dylib" + elif t == "Windows": + pfx, ext = "", ".dll" else: - pfx, ext = 'lib', '.so' + pfx, ext = "lib", ".so" for i in names: try: @@ -122,4 +127,4 @@ def get_library(): t = ctypes.util.find_library(i) if t: return cdll.LoadLibrary(t) - raise Exception('LLVM shared library not found!') + raise Exception("LLVM shared library not found!") diff --git a/llvm/bindings/python/llvm/core.py b/llvm/bindings/python/llvm/core.py index 812d5d0..a2de827 100644 --- a/llvm/bindings/python/llvm/core.py +++ b/llvm/bindings/python/llvm/core.py @@ -1,10 +1,10 @@ -#===- core.py - Python LLVM Bindings -------------------------*- python -*--===# +# ===- core.py - Python LLVM Bindings -------------------------*- python -*--===# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # -#===------------------------------------------------------------------------===# +# ===------------------------------------------------------------------------===# from __future__ import print_function from .common import LLVMObject @@ -36,6 +36,7 @@ __all__ = [ lib = get_library() Enums = [] + class LLVMEnumeration(object): """Represents an individual LLVM enumeration.""" @@ -44,8 +45,7 @@ class LLVMEnumeration(object): self.value = value def __repr__(self): - return '%s.%s' % (self.__class__.__name__, - self.name) + return "%s.%s" % (self.__class__.__name__, self.name) @classmethod def from_value(cls, value): @@ -53,8 +53,7 @@ class LLVMEnumeration(object): result = cls._value_map.get(value, None) if result is None: - raise ValueError('Unknown %s: %d' % (cls.__name__, - value)) + raise ValueError("Unknown %s: %d" % (cls.__name__, value)) return result @@ -66,12 +65,12 @@ class LLVMEnumeration(object): enumerations. You should not need to call this outside this module. """ if value in cls._value_map: - raise ValueError('%s value already registered: %d' % (cls.__name__, - value)) + raise ValueError("%s value already registered: %d" % (cls.__name__, value)) enum = cls(name, value) cls._value_map[value] = enum setattr(cls, name, enum) + class Attribute(LLVMEnumeration): """Represents an individual Attribute enumeration.""" @@ -80,6 +79,7 @@ class Attribute(LLVMEnumeration): def __init__(self, name, value): super(Attribute, self).__init__(name, value) + class OpCode(LLVMEnumeration): """Represents an individual OpCode enumeration.""" @@ -88,6 +88,7 @@ class OpCode(LLVMEnumeration): def __init__(self, name, value): super(OpCode, self).__init__(name, value) + class TypeKind(LLVMEnumeration): """Represents an individual TypeKind enumeration.""" @@ -96,6 +97,7 @@ class TypeKind(LLVMEnumeration): def __init__(self, name, value): super(TypeKind, self).__init__(name, value) + class Linkage(LLVMEnumeration): """Represents an individual Linkage enumeration.""" @@ -104,6 +106,7 @@ class Linkage(LLVMEnumeration): def __init__(self, name, value): super(Linkage, self).__init__(name, value) + class Visibility(LLVMEnumeration): """Represents an individual visibility enumeration.""" @@ -112,6 +115,7 @@ class Visibility(LLVMEnumeration): def __init__(self, name, value): super(Visibility, self).__init__(name, value) + class CallConv(LLVMEnumeration): """Represents an individual calling convention enumeration.""" @@ -120,6 +124,7 @@ class CallConv(LLVMEnumeration): def __init__(self, name, value): super(CallConv, self).__init__(name, value) + class IntPredicate(LLVMEnumeration): """Represents an individual IntPredicate enumeration.""" @@ -128,6 +133,7 @@ class IntPredicate(LLVMEnumeration): def __init__(self, name, value): super(IntPredicate, self).__init__(name, value) + class RealPredicate(LLVMEnumeration): """Represents an individual RealPredicate enumeration.""" @@ -136,6 +142,7 @@ class RealPredicate(LLVMEnumeration): def __init__(self, name, value): super(RealPredicate, self).__init__(name, value) + class LandingPadClauseTy(LLVMEnumeration): """Represents an individual LandingPadClauseTy enumeration.""" @@ -144,6 +151,7 @@ class LandingPadClauseTy(LLVMEnumeration): def __init__(self, name, value): super(LandingPadClauseTy, self).__init__(name, value) + class MemoryBuffer(LLVMObject): """Represents an opaque memory buffer.""" @@ -159,8 +167,9 @@ class MemoryBuffer(LLVMObject): memory = c_object_p() out = c_char_p(None) - result = lib.LLVMCreateMemoryBufferWithContentsOfFile(filename, - byref(memory), byref(out)) + result = lib.LLVMCreateMemoryBufferWithContentsOfFile( + filename, byref(memory), byref(out) + ) if result: raise Exception("Could not create memory buffer: %s" % out.value) @@ -170,8 +179,8 @@ class MemoryBuffer(LLVMObject): def __len__(self): return lib.LLVMGetBufferSize(self) + class Value(LLVMObject): - def __init__(self, value): LLVMObject.__init__(self, value) @@ -181,16 +190,17 @@ class Value(LLVMObject): def dump(self): lib.LLVMDumpValue(self) - + def get_operand(self, i): return Value(lib.LLVMGetOperand(self, i)) - + def set_operand(self, i, v): return lib.LLVMSetOperand(self, i, v) - + def __len__(self): return lib.LLVMGetNumOperands(self) + class Module(LLVMObject): """Represents the top-level structure of an llvm program in an opaque object.""" @@ -232,10 +242,10 @@ class Module(LLVMObject): self.function = self.module.last else: self.function = self.module.first - + def __iter__(self): return self - + def __next__(self): if not isinstance(self.function, Function): raise StopIteration("") @@ -266,25 +276,25 @@ class Module(LLVMObject): def print_module_to_file(self, filename): out = c_char_p(None) # Result is inverted so 0 means everything was ok. - result = lib.LLVMPrintModuleToFile(self, filename, byref(out)) + result = lib.LLVMPrintModuleToFile(self, filename, byref(out)) if result: raise RuntimeError("LLVM Error: %s" % out.value) -class Function(Value): +class Function(Value): def __init__(self, value): Value.__init__(self, value) - + @property def next(self): f = lib.LLVMGetNextFunction(self) return f and Function(f) - + @property def prev(self): f = lib.LLVMGetPreviousFunction(self) return f and Function(f) - + @property def first(self): b = lib.LLVMGetFirstBasicBlock(self) @@ -303,10 +313,10 @@ class Function(Value): self.bb = function.last else: self.bb = function.first - + def __iter__(self): return self - + def __next__(self): if not isinstance(self.bb, BasicBlock): raise StopIteration("") @@ -319,18 +329,18 @@ class Function(Value): if sys.version_info.major == 2: next = __next__ - + def __iter__(self): return Function.__bb_iterator(self) def __reversed__(self): return Function.__bb_iterator(self, reverse=True) - + def __len__(self): return lib.LLVMCountBasicBlocks(self) + class BasicBlock(LLVMObject): - def __init__(self, value): LLVMObject.__init__(self, value) @@ -343,7 +353,7 @@ class BasicBlock(LLVMObject): def prev(self): b = lib.LLVMGetPreviousBasicBlock(self) return b and BasicBlock(b) - + @property def first(self): i = lib.LLVMGetFirstInstruction(self) @@ -356,7 +366,7 @@ class BasicBlock(LLVMObject): def __as_value(self): return Value(lib.LLVMBasicBlockAsValue(self)) - + @property def name(self): return lib.LLVMGetValueName(self.__as_value()) @@ -365,28 +375,26 @@ class BasicBlock(LLVMObject): lib.LLVMDumpValue(self.__as_value()) def get_operand(self, i): - return Value(lib.LLVMGetOperand(self.__as_value(), - i)) - + return Value(lib.LLVMGetOperand(self.__as_value(), i)) + def set_operand(self, i, v): - return lib.LLVMSetOperand(self.__as_value(), - i, v) - + return lib.LLVMSetOperand(self.__as_value(), i, v) + def __len__(self): return lib.LLVMGetNumOperands(self.__as_value()) class __inst_iterator(object): - def __init__(self, bb, reverse=False): + def __init__(self, bb, reverse=False): self.bb = bb self.reverse = reverse if self.reverse: self.inst = self.bb.last else: self.inst = self.bb.first - + def __iter__(self): return self - + def __next__(self): if not isinstance(self.inst, Instruction): raise StopIteration("") @@ -408,7 +416,6 @@ class BasicBlock(LLVMObject): class Instruction(Value): - def __init__(self, value): Value.__init__(self, value) @@ -426,8 +433,8 @@ class Instruction(Value): def opcode(self): return OpCode.from_value(lib.LLVMGetInstructionOpcode(self)) -class Context(LLVMObject): +class Context(LLVMObject): def __init__(self, context=None): if context is None: context = lib.LLVMContextCreate() @@ -439,6 +446,7 @@ class Context(LLVMObject): def GetGlobalContext(cls): return Context(lib.LLVMGetGlobalContext()) + def register_library(library): # Initialization/Shutdown declarations. library.LLVMShutdown.argtypes = [] @@ -455,8 +463,11 @@ def register_library(library): library.LLVMGetGlobalContext.restype = c_object_p # Memory buffer declarations - library.LLVMCreateMemoryBufferWithContentsOfFile.argtypes = [c_char_p, - POINTER(c_object_p), POINTER(c_char_p)] + library.LLVMCreateMemoryBufferWithContentsOfFile.argtypes = [ + c_char_p, + POINTER(c_object_p), + POINTER(c_char_p), + ] library.LLVMCreateMemoryBufferWithContentsOfFile.restype = bool library.LLVMGetBufferSize.argtypes = [MemoryBuffer] @@ -485,8 +496,7 @@ def register_library(library): library.LLVMDumpModule.argtypes = [Module] library.LLVMDumpModule.restype = None - library.LLVMPrintModuleToFile.argtypes = [Module, c_char_p, - POINTER(c_char_p)] + library.LLVMPrintModuleToFile.argtypes = [Module, c_char_p, POINTER(c_char_p)] library.LLVMPrintModuleToFile.restype = bool library.LLVMGetFirstFunction.argtypes = [Module] @@ -552,6 +562,7 @@ def register_library(library): library.LLVMGetInstructionOpcode.argtypes = [Instruction] library.LLVMGetInstructionOpcode.restype = c_uint + def register_enumerations(): if Enums: return None @@ -572,9 +583,11 @@ def register_enumerations(): enum_class.register(name, value) return enums + def initialize_llvm(): Context.GetGlobalContext() + register_library(lib) Enums = register_enumerations() initialize_llvm() diff --git a/llvm/bindings/python/llvm/disassembler.py b/llvm/bindings/python/llvm/disassembler.py index 7562558..a57b8b8 100644 --- a/llvm/bindings/python/llvm/disassembler.py +++ b/llvm/bindings/python/llvm/disassembler.py @@ -1,10 +1,10 @@ -#===- disassembler.py - Python LLVM Bindings -----------------*- python -*--===# +# ===- disassembler.py - Python LLVM Bindings -----------------*- python -*--===# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # -#===------------------------------------------------------------------------===# +# ===------------------------------------------------------------------------===# from ctypes import CFUNCTYPE from ctypes import POINTER @@ -23,7 +23,7 @@ from .common import c_object_p from .common import get_library __all__ = [ - 'Disassembler', + "Disassembler", ] lib = get_library() @@ -33,9 +33,23 @@ callbacks = {} Option_UseMarkup = 1 - _initialized = False -_targets = ['AArch64', 'ARM', 'Hexagon', 'MSP430', 'Mips', 'NVPTX', 'PowerPC', 'R600', 'Sparc', 'SystemZ', 'X86', 'XCore'] +_targets = [ + "AArch64", + "ARM", + "Hexagon", + "MSP430", + "Mips", + "NVPTX", + "PowerPC", + "R600", + "Sparc", + "SystemZ", + "X86", + "XCore", +] + + def _ensure_initialized(): global _initialized if not _initialized: @@ -63,6 +77,7 @@ class Disassembler(LLVMObject): Disassembler instances can disassemble instructions from multiple sources. """ + def __init__(self, triple): """Create a new disassembler instance. @@ -72,11 +87,15 @@ class Disassembler(LLVMObject): _ensure_initialized() - ptr = lib.LLVMCreateDisasm(c_char_p(triple), c_void_p(None), c_int(0), - callbacks['op_info'](0), callbacks['symbol_lookup'](0)) + ptr = lib.LLVMCreateDisasm( + c_char_p(triple), + c_void_p(None), + c_int(0), + callbacks["op_info"](0), + callbacks["symbol_lookup"](0), + ) if not ptr: - raise Exception('Could not obtain disassembler for triple: %s' % - triple) + raise Exception("Could not obtain disassembler for triple: %s" % triple) LLVMObject.__init__(self, ptr, disposer=lib.LLVMDisasmDispose) @@ -100,8 +119,9 @@ class Disassembler(LLVMObject): buf = cast(c_char_p(source), POINTER(c_ubyte)) out_str = cast((c_byte * 255)(), c_char_p) - result = lib.LLVMDisasmInstruction(self, buf, c_uint64(len(source)), - c_uint64(pc), out_str, 255) + result = lib.LLVMDisasmInstruction( + self, buf, c_uint64(len(source)), c_uint64(pc), out_str, 255 + ) return (result, out_str.value) @@ -128,9 +148,9 @@ class Disassembler(LLVMObject): end_address = pc + len(source) while address < end_address: b = cast(addressof(buf) + offset, POINTER(c_ubyte)) - result = lib.LLVMDisasmInstruction(self, b, - c_uint64(len(source) - offset), c_uint64(address), - out_str, 255) + result = lib.LLVMDisasmInstruction( + self, b, c_uint64(len(source) - offset), c_uint64(address), out_str, 255 + ) if result == 0: break @@ -142,28 +162,40 @@ class Disassembler(LLVMObject): def set_options(self, options): if not lib.LLVMSetDisasmOptions(self, options): - raise Exception('Unable to set all disassembler options in %i' % options) + raise Exception("Unable to set all disassembler options in %i" % options) def register_library(library): - library.LLVMCreateDisasm.argtypes = [c_char_p, c_void_p, c_int, - callbacks['op_info'], callbacks['symbol_lookup']] + library.LLVMCreateDisasm.argtypes = [ + c_char_p, + c_void_p, + c_int, + callbacks["op_info"], + callbacks["symbol_lookup"], + ] library.LLVMCreateDisasm.restype = c_object_p library.LLVMDisasmDispose.argtypes = [Disassembler] - library.LLVMDisasmInstruction.argtypes = [Disassembler, POINTER(c_ubyte), - c_uint64, c_uint64, c_char_p, c_size_t] + library.LLVMDisasmInstruction.argtypes = [ + Disassembler, + POINTER(c_ubyte), + c_uint64, + c_uint64, + c_char_p, + c_size_t, + ] library.LLVMDisasmInstruction.restype = c_size_t library.LLVMSetDisasmOptions.argtypes = [Disassembler, c_uint64] library.LLVMSetDisasmOptions.restype = c_int -callbacks['op_info'] = CFUNCTYPE(c_int, c_void_p, c_uint64, c_uint64, c_uint64, - c_int, c_void_p) -callbacks['symbol_lookup'] = CFUNCTYPE(c_char_p, c_void_p, c_uint64, - POINTER(c_uint64), c_uint64, - POINTER(c_char_p)) +callbacks["op_info"] = CFUNCTYPE( + c_int, c_void_p, c_uint64, c_uint64, c_uint64, c_int, c_void_p +) +callbacks["symbol_lookup"] = CFUNCTYPE( + c_char_p, c_void_p, c_uint64, POINTER(c_uint64), c_uint64, POINTER(c_char_p) +) register_library(lib) diff --git a/llvm/bindings/python/llvm/enumerations.py b/llvm/bindings/python/llvm/enumerations.py index ebb39a4..34e2976 100644 --- a/llvm/bindings/python/llvm/enumerations.py +++ b/llvm/bindings/python/llvm/enumerations.py @@ -1,10 +1,10 @@ -#===- enumerations.py - Python LLVM Enumerations -------------*- python -*--===# +# ===- enumerations.py - Python LLVM Enumerations -------------*- python -*--===# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # -#===------------------------------------------------------------------------===# +# ===------------------------------------------------------------------------===# r""" LLVM Enumerations @@ -18,193 +18,193 @@ defined in this file so they are easier to locate and maintain. """ __all__ = [ - 'Attributes', - 'OpCodes', - 'TypeKinds', - 'Linkages', - 'Visibility', - 'CallConv', - 'IntPredicate', - 'RealPredicate', - 'LandingPadClauseTy', + "Attributes", + "OpCodes", + "TypeKinds", + "Linkages", + "Visibility", + "CallConv", + "IntPredicate", + "RealPredicate", + "LandingPadClauseTy", ] Attributes = [ - ('ZExt', 1 << 0), - ('MSExt', 1 << 1), - ('NoReturn', 1 << 2), - ('InReg', 1 << 3), - ('StructRet', 1 << 4), - ('NoUnwind', 1 << 5), - ('NoAlias', 1 << 6), - ('ByVal', 1 << 7), - ('Nest', 1 << 8), - ('ReadNone', 1 << 9), - ('ReadOnly', 1 << 10), - ('NoInline', 1 << 11), - ('AlwaysInline', 1 << 12), - ('OptimizeForSize', 1 << 13), - ('StackProtect', 1 << 14), - ('StackProtectReq', 1 << 15), - ('Alignment', 31 << 16), - ('NoCapture', 1 << 21), - ('NoRedZone', 1 << 22), - ('ImplicitFloat', 1 << 23), - ('Naked', 1 << 24), - ('InlineHint', 1 << 25), - ('StackAlignment', 7 << 26), - ('ReturnsTwice', 1 << 29), - ('UWTable', 1 << 30), - ('NonLazyBind', 1 << 31), + ("ZExt", 1 << 0), + ("MSExt", 1 << 1), + ("NoReturn", 1 << 2), + ("InReg", 1 << 3), + ("StructRet", 1 << 4), + ("NoUnwind", 1 << 5), + ("NoAlias", 1 << 6), + ("ByVal", 1 << 7), + ("Nest", 1 << 8), + ("ReadNone", 1 << 9), + ("ReadOnly", 1 << 10), + ("NoInline", 1 << 11), + ("AlwaysInline", 1 << 12), + ("OptimizeForSize", 1 << 13), + ("StackProtect", 1 << 14), + ("StackProtectReq", 1 << 15), + ("Alignment", 31 << 16), + ("NoCapture", 1 << 21), + ("NoRedZone", 1 << 22), + ("ImplicitFloat", 1 << 23), + ("Naked", 1 << 24), + ("InlineHint", 1 << 25), + ("StackAlignment", 7 << 26), + ("ReturnsTwice", 1 << 29), + ("UWTable", 1 << 30), + ("NonLazyBind", 1 << 31), ] OpCodes = [ - ('Ret', 1), - ('Br', 2), - ('Switch', 3), - ('IndirectBr', 4), - ('Invoke', 5), - ('Unreachable', 7), - ('Add', 8), - ('FAdd', 9), - ('Sub', 10), - ('FSub', 11), - ('Mul', 12), - ('FMul', 13), - ('UDiv', 14), - ('SDiv', 15), - ('FDiv', 16), - ('URem', 17), - ('SRem', 18), - ('FRem', 19), - ('Shl', 20), - ('LShr', 21), - ('AShr', 22), - ('And', 23), - ('Or', 24), - ('Xor', 25), - ('Alloca', 26), - ('Load', 27), - ('Store', 28), - ('GetElementPtr', 29), - ('Trunc', 30), - ('ZExt', 31), - ('SExt', 32), - ('FPToUI', 33), - ('FPToSI', 34), - ('UIToFP', 35), - ('SIToFP', 36), - ('FPTrunc', 37), - ('FPExt', 38), - ('PtrToInt', 39), - ('IntToPtr', 40), - ('BitCast', 41), - ('ICmp', 42), - ('FCmpl', 43), - ('PHI', 44), - ('Call', 45), - ('Select', 46), - ('UserOp1', 47), - ('UserOp2', 48), - ('AArg', 49), - ('ExtractElement', 50), - ('InsertElement', 51), - ('ShuffleVector', 52), - ('ExtractValue', 53), - ('InsertValue', 54), - ('Fence', 55), - ('AtomicCmpXchg', 56), - ('AtomicRMW', 57), - ('Resume', 58), - ('LandingPad', 59), + ("Ret", 1), + ("Br", 2), + ("Switch", 3), + ("IndirectBr", 4), + ("Invoke", 5), + ("Unreachable", 7), + ("Add", 8), + ("FAdd", 9), + ("Sub", 10), + ("FSub", 11), + ("Mul", 12), + ("FMul", 13), + ("UDiv", 14), + ("SDiv", 15), + ("FDiv", 16), + ("URem", 17), + ("SRem", 18), + ("FRem", 19), + ("Shl", 20), + ("LShr", 21), + ("AShr", 22), + ("And", 23), + ("Or", 24), + ("Xor", 25), + ("Alloca", 26), + ("Load", 27), + ("Store", 28), + ("GetElementPtr", 29), + ("Trunc", 30), + ("ZExt", 31), + ("SExt", 32), + ("FPToUI", 33), + ("FPToSI", 34), + ("UIToFP", 35), + ("SIToFP", 36), + ("FPTrunc", 37), + ("FPExt", 38), + ("PtrToInt", 39), + ("IntToPtr", 40), + ("BitCast", 41), + ("ICmp", 42), + ("FCmpl", 43), + ("PHI", 44), + ("Call", 45), + ("Select", 46), + ("UserOp1", 47), + ("UserOp2", 48), + ("AArg", 49), + ("ExtractElement", 50), + ("InsertElement", 51), + ("ShuffleVector", 52), + ("ExtractValue", 53), + ("InsertValue", 54), + ("Fence", 55), + ("AtomicCmpXchg", 56), + ("AtomicRMW", 57), + ("Resume", 58), + ("LandingPad", 59), ] TypeKinds = [ - ('Void', 0), - ('Half', 1), - ('Float', 2), - ('Double', 3), - ('X86_FP80', 4), - ('FP128', 5), - ('PPC_FP128', 6), - ('Label', 7), - ('Integer', 8), - ('Function', 9), - ('Struct', 10), - ('Array', 11), - ('Pointer', 12), - ('Vector', 13), - ('Metadata', 14), - ('X86_MMX', 15), + ("Void", 0), + ("Half", 1), + ("Float", 2), + ("Double", 3), + ("X86_FP80", 4), + ("FP128", 5), + ("PPC_FP128", 6), + ("Label", 7), + ("Integer", 8), + ("Function", 9), + ("Struct", 10), + ("Array", 11), + ("Pointer", 12), + ("Vector", 13), + ("Metadata", 14), + ("X86_MMX", 15), ] Linkages = [ - ('External', 0), - ('AvailableExternally', 1), - ('LinkOnceAny', 2), - ('LinkOnceODR', 3), - ('WeakAny', 4), - ('WeakODR', 5), - ('Appending', 6), - ('Internal', 7), - ('Private', 8), - ('DLLImport', 9), - ('DLLExport', 10), - ('ExternalWeak', 11), - ('Ghost', 12), - ('Common', 13), - ('LinkerPrivate', 14), - ('LinkerPrivateWeak', 15), - ('LinkerPrivateWeakDefAuto', 16), + ("External", 0), + ("AvailableExternally", 1), + ("LinkOnceAny", 2), + ("LinkOnceODR", 3), + ("WeakAny", 4), + ("WeakODR", 5), + ("Appending", 6), + ("Internal", 7), + ("Private", 8), + ("DLLImport", 9), + ("DLLExport", 10), + ("ExternalWeak", 11), + ("Ghost", 12), + ("Common", 13), + ("LinkerPrivate", 14), + ("LinkerPrivateWeak", 15), + ("LinkerPrivateWeakDefAuto", 16), ] Visibility = [ - ('Default', 0), - ('Hidden', 1), - ('Protected', 2), + ("Default", 0), + ("Hidden", 1), + ("Protected", 2), ] CallConv = [ - ('CCall', 0), - ('FastCall', 8), - ('ColdCall', 9), - ('X86StdcallCall', 64), - ('X86FastcallCall', 65), + ("CCall", 0), + ("FastCall", 8), + ("ColdCall", 9), + ("X86StdcallCall", 64), + ("X86FastcallCall", 65), ] IntPredicate = [ - ('EQ', 32), - ('NE', 33), - ('UGT', 34), - ('UGE', 35), - ('ULT', 36), - ('ULE', 37), - ('SGT', 38), - ('SGE', 39), - ('SLT', 40), - ('SLE', 41), + ("EQ", 32), + ("NE", 33), + ("UGT", 34), + ("UGE", 35), + ("ULT", 36), + ("ULE", 37), + ("SGT", 38), + ("SGE", 39), + ("SLT", 40), + ("SLE", 41), ] RealPredicate = [ - ('PredicateFalse', 0), - ('OEQ', 1), - ('OGT', 2), - ('OGE', 3), - ('OLT', 4), - ('OLE', 5), - ('ONE', 6), - ('ORD', 7), - ('UNO', 8), - ('UEQ', 9), - ('UGT', 10), - ('UGE', 11), - ('ULT', 12), - ('ULE', 13), - ('UNE', 14), - ('PredicateTrue', 15), + ("PredicateFalse", 0), + ("OEQ", 1), + ("OGT", 2), + ("OGE", 3), + ("OLT", 4), + ("OLE", 5), + ("ONE", 6), + ("ORD", 7), + ("UNO", 8), + ("UEQ", 9), + ("UGT", 10), + ("UGE", 11), + ("ULT", 12), + ("ULE", 13), + ("UNE", 14), + ("PredicateTrue", 15), ] LandingPadClauseTy = [ - ('Catch', 0), - ('Filter', 1), + ("Catch", 0), + ("Filter", 1), ] diff --git a/llvm/bindings/python/llvm/object.py b/llvm/bindings/python/llvm/object.py index e8841b6..b63b9ce 100644 --- a/llvm/bindings/python/llvm/object.py +++ b/llvm/bindings/python/llvm/object.py @@ -1,10 +1,10 @@ -#===- object.py - Python Object Bindings --------------------*- python -*--===# +# ===- object.py - Python Object Bindings --------------------*- python -*--===# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # -#===------------------------------------------------------------------------===# +# ===------------------------------------------------------------------------===# r""" Object File Interface @@ -96,6 +96,7 @@ __all__ = [ "Symbol", ] + class ObjectFile(LLVMObject): """Represents an object/binary file.""" @@ -113,7 +114,7 @@ class ObjectFile(LLVMObject): contents = MemoryBuffer(filename=filename) if contents is None: - raise Exception('No input found.') + raise Exception("No input found.") ptr = lib.LLVMCreateObjectFile(contents) LLVMObject.__init__(self, ptr, disposer=lib.LLVMDisposeObjectFile) @@ -175,6 +176,7 @@ class ObjectFile(LLVMObject): lib.LLVMDisposeSymbolIterator(symbols) + class Section(LLVMObject): """Represents a section in an object file.""" @@ -196,7 +198,7 @@ class Section(LLVMObject): This is typically something like '.dynsym' or '.rodata'. """ if self.expired: - raise Exception('Section instance has expired.') + raise Exception("Section instance has expired.") return lib.LLVMGetSectionName(self) @@ -204,14 +206,14 @@ class Section(LLVMObject): def size(self): """The size of the section, in long bytes.""" if self.expired: - raise Exception('Section instance has expired.') + raise Exception("Section instance has expired.") return lib.LLVMGetSectionSize(self) @CachedProperty def contents(self): if self.expired: - raise Exception('Section instance has expired.') + raise Exception("Section instance has expired.") siz = self.size @@ -224,14 +226,14 @@ class Section(LLVMObject): def address(self): """The address of this section, in long bytes.""" if self.expired: - raise Exception('Section instance has expired.') + raise Exception("Section instance has expired.") return lib.LLVMGetSectionAddress(self) def has_symbol(self, symbol): """Returns whether a Symbol instance is present in this Section.""" if self.expired: - raise Exception('Section instance has expired.') + raise Exception("Section instance has expired.") assert isinstance(symbol, Symbol) return lib.LLVMGetSectionContainsSymbol(self, symbol) @@ -245,7 +247,7 @@ class Section(LLVMObject): on iterators for more. """ if self.expired: - raise Exception('Section instance has expired.') + raise Exception("Section instance has expired.") relocations = lib.LLVMGetRelocations(self) last = None @@ -274,10 +276,10 @@ class Section(LLVMObject): limitation. When called, the properties of the Section are fetched so they are still available after the Section has been marked inactive. """ - getattr(self, 'name') - getattr(self, 'size') - getattr(self, 'contents') - getattr(self, 'address') + getattr(self, "name") + getattr(self, "size") + getattr(self, "contents") + getattr(self, "address") def expire(self): """Expire the section. @@ -286,8 +288,10 @@ class Section(LLVMObject): """ self.expired = True + class Symbol(LLVMObject): """Represents a symbol in an object file.""" + def __init__(self, ptr, object_file): assert isinstance(ptr, c_object_p) assert isinstance(object_file, ObjectFile) @@ -305,7 +309,7 @@ class Symbol(LLVMObject): mangling could be in effect. """ if self.expired: - raise Exception('Symbol instance has expired.') + raise Exception("Symbol instance has expired.") return lib.LLVMGetSymbolName(self) @@ -313,7 +317,7 @@ class Symbol(LLVMObject): def address(self): """The address of this symbol, in long bytes.""" if self.expired: - raise Exception('Symbol instance has expired.') + raise Exception("Symbol instance has expired.") return lib.LLVMGetSymbolAddress(self) @@ -321,7 +325,7 @@ class Symbol(LLVMObject): def size(self): """The size of the symbol, in long bytes.""" if self.expired: - raise Exception('Symbol instance has expired.') + raise Exception("Symbol instance has expired.") return lib.LLVMGetSymbolSize(self) @@ -342,9 +346,9 @@ class Symbol(LLVMObject): def cache(self): """Cache all cacheable properties.""" - getattr(self, 'name') - getattr(self, 'address') - getattr(self, 'size') + getattr(self, "name") + getattr(self, "address") + getattr(self, "size") def expire(self): """Mark the object as expired to prevent future API accesses. @@ -354,8 +358,10 @@ class Symbol(LLVMObject): """ self.expired = True + class Relocation(LLVMObject): """Represents a relocation definition.""" + def __init__(self, ptr): """Create a new relocation instance. @@ -374,7 +380,7 @@ class Relocation(LLVMObject): def offset(self): """The offset of this relocation, in long bytes.""" if self.expired: - raise Exception('Relocation instance has expired.') + raise Exception("Relocation instance has expired.") return lib.LLVMGetRelocationOffset(self) @@ -382,7 +388,7 @@ class Relocation(LLVMObject): def symbol(self): """The Symbol corresponding to this Relocation.""" if self.expired: - raise Exception('Relocation instance has expired.') + raise Exception("Relocation instance has expired.") ptr = lib.LLVMGetRelocationSymbol(self) return Symbol(ptr) @@ -391,7 +397,7 @@ class Relocation(LLVMObject): def type_number(self): """The relocation type, as a long.""" if self.expired: - raise Exception('Relocation instance has expired.') + raise Exception("Relocation instance has expired.") return lib.LLVMGetRelocationType(self) @@ -399,14 +405,14 @@ class Relocation(LLVMObject): def type_name(self): """The relocation type's name, as a str.""" if self.expired: - raise Exception('Relocation instance has expired.') + raise Exception("Relocation instance has expired.") return lib.LLVMGetRelocationTypeName(self) @CachedProperty def value_string(self): if self.expired: - raise Exception('Relocation instance has expired.') + raise Exception("Relocation instance has expired.") return lib.LLVMGetRelocationValueString(self) @@ -416,12 +422,13 @@ class Relocation(LLVMObject): def cache(self): """Cache all cacheable properties on this instance.""" - getattr(self, 'address') - getattr(self, 'offset') - getattr(self, 'symbol') - getattr(self, 'type') - getattr(self, 'type_name') - getattr(self, 'value_string') + getattr(self, "address") + getattr(self, "offset") + getattr(self, "symbol") + getattr(self, "type") + getattr(self, "type_name") + getattr(self, "value_string") + def register_library(library): """Register function prototypes with LLVM library instance.""" @@ -504,5 +511,6 @@ def register_library(library): library.LLVMGetRelocationValueString.argtypes = [c_object_p] library.LLVMGetRelocationValueString.restype = c_char_p + lib = get_library() register_library(lib) diff --git a/llvm/bindings/python/llvm/tests/base.py b/llvm/bindings/python/llvm/tests/base.py index aa435bc..7350cb4 100644 --- a/llvm/bindings/python/llvm/tests/base.py +++ b/llvm/bindings/python/llvm/tests/base.py @@ -4,18 +4,19 @@ import unittest POSSIBLE_TEST_BINARIES = [ - 'libreadline.so.5', - 'libreadline.so.6', + "libreadline.so.5", + "libreadline.so.6", ] POSSIBLE_TEST_BINARY_PATHS = [ - '/usr/lib/debug', - '/lib', - '/usr/lib', - '/usr/local/lib', - '/lib/i386-linux-gnu', + "/usr/lib/debug", + "/lib", + "/usr/lib", + "/usr/local/lib", + "/lib/i386-linux-gnu", ] + class TestBase(unittest.TestCase): if sys.version_info.major == 2: assertRaisesRegex = unittest.TestCase.assertRaisesRegexp @@ -33,7 +34,8 @@ class TestBase(unittest.TestCase): if os.path.exists(path): return path - raise Exception('No suitable test binaries available!') + raise Exception("No suitable test binaries available!") + get_test_binary.__test__ = False def get_test_file(self): diff --git a/llvm/bindings/python/llvm/tests/test_bitreader.py b/llvm/bindings/python/llvm/tests/test_bitreader.py index 460005a..08e55e1 100644 --- a/llvm/bindings/python/llvm/tests/test_bitreader.py +++ b/llvm/bindings/python/llvm/tests/test_bitreader.py @@ -8,8 +8,8 @@ from ..core import Context from ..core import Module from ..bit_reader import parse_bitcode -class TestBitReader(TestBase): +class TestBitReader(TestBase): def test_parse_bitcode(self): source = self.get_test_bc() m = parse_bitcode(MemoryBuffer(filename=source)) diff --git a/llvm/bindings/python/llvm/tests/test_core.py b/llvm/bindings/python/llvm/tests/test_core.py index 68572b5..76a2eaf 100644 --- a/llvm/bindings/python/llvm/tests/test_core.py +++ b/llvm/bindings/python/llvm/tests/test_core.py @@ -9,6 +9,7 @@ from ..core import Enums from ..core import OpCode from ..bit_reader import parse_bitcode + class TestCore(TestBase): def test_enumerations(self): for enum_cls, enum_spec in Enums: @@ -77,8 +78,7 @@ class TestCore(TestBase): def test_module_function_iteration(self): m = parse_bitcode(MemoryBuffer(filename=self.get_test_bc())) i = 0 - functions = ["f", "f2", "f3", "f4", "f5", "f6", "g1", "g2", "h1", "h2", - "h3"] + functions = ["f", "f2", "f3", "f4", "f5", "f6", "g1", "g2", "h1", "h2", "h3"] # Forward for f in m: self.assertEqual(f.name, functions[i]) @@ -94,7 +94,7 @@ class TestCore(TestBase): m = parse_bitcode(MemoryBuffer(filename=self.get_test_bc())) i = 0 - bb_list = ['b1', 'b2', 'end'] + bb_list = ["b1", "b2", "end"] f = m.first while f.name != "f6": @@ -116,10 +116,12 @@ class TestCore(TestBase): m = parse_bitcode(MemoryBuffer(filename=self.get_test_bc())) i = 0 - inst_list = [('arg1', OpCode.ExtractValue), - ('arg2', OpCode.ExtractValue), - ('', OpCode.Call), - ('', OpCode.Ret)] + inst_list = [ + ("arg1", OpCode.ExtractValue), + ("arg2", OpCode.ExtractValue), + ("", OpCode.Call), + ("", OpCode.Ret), + ] bb = m.first.first diff --git a/llvm/bindings/python/llvm/tests/test_disassembler.py b/llvm/bindings/python/llvm/tests/test_disassembler.py index 29f2f70..d4620f6 100644 --- a/llvm/bindings/python/llvm/tests/test_disassembler.py +++ b/llvm/bindings/python/llvm/tests/test_disassembler.py @@ -4,42 +4,45 @@ from .base import TestBase from ..disassembler import Disassembler, Option_UseMarkup + class TestDisassembler(TestBase): def test_instantiate(self): - Disassembler('i686-apple-darwin9') + Disassembler("i686-apple-darwin9") def test_basic(self): - sequence = '\x67\xe3\x81' # jcxz -127 - triple = 'i686-apple-darwin9' + sequence = "\x67\xe3\x81" # jcxz -127 + triple = "i686-apple-darwin9" disassembler = Disassembler(triple) count, s = disassembler.get_instruction(sequence) self.assertEqual(count, 3) - self.assertEqual(s, '\tjcxz\t-127') + self.assertEqual(s, "\tjcxz\t-127") def test_nonexistent_triple(self): - with self.assertRaisesRegex(Exception, "Could not obtain disassembler for triple"): + with self.assertRaisesRegex( + Exception, "Could not obtain disassembler for triple" + ): Disassembler("nonexistent-triple-raises") def test_get_instructions(self): - sequence = '\x67\xe3\x81\x01\xc7' # jcxz -127; addl %eax, %edi + sequence = "\x67\xe3\x81\x01\xc7" # jcxz -127; addl %eax, %edi - disassembler = Disassembler('i686-apple-darwin9') + disassembler = Disassembler("i686-apple-darwin9") instructions = list(disassembler.get_instructions(sequence)) self.assertEqual(len(instructions), 2) - self.assertEqual(instructions[0], (0, 3, '\tjcxz\t-127')) - self.assertEqual(instructions[1], (3, 2, '\taddl\t%eax, %edi')) + self.assertEqual(instructions[0], (0, 3, "\tjcxz\t-127")) + self.assertEqual(instructions[1], (3, 2, "\taddl\t%eax, %edi")) def test_set_options(self): - sequence = '\x10\x40\x2d\xe9' - triple = 'arm-linux-android' + sequence = "\x10\x40\x2d\xe9" + triple = "arm-linux-android" disassembler = Disassembler(triple) disassembler.set_options(Option_UseMarkup) count, s = disassembler.get_instruction(sequence) print(s) self.assertEqual(count, 4) - self.assertEqual(s, '\tpush\t{<reg:r4>, <reg:lr>}') + self.assertEqual(s, "\tpush\t{<reg:r4>, <reg:lr>}") diff --git a/llvm/bindings/python/llvm/tests/test_object.py b/llvm/bindings/python/llvm/tests/test_object.py index a45b7be..b9d5868 100644 --- a/llvm/bindings/python/llvm/tests/test_object.py +++ b/llvm/bindings/python/llvm/tests/test_object.py @@ -6,6 +6,7 @@ from ..object import Relocation from ..object import Section from ..object import Symbol + class TestObjectFile(TestBase): def get_object_file(self): source = self.get_test_binary() |