Git Product home page Git Product logo

pycdc's Introduction

Decompyle++

A Python Byte-code Disassembler/Decompiler

Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python.

Decompyle++ includes both a byte-code disassembler (pycdas) and a decompiler (pycdc).

As the name implies, Decompyle++ is written in C++. If you wish to contribute, please fork us on github at https://github.com/zrax/pycdc

Building Decompyle++

  • Generate a project or makefile with CMake (See CMake's documentation for details)

    • The following options can be passed to CMake to control debug features:

      Option Description
      -DCMAKE_BUILD_TYPE=Debug Produce debugging symbols
      -DENABLE_BLOCK_DEBUG=ON Enable block debugging output
      -DENABLE_STACK_DEBUG=ON Enable stack debugging output
  • Build the generated project or makefile

    • For projects (e.g. MSVC), open the generated project file and build it
    • For makefiles, just run make
    • To run tests (on *nix or MSYS), run make check

Usage

To run pycdas, the PYC Disassembler: ./pycdas [PATH TO PYC FILE] The byte-code disassembly is printed to stdout.

To run pycdc, the PYC Decompiler: ./pycdc [PATH TO PYC FILE] The decompiled Python source is printed to stdout. Any errors are printed to stderr.

Marshalled code objects: Both tools support Python marshalled code objects, as output from marshal.dumps(compile(...)).

To use this feature, specify -c -v <version> on the command line - the version must be specified as the objects themselves do not contain version metadata.

Authors, Licence, Credits

Decompyle++ is the work of Michael Hansen and Darryl Pogue.

Additional contributions from:

  • charlietang98
  • Kunal Parmar
  • Olivier Iffrig
  • Zlodiy

It is released under the terms of the GNU General Public License, version 3; See LICENSE file for details.

pycdc's People

Contributors

ace314159 avatar almamu avatar aralox avatar arthurzam avatar asas1asas200 avatar caot avatar clubby789 avatar ddouworld avatar dotjrich avatar dpogue avatar eximius avatar fabiensiron avatar greenozon avatar gurnec avatar kako57 avatar kholia avatar kunalparmar avatar lnsspsd avatar ncaklovic avatar oiffrig avatar percevalw avatar polyflower avatar seashell11234455 avatar smdevji avatar thehelltower avatar tizcrocodile avatar trollerofholland avatar zlodiy avatar zrax avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pycdc's Issues

``yield from`` for coroutines not supported. ``Opcode = GET_YEILD_FROM_ITER``

Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER
Unsupported opcode: GET_YEILD_FROM_ITER

And yield from is still valid in 3.5 as long as you have the @asyncio.coroutine decorator on top of the function.

lambda wrong output

it outputs this:

    def onPressKeyDict[app.DIK_1]():
        return self._GameWindow__PressNumKey(1)

but schould be:

onPressKeyDict[app.DIK_1] = lambda : self._GameWindow__PressNumKey(1)

Python 3.5: new opcodes for "with" statement unsupported (WITH_CLEANUP_START and _FINISH)

In Python 3.5 the opcode for WITH_CLEANUP is replaced by the pair of opcodes WITH_CLEANUP_START and WITH_CLEANUP_FINISH. This is to support async "with". These opcodes are not handled by pycdc, so the "with" statement compiled to bytecode with python 3.5 cannot be decompiled.

A quick and dirty solution is to add the following after the Pyc::WITH_CLEANUP block in ASTree.cpp. As the comment below says, this does not support async "with". In the case of not using async "with", the two opcodes will follow eachother immediately, and so should do the same as the old WITH_CLEANUP.

        case Pyc::WITH_CLEANUP_START:
            {
                // This is just a copy of the WITH_CLEANUP block
                // Stack top should be a None. Ignore it.
                PycRef<ASTNode> none = stack.top();
                stack.pop();

                if (none != Node_NULL) {
                    fprintf(stderr, "Something TERRIBLE happened!\n");
                    break;
                }

                if (curblock->blktype() == ASTBlock::BLK_WITH
                        && curblock->end() == curpos) {
                    PycRef<ASTBlock> with = curblock;
                    blocks.pop();
                    curblock = blocks.top();
                    curblock->append(with.cast<ASTNode>());
                }
                else {
                    fprintf(stderr, "Something TERRIBLE happened! No matching with block found for WITH_CLEANUP at %d\n", curpos);
                }
            }
            break;
        case Pyc::WITH_CLEANUP_FINISH:
            {
                // Do nothing. (This does not support async with.)
            }
            break;

pycdc crashes, any tutorial to trace where is the problem

when I run pycdc on some pyc, pycdc crashes. So is there any guide to find which cause this problem, and then we can fix it. I know we can debug the C source file, but it is some difficult for C newbie. So if there some way can aid debug, it will be good for this project and the user. Thanks

Python 3.2 name and parameter handling:

On python 3.2.6, this

# From python 3.2 configparser.py
def __init__(self, defaults=None, dict_type=_default_dict,
             allow_no_value=False, *, delimiters=('=', ':'),
             comment_prefixes=('#', ';'), inline_comment_prefixes=None,
             strict=True, empty_lines_in_values=True,
             default_section=DEFAULTSECT,
             interpolation=_UNSET):
    return 

gives:

def __init__(self = None, defaults = None, dict_type = None, allow_no_value = None):
    pass

At one point I went though all of the test case from that repo and there were/are a number of other failures, including some SEGV's. If it is of interest I can open a ticket for each one.

BTW great work. I wish uncompyle6 were as simple and tight and handled its control structures as well as pycdc.

"Bad MAGIC!"

After I've compiled complete package (using Microsoft Visual Studio 2012), whenever I try to decompile or disassemble ANY python .pyc file (for example - any file located in "tests" directory) I'm getting as a result

Bad MAGIC!
Could not load file test_with.pyc

Is there any specific reason why it doesn't work?

thanks

Output File

I use this Tool to decompyle .pyc Files and want write this to a File.
Now i use the freopen Method like this: "freopen( "output.py", "w", stdout );"

My problem is that every time I decompyle a file will be named output.py. But I want that when I e.g. decompyle test.pyc this is then named test.py and when I load test-2.pyc this is then named test-2.py.

Can you help me?

lambda decompyle generate error python code

a = lambda x: [i**2 for i in x]
def f4(x):
    return a(x)

compile and use pycdc to decompile ,generate:

a = lambda x: continue[ i ** 2 for i in x ]

def f4(x):
    return a(x)

In particular,when lambda return a generator like this:

a = lambda x: (i**2 for i in x)
def f4(x):
    return a(x)

use pycdc to decompile ,generate:

a = lambda x: (lambda .0: continue)(x)
def f4(x):
    return a(x)

look like something wrong....

one bug : can not do some pyc

when use pycdc
there is an error
PycData::get16()
{
/* Ensure endianness */
int result = getByte() & 0xFF;
result |= (getByte() & 0xFF) << 8;
return (result | -(result & 0x8000));
}

Build Error: error: 'this' pointer cannot be null in well-defined C++ code;

$ git clone https://github.com/zrax/pycdc.git
$ cd pycdc
$ brew install cmake
$ cmake ../pycdc/
CMake Warning (dev) at CMakeLists.txt:58 (add_custom_target):
  Policy CMP0037 is not set: Target names should not be reserved and should
  match a validity pattern.  Run "cmake --help-policy CMP0037" for policy
  details.  Use the cmake_policy command to set the policy and suppress this
  warning.

  The target name "test" is reserved or not valid for certain CMake features,
  such as generator expressions, and may result in undefined behavior.
This warning is for project developers.  Use -Wno-dev to suppress it.

-- Configuring done
-- Generating done
-- Build files have been written to: ~/pycdc
$
$
$ make
[  3%] Building CXX object CMakeFiles/pycxx.dir/bytecode.cpp.o
In file included from ~/pycdc/bytecode.cpp:1:
In file included from ~/pycdc/pyc_numeric.h:4:
~/pycdc/pyc_object.h:109:32: error: 'this' pointer cannot be null in well-defined C++ code;
      pointer may be assumed to always convert to true [-Werror,-Wundefined-bool-conversion]
    int type() const { return (this) ? m_type : TYPE_NULL; }
                               ^~~~  ~
1 error generated.
make[2]: *** [CMakeFiles/pycxx.dir/bytecode.cpp.o] Error 1
make[1]: *** [CMakeFiles/pycxx.dir/all] Error 2
make: *** [all] Error 2
$

Wrong tuple unpacking in for loops

Tuple unpacking in for loops is not handled correctly:

def map_with_index(func, lst):
    res = []
    for i, x in enumerate(lst):
        res.append(func(i, x)) 
    return res

is reconstructed as

def map_with_index(func, lst):
    res = []
    for None in enumerate(lst):
        (i, x) = None
    return res

If I unpack the tuple inside the loop, there is no problem, aka

def map_with_index_2(func, lst):
    res = []
    for t in enumerate(lst):
        i, x = t
        res.append(func(i, x))
    return res

is fine.

Python version: 2.7.3

Hangs while parsing 22_z_test_integers.pyc

This came from decompyle's suite of Python 2.2 tests, so I'm presuming that it's actually a valid PYC file. pycdc and pycdas both hang while trying to parse it.

I'm not familiar with the bytecode parsing code, so my attempts to debug it have just led me in circles. It doesn't crash at any point, it just seems to either keep parsing the same thing or sit there waiting for something.

No releases yet

Your Python Decompiler is awesome! At least works for me on python2.2 generated ancient .pyc files.

I am currently struggling to port the CASIO IDES waveconverter (synth patch compressor) on Linux. Fortunately, it is a py2exe PE containing all the .py/.pyc. With your handy tool, the interface (wxWidgets) got working on my LinuxMint 17.2 x64 (yet there are .pyd libraries).

However, I had to $git clone $cmake $make just to run the $pycdc for the first time. Why don't you create some Releases with binary files on GitHub? That would be easier for some people, if, say, they wanted to just decompyle a bunch of .pyc. (I even found out I had no CMake in the system)

After building pycdc Virus Total reports Troj.W32.Gen

Hi,

After downloading CMake as suggested and building the project files in Visual Studio 2013 I took the precaution of throwing the exe (pycdc.exe) at Virus total. AegisLab reports Troj.W32.Gen. Has anyone come across this before?

I hope it is anomalous..

Kithara

unusual synax crashed the build

Today I found this decompiler don't support following codes:

def useVoxCheck(arg):
  global useVoxCtrl
  useVoxCtrl = True if arg == "true" else False
  cmds.floatFieldGrp('voxSizeText', edit=True, enable=1 if arg == "false" else 0)  # crash at this line

this will crash pycdc, after several unit test, I'm sure it is cause by the arg in line 3: 'edit=True, enable=1 if arg == "false" else 0', but pydas is fine on this. I tried debuging it but failed.

Would anyone fix it ? Thanks!

Warning: block stack

Hey nice Project i modified it to use it in one of my project as dll im actually running it for every *.PYC file in the directory.

Its a for loop my only problem is i get the following error:
Warning: block stack is not empty!
Warning: Stack history is not empty!
Warning: Stack history is not empty!
Warning: Stack history is not empty!

Why is this happening im calling

        if((stream = freopen(p3, "w", stdout)) == NULL)
          exit(-1);
        mod.loadFromFile(p1);
        if (!mod.isValid()) {
            fprintf(stderr, "Could not load file %s\n", p2);
            return 1;
        }
        decompyle(mod.code(), &mod);
        stream = freopen("CON", "w", stdout); // Redirect the output back to console
        return 1;

Kind Regards

Tuples as named arguments

def myfunc((a, b) = (0, 1)):
    print a
    print b

gets decompyled into

def myfunc(.0 = (0, 1))
    (a, b) = .0
    print a
    print b

This is especially problematic for lambdas, and requires some way of replacing function argument names with nodes as the code is parsed.

Missing global keyword

Any function that changes the value of a global variable should declare that global variable in scope with the global keyword.

This would require each function to keep a list/set of global variables that are used within that function, and print out that list with the global keyword as the first line of disassembled output.

This is mostly just a reminder that this needs to be done at some point.

3xxx segmentation fault

I used pycdc to decompile a pyc file

./pycdc x.pyc
it can print the part of source code
but after running for a moment , it get this error
it cannot print all the source code

I can give the pyc file if needed

Convert stdio to iostream

Currently the usage of the older C I/O stuff usage and association with "FILE *" (pyc_output) is scattered throughout the code, I have already done an initial re-write of this to use std::ostream, which come out with a bit cleaner code. (Personal opinion)

This is a reasonable size change (non-isolated) so this is more of a discussion 'issue' of the pro's/con's of the different approaches.

Pros of keeping current / Cons of change:

  • Giant diff (Counter: No frequent commits, conflicts rare)
  • Ain't broke don't fix it (Counter: Limited room for customize-ability)
  • printf easier to read (Counter: Personal preference, helpers can be made easier with iostream - less mystical format strings, and 'printf' validation, type safety)

Cons of current / Pros of change:

  • (All counter of other)
  • Use std::stringstream to store intermediate formats (I found very useful debugging)
  • Easier to define different output types (Not something FILE_) (Counter: Not often non-FILE_; Count-counter: Debug buffer)
  • Debug output more closely associated with object (Start using operator<<) not switch(x)
  • More common common functionality (Similar to previous; could be done with stdio)
  • C++ not C (could be straw-man)

complex list comprehension fail

input:

pairs = [('a',2)]
def filter_n_sort_pairs():
    z = [int(x) for (x, y) in pairs if (x not in ['c',4] and not isinstance(x, int))]
    return z.sort()

decompilation result: (+warning blocks not empty)

def filter_n_sort_pairs():
    for (x, y) in pairs:
        if isinstance(x, int) and x not in ['c',4]:
            continue
            z = [][int(var_1)]
            z.sort()
            return z

I think checking current block boundaries (when known) could solve this issue, I may take a look at it myself. (v2.7.10)

Bad documentation

Simply use "make" command not found. Where is the Makefile ? Please make a more precise documentation...

pycdc crash. python34 win7

I compiled pycdc with python34.
This file is not decompiled:

REM this is batch file *.bat
pycdc.exe pyc\bughurt.pyc > py\bughurt.py
pycdc.exe pyc\checkers_g.pyc > py\checkers_g.py
pycdc.exe pyc\1_Lisa.pyc > py\1_Lisa.py
pycdc.exe pyc\memgen.pyc > py\memgen.py
pycdc.exe pyc\mirror.pyc > py\mirror.py
pycdc.exe pyc\pixel.pyc > py\pixel.py
pycdc.exe pyc\weather.pyc > py\weather.py
pycdc.exe pyc\imsearch.pyc > py\imsearch.py
pycdc.exe pyc\like.pyc > py\like.py
pycdc.exe pyc\func.pyc > py\func.py
pause

all pyc, py and screenshots files in archive https://drive.google.com/open?id=0B69FzC4j62F9ZmlILUt3eWlvSVE

Please check and help me!

pycdc coredump

FILE: ASTree.cpp,
FUNCTION: PycRef BuildFromCode(PycRef code, PycModule* mod)
LINE: 1219
REASON: empty stack_hist cause stack_hist.top() core.

issue in install

gmake
g++ -g -Wall -fprofile-arcs -ftest-coverage -DBLOCK_DEBUG -DSTACK_DEBUG -c data.cpp -o out/data.o
g++ -g -Wall -fprofile-arcs -ftest-coverage -DBLOCK_DEBUG -DSTACK_DEBUG -c bytecode.cpp -o out/bytecode.o
g++ -g -Wall -fprofile-arcs -ftest-coverage -DBLOCK_DEBUG -DSTACK_DEBUG -c pyc_module.cpp -o out/pyc_module.o
g++ -g -Wall -fprofile-arcs -ftest-coverage -DBLOCK_DEBUG -DSTACK_DEBUG -c pyc_object.cpp -o out/pyc_object.o
g++ -g -Wall -fprofile-arcs -ftest-coverage -DBLOCK_DEBUG -DSTACK_DEBUG -c pyc_numeric.cpp -o out/pyc_numeric.o
g++ -g -Wall -fprofile-arcs -ftest-coverage -DBLOCK_DEBUG -DSTACK_DEBUG -c pyc_code.cpp -o out/pyc_code.o
g++ -g -Wall -fprofile-arcs -ftest-coverage -DBLOCK_DEBUG -DSTACK_DEBUG -c pyc_sequence.cpp -o out/pyc_sequence.o
g++ -g -Wall -fprofile-arcs -ftest-coverage -DBLOCK_DEBUG -DSTACK_DEBUG -c pyc_string.cpp -o out/pyc_string.o
g++ -g -Wall -fprofile-arcs -ftest-coverage -DBLOCK_DEBUG -DSTACK_DEBUG -c ASTree.cpp -o out/ASTree.o
g++ -g -Wall -fprofile-arcs -ftest-coverage -DBLOCK_DEBUG -DSTACK_DEBUG -c ASTNode.cpp -o out/ASTNode.o
( cd bytes ; ./comp_map.py )
File "./comp_map.py", line 26
with infile and outfile:
^
SyntaxError: invalid syntax
gmake: *** [bytes/python_10.cpp] Error 1

Building: 'str' does not support the buffer interface

When I try to build using MinGW's make, I get the following command line output - it's not possible to build:

g++  -g -Wall -Wextra -Werror -c data.cpp -o out/data.o
g++  -g -Wall -Wextra -Werror -c bytecode.cpp -o out/bytecode.o
g++  -g -Wall -Wextra -Werror -c pyc_module.cpp -o out/pyc_module.o
g++  -g -Wall -Wextra -Werror -c pyc_object.cpp -o out/pyc_object.o
g++  -g -Wall -Wextra -Werror -c pyc_numeric.cpp -o out/pyc_numeric.o
g++  -g -Wall -Wextra -Werror -c pyc_code.cpp -o out/pyc_code.o
g++  -g -Wall -Wextra -Werror -c pyc_sequence.cpp -o out/pyc_sequence.o
g++  -g -Wall -Wextra -Werror -c pyc_string.cpp -o out/pyc_string.o
g++  -g -Wall -Wextra -Werror -c ASTree.cpp -o out/ASTree.o
g++  -g -Wall -Wextra -Werror -c ASTNode.cpp -o out/ASTNode.o
( cd bytes ; ./comp_map.py )
Traceback (most recent call last):
  File "./comp_map.py", line 33, in <module>
    outfile.write('/* This file was auto-generated with comp_map.py.  DO NOT EDIT! */\n\n')
TypeError: 'str' does not support the buffer interface
make: *** [bytes/python_10.cpp] Error 1

enhancement - support output to file from arg[2]

`int main(int argc, char* argv[])
{
if (argc < 2) {
fprintf(stderr, "No input file specified\n");
return 1;
}

PycModule mod;
mod.loadFromFile(argv[1]);
if (!mod.isValid()) {
    fprintf(stderr, "Could not load file %s\n", argv[1]);
    return 1;
}
const char* dispname = strrchr(argv[1], PATHSEP);
dispname = (dispname == NULL) ? argv[1] : dispname + 1;
fprintf(pyc_output, "# Source Generated with Decompyle++\n");
fprintf(pyc_output, "# File: %s (Python %d.%d%s)\n\n", dispname, mod.majorVer(), mod.minorVer(),
        (mod.majorVer() < 3 && mod.isUnicode()) ? " Unicode" : "");
decompyle(mod.code(), &mod);

return 0;

}
`

Fails to build

VC++ 2008 Express Edition

1>Compiling...
1>python_10.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_10.cpp': No such file or directory
1>python_11.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_11.cpp': No such file or directory
1>python_13.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_13.cpp': No such file or directory
1>python_14.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_14.cpp': No such file or directory
1>python_15.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_15.cpp': No such file or directory
1>python_16.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_16.cpp': No such file or directory
1>python_20.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_20.cpp': No such file or directory
1>python_21.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_21.cpp': No such file or directory
1>python_22.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_22.cpp': No such file or directory
1>python_23.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_23.cpp': No such file or directory
1>python_24.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_24.cpp': No such file or directory
1>python_25.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_25.cpp': No such file or directory
1>python_26.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_26.cpp': No such file or directory
1>python_27.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_27.cpp': No such file or directory
1>python_30.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_30.cpp': No such file or directory
1>python_31.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_31.cpp': No such file or directory
1>python_32.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_32.cpp': No such file or directory
1>python_33.cpp
1>c1xx : fatal error C1083: Cannot open source file: '.\bytes\python_33.cpp': No such file or directory
1>ASTNode.cpp
1>ASTree.cpp

is Project file outdated?

pass in classes are not retained but pass in Functions Are.

In my Original Code the Following Classes I have:

class BaseErrors(Exception):
    pass


class FilePathNotProvided(BaseErrors):
    pass


class FileNameNotProvided(BaseErrors):
    pass


class FileNotFound(BaseErrors):
    pass

Becomes this in pycdc:

class BaseErrors(Exception):
    __qualname__ = 'BaseErrors'


class FilePathNotProvided(BaseErrors):
    __qualname__ = 'FilePathNotProvided'


class FileNameNotProvided(BaseErrors):
    __qualname__ = 'FileNameNotProvided'


class FileNotFound(BaseErrors):
    __qualname__ = 'FileNotFound'

But in a Function in my Code:

def this_is_not_a_function_to_keep_this_coment_in_byte_codes():
    """
    I would like for the data returned from this to be importable without  having to cache (only if 
    sys.dont_write_bytecode is True) and without having to generate the normal py file as well.
    Why do this? what is the point?
    The Point for this is to make a interface to make python scripts smaller.
    With a range of 1/3 ~ 1/2 (results vary from file to file) the original sizes this is a dam good api for that.
    the cool thing is it uses python modules that comes with it. No External libs. (yet)
    Sadly this means somehow either recodign the original import statement in probably the C code to python itself.
    or finding how it reads from the pyc files (hopefully from within a python script).
    __init__.py:
        Normal Size: 598 bytes
        Compressed Size: 488 bytes
    api.py (this file):
        Normal Size: 6753 bytes
        Compressed Size: 3071 bytes
    compresspy.py:
        Normal Size: 1152 bytes
        Compressed Size: 746 bytes
    decompresspy.py:
        Normal Size: 1014 bytes
        Compressed Size: 688 bytes
    """
    pass

Becomes this in pycdc:

def this_is_not_a_function_to_keep_this_coment_in_byte_codes():
    '''
    I would like for the data returned from this to be importable without  having to cache (only if 
    sys.dont_write_bytecode is True) and without having to generate the normal py file as well.
    Why do this? what is the point?
    The Point for this is to make a interface to make python scripts smaller.
    With a range of 1/3 ~ 1/2 (results vary from file to file) the original sizes this is a dam good api for that.
    the cool thing is it uses python modules that comes with it. No External libs. (yet)
    Sadly this means somehow either recodign the original import statement in probably the C code to python itself.
    or finding how it reads from the pyc files (hopefully from within a python script).
    __init__.py:
        Normal Size: 598 bytes
        Compressed Size: 488 bytes
    api.py (this file):
        Normal Size: 6753 bytes
        Compressed Size: 3071 bytes
    compresspy.py:
        Normal Size: 1152 bytes
        Compressed Size: 746 bytes
    decompresspy.py:
        Normal Size: 1014 bytes
        Compressed Size: 688 bytes
    '''
    pass

can we take part of disassembled bytecode and translate it back into pyc?

My question is composed by 2 aspects

  1. incompleted pyc is valid in python
    for example. I have tested the following a.py and b.py. After running a.py, we can find that b.pyc is created. But obviously, b.py is not a completed code since there is no defination of function "fib". So the bytecode of I-called incompleted pyc is valid too
  2. we can use pycdc to disassemble. But is there a way to find just the code of function (for example "fun") and convert it back into pyc? thanks

[code a.py]
import b
[/code]

[code b.py]
n=10

def fun(x, y):
return x+fib(y)
[/code]

``else:`` lines in if statements are not kept when the bytecodes is decompiled.

Nice job on the Decompiler just a few bugs where the else: statements for certain if blocks get removed for some reason. btw you guys also know of a way to append some interface to normal import statements for any modules imported in the interpreter? basically a overload to the normal one that would allow loading files with a custom compression without havign to use byecodes. funny thing is with my special format it could replace bytecode files to and is 100% easy to decompile (hehe) it is cool tbh.

py2pycx.zip

run-time error

pycdc.exe!BuildFromCode(PycRef code={...}, PycModule * mod=0x0040fd9c)
case Pyc::END_FINALLY:
curblock->blktype() == ASTBlock::BLK_EXCEPT
blocks.pop(); blocks.size() == 0
behind
blocks.top() assert error
file:https://www.dropbox.com/s/b76j1bsvs6ph3j5/loglevels.pyc
Software may have logic problems,src file: https://www.dropbox.com/s/cmbtl8huyck3ynb/loglevels.py
Try this code:
def exception_to_unicode(e):
if e:
return "\n".join(a for a in e.args)
try:
return unicode(e)
except Exception:
return u"Unknown message"

Python 3.4 Decompile Failure.

I'm finding compiled source with defined functions is crashing the decompiler for Python 3.4.x.

Example Code:

def func_name():
print ("yelloo")
return False

print ('Hello, World!')
func_name()

Note that the decompiler won't even work unless you implement mancoast's fix for the Magic Number here: #49

the line in ASTree.cpp fails:
if (strcmp(code_src->name()->value(), "") == 0) {
because code_src->name() is empty. in fact the whole structure is filled with nulls. Something isn't parsing right.

Python 3.4.0 Magic Number

Hello All!

I have been working on updates for 3.4.0.
Issue is simple to fix and easy to replicate:
1.) make a simple Hello.py script with contents:
print ('Hello, World!')

2.) make compile script Compile.py with contents:
import py_compile
py_compile.compile('Hello.py')

3.) execute "python Compile.py" to produce the output file Hello.cpython-34.pyc

4.) now execute "pycdc Hello.cpython-34.pyc"
image

Fix:
image

Results:
image

I am not sure if the magic number MAGIC_3_4 = 0x0A0D0CE4 is for a different 3.4?

Thanks,
mancoast

Segmentation fault in PycRef<ASTBlock>::operator=

Got a segfault when trying to decompile a particular .pyc. A quick inspection by building with debug symbols and firing up gdb shows it's in the function PycRef::operator=.

    Stopped reason: SIGSEGV

0x000000000044db54 in PycRef<ASTBlock>::operator= (this=0x7fffffff5cc0, obj=...)
    at /home/dtouch3d/src/pycdc/pyc_object.h:39
39              if (obj.m_obj)
gdb-peda$ bt
#0  0x000000000044db54 in PycRef<ASTBlock>::operator= (this=0x7fffffff5cc0, obj=...)
    at /home/dtouch3d/src/pycdc/pyc_object.h:39
#1  0x0000000000436b8f in BuildFromCode (code=..., mod=0x7fffffffe600)
    at /home/dtouch3d/src/pycdc/ASTree.cpp:1243
#2  0x00000000004497ff in decompyle (code=..., mod=0x7fffffffe600)
    at /home/dtouch3d/src/pycdc/ASTree.cpp:2798
#3  0x0000000000445861 in print_src (node=..., mod=0x7fffffffe600)
    at /home/dtouch3d/src/pycdc/ASTree.cpp:2452
#4  0x000000000044731d in print_src (node=..., mod=0x7fffffffe600)
    at /home/dtouch3d/src/pycdc/ASTree.cpp:2656
#5  0x0000000000444f42 in print_src (node=..., mod=0x7fffffffe600)
    at /home/dtouch3d/src/pycdc/ASTree.cpp:2386
#6  0x000000000044a2e3 in decompyle (code=..., mod=0x7fffffffe600)
...
gdb-peda$ p obj
$1 = (const PycRef<ASTBlock> &) @0xdd00000200: <error reading variable>
gdb-peda$ 

I am guessing it is has something to do with the FastStack implementation, although I did not have much time to investigate further.

The offending file is snapconnect/SnapXmlRpc.pyc at http://forums.synapse-wireless.com/upload/snapconnect-3.1.0-python2.7.zip

Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.