├── .gitignore ├── COPYING ├── README ├── const.py ├── decompile ├── __init__.py ├── binary_ops.py ├── bloc.py ├── boolean_conditions.py ├── branch_info.py ├── branches_ender.py ├── clause_footprints.py ├── constructs │ ├── __init__.py │ ├── conditionals.py │ ├── for_loops.py │ ├── if_constructs.py │ ├── try_constructs.py │ └── while_loops.py ├── decompilator.py ├── disassemble.py ├── embedded_functions.py ├── tree_traversal.py └── unary_ops.py ├── inspection ├── __init__.py ├── classes.py ├── data.py ├── functions.py └── modules.py ├── main.py └── tools ├── __init__.py └── out_saver.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[co] 2 | 3 | # Packages 4 | *.egg 5 | *.egg-info 6 | dist 7 | build 8 | eggs 9 | parts 10 | bin 11 | var 12 | sdist 13 | develop-eggs 14 | .installed.cfg 15 | 16 | # Installer logs 17 | pip-log.txt 18 | 19 | # Unit test / coverage reports 20 | .coverage 21 | .tox 22 | 23 | #Translations 24 | *.mo 25 | 26 | #Mr Developer 27 | .mr.developer.cfg 28 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | pyc2py 2 | ====== 3 | Pyc2py is a python decompiler: you can use it to retrieve the source code 4 | when having the bytecode file (*.pyc). 5 | 6 | It is currently beta software and was only tested with python2.6 bytecode 7 | files. 8 | 9 | Usage: 10 | ./main.py > output.py 11 | 12 | Important note 13 | ============== 14 | In order to simplify its design, pyc2py uses python introspection features. 15 | Thanks to this, bytecode analysis is limited to function and class methods. 16 | As a consequence, the first step of the analysis is the import of the module 17 | implemented in the *.pyc input file; if this module imports other modules, 18 | these additional modules must be present in the "python path" (in either form, 19 | '.py' or '.pyc'), otherwise this preliminary import will fail. 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /const.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | 21 | # kinds of indexes used to point to the 22 | # next instruction 23 | # values must reflect the order of clauses: 24 | # IF_CLAUSE < ELSE_CLAUSE < END_OF_CONSTRUCT 25 | # FOR_CLAUSE < END_OF_CONSTRUCT 26 | NORMAL_FLOW = -1 27 | IF_CLAUSE = 10 28 | ELSE_CLAUSE = 11 29 | TRY_CLAUSE = 12 30 | EXCEPT_EXPRESSION_CLAUSE = 13 31 | EXCEPT_CLAUSE = 14 32 | FINALLY_CLAUSE = 15 33 | FOR_CLAUSE = 16 34 | WHILE_CLAUSE = 17 35 | END_OF_CONSTRUCT = 18 # end of 'if', 'for', 'try' constructs 36 | 37 | # constants used when we want to specify that an action 38 | # must be performed in any clause, none of the clauses 39 | # of a given construct, the 'FORWARD' or the 'JUMP 'clause only. 40 | # The FORWARD and JUMP clauses are different depending on the 41 | # construct (while or if-then-else) and the conditional jump 42 | # used. 43 | # 44 | # (values must be different from the values of clauses above) 45 | NO_CLAUSE = 0 46 | ANY_CLAUSE = 1 47 | FORWARD_CLAUSE = 2 48 | JUMP_CLAUSE = 3 49 | 50 | # constants needed to specify if a statement is complete 51 | # or not, or 'candidate'. 52 | # For example if we have a function call, f(), this is a 53 | # candidate statement, because: 54 | # - "f()" is a valid statement itself 55 | # - but "g(f())" or "a = f()" are valid statements also 56 | PARTIAL_STATEMENT = 0 57 | COMPLETE_STATEMENT = 1 58 | CANDIDATE_STATEMENT = 2 59 | 60 | # data about branches and jumps 61 | BRANCH_IS_OPTIONAL = { 62 | IF_CLAUSE: False, 63 | ELSE_CLAUSE: True, 64 | TRY_CLAUSE: False, 65 | EXCEPT_CLAUSE: False, 66 | FINALLY_CLAUSE: True, 67 | FOR_CLAUSE: False, 68 | WHILE_CLAUSE: False, 69 | EXCEPT_EXPRESSION_CLAUSE: True 70 | } 71 | 72 | CONDITIONAL_JUMPS_DESC = { 73 | 'JUMP_IF_TRUE' : { # python 2.6 74 | 'jump_cond' : True, 75 | 'pop_cond' : NO_CLAUSE, 76 | 'relative' : True 77 | }, 78 | 'JUMP_IF_FALSE' : { # python 2.6 79 | 'jump_cond' : False, 80 | 'pop_cond' : NO_CLAUSE, 81 | 'relative' : True 82 | }, 83 | 'POP_JUMP_IF_TRUE' : { # python 2.7 84 | 'jump_cond' : True, 85 | 'pop_cond' : ANY_CLAUSE, 86 | 'relative' : False 87 | }, 88 | 'POP_JUMP_IF_FALSE' : { # python 2.7 89 | 'jump_cond' : False, 90 | 'pop_cond' : ANY_CLAUSE, 91 | 'relative' : False 92 | }, 93 | 'JUMP_IF_TRUE_OR_POP' : { # python 2.7 94 | 'jump_cond' : True, 95 | 'pop_cond' : FORWARD_CLAUSE, 96 | 'relative' : False 97 | }, 98 | 'JUMP_IF_FALSE_OR_POP' : { # python 2.7 99 | 'jump_cond' : False, 100 | 'pop_cond' : FORWARD_CLAUSE, 101 | 'relative' : False 102 | } 103 | } 104 | 105 | CONDITIONAL_JUMPS = CONDITIONAL_JUMPS_DESC.keys() 106 | -------------------------------------------------------------------------------- /decompile/__init__.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from decompile.bloc import decompile_bloc 21 | from decompile.constructs import analyse_structures 22 | from decompile.disassemble import disassemble_code 23 | 24 | 25 | def decompile_func_body(func_code, known_globals, body_indent): 26 | asm_indexes, indexed_asm = disassemble_code(func_code) 27 | asm_indexes, indexed_asm = analyse_structures(asm_indexes, indexed_asm) 28 | return decompile_bloc( 29 | indexed_asm, func_code, known_globals, index=asm_indexes[0], indent=body_indent, 30 | is_top_level_bloc=True) 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /decompile/binary_ops.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from const import PARTIAL_STATEMENT 21 | 22 | BINARY_OPS = { 23 | 'POWER': '**', 24 | 'MULTIPLY': '*', 25 | 'DIVIDE': '/', 26 | 'FLOOR_DIVIDE': '//', 27 | 'MODULO': '%', 28 | 'ADD': '+', 29 | 'SUBTRACT': '-', 30 | 'SUBSCR': '', 31 | 'LSHIFT': '<<', 32 | 'RSHIFT': '>>', 33 | 'AND': '&', 34 | 'XOR': '^', 35 | 'OR': '|' 36 | } 37 | 38 | def manage_binary_op(mnemo, info): 39 | after_underscore = mnemo.partition('_')[2] 40 | TOS = info.pop() 41 | TOS1 = info.pop() 42 | if after_underscore == 'SUBSCR': 43 | full_op = TOS1 + '[' + TOS + ']' 44 | else: 45 | full_op = TOS1 + ' ' + BINARY_OPS[after_underscore] + ' ' + TOS 46 | info.push('(' + full_op + ')', PARTIAL_STATEMENT) 47 | 48 | 49 | -------------------------------------------------------------------------------- /decompile/bloc.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from decompile.branch_info import BranchDecompilationInfo 21 | import decompile.decompilator 22 | 23 | def decompile_bloc(indexed_asm, func_code, known_globals, index=0, indent=1, 24 | is_top_level_bloc=False): 25 | info = BranchDecompilationInfo(indent, 26 | is_top_level_bloc=is_top_level_bloc) 27 | decompile.decompilator.Decompilator( 28 | indexed_asm, func_code, known_globals).traverse( 29 | index=index, 30 | data=info) 31 | return info.retrieve_statements() 32 | -------------------------------------------------------------------------------- /decompile/boolean_conditions.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from const import IF_CLAUSE, ELSE_CLAUSE 21 | from tree_traversal import TreeTraversal 22 | 23 | OR_CONDITION = 0 24 | AND_CONDITION = 1 25 | 26 | def handle_boolean_conditions(indexed_asm, start_index): 27 | conditions_path = [] 28 | handler = BooleanConditionsHandler(indexed_asm) 29 | handler.traverse(index=start_index, data=conditions_path) 30 | handler.store_results() 31 | 32 | class BooleanConditionsHandler(TreeTraversal): 33 | def __init__(self, elems): 34 | TreeTraversal.__init__(self, elems) 35 | self.longest_condition_suite = {} 36 | 37 | def handle_new_branch_traversed(self, clause_type, jump_index, branch_start_index, 38 | parent_branch_conditions_path): 39 | conditions_path = parent_branch_conditions_path[:] # copy 40 | if clause_type in [ IF_CLAUSE, ELSE_CLAUSE ]: 41 | cond_elem = self.elems[jump_index] 42 | conditions_path.append((cond_elem, clause_type)) 43 | self.handle_boolean_suite_of_constructs( 44 | cond_elem, conditions_path) 45 | return conditions_path 46 | 47 | def analyse_consecutive_clauses(self, 48 | cond_elem, conditions_path): 49 | num = 1 50 | types = [] 51 | indexes = cond_elem['next_indexes'] 52 | if indexes[IF_CLAUSE] > cond_elem['index'] and \ 53 | indexes[ELSE_CLAUSE] > cond_elem['index']: 54 | while len(conditions_path) > num: 55 | other_elem = conditions_path[-1-num][0] 56 | other_indexes = other_elem['next_indexes'] 57 | if len(other_indexes) < 2: 58 | break # we have already treated this element before 59 | elif indexes[IF_CLAUSE] == other_indexes[IF_CLAUSE]: 60 | # same if clause, this is an "or" operation 61 | types.append(OR_CONDITION) 62 | num += 1 63 | elif indexes[ELSE_CLAUSE] == other_indexes[ELSE_CLAUSE]: 64 | # same else clause, this is an "and" operation 65 | types.append(AND_CONDITION) 66 | num += 1 67 | else: 68 | break 69 | return num, types 70 | 71 | def handle_boolean_suite_of_constructs(self, 72 | cond_elem, conditions_path): 73 | num_conditions, condition_types = self.analyse_consecutive_clauses( 74 | cond_elem, conditions_path) 75 | self.update_condition_suite(cond_elem['index'], num_conditions, condition_types, conditions_path) 76 | 77 | def update_condition_suite(self, index, num_conditions, condition_types, conditions_path): 78 | if index in self.longest_condition_suite: 79 | previous_num_conditions = \ 80 | self.longest_condition_suite[index]['num_conditions'] 81 | else: 82 | self.longest_condition_suite[index] = {} 83 | previous_num_conditions = 0 84 | if num_conditions > previous_num_conditions: 85 | condition_suite = self.longest_condition_suite[index] 86 | condition_suite['num_conditions'] = num_conditions 87 | condition_suite['condition_types'] = condition_types 88 | condition_suite['conditions_path'] = conditions_path 89 | 90 | def store_results(self): 91 | # consider the longest suites of conditions first 92 | sorted_indexes = sorted(self.longest_condition_suite, 93 | key=lambda index: self.longest_condition_suite[index]['num_conditions'], 94 | reverse=True) 95 | ignored_indexes = set([]) 96 | for index in sorted_indexes: 97 | if index in ignored_indexes: 98 | continue 99 | condition_suite = self.longest_condition_suite[index] 100 | num_conditions = condition_suite['num_conditions'] 101 | if num_conditions > 1: 102 | # yes, several if or else going to the same point, 103 | # that's an or-ed or and-ed condition. 104 | condition_types = condition_suite['condition_types'] 105 | conditions_path = condition_suite['conditions_path'] 106 | # record the combination of boolean conditions 107 | final_if_elem, clause = conditions_path[-1] 108 | final_if_elem['apply_conditions'] = condition_types 109 | # format previous if constructs accordingly 110 | for num in range(num_conditions-1): 111 | elem, clause = conditions_path[-2-num] 112 | # the path we took is the elected flow: 113 | elem['forced_index'] = elem['next_indexes'][clause] 114 | if clause in elem['pop_clauses']: 115 | elem['dup_cond'] = False 116 | else: 117 | # if the pop() operation was not specified 118 | # at jump time, this means that we will 119 | # have a POP_TOP as the 1st instruction 120 | # of the branch. 121 | # we want to keep the condition on the stack, 122 | # so we will have to duplicate it. 123 | elem['dup_cond'] = True 124 | # elements considered in this conditions list 125 | # should be ignored in next ones, except 126 | # the first element. 127 | if num != num_conditions-2: 128 | ignored_indexes.add(elem['index']) 129 | 130 | def handle_traversed_element(self, elem, conditions_path): 131 | should_continue = True 132 | previous = self.get_previous_elem() 133 | if previous != None and elem['index'] < previous['index']: 134 | # going backward! 135 | should_continue = False 136 | return should_continue 137 | -------------------------------------------------------------------------------- /decompile/branch_info.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from const import COMPLETE_STATEMENT, CANDIDATE_STATEMENT 21 | 22 | FUNCTION_CALLS_DESC = { 23 | 'CALL_FUNCTION': { 'varargs': False, 'kw': False }, 24 | 'CALL_FUNCTION_VAR': { 'varargs': True, 'kw': False }, 25 | 'CALL_FUNCTION_KW': { 'varargs': False, 'kw': True }, 26 | 'CALL_FUNCTION_VAR_KW': { 'varargs': True, 'kw': True }, 27 | } 28 | 29 | INT_VALUE = { 30 | 'TWO': 2, 31 | 'THREE': 3, 32 | 'FOUR': 4, 33 | } 34 | 35 | class BranchDecompilationInfo(object): 36 | def __init__(self, indent, stack=[], optional_bloc=False, 37 | preliminary_statement=None, is_top_level_bloc=False): 38 | self.stack = stack 39 | self.indent = indent 40 | self.optional_bloc = optional_bloc 41 | self.statements = [] 42 | self.preliminary_statement = preliminary_statement 43 | self.warnings = set([]) 44 | self.global_variables = set([]) 45 | self.is_top_level_bloc = is_top_level_bloc 46 | def warning(self, text): 47 | self.warnings.add(text) 48 | def get_indent(self): 49 | return self.indent 50 | def get_stack(self): 51 | return self.stack 52 | def print_stack(self): 53 | print 'stack is:' 54 | for statement in self.stack: 55 | print statement[0] 56 | def add_statement(self, statement): 57 | complete_statement = statement 58 | if len(self.warnings) > 0: 59 | complete_statement += " # WARNING: " + "; ".join(self.warnings) 60 | self.warnings = set([]) 61 | self.statements.append((self.indent, complete_statement)) 62 | def append_bloc_of_statements(self, bloc_of_statements): 63 | self.statements += bloc_of_statements 64 | def append_global_variables(self, set_of_global_variables): 65 | self.global_variables = self.global_variables.union(set_of_global_variables) 66 | def push(self, obj, type_of_statement): 67 | if type_of_statement == COMPLETE_STATEMENT: 68 | self.validate_candidate_statements_if_any() 69 | self.add_statement(obj) 70 | else: 71 | self.stack.append((obj, type_of_statement)) 72 | def pop(self): 73 | return self.stack.pop()[0] 74 | def top(self): 75 | return self.stack[-1][0] 76 | def delete_top(self): 77 | top_obj, top_type = self.stack[-1] 78 | if top_type == CANDIDATE_STATEMENT: 79 | self.add_statement(top_obj) 80 | self.stack.pop() 81 | def dup_top(self): 82 | top_obj, top_type = self.stack[-1] 83 | self.push(top_obj, top_type) 84 | def rotate(self, mnemo): 85 | after_underscore = mnemo.partition('_')[2] 86 | num = INT_VALUE[after_underscore] 87 | # rotate num top values 88 | new_stack = self.stack[:-num] 89 | new_stack.append(self.stack[-1]) 90 | new_stack.extend(self.stack[-num:-1]) 91 | # replace stack with this new one 92 | self.stack = new_stack 93 | def retrieve_global_variables(self): 94 | return self.global_variables 95 | def retrieve_statements(self): 96 | self.validate_candidate_statements_if_any() 97 | if len(self.statements) == 0 and self.optional_bloc == False: 98 | #print '# no statements: adding "pass"' 99 | self.add_statement('pass') 100 | if len(self.statements) > 0: 101 | if self.preliminary_statement != None: 102 | # add the branch preliminary statement if any 103 | self.statements.insert(0, self.preliminary_statement) 104 | if self.is_top_level_bloc: 105 | # add global variables declarations 106 | for var in self.global_variables: 107 | stmt = 'global ' + var 108 | self.statements.insert(0, (self.get_indent(), stmt)) 109 | return self.statements 110 | def validate_candidate_statements_if_any(self): 111 | new_stack = [] 112 | for e in self.stack: 113 | obj, obj_type = e 114 | if obj_type == CANDIDATE_STATEMENT: 115 | self.add_statement(obj) 116 | else: 117 | new_stack.append(e) 118 | self.stack = new_stack 119 | def function_call(self, mnemo, param_info): 120 | desc = FUNCTION_CALLS_DESC[mnemo] 121 | params = [] 122 | if desc['kw']: 123 | params.insert(0, '**' + self.pop()) 124 | if desc['varargs']: 125 | params.insert(0, '*' + self.pop()) 126 | num_positional_params = param_info % (1 << 8) 127 | num_keyword_params = param_info / (1 << 8) 128 | for _ in range(num_keyword_params): 129 | arg_value = self.pop() 130 | arg_name = self.pop()[1:-1] 131 | params.insert(0, arg_name + '=' + arg_value) 132 | for _ in range(num_positional_params): 133 | params.insert(0, self.pop()) 134 | func_name = self.pop() 135 | full_call = '%s(%s)' % (func_name, ', '.join(params)) 136 | self.push(full_call, CANDIDATE_STATEMENT) 137 | def record_loading_of_variable(self, known_globals, mnemo, name): 138 | if mnemo == 'LOAD_GLOBAL': 139 | # check that this variable is defined in our module 140 | if name in known_globals: 141 | self.global_variables.add(name) 142 | -------------------------------------------------------------------------------- /decompile/branches_ender.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | 21 | from tree_traversal import TreeTraversal 22 | 23 | class BranchesEnder(TreeTraversal): 24 | def __init__(self, elems): 25 | TreeTraversal.__init__(self, elems) 26 | 27 | def handle_traversed_element(self, elem, end_of_constructs): 28 | index = elem['index'] 29 | next_indexes = elem['next_indexes'] 30 | for next_index_type in next_indexes.copy(): 31 | next_index = next_indexes[next_index_type] 32 | if next_index in end_of_constructs: 33 | # if jumping to the end of another construct 34 | if index != end_of_constructs[next_index]: 35 | del next_indexes[next_index_type] 36 | -------------------------------------------------------------------------------- /decompile/clause_footprints.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from const import ELSE_CLAUSE, IF_CLAUSE, TRY_CLAUSE, EXCEPT_CLAUSE, ANY_CLAUSE 21 | from decompile.tree_traversal import TreeTraversal 22 | 23 | OPPOSITE_CLAUSES = { 24 | IF_CLAUSE: ELSE_CLAUSE, 25 | ELSE_CLAUSE: IF_CLAUSE, 26 | TRY_CLAUSE: EXCEPT_CLAUSE, 27 | EXCEPT_CLAUSE: TRY_CLAUSE 28 | } 29 | 30 | CLAUSES_THAT_NEED_A_FOOTPRINT = OPPOSITE_CLAUSES.keys() 31 | 32 | def add_clause_footprint(clause_footprints, construct_index, clause_type): 33 | merged = False 34 | if not construct_index in clause_footprints: 35 | clause_footprints[construct_index] = clause_type 36 | else: 37 | curr_clause_footprint = clause_footprints[construct_index] 38 | if curr_clause_footprint == clause_type: 39 | pass # already recorded (could happen in case of 40 | # 2 imbricated if constructs) 41 | else: # 2 opposite clauses pass through this instruction 42 | # => indicate the merge (by returning True) 43 | clause_footprints[construct_index] = ANY_CLAUSE 44 | merged = True 45 | return merged 46 | 47 | def record_clause_footprints(elem, clause_footprints, merge_infos): 48 | elem_clause_footprints = elem['clause_footprints'] 49 | at_least_one_merge = False 50 | for construct_index in clause_footprints: 51 | merged = add_clause_footprint( 52 | elem_clause_footprints, 53 | construct_index, 54 | clause_footprints[construct_index]) 55 | if merged: 56 | if construct_index not in merge_infos: 57 | # first time we merge with the other branch 58 | # (that's the end of the if construct) 59 | merge_infos[construct_index] = elem['index'] 60 | at_least_one_merge = True 61 | return at_least_one_merge 62 | 63 | 64 | def get_opposite_clause(clause): 65 | if clause not in OPPOSITE_CLAUSES: 66 | raise Exception("Wrong clause number in get_opposite_clause()! Sorry.") 67 | else: 68 | return OPPOSITE_CLAUSES[clause] 69 | 70 | # our goal here is to deduce information in order 71 | # to retrieve 'if then [else]' or 'try except' constructs. 72 | # we traverse the tree and, at each instruction traversed, 73 | # we record a 'footprint' of the current path of clauses. 74 | # we we pass twice on the same instruction, and we observe 75 | # that we have both opposite clauses (if and else, or try and except), 76 | # then we know that this instruction is a merge point 77 | # (i.e. we just left the construct). 78 | class BranchMergingDetector(TreeTraversal): 79 | def __init__(self, elems): 80 | TreeTraversal.__init__(self, elems) 81 | 82 | def handle_traversed_element(self, elem, if_construct_infos): 83 | #if elem['mnemo'] == 'JUMP_ABSOLUTE' and elem['next_indexes'][NORMAL_FLOW] < elem['index']: 84 | # raise Exception('Jumping backward at the following element. Giving up.' + elem) 85 | branch_clause_footprints = if_construct_infos['branch_clause_footprints'] 86 | merge_infos = if_construct_infos['merge_infos'] 87 | merge_point_detected = record_clause_footprints(elem, branch_clause_footprints, merge_infos) 88 | # if we detect a merge point we can stop the branch traversal 89 | # because what follows was already traversed when inspecting 90 | # the opposite clause. 91 | should_continue = not merge_point_detected 92 | return should_continue 93 | 94 | def handle_new_branch_traversed(self, branch_type, jump_index, branch_start_index, if_construct_infos): 95 | # update clause_footprints for this new branch 96 | #print "#BranchMergingDetector: new branch detected", branch_type, jump_index, branch_start_index, if_construct_infos 97 | branch_clause_footprints = if_construct_infos['branch_clause_footprints'].copy() 98 | branch_path = if_construct_infos['branch_path'] 99 | branch_path = branch_path[:] 100 | branch_path.append(str(jump_index) + '.' + str(branch_type)) 101 | #print branch_path 102 | if branch_type in CLAUSES_THAT_NEED_A_FOOTPRINT: 103 | cond = branch_type 104 | add_clause_footprint( branch_clause_footprints, 105 | jump_index, 106 | cond) 107 | return { 'branch_clause_footprints' : branch_clause_footprints, 108 | 'merge_infos' : if_construct_infos['merge_infos'], 109 | 'branch_path' : branch_path 110 | } 111 | -------------------------------------------------------------------------------- /decompile/constructs/__init__.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from const import END_OF_CONSTRUCT, NORMAL_FLOW, CONDITIONAL_JUMPS 21 | from decompile.branches_ender import BranchesEnder 22 | from decompile.clause_footprints import BranchMergingDetector, \ 23 | get_opposite_clause 24 | from decompile.constructs.for_loops import recognise_for_loops 25 | from decompile.constructs.if_constructs import prepare_if_element 26 | from decompile.constructs.try_constructs import prepare_try_element 27 | from decompile.constructs.while_loops import recognise_while_loops 28 | from decompile.disassemble import parse_absolute_index_from_elem_indic 29 | from decompile.boolean_conditions import handle_boolean_conditions 30 | 31 | def analyse_structures(asm_indexes, indexed_asm): 32 | next_asm_indexes = {} 33 | # compute a dict of next indexes in the sequence 34 | for i in range(len(asm_indexes)-1): 35 | index = asm_indexes[i] 36 | next_index = asm_indexes[i+1] 37 | next_asm_indexes[index] = next_index 38 | next_asm_indexes[next_index] = None 39 | for index in asm_indexes: 40 | next_index_in_sequence = next_asm_indexes[index] 41 | elem = indexed_asm[index] 42 | # by default next index is the next instruction 43 | elem['next_indexes'] = { NORMAL_FLOW: next_index_in_sequence } 44 | mnemo = elem['mnemo'] 45 | if mnemo == 'JUMP_FORWARD': 46 | # replace relative indexes by absolute ones 47 | elem['mnemo'] = 'JUMP_ABSOLUTE' 48 | elem['arg'] = None # for clarity 49 | elem['next_indexes'] = { NORMAL_FLOW: parse_absolute_index_from_elem_indic(elem) } 50 | elif mnemo == 'JUMP_ABSOLUTE': 51 | # set next index to the jump target 52 | elem['next_indexes'] = { NORMAL_FLOW: elem['arg'] } 53 | elif mnemo == 'LOAD_CONST' and elem['indic'].startswith('. 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from const import NO_CLAUSE, ANY_CLAUSE, FORWARD_CLAUSE, JUMP_CLAUSE 21 | 22 | def update_pop_clauses_of_conditional(elem, pop_condition, jump_clause, forward_clause): 23 | if pop_condition == NO_CLAUSE: 24 | pop_clauses = [] 25 | elif pop_condition == ANY_CLAUSE: 26 | pop_clauses = [ jump_clause, forward_clause ] 27 | elif pop_condition == FORWARD_CLAUSE: 28 | pop_clauses = [ forward_clause ] 29 | elif pop_condition == JUMP_CLAUSE: 30 | pop_clauses = [ jump_clause ] 31 | elem['pop_clauses'] = pop_clauses 32 | 33 | def update_next_indexes_of_conditional(elem, jump_clause, jump_index, 34 | forward_clause, forward_index): 35 | next_indexes = {} 36 | next_indexes[jump_clause] = jump_index 37 | next_indexes[forward_clause] = forward_index 38 | elem['next_indexes'] = next_indexes 39 | -------------------------------------------------------------------------------- /decompile/constructs/for_loops.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from const import NORMAL_FLOW, FOR_CLAUSE, END_OF_CONSTRUCT 21 | from decompile.disassemble import parse_absolute_index_from_indic 22 | 23 | def recognise_for_loops(asm_indexes, indexed_asm): 24 | last_mnemos = [] 25 | last_indics = [] 26 | last_indexes = [] 27 | detected_loops = [] 28 | for index in asm_indexes: 29 | elem = indexed_asm[index] 30 | last_mnemos.append(elem['mnemo']) 31 | last_mnemos = last_mnemos[-3:] 32 | last_indics.append(elem['indic']) 33 | last_indics = last_indics[-2:] 34 | last_indexes.append(index) 35 | last_indexes = last_indexes[-3:] 36 | if last_mnemos == [ 'GET_ITER', 'FOR_ITER', 'STORE_FAST' ]: 37 | detected_loops.append({ 38 | 'get_iter_index': last_indexes[-3], 39 | 'for_iter_index': last_indexes[-2], 40 | 'for_clause_index': elem['next_indexes'][NORMAL_FLOW], 41 | 'end_for_index': parse_absolute_index_from_indic( 42 | last_indics[-2]), 43 | 'var': last_indics[-1] 44 | }) 45 | for loop in detected_loops: 46 | get_iter_index = loop['get_iter_index'] 47 | for_iter_index = loop['for_iter_index'] 48 | indexed_asm[get_iter_index]['mnemo'] = 'PASS' 49 | next_indexes = {} 50 | next_indexes[FOR_CLAUSE] = loop['for_clause_index'] 51 | next_indexes[END_OF_CONSTRUCT] = loop['end_for_index'] 52 | for_elem = indexed_asm[for_iter_index] 53 | for_elem['next_indexes'] = next_indexes 54 | for_elem['var'] = loop['var'] 55 | for_elem['mnemo'] = 'FOR_LOOP' 56 | max_index = -1 57 | for elem in indexed_asm.values(): 58 | if elem['mnemo'] == 'JUMP_ABSOLUTE' and \ 59 | elem['next_indexes'][NORMAL_FLOW] == for_iter_index: 60 | elem['mnemo'] = 'CONTINUE' 61 | elem['next_indexes'] = {} 62 | if elem['index'] > max_index: 63 | max_index = elem['index'] 64 | 65 | 66 | -------------------------------------------------------------------------------- /decompile/constructs/if_constructs.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from const import IF_CLAUSE, ELSE_CLAUSE, CONDITIONAL_JUMPS_DESC 21 | from decompile.constructs.conditionals import update_next_indexes_of_conditional, \ 22 | update_pop_clauses_of_conditional 23 | from decompile.disassemble import parse_absolute_index_from_elem_indic 24 | 25 | IF_CONSTRUCT_CLAUSES = { True: IF_CLAUSE, False: ELSE_CLAUSE } 26 | 27 | def get_jump_index_of_conditional(elem, desc): 28 | # depending on the python version the jump 29 | # index may be given relative or absolute 30 | if desc['relative']: 31 | jump_index = parse_absolute_index_from_elem_indic(elem) 32 | else: 33 | jump_index = elem['arg'] 34 | return jump_index 35 | 36 | def get_if_jump_and_forward_clauses(jump_condition): 37 | forward_condition = not jump_condition 38 | jump_clause = IF_CONSTRUCT_CLAUSES[jump_condition] 39 | forward_clause = IF_CONSTRUCT_CLAUSES[forward_condition] 40 | return jump_clause, forward_clause 41 | 42 | def prepare_if_element(elem, mnemo, next_index_in_sequence): 43 | desc = CONDITIONAL_JUMPS_DESC[mnemo] 44 | jump_cond = desc['jump_cond'] 45 | elem['jump_cond'] = jump_cond # useful for while loops 46 | jump_clause, forward_clause = get_if_jump_and_forward_clauses(jump_cond) 47 | jump_index = get_jump_index_of_conditional(elem, desc) 48 | elem['jump_index'] = jump_index # useful for while loops 49 | forward_index = next_index_in_sequence 50 | pop_cond = desc['pop_cond'] 51 | elem['pop_cond'] = pop_cond # useful for while loops 52 | update_next_indexes_of_conditional(elem, 53 | jump_clause, jump_index, forward_clause, forward_index) 54 | update_pop_clauses_of_conditional(elem, pop_cond, jump_clause, forward_clause) 55 | elem['mnemo'] = 'IF_CONSTRUCT' 56 | elem['apply_conditions'] = [] 57 | elem['dup_cond'] = False 58 | -------------------------------------------------------------------------------- /decompile/constructs/try_constructs.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from const import EXCEPT_CLAUSE, TRY_CLAUSE, EXCEPT_EXPRESSION_CLAUSE 21 | from decompile.disassemble import parse_absolute_index_from_elem_indic 22 | 23 | def analyse_except_startup_code(elems, next_asm_indexes, except_index): 24 | # there are different kinds of startup clauses, 25 | # as shown in the following examples: 26 | # 'except:' 27 | # 'except Exception:' 28 | # 'except Exception, e:' 29 | # we analyse it here. 30 | # We also have to remove 3 (or 4) POP_TOP instructions. 31 | info = { 32 | 'except_expression_index': None, 33 | 'except_target': None 34 | } 35 | index = except_index 36 | pop_top_to_be_removed = 3 37 | while pop_top_to_be_removed > 0: 38 | elem = elems[index] 39 | next_index = next_asm_indexes[index] 40 | if elem['mnemo'] == 'DUP_TOP': 41 | info['except_expression_index'] = next_index 42 | pop_top_to_be_removed += 1 43 | elif elem['mnemo'] == 'COMPARE_OP': 44 | if elem['indic'] == 'exception match': 45 | elem['mnemo'] = 'END_OF_CLAUSE' 46 | elif elem['mnemo'] == 'STORE_FAST': 47 | info['except_target'] = elem['indic'] 48 | pop_top_to_be_removed -= 1 49 | elif elem['mnemo'] == 'POP_TOP': 50 | pop_top_to_be_removed -= 1 51 | index = next_index 52 | info['except_adapted_index'] = index 53 | return info 54 | 55 | def prepare_try_element(elems, next_asm_indexes, 56 | elem, next_index_in_sequence): 57 | elem['mnemo'] = 'TRY_CONSTRUCT' # update name for clarity 58 | next_indexes = {} 59 | except_index = parse_absolute_index_from_elem_indic(elem) 60 | except_info = analyse_except_startup_code( 61 | elems, next_asm_indexes, except_index) 62 | except_expr_index = except_info['except_expression_index'] 63 | if except_expr_index != None: 64 | next_indexes[EXCEPT_EXPRESSION_CLAUSE] = \ 65 | except_info['except_expression_index'] 66 | next_indexes[EXCEPT_CLAUSE] = except_info['except_adapted_index'] 67 | next_indexes[TRY_CLAUSE] = next_index_in_sequence 68 | elem['next_indexes'] = next_indexes 69 | elem['except_target'] = except_info['except_target'] 70 | elem['except_expression'] = None # if any, we don't know it yet anyway 71 | 72 | def format_except_statement(try_construct_elem): 73 | statement = "except" 74 | except_expression = try_construct_elem['except_expression'] 75 | except_target = try_construct_elem['except_target'] 76 | if except_expression != None: 77 | statement += ' ' + except_expression 78 | if except_target != None: 79 | statement += ', ' + except_target 80 | return statement + ":" 81 | -------------------------------------------------------------------------------- /decompile/constructs/while_loops.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from const import NORMAL_FLOW, END_OF_CONSTRUCT, WHILE_CLAUSE 21 | from decompile.constructs.conditionals import \ 22 | update_next_indexes_of_conditional, update_pop_clauses_of_conditional 23 | 24 | BEFORE_SETUP_LOOP = 0 25 | AFTER_SETUP_LOOP = 1 26 | 27 | def turn_if_to_while(elem, next_index_in_sequence): 28 | elem['mnemo'] = 'WHILE_LOOP' 29 | # we must also update the clauses describing this construct 30 | jump_clause, forward_clause = (END_OF_CONSTRUCT, WHILE_CLAUSE) 31 | pop_cond = elem['pop_cond'] 32 | forward_index = next_index_in_sequence 33 | jump_index = elem['jump_index'] 34 | update_next_indexes_of_conditional(elem, 35 | jump_clause, jump_index, forward_clause, forward_index) 36 | update_pop_clauses_of_conditional(elem, pop_cond, jump_clause, forward_clause) 37 | 38 | def recognise_while_loops(asm_indexes, indexed_asm): 39 | while_loop_indexes = [] 40 | state = BEFORE_SETUP_LOOP 41 | for i in range(len(asm_indexes)): 42 | index = asm_indexes[i] 43 | elem = indexed_asm[index] 44 | mnemo = elem['mnemo'] 45 | if state == BEFORE_SETUP_LOOP: 46 | if mnemo == 'SETUP_LOOP': 47 | state = AFTER_SETUP_LOOP 48 | loop_index = None 49 | else: 50 | if loop_index == None: 51 | loop_index = index # the index just after SETUP_LOOP 52 | if mnemo == 'FOR_LOOP': 53 | # this is actually a for loop, not while, give up 54 | state = BEFORE_SETUP_LOOP 55 | elif mnemo == 'IF_CONSTRUCT' and \ 56 | 'forced_index' not in elem: 57 | # this is actually a while loop! :) 58 | while_loop_indexes.append(loop_index) 59 | next_index_in_sequence = asm_indexes[i+1] 60 | turn_if_to_while(elem, next_index_in_sequence) 61 | state = BEFORE_SETUP_LOOP # done, look for next one 62 | for elem in indexed_asm.values(): 63 | if elem['mnemo'] == 'JUMP_ABSOLUTE' and \ 64 | elem['next_indexes'][NORMAL_FLOW] in while_loop_indexes: 65 | #print '#Changing a jump to %d into a "continue" instruction' % elem['next_indexes'][NORMAL_FLOW] 66 | elem['mnemo'] = 'CONTINUE' 67 | elem['next_indexes'] = {} 68 | 69 | 70 | -------------------------------------------------------------------------------- /decompile/decompilator.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from binary_ops import manage_binary_op 21 | from const import PARTIAL_STATEMENT, BRANCH_IS_OPTIONAL, COMPLETE_STATEMENT, \ 22 | ELSE_CLAUSE, TRY_CLAUSE, FINALLY_CLAUSE, IF_CLAUSE, FOR_CLAUSE, EXCEPT_CLAUSE, \ 23 | EXCEPT_EXPRESSION_CLAUSE, WHILE_CLAUSE 24 | from decompile.boolean_conditions import OR_CONDITION 25 | from decompile.branch_info import BranchDecompilationInfo 26 | from decompile.constructs.try_constructs import format_except_statement 27 | from decompile.embedded_functions import pack_function_object 28 | from decompile.unary_ops import manage_unary_op 29 | from tree_traversal import TreeTraversal 30 | import decompile.embedded_functions 31 | 32 | # only when static, see below 33 | BRANCH_PRELIMINARY_STATEMENT = { 34 | ELSE_CLAUSE: "else:", 35 | TRY_CLAUSE: "try:", 36 | FINALLY_CLAUSE: "finally:", 37 | EXCEPT_EXPRESSION_CLAUSE: None 38 | } 39 | 40 | class Decompilator(TreeTraversal): 41 | def __init__(self, elems, func_code, known_globals): 42 | TreeTraversal.__init__(self, elems) 43 | self.func_code = func_code 44 | self.known_globals = known_globals 45 | self.bypass_next = False 46 | 47 | def build_compound_object(self, info, size, start_char, end_char): 48 | objs = [] 49 | for _ in range(size): 50 | objs.insert(0, info.pop()) 51 | info.push(start_char + ', '.join(objs) + end_char, PARTIAL_STATEMENT) 52 | 53 | def pop_condition_if_needed(self, branch_info, construct_elem, branch_type): 54 | pop_clauses = construct_elem['pop_clauses'] 55 | if branch_type in pop_clauses: 56 | branch_info.pop() 57 | 58 | def unpack_sequence(self, info, num): 59 | sequence_statement = info.pop(); 60 | variables = [ 'item' + str(i) for i in range(num) ] 61 | info.push(', '.join(variables) + ' = ' + sequence_statement, 62 | COMPLETE_STATEMENT) 63 | variables.reverse() 64 | for var in variables: 65 | info.push(var, PARTIAL_STATEMENT) 66 | 67 | def get_branch_preliminary_statement(self, construct_elem, branch_type, info): 68 | statement = None 69 | if branch_type == IF_CLAUSE: 70 | # keep condition on the stack for now 71 | # but ensure that it is flagged as a PARTIAL_STATEMENT. 72 | # Otherwise, if it was a CANDIDATE_STATEMENT, 73 | # and a POP_TOP instruction follows, 74 | # we would validate this statement although the condition 75 | # has already been taken into account in this 'if' statement. 76 | condition = info.pop() 77 | info.push(condition, PARTIAL_STATEMENT) 78 | statement = 'if ' + condition + ':' 79 | elif branch_type == FOR_CLAUSE: 80 | statement = 'for ' + construct_elem['var'] + \ 81 | ' in ' + info.pop() + ':' 82 | elif branch_type == EXCEPT_CLAUSE: 83 | statement = format_except_statement(construct_elem) 84 | elif branch_type == WHILE_CLAUSE: 85 | jump_cond = construct_elem['jump_cond'] 86 | condition = info.top() # keep condition on the stack for now 87 | if jump_cond == True: 88 | # we leave the loop when the condition is True, then... 89 | statement = 'while not (' + condition + '):' 90 | else: 91 | # we leave the loop when the condition is False, then... 92 | statement = 'while ' + condition + ':' 93 | else: 94 | statement = BRANCH_PRELIMINARY_STATEMENT[branch_type] 95 | return statement 96 | 97 | def handle_new_branch_traversed(self, branch_type, jump_index, branch_start_index, info): 98 | construct_elem = self.elems[jump_index] 99 | preliminary_statement = self.get_branch_preliminary_statement( 100 | construct_elem, branch_type, info) 101 | if (preliminary_statement != None): 102 | preliminary_statement = (info.get_indent(), preliminary_statement) 103 | new_info = BranchDecompilationInfo( 104 | info.get_indent()+1, 105 | stack=info.get_stack()[:], # copy 106 | optional_bloc=BRANCH_IS_OPTIONAL[branch_type], 107 | preliminary_statement=preliminary_statement 108 | ) 109 | mnemo = construct_elem['mnemo'] 110 | if mnemo in [ 'IF_CONSTRUCT', 'WHILE_LOOP' ]: 111 | self.pop_condition_if_needed(new_info, self.elems[jump_index], branch_type) 112 | return new_info 113 | 114 | def handle_end_of_child_branch(self, branch_type, jump_index, 115 | child_branch_info, parent_branch_info): 116 | if branch_type == EXCEPT_EXPRESSION_CLAUSE: 117 | try_elem = self.elems[jump_index] 118 | try_elem['except_expression'] = child_branch_info.pop() 119 | else: 120 | child_statements = child_branch_info.retrieve_statements() 121 | parent_branch_info.append_bloc_of_statements(child_statements) 122 | child_global_variables = child_branch_info.retrieve_global_variables() 123 | parent_branch_info.append_global_variables(child_global_variables) 124 | 125 | def comment(self, elem): 126 | return ' # ' + str(elem['index']) 127 | 128 | def handle_traversed_element(self, elem, info): 129 | #print "handle_traversed_element(), elem =", elem 130 | mnemo = elem['mnemo'] 131 | indic = elem['indic'] 132 | arg = elem['arg'] 133 | if elem['decompiled']: 134 | info.warning('bytecode traversed several times') 135 | else: 136 | elem['decompiled'] = True # record that we passed through this 137 | if self.bypass_next: 138 | # bypass this element and 139 | # reset the variable to False for the next one. 140 | self.bypass_next = False 141 | elif mnemo in [ 'LOAD_FAST', 'LOAD_GLOBAL', 'LOAD_CONST' ]: 142 | info.record_loading_of_variable(self.known_globals, mnemo, indic) 143 | info.push(indic, PARTIAL_STATEMENT) 144 | elif mnemo == 'LOAD_CONST_CODE': 145 | code_object = self.func_code.co_consts[arg] 146 | info.push(code_object, PARTIAL_STATEMENT) 147 | elif mnemo == 'MAKE_FUNCTION': 148 | pack_function_object(info, arg) 149 | elif mnemo in [ 'STORE_FAST', 'STORE_GLOBAL' ]: 150 | variable = indic 151 | value = info.pop() 152 | if type(value).__name__ != 'str': 153 | # this is supposedly an embedded function object 154 | decompile.embedded_functions.format_embedded_function( 155 | self.known_globals, variable, value, info) 156 | else: 157 | statement = variable + " = " + value 158 | info.push(statement, COMPLETE_STATEMENT) 159 | elif mnemo == 'UNPACK_SEQUENCE': 160 | self.unpack_sequence(info, arg) 161 | elif mnemo == 'LOAD_ATTR': 162 | s = info.pop() 163 | s += "." + indic 164 | info.push(s, PARTIAL_STATEMENT) 165 | elif mnemo == 'BUILD_MAP': # create a dictionary object 166 | info.push('{}', PARTIAL_STATEMENT) 167 | elif mnemo == 'STORE_ATTR': 168 | obj = info.pop() 169 | value = info.pop() 170 | statement = obj + "." + indic + " = " + value 171 | info.push(statement, COMPLETE_STATEMENT) 172 | elif mnemo == 'POP_TOP': 173 | info.delete_top() 174 | elif mnemo == 'DUP_TOP': 175 | info.dup_top() 176 | elif mnemo.startswith('ROT_'): 177 | info.rotate(mnemo) 178 | elif mnemo.startswith('CALL_FUNCTION'): 179 | info.function_call(mnemo, arg) 180 | elif mnemo == 'SLICE+0': 181 | obj = info.pop() 182 | info.push(obj + '[:]', PARTIAL_STATEMENT) 183 | elif mnemo == 'SLICE+1': 184 | sl = info.pop() 185 | obj = info.pop() 186 | info.push(obj + '[' + sl + ':]', PARTIAL_STATEMENT) 187 | elif mnemo == 'SLICE+2': 188 | sl = info.pop() 189 | obj = info.pop() 190 | info.push(obj + '[:' + sl + ']', PARTIAL_STATEMENT) 191 | elif mnemo == 'SLICE+3': 192 | sl_end = info.pop() 193 | sl_start = info.pop() 194 | obj = info.pop() 195 | info.push(obj + '[' + sl_start + ':' + sl_end + ']', PARTIAL_STATEMENT) 196 | elif mnemo == 'COMPARE_OP': 197 | obj2 = info.pop() 198 | obj1 = info.pop() 199 | info.push(obj1 + ' ' + indic + ' ' + obj2, PARTIAL_STATEMENT) 200 | elif mnemo == 'BUILD_TUPLE': 201 | size = arg 202 | if size == 1: 203 | # special case of tuples with 1 element 204 | info.push('(' + info.pop() + ',)', PARTIAL_STATEMENT) 205 | else: 206 | self.build_compound_object(info, size, '(', ')') 207 | elif mnemo == 'BUILD_LIST': 208 | self.build_compound_object(info, arg, '[', ']') 209 | elif mnemo == 'JUMP_ABSOLUTE': # nothing to do, next_index is already aware about the jump 210 | pass 211 | elif mnemo == 'RETURN_VALUE': 212 | value = info.pop() 213 | info.push('return ' + value, COMPLETE_STATEMENT) 214 | # next_indexes is empty, so it will stop below 215 | elif mnemo == 'YIELD_VALUE': 216 | value = info.pop() 217 | info.push(value, COMPLETE_STATEMENT) 218 | # next_indexes is empty, so it will stop below 219 | elif mnemo.startswith('BINARY_') or \ 220 | mnemo.startswith('INPLACE_'): 221 | manage_binary_op(mnemo, info) 222 | elif mnemo.startswith('UNARY_'): 223 | manage_unary_op(mnemo, info) 224 | elif mnemo == 'STORE_SUBSCR': 225 | TOS = info.pop() 226 | TOS1 = info.pop() 227 | TOS2 = info.pop() 228 | info.push(TOS1 + '[' + TOS + '] = ' + TOS2, COMPLETE_STATEMENT) 229 | elif mnemo == 'STORE_MAP': 230 | # add a key-value pair in a dictionary 231 | key = info.pop() 232 | value = info.pop() 233 | d = info.pop() 234 | element = key + ': ' + value 235 | if d == '{}': 236 | info.push('{ ' + element + ' }', PARTIAL_STATEMENT) 237 | else: 238 | # d[:-1] will remove the ending '}' 239 | info.push(d[:-1] + ', ' + element + ' }', PARTIAL_STATEMENT) 240 | elif mnemo == 'PRINT_ITEM': 241 | TOS = info.pop() 242 | info.push('print ' + TOS + ',', COMPLETE_STATEMENT) 243 | elif mnemo == 'PRINT_NEWLINE': 244 | info.push('print', COMPLETE_STATEMENT) 245 | elif mnemo == 'RAISE_VARARGS': 246 | raise_args = [] 247 | for _ in range(arg): 248 | raise_args.append(info.pop()) 249 | statement = 'raise ' + ', '.join(raise_args) 250 | info.push(statement, COMPLETE_STATEMENT) 251 | elif mnemo == 'BREAK_LOOP': 252 | info.push('break', COMPLETE_STATEMENT) 253 | elif mnemo == 'CONTINUE': 254 | info.push('continue', COMPLETE_STATEMENT) 255 | elif mnemo == 'GET_ITER': 256 | # we consider it is a list comprehension 257 | # (other uses not handled yet) 258 | decompile.embedded_functions.handle_list_comprehension( 259 | self.known_globals, info) 260 | # bypass the following 'CALL_FUNCTION' instruction, 261 | # we handled everything here 262 | self.bypass_next = True 263 | elif mnemo in [ 'IF_CONSTRUCT', 'WHILE_LOOP' ]: 264 | condition = info.pop() 265 | for cond_type in elem['apply_conditions']: 266 | if cond_type == OR_CONDITION: 267 | bool_op = ' or ' 268 | else: 269 | bool_op = ' and ' 270 | condition = '(' + info.pop() + bool_op + condition + ')' 271 | info.push(condition, PARTIAL_STATEMENT) 272 | if elem['dup_cond']: 273 | info.push(condition, PARTIAL_STATEMENT) 274 | elif mnemo in [ 'SETUP_LOOP', 'POP_BLOCK', 'PASS', 275 | 'TRY_CONSTRUCT', 'FOR_LOOP', 'WHILE_LOOP', 276 | 'END_OF_CLAUSE' ]: 277 | pass 278 | else: 279 | info.print_stack() 280 | raise Exception("Unknown instruction %s. Sorry." % mnemo) 281 | -------------------------------------------------------------------------------- /decompile/disassemble.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from tools.out_saver import out_saver 21 | import dis 22 | import re 23 | 24 | def disassemble(code_object): 25 | saver = out_saver() 26 | saver.start() 27 | dis.disassemble(code_object) 28 | s = saver.stop() 29 | return s 30 | 31 | def disassemble_code(func_code): 32 | asm_indexes = [] 33 | indexed_asm = {} 34 | elem = None 35 | for line in disassemble(func_code).splitlines(): 36 | #print line 37 | if len(line.strip()) > 0: 38 | elem = parse_bytecode_line(line) 39 | index = elem['index'] 40 | asm_indexes.append(index) 41 | indexed_asm[index] = elem 42 | return asm_indexes, indexed_asm 43 | 44 | def parse_absolute_index_from_elem_indic(elem): 45 | return parse_absolute_index_from_indic(elem['indic']) 46 | 47 | def parse_absolute_index_from_indic(indic): 48 | return int(indic.split()[1]) 49 | 50 | def parse_bytecode_line(line): 51 | m = re.match('.* ([0-9]+ \w.*)', line) 52 | interesting_part = m.group(1) 53 | words = interesting_part.split() 54 | index, mnemo = words[:2] 55 | arg = None 56 | indic = None 57 | if len(words) > 2: 58 | arg = int(words[2]) 59 | m = re.match('[^(]*\((.*)\)$', interesting_part) 60 | if m is not None: 61 | indic = m.group(1) 62 | return { 'mnemo' : mnemo, 63 | 'arg' : arg, 64 | 'indic': indic, 65 | 'index': int(index), 66 | 'decompiled': False # for now 67 | } 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /decompile/embedded_functions.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from const import CANDIDATE_STATEMENT, PARTIAL_STATEMENT 21 | from decompile.constructs import analyse_structures 22 | from decompile.disassemble import disassemble_code 23 | from tools import print_code_line, print_code 24 | import decompile.bloc 25 | import inspect 26 | 27 | def pack_function_object(info, num_default_values): 28 | code_object = info.pop() 29 | default_values = [] 30 | for _ in range(num_default_values): 31 | default_values.insert(0, info.pop()) 32 | args, varargs, varkw = inspect.getargs(code_object) 33 | specs = [] 34 | firstdefault = len(args) - len(default_values) 35 | #print args 36 | for i in range(len(args)): 37 | spec = str(args[i]) 38 | if i >= firstdefault: 39 | spec = spec + '=' + default_values[i - firstdefault] 40 | specs.append(spec) 41 | if varargs is not None: 42 | specs.append('*' + varargs) 43 | if varkw is not None: 44 | specs.append('**' + varkw) 45 | #print specs 46 | args_string = ', '.join(specs) 47 | info.push({ 'code': code_object, 'args_string': args_string }, 48 | PARTIAL_STATEMENT) 49 | 50 | #def analyse_lambda_expression_code(lambda_code): 51 | # asm_indexes, indexed_asm = disassemble_code(lambda_code) 52 | # asm_indexes, indexed_asm = analyse_structures(asm_indexes, indexed_asm) 53 | # statements = decompile.bloc.decompile_bloc( 54 | # indexed_asm, lambda_code, index=asm_indexes[0], indent=0) 55 | # #print 'statements:', statements 56 | # expr_code = statements[0][1] # first statement, code part (first part is indent) 57 | # return expr_code 58 | 59 | def analyse_generator_code(known_globals, generator_code): 60 | asm_indexes, indexed_asm = disassemble_code(generator_code) 61 | for i in range(len(asm_indexes)): 62 | index = asm_indexes[i] 63 | elem = indexed_asm[index] 64 | if elem['mnemo'] == 'STORE_FAST': 65 | variable_name = elem['indic'] 66 | expr_start = i+1 67 | break 68 | asm_indexes = asm_indexes[expr_start:] 69 | asm_indexes, indexed_asm = analyse_structures(asm_indexes, indexed_asm) 70 | statements = decompile.bloc.decompile_bloc( 71 | indexed_asm, generator_code, known_globals, index=asm_indexes[0], indent=0) 72 | #print 'statements:', statements 73 | expr_code = statements[0][1] # first statement, code part (first part is indent) 74 | return expr_code, variable_name 75 | 76 | def format_embedded_function(known_globals, func_name, func_object, info): 77 | indent = info.get_indent() 78 | info.add_statement('def %s(%s):' % (func_name, func_object['args_string'])) 79 | info.append_bloc_of_statements( 80 | decompile.decompile_func_body(func_object['code'], known_globals, indent+1)) 81 | 82 | def handle_list_comprehension(known_globals, info): 83 | set_of_values_expr = info.pop() 84 | function_object = info.pop() 85 | generator_code = function_object['code'] 86 | expression, variable_name = analyse_generator_code(known_globals, generator_code) 87 | info.push(expression + ' for ' + variable_name + ' in ' + 88 | set_of_values_expr, CANDIDATE_STATEMENT) 89 | 90 | -------------------------------------------------------------------------------- /decompile/tree_traversal.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | 21 | from const import NORMAL_FLOW, END_OF_CONSTRUCT 22 | 23 | class TreeTraversal(object): 24 | def __init__(self, elems): 25 | self.elems = elems 26 | self.previous_element = None 27 | def get_previous_elem(self): 28 | return self.previous_element 29 | def handle_traversed_element(self, elem, data): 30 | pass # override in subclass if needed 31 | def handle_new_branch_traversed(self, branch_type, jump_index, branch_start_index, parent_branch_data): 32 | return parent_branch_data # override in subclass if needed 33 | def handle_end_of_child_branch(self, branch_type, jump_index, child_branch_data, parent_branch_data): 34 | pass # override in subclass if needed 35 | def traverse(self, index=0, data={}, previous_elem=None): 36 | self.previous_element = previous_elem 37 | while True: 38 | elem = self.elems[index] 39 | #print '#traversing element ' + str(index), elem 40 | should_continue = self.handle_traversed_element(elem, data) 41 | if should_continue == False: 42 | break 43 | curr_index = elem['index'] 44 | next_indexes = elem['next_indexes'] 45 | self.previous_element = elem # if we do not break the loop below 46 | if 'forced_index' in elem: 47 | index = elem['forced_index'] 48 | elif len(next_indexes) == 0: 49 | break # end of a branch 50 | elif NORMAL_FLOW in next_indexes: 51 | index = next_indexes[NORMAL_FLOW] # continue with next instruction 52 | else: 53 | should_continue = False 54 | for branch_type in sorted(next_indexes): 55 | if branch_type == END_OF_CONSTRUCT: 56 | should_continue = True 57 | break 58 | branch_start_index = next_indexes[branch_type] 59 | new_data = self.handle_new_branch_traversed( 60 | branch_type, curr_index, 61 | branch_start_index, data) 62 | self.traverse(index=branch_start_index, data=new_data, 63 | previous_elem=elem) 64 | self.handle_end_of_child_branch( 65 | branch_type, curr_index, new_data, data) 66 | if should_continue: 67 | index = next_indexes[END_OF_CONSTRUCT] 68 | else: 69 | break # no more code after this construct 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /decompile/unary_ops.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from const import PARTIAL_STATEMENT 21 | 22 | UNARY_OPS = { 23 | 'POSITIVE': '+', 24 | 'NEGATIVE': '-', 25 | 'NOT': 'not ', 26 | 'CONVERT': '', 27 | 'INVERT': '~', 28 | } 29 | 30 | def manage_unary_op(mnemo, info): 31 | after_underscore = mnemo.partition('_')[2] 32 | TOS = info.pop() 33 | if after_underscore == 'CONVERT': 34 | full_op = '`' + TOS + '`' 35 | else: 36 | full_op = UNARY_OPS[after_underscore] + TOS 37 | info.push('(' + full_op + ')', PARTIAL_STATEMENT) 38 | 39 | 40 | -------------------------------------------------------------------------------- /inspection/__init__.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | -------------------------------------------------------------------------------- /inspection/classes.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from inspection.data import get_data 21 | from inspection.functions import show_function 22 | from tools import print_doc_string, print_code_line 23 | import inspect 24 | 25 | def show_class(class_name, cls, known_globals): 26 | base_names = [] 27 | for base in cls.__bases__: 28 | baseclass_fullname = str(base).split("'")[1] 29 | baseclass_name = baseclass_fullname.split('.')[-1] 30 | base_names.append(baseclass_name) 31 | print 'class %s(%s):' % (class_name, ', '.join(base_names)) 32 | print_doc_string(1, cls) 33 | # retrieve class attributes 34 | for name, value in get_data(cls): 35 | print_code_line(1, name + ' = ' + repr(value)) 36 | # retrieve methods 37 | for class_attr in inspect.classify_class_attrs(cls): 38 | #print '#', class_attr 39 | name, kind, owner_cls, attr = class_attr 40 | # a method may be inherited from a parent class 41 | # we want to only print methods defined in this 42 | # object. 43 | # also we only print methods. 44 | if owner_cls == cls and kind != 'data': 45 | show_function(name, attr, known_globals, indent=1) 46 | print 47 | # print class_name, name 48 | # if class_name.startswith('rs232') and name == 'reset': 49 | print 50 | 51 | -------------------------------------------------------------------------------- /inspection/data.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | import inspect 21 | 22 | def isdata(attr): 23 | """Check if an object is of a type that probably means it's data.""" 24 | return not (inspect.ismodule(attr) or inspect.isclass(attr) or 25 | inspect.isroutine(attr) or inspect.isframe(attr) or 26 | inspect.istraceback(attr) or inspect.iscode(attr)) 27 | 28 | def visiblename(name): 29 | """Decide whether to show a data variable.""" 30 | _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__', 31 | '__module__', '__name__', '__slots__', '__package__', 32 | '__dict__', '__weakref__') 33 | return not name in _hidden_names 34 | 35 | def can_be_evaluated(value): 36 | """Check if the textual representation of this value 37 | can be re-read.""" 38 | try: 39 | eval(repr(value)) 40 | except: 41 | return False 42 | return True 43 | 44 | def get_data(obj): 45 | """Retrieve internal data attributes of an object.""" 46 | data = [] 47 | for key, value in inspect.getmembers(obj, isdata): 48 | if visiblename(key): 49 | if not can_be_evaluated(value): 50 | value = None 51 | data.append((key, value)) 52 | return data 53 | -------------------------------------------------------------------------------- /inspection/functions.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from decompile import decompile_func_body 21 | from tools import print_doc_string, print_code, print_code_line 22 | import inspect 23 | 24 | def show_function(func_name, func, known_globals, indent=0): 25 | f_args = inspect.getargspec(func) 26 | func_args = inspect.formatargspec(f_args.args, f_args.varargs, f_args.keywords, f_args.defaults) 27 | print_code_line(indent, 'def %s%s:' % (func_name, func_args)) 28 | print_doc_string(indent+1, func) 29 | print_code(decompile_func_body(func.func_code, known_globals, indent+1)) 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /inspection/modules.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | from inspection.classes import show_class 21 | from inspection.functions import show_function 22 | from inspection.data import get_data 23 | import inspect 24 | 25 | def is_imported_obj(mod, obj): 26 | obj_mod = inspect.getmodule(obj) 27 | return (inspect.isroutine(obj) or inspect.isclass(obj)) and \ 28 | obj_mod != mod and \ 29 | obj_mod.__name__ != '__builtin__' 30 | 31 | def show_module(mod): 32 | 33 | for key, value in inspect.getmembers(mod, inspect.ismodule): 34 | print 'import ' + key 35 | for key, value in inspect.getmembers(mod, 36 | lambda obj: is_imported_obj(mod, obj)): 37 | print 'from ' + value.__module__ + ' import ' + key 38 | 39 | print 40 | known_globals = set([]) 41 | for name, value in get_data(mod): 42 | print name, '=', repr(value) 43 | known_globals.add(name) 44 | 45 | print 46 | 47 | for key, value in inspect.getmembers(mod, inspect.isclass): 48 | if inspect.getmodule(value) == mod: 49 | show_class(key, value, known_globals) 50 | 51 | print 52 | 53 | for key, value in inspect.getmembers(mod, inspect.isfunction): 54 | if inspect.getmodule(value) == mod: 55 | show_function(key, value, known_globals) 56 | print 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | 3 | # pyc2py - The smart python decompiler. 4 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 5 | # 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | # 19 | # Developper: Etienne Duble 20 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 21 | 22 | 23 | from inspection.modules import show_module 24 | import os 25 | import sys 26 | 27 | def usage(): 28 | print "Usage:", sys.argv[0], '' 29 | 30 | if len(sys.argv) < 2: 31 | usage() 32 | sys.exit(1) 33 | 34 | file_path = sys.argv[1] 35 | module_dir = os.path.dirname(file_path) 36 | if module_dir != '': 37 | sys.path.append(module_dir) 38 | module_name, ext = os.path.splitext(os.path.basename(file_path)) 39 | mod = __import__(module_name) 40 | 41 | show_module(mod) 42 | 43 | -------------------------------------------------------------------------------- /tools/__init__.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | 21 | def print_doc_string(indent, obj): 22 | doc_string = obj.__doc__ 23 | if doc_string: 24 | lines = doc_string.splitlines() 25 | if len(lines) < 2: 26 | print_code_line(indent, '"""' + doc_string + '"""') 27 | else: 28 | print_code_line(indent, '"""') 29 | for line in lines: 30 | print_code_line(indent, line) 31 | print_code_line(indent, '"""') 32 | 33 | def print_code(statements): 34 | for statement in statements: 35 | indent, text = statement 36 | space = ('%' + str(2*indent) + 's') % '' 37 | print '%s%s' % (space, text) 38 | 39 | def print_code_line(indent, statement): 40 | print_code([(indent, statement)]) 41 | -------------------------------------------------------------------------------- /tools/out_saver.py: -------------------------------------------------------------------------------- 1 | # pyc2py - The smart python decompiler. 2 | # Copyright (C) 2012 Centre National de la Recherche Scientifique 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | # 17 | # Developper: Etienne Duble 18 | # Contact me at: etienne _dot_ duble _at_ imag _dot_ fr 19 | 20 | 21 | import sys 22 | 23 | class out_saver: 24 | def __init__(self): 25 | self.saved_stdout = sys.stdout 26 | def write(self, text): 27 | self.s += text 28 | def retrieve(self): 29 | return self.s 30 | def start(self): 31 | self.s = "" 32 | sys.stdout = self 33 | def stop(self): 34 | sys.stdout = self.saved_stdout 35 | return self.s 36 | 37 | 38 | --------------------------------------------------------------------------------