How to use xdis - 10 common examples

To help you get started, we’ve selected a few xdis examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rocky / python-xdis / pytest / test_bytecode.py View on Github external
def test_get_jump_targets():
    my_dir = osp.dirname(osp.abspath(__file__))

    # Python 2.7 code
    code = bug708901.__code__

    # FIXME: Consider loading from a file like below to remove
    # dependence on running interpreter
    if PYTHON_VERSION == 2.7:
        # 19:           0 SETUP_LOOP               23 (to 26)
        #               3 LOAD_GLOBAL               0 (range)
        #               6 LOAD_CONST                1 (1)
        #
        # 20:           9 LOAD_CONST                2 (10)
        #              12 CALL_FUNCTION             2 (2 positional, 0 keyword pair)
        #              15 GET_ITER
        #         >>   16 FOR_ITER                  6 (to 25)
        #              19 STORE_FAST                0 (res)
        #
        # 21:          22 JUMP_ABSOLUTE            16 (to 16)
        #         >>   25 POP_BLOCK
        #         >>   26 LOAD_CONST                0 (None)
        #              29 RETURN_VALUE
        offset_map = opcode_27.get_jump_target_maps(code,  opcode_27)
github rocky / python-xdis / pytest / test_opcode.py View on Github external
def test_opcode():
    opc = get_opcode(PYTHON_VERSION, IS_PYPY)
    opmap = dict([(k.replace('+', '_'), v)
                  for (k, v) in dis.opmap.items()])

    print("Extra in dis:", set(opmap.items()) - set(opc.opmap.items()))
    print("Extra in xdis:", set(opc.opmap.items()) - set(opmap.items()))

    for item in opmap.items():
        assert item in opc.opmap.items(), item

    fields_str = "hascompare hasconst hasfree hasjabs hasjrel haslocal"
    # PyPy 2.7.13 changes opcodes mid-version. It is too complicated
    # to figure out where the change actually occurred
    # Pypy 3.6.9 may or may not have JUMP_IF_NOT_DEBUG
    if not (IS_PYPY and PYTHON_VERSION in (2.7, 3.6)):
        assert all(item in opmap.items() for item in opc.opmap.items())
    elif (IS_PYPY and PYTHON_VERSION == 3.6):
github rocky / python-xdis / test / test_pythonlib.py View on Github external
files.extend(
            [os.path.normpath(os.path.join(root, n))
                 for n in basenames
                    for pat in patterns
                        if fnmatch(n, pat)])

    files = []
    # Change directories so use relative rather than
    # absolute paths. This speeds up things, and allows
    # main() to write to a relative-path destination.
    cwd = os.getcwd()
    os.chdir(src_dir)

    if opts['do_compile']:
        compiled_version = opts['compiled_version']
        if compiled_version and PYTHON_VERSION != compiled_version:
            sys.stderr.write("Not compiling: desired Python version is %s "
                                 "but we are running %s\n" %
                                 (compiled_version, PYTHON_VERSION))
        else:
            for root, dirs, basenames in os.walk(src_dir):
                file_matches(files, root, basenames, PY)
                for sfile in files:
                    py_compile.compile(sfile)
                    pass
                pass
            files = []
            pass
        pass

    for root, dirs, basenames in os.walk('.'):
        # Turn root into a relative path
github rocky / python-xdis / pytest / test_stack_effect.py View on Github external
assert effect != -100, (
            "%d (%s) needs adjusting; should be: should have effect %d"
            % (opcode, opname, check_effect)
        )
        if has_arg:
            op_val = "with operand %d" % dis_args[1]
        else:
            op_val = ""

        assert check_effect == effect, (
            "%d (%s) %s not okay; effect %d vs %d"
            % (opcode, opname, op_val, effect, check_effect)
        )
        print("%d (%s) is good: effect %d" % (opcode, opname, effect))

    if xdis.IS_PYPY:
        variant = "pypy"
    else:
        variant = ""
    opc = get_opcode_module(None, variant)
    for opname, opcode, in opc.opmap.items():
        if opname in ("EXTENDED_ARG", "NOP"):
            continue
        xdis_args = [opcode, opc]
        dis_args = [opcode]

        # TODO: if opcode takes an argument, we should vary the arg and try
        # values in addition to 0 as done below.
        if op_has_argument(opcode, opc):
            xdis_args.append(0)
            dis_args.append(0)
            has_arg = True
github rocky / python3-trepan / test / unit / test-completion.py View on Github external
def test_complete_identifier(self):
        from trepan.processor.command import base_cmd as mBaseCmd
        from trepan.processor import complete as mComplete
        self.dbgr = Mdebugger.Trepan()

        cmdproc = self.dbgr.core.processor
        cmdproc.curframe = inspect.currentframe()
        cmd = mBaseCmd.DebuggerCommand(cmdproc)

        self.assertEqual(mComplete.complete_id_and_builtins(cmd, 'ma'),
                         ['map', 'max'])
        self.assertEqual(mComplete.complete_identifier(cmd, 'm'),
                         ['mBaseCmd', 'mComplete'])
        return

    if not IS_PYPY:
        def test_completion(self):

            self.dbgr = Mdebugger.Trepan()

            for line, expect_completion in [
                    ['set basename ', ['off', 'on']],
                    ['where', ['where ']],  # Single alias completion
                    ['sho', ['show']],  # Simple single completion
                    ['un', ['unalias', 'undisplay']],  # Simple multiple completion
                    ['python ', []],        # Don't add anything - no more
                    ['set basename o', ['off', 'on']],
                    ['set basename of', ['off']],

                    # Multiple completion on two words
                    ['set auto', ['autoeval', 'autolist', 'autopc', 'autopython']],
github rocky / python-xdis / test_unit / test_magic.py View on Github external
def test_basic(self):
        """Basic test of magic numbers"""
        current = imp.get_magic()
        if hasattr(sys, 'version_info'):
            version = '.'.join([str(v) for v in sys.version_info[0:3]])
            if IS_PYPY:
                version += 'pypy'
            self.assertTrue(version in magics.magics.keys(),
                            "version %s is not in magic.magics.keys: %s" %
                            (version, magics.magics.keys()))

        self.assertEqual(current, magics.int2magic(magics.magic2int(current)))
        lookup = str(PYTHON_VERSION)
        if IS_PYPY:
            lookup += 'pypy'
        self.assertTrue(lookup in magics.magics.keys(),
                        "PYTHON VERSION %s is not in magic.magics.keys: %s" %
                        (lookup, magics.magics.keys()))

        if not (3, 5, 2) <= sys.version_info < (3, 6, 0):
            self.assertEqual(magics.sysinfo2magic(), current,
                            "magic from imp.get_magic() for %s "
github rocky / python-xdis / pytest / test_instructions.py View on Github external
def test_inst_size():
    if (sys.version_info == (3,6)):
        variant = 'pypy' if IS_PYPY else None
        opc = get_opcode_module(sys.version_info, variant)
        bytecode_obj = Bytecode(extended_arg_fn36, opc)
        instructions = list(bytecode_obj.get_instructions(extended_arg_fn36))

        inst1 = instructions[1]
        assert inst1.opname == 'EXTENDED_ARG'
        assert inst1.argval == 0

        inst2 = instructions[2]
        assert inst2.opname == 'POP_JUMP_IF_FALSE'
        assert inst2.has_extended_arg == True
        assert inst2.inst_size == 4

        # for inst in instructions:
        #     print(inst)
    else:
        assert True
github rocky / python-xdis / pytest / test_instructions.py View on Github external
def test_inst_jumps():
    if (sys.version_info >= (2,7)):
        variant = 'pypy' if IS_PYPY else None
        opc = get_opcode_module(sys.version_info, variant)
        bytecode_obj = Bytecode(extended_arg_fn36, opc)
        instructions = list(bytecode_obj.get_instructions(loop))
        seen_pjif = False
        seen_ja = False
        for inst in instructions:
            if inst.opname == "POP_JUMP_IF_FALSE":
                assert inst.is_jump()
                seen_pjif = True
            elif inst.opname == "JUMP_ABSOLUTE":
                assert inst.is_jump()
                assert not inst.jumps_forward()
                seen_ja = True
                pass
            pass
        assert seen_pjif
        assert seen_ja
github rocky / python-xdis / pytest / test_load_file.py View on Github external
def test_load_file():
    srcdir = get_srcdir()
    load_py = osp.realpath(osp.join(srcdir, "..", "xdis", "load.py"))

    co_file = load_file(load_py)
    obj_path = check_object_path(load_py)
    (version, timestamp, magic_int, co_module, pypy,
     source_size, sip_hash) = load_module(obj_path)
    if 3.3 <= version <= 3.7:
        statinfo = os.stat(load_py)
        assert statinfo.st_size == source_size
        assert sip_hash is None
    elif version < 3.3:
        assert source_size is None, source_size
        assert sip_hash is None

    for field in CodeTypeUnionFields:
        if hasattr(co_file, field):
            if field == "co_code" and (pypy or IS_PYPY):
                continue
            load_file_field = getattr(co_file, field)
            load_module_field = getattr(co_module, field)
            assert load_module_field == load_file_field, (
                "field %s\nmodule:\n\t%s\nfile:\n\t%s" % (field, load_module_field, load_file_field)
github rocky / python-xdis / pytest / test_bytecode.py View on Github external
#         >>   25 POP_BLOCK
        #         >>   26 LOAD_CONST                0 (None)
        #              29 RETURN_VALUE
        offset_map = opcode_27.get_jump_target_maps(code,  opcode_27)

        expected = { 3: [0], 6: [3], 9: [6], 12: [9], 15: [12],
                    16: [15, 22], 19: [16], 22: [19], 25: [16],
                    26: [0, 25], 29: [26]}
        assert expected == offset_map

        offsets = opcode_27.get_jump_targets(code,  opcode_27)
        assert offsets == [26, 25, 16]

    test_pyc = my_dir +'/../test/bytecode_2.7/01_dead_code.pyc'
    (version, timestamp, magic_int, co, pypy,
     source_size, _) = load_module(test_pyc)
    code = co.co_consts[0]
    offsets = opcode_27.get_jump_targets(code,  opcode_27)
    assert [10] == offsets

    # from xdis import disassemble_file
    # print('\n')
    # disassemble_file(test_pyc)

    #  2:           0 LOAD_FAST                 0 (a)
    #               3 POP_JUMP_IF_FALSE        10 (to 10)
    #
    #  3:           6 LOAD_CONST                1 (5)
    #               9 RETURN_VALUE
    #
    #  5:     >>   10 LOAD_CONST                2 (6)
    #              13 RETURN_VALUE