├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── Makefile ├── README.md ├── client ├── __init__.py ├── editorwidget.py ├── hexeditor.py └── mainwindow.py ├── docs ├── Makefile ├── api.rst ├── branching.md ├── bug_template.txt ├── conf.py ├── dev │ ├── branching.md │ ├── documenting_code.md │ ├── env_setup.md │ ├── getting_started.md │ ├── life_of_a_bug.md │ ├── life_of_a_feature.md │ └── styleguide.md ├── file.rst ├── index.rst ├── make.bat └── project.rst ├── pylintrc ├── pytest.ini ├── qspade ├── setup.cfg ├── setup.py ├── spade ├── __init__.py ├── core │ ├── __init__.py │ ├── file.py │ ├── models │ │ ├── __init__.py │ │ └── project.py │ └── project.py └── typesystem │ ├── __init__.py │ ├── manager.py │ ├── typedef.py │ └── types │ ├── __init__.py │ ├── byte.py │ ├── char.py │ ├── int32.py │ └── uint32.py └── tests ├── __init__.py ├── core ├── fixtures.py ├── test_file.py ├── test_project.py └── testdata │ ├── testfile1 │ └── testfile2 ├── typesystem ├── __init__.py ├── fixtures.py ├── test_byte.py ├── test_char.py ├── test_int32.py ├── test_manager.py └── test_uint32.py └── utils ├── __init__.py └── project_sql.py /.gitignore: -------------------------------------------------------------------------------- 1 | venv/ 2 | build/ 3 | dist/ 4 | docs/.build 5 | spade.egg-info 6 | .cache 7 | .eggs/ 8 | *__pycache__ 9 | tests/testdb.sdb 10 | .coverage 11 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | Spade welcomes all kinds from contributions from anyone who wants to 3 | contribute their skill and vision to the tool. This file serves as a guide 4 | intended to help you figure out how and what to contribute to spade. 5 | 6 | ## How do I get started? 7 | If you haven't worked on this project, the following docs should help. 8 | * [Getting Started][1], some notes on getting started. 9 | * [Setting Up the Environment][2], so you can run spade's code locally. 10 | * [Documenting code][3], useful to understand how to read docs. 11 | 12 | ## I want to contribute... 13 | 14 | ### ...A bug (report/fix) 15 | Since the project is still pretty small and our bug tracker isn't swamped with 16 | useless crap, feel free to submit any issue you have experienced with spade or 17 | any problems you've had with it. Check out the following docs for more info: 18 | * [Life of a Bug][5]. 19 | 20 | ### ...A feature 21 | We define a feature as any code addition or modification intended to add or 22 | improve functionality. A feature is meant to be a discrete unit of change; try 23 | to isolate separate components into their own features as much as possible. 24 | The following documentation should be useful in getting up to speed with 25 | contributing a feature: 26 | * [Life of a Feature][6]. 27 | 28 | ### ...A documentation 29 | If you feel documentation is lacking for a particular aspect of spade or feel 30 | that some insight you've had might be benifical to the community, feel free to 31 | submit documentation. The following might be helpful: 32 | * [Documenting code][4]. 33 | 34 | [1]: docs/dev/getting_started.md 35 | [2]: docs/dev/env_setup.md 36 | [3]: docs/dev/styleguide.md 37 | [4]: docs/dev/documenting_code.md 38 | [5]: docs/dev/life_of_a_bug.md 39 | [6]: docs/dev/life_of_a_feature.md 40 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nyxxxie/serenity/429cd9dbea77d63e624b9b738668848208176a22/Makefile -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spade 2 | Spade is an editor and reverse engineering tool that operates directly on opaque 3 | file-resident binary data. Unlike other tools, Spade allows you to interact 4 | with targets at the [file-format][1] level, meaning you can work on familar 5 | formats (ELF, PE, etc) with the same ease as exotic and/or obfuscated formats. 6 | Spade makes no assumptions about what kind of file you're working on, everything 7 | is definable and modifiable by the user. 8 | 9 | ## Installing 10 | Spade is currently not production ready, so it is not advised that 11 | non-developers attempt to install. Check out progress to v1 [here][2] 12 | 13 | ## Contributing 14 | See [contributing docs][3] for more info. 15 | 16 | [1]: https://en.wikipedia.org/wiki/File_format 17 | [2]: https://github.com/nyxxxie/spade/milestone/1 18 | [3]: CONTRIBUTING.md 19 | -------------------------------------------------------------------------------- /client/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nyxxxie/serenity/429cd9dbea77d63e624b9b738668848208176a22/client/__init__.py -------------------------------------------------------------------------------- /client/editorwidget.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QTabWidget 2 | from client.hexeditor import HexEditor 3 | 4 | class EditorWidget(QTabWidget): 5 | """Container widget for editors.""" 6 | 7 | def __init__(self): 8 | super().__init__() 9 | self._add_hexeditor() 10 | 11 | def _add_hexeditor(self): 12 | hexedit = HexEditor() 13 | self.addTab(hexedit, "Hex Editor") 14 | -------------------------------------------------------------------------------- /client/hexeditor.py: -------------------------------------------------------------------------------- 1 | import os 2 | from math import log 3 | from PyQt5.QtWidgets import QAbstractScrollArea 4 | from PyQt5.QtCore import Qt, QRect 5 | from PyQt5.QtGui import QPainter, QFont, QFontMetrics, QColor 6 | 7 | COLUMN_GAP=6 8 | TEXT_OFFSET=4 9 | ROW_OFFSET=0 10 | BYTE_GAP=4 11 | BYTES_PER_ROW=16 12 | 13 | # TODO: delete this when SFile is integrated into the hex editor 14 | def get_file_size(f): 15 | old_pos = f.tell() 16 | f.seek(0, os.SEEK_END) 17 | size = f.tell() 18 | f.seek(old_pos, os.SEEK_SET) 19 | return size 20 | 21 | 22 | class HexEditorColumn(object): 23 | """Abstract class that defines the basis for a column in the hex editor.""" 24 | 25 | def __init__(self, hexeditor): 26 | self.hexeditor = hexeditor 27 | self.width = 0 28 | 29 | def render(self, start, paint): 30 | pass 31 | 32 | def cursor(self): 33 | return self.hexeditor.cursor 34 | 35 | def rows(self): 36 | return self.hexeditor.rows_total 37 | 38 | def rows_visible(self): 39 | return self.hexeditor.rows_shown 40 | 41 | def row_start(self): 42 | return self.hexeditor.cursor 43 | 44 | def viewport(self): 45 | return self.hexeditor.viewport() 46 | 47 | def font_width(self): 48 | return self.hexeditor.font_width 49 | 50 | def font_height(self): 51 | return self.hexeditor.font_height 52 | 53 | def file(self): 54 | return self.hexeditor.file 55 | 56 | def file_size(self): 57 | return get_file_size(self.hexeditor.file) 58 | 59 | 60 | class AddressColumn(HexEditorColumn): 61 | """Hex editor column that displays the address each line starts on.""" 62 | 63 | def render(self, start, paint): 64 | # If this isn't the first column rendered, space ourselves out from the 65 | # previous column 66 | if start: 67 | start += COLUMN_GAP 68 | 69 | # Calc width of the address bar 70 | fsize = self.file_size() 71 | byte_num = int(log(fsize, 0xff)) + 1 if fsize != 0 else 1 72 | if byte_num < 4: 73 | byte_num = 4 # byte num should at least be 4 74 | width = ((byte_num+1)*self.font_width()) + (2*TEXT_OFFSET) 75 | 76 | # Draw bar 77 | paint.fillRect( 78 | QRect(start, 0, width, self.viewport().height()), 79 | QColor(255, 0, 0)) 80 | 81 | # Draw addresses 82 | start += TEXT_OFFSET 83 | for row in range(1, self.rows_visible()): 84 | addr = (row + self.row_start() - 1) * BYTES_PER_ROW 85 | paint.drawText(start, 86 | row*(ROW_OFFSET + self.font_height()*2), 87 | ("%x" % addr).zfill(byte_num) + "h") 88 | 89 | # Let caller know how much space we took up while drawing 90 | return start + width 91 | 92 | 93 | class HexColumn(HexEditorColumn): 94 | """Hex editor column that displays hex-formatted data.""" 95 | 96 | def render(self, start, paint): 97 | # If this isn't the first column rendered, space ourselves out from the 98 | # previous column 99 | if start: 100 | start += COLUMN_GAP 101 | 102 | # Calc width of the address bar 103 | width = BYTES_PER_ROW * (2*self.font_width()) 104 | width += (BYTES_PER_ROW-1) * BYTE_GAP 105 | width += (2 * TEXT_OFFSET) 106 | 107 | # Draw bar 108 | paint.fillRect( 109 | QRect(start, 0, width, self.viewport().height()), 110 | QColor(0, 255, 0)) 111 | 112 | # Draw hex 113 | start += TEXT_OFFSET 114 | old_pos = self.file().tell() 115 | self.file().seek(self.row_start() * BYTES_PER_ROW, os.SEEK_SET) 116 | 117 | for row in range(1, self.rows_visible()): 118 | data = self.file().read(BYTES_PER_ROW) 119 | for i, byte in enumerate(data): 120 | paint.drawText(start+i*(BYTE_GAP+self.font_width()*2), 121 | row*(ROW_OFFSET + self.font_height()*2), 122 | "%02x " % byte) 123 | 124 | self.file().seek(old_pos, os.SEEK_SET) 125 | 126 | # Let caller know how much space we took up while drawing 127 | return start + width 128 | 129 | 130 | class AsciiColumn(HexEditorColumn): 131 | """Hex editor column that displays ascii-formatted data.""" 132 | 133 | def render(self, start, paint): 134 | # If this isn't the first column rendered, space ourselves out from the 135 | # previous column 136 | if start: 137 | start += COLUMN_GAP 138 | 139 | # Calc width of the address bar 140 | width = BYTES_PER_ROW * self.font_width() 141 | width += (2 * TEXT_OFFSET) 142 | 143 | # Draw bar 144 | paint.fillRect( 145 | QRect(start, 0, width, self.viewport().height()), 146 | QColor(0, 0, 255)) 147 | 148 | # Draw hex 149 | start += TEXT_OFFSET 150 | old_pos = self.file().tell() 151 | self.file().seek(self.row_start() * BYTES_PER_ROW, os.SEEK_SET) 152 | 153 | for row in range(1, self.rows_visible()): 154 | data = self.file().read(BYTES_PER_ROW) 155 | for i, byte in enumerate(data): 156 | paint.drawText(start + (i*self.font_width()), 157 | row*(ROW_OFFSET + self.font_height()*2), 158 | "%c" % byte) 159 | 160 | self.file().seek(old_pos, os.SEEK_SET) 161 | 162 | # Let caller know how much space we took up while drawing 163 | return start + width 164 | 165 | 166 | class HexEditor(QAbstractScrollArea): 167 | """Hex editor widget implementation.""" 168 | 169 | def __init__(self): 170 | super().__init__() 171 | 172 | self.file = None 173 | self.cursor = 0 174 | self.rows_total = 0 175 | self.rows_shown = 0 176 | self.widgets_width = 0 177 | self.font_width = 0 178 | self.font_height = 0 179 | 180 | # Columns in the hex editor that will be displayed by default 181 | self.widgets = [ 182 | AddressColumn(self), 183 | HexColumn(self), 184 | AsciiColumn(self) 185 | ] 186 | 187 | self.verticalScrollBar().setValue(0) 188 | self.horizontalScrollBar().setValue(0) 189 | 190 | self.setFont(QFont("Monospace", 7, QFont.Light)) 191 | #self.setFile(open("testfile", "rb")) 192 | 193 | def setFont(self, font): 194 | """Sets the font to use in the hex editor. 195 | 196 | :param font: Font to use. 197 | :type font: QFont 198 | """ 199 | # Set font 200 | super().setFont(font) 201 | 202 | # Calculate font width and height 203 | fm = QFontMetrics(font) 204 | self.font_width = fm.width(" ") 205 | self.font_height = int(fm.height()/2) - 1 206 | 207 | # Recalc vars since font has changed 208 | self._adjust() 209 | self.viewport().update() 210 | 211 | def setFile(self, f): 212 | """Sets the file to get data from. 213 | 214 | :param font: File to get data from. 215 | :type font: SFile 216 | """ 217 | self.file = f 218 | self._adjust() 219 | self.viewport().update() 220 | 221 | def _draw_no_file(self, paint): 222 | """Draws a message when no file has been set.""" 223 | paint.drawText(self.geometry(), Qt.AlignCenter, "No file, add one!") 224 | 225 | def _draw_file(self, paint): 226 | """Draw each of the widgets in this hex editor.""" 227 | start = 0 228 | for widget in self.widgets: 229 | start = widget.render(start, paint) 230 | 231 | def paintEvent(self, event): #pylint: disable=unused-argument 232 | """Called by QT when window wants to paint itself.""" 233 | paint = QPainter(self.viewport()) 234 | 235 | if self.file: 236 | self._draw_file(paint) 237 | else: 238 | self._draw_no_file(paint) 239 | 240 | def _adjust(self): 241 | """Recalculates sizing vars when window size/contents are changed.""" 242 | # We don't need to set any of this if file is bad 243 | if not self.file: 244 | return 245 | 246 | self.widgets_width = 1000 247 | self.rows_total = int(get_file_size(self.file) 248 | / BYTES_PER_ROW) 249 | self.rows_shown = int((self.viewport().height() 250 | / (self.font_height+ROW_OFFSET))) + 1 251 | 252 | self.horizontalScrollBar().setRange(0, 253 | self.widgets_width - self.viewport().width()) 254 | self.horizontalScrollBar().setPageStep(self.viewport().width()) 255 | self.verticalScrollBar().setRange(0, self.rows_total) 256 | self.verticalScrollBar().setPageStep(self.rows_shown) 257 | -------------------------------------------------------------------------------- /client/mainwindow.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtCore import Qt 2 | from PyQt5.QtWidgets import QAction, QDesktopWidget, QMainWindow, QDockWidget, QTextEdit, qApp 3 | from client.editorwidget import EditorWidget 4 | 5 | # https://github.com/baoboa/pyqt5/blob/master/examples/mainwindows/dockwidgets/dockwidgets.py 6 | # http://zetcode.com/gui/pyqt5/firstprograms/ 7 | 8 | class SpadeMainWindow(QMainWindow): 9 | """Spade's main window.""" 10 | 11 | def __init__(self): 12 | super().__init__() 13 | self._init_ui() 14 | self._create_central_widget() 15 | self._create_projectview() 16 | self._create_templateview() 17 | 18 | def center(self): 19 | """Place the window in the center of the screen.""" 20 | qr = self.frameGeometry() 21 | cp = QDesktopWidget().availableGeometry().center() 22 | qr.moveCenter(cp) 23 | self.move(qr.topLeft()) 24 | 25 | def _init_menubar(self): 26 | """Set up the menu bar.""" 27 | action_exit = QAction("Exit", self) 28 | action_exit.setStatusTip("Exit application") 29 | action_exit.triggered.connect(qApp.quit) 30 | 31 | menubar = self.menuBar() 32 | menu_file = menubar.addMenu("File") 33 | menu_file.addAction(action_exit) 34 | 35 | def _init_ui(self): 36 | """Set up main window attributes.""" 37 | self.resize(1200, 800) 38 | self.center() 39 | self.setWindowTitle("Spade") 40 | self._init_menubar() 41 | self.statusBar().showMessage("Ready") 42 | 43 | def _create_central_widget(self): 44 | """Set up the central widget.""" 45 | self.central_widget = EditorWidget() 46 | self.setCentralWidget(self.central_widget) 47 | 48 | def _create_projectview(self): 49 | """Spawn projectview.""" 50 | self.dock_projectview = QDockWidget() 51 | self.dock_projectview.setAllowedAreas(Qt.LeftDockWidgetArea 52 | | Qt.RightDockWidgetArea) 53 | self.dock_projectview.setWidget(QTextEdit()) 54 | self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_projectview) 55 | 56 | def _create_templateview(self): 57 | """Spawn templateview.""" 58 | self.dock_templateview = QDockWidget() 59 | self.dock_templateview.setAllowedAreas(Qt.LeftDockWidgetArea 60 | | Qt.RightDockWidgetArea | Qt.BottomDockWidgetArea) 61 | self.dock_templateview.setWidget(QTextEdit()) 62 | self.addDockWidget(Qt.BottomDockWidgetArea, self.dock_templateview) 63 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SPHINXPROJ = spade 8 | SOURCEDIR = . 9 | BUILDDIR = .build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /docs/api.rst: -------------------------------------------------------------------------------- 1 | .. _api: 2 | 3 | API 4 | === 5 | 6 | This is the documentation for the api. 7 | 8 | .. toctree:: 9 | :maxdepth: 2 10 | 11 | file 12 | project 13 | -------------------------------------------------------------------------------- /docs/branching.md: -------------------------------------------------------------------------------- 1 | ## Branching 2 | Please implement all features in feature branches named with the template 3 | `/`. Valid types include: 4 | * `feature` - For use on branches that add new functionality or improvements 5 | to spade 6 | * `bug` - For use on branches that are intended to address a bug. 7 | 8 | Please use the `` field to reference an issue number, especially for bugs. 9 | If you want to contribute a feature and there is no issue for it in the issue 10 | tracker, you may use a descriptive english name for `` 11 | (EG: `feature/new_widget`). Favor underscores over dashes for spaces. 12 | 13 | 14 | -------------------------------------------------------------------------------- /docs/bug_template.txt: -------------------------------------------------------------------------------- 1 | # Platform 2 | Please list your OS, CPU architecture, spade version, etc here. This helps 3 | us determine how to replicate your bug as well as lets us identify specific 4 | platforms that cause consistant problems. 5 | 6 | # Descripion of Issue 7 | Remember that those reviewing your bug do not have all the information you 8 | have about your bug. Please be as detailed as possible in describing your bug 9 | if you actually want it to be fixed. Don't leave out details because you think 10 | they are obvious or assume we know what you're talking about. Be prepared to 11 | provide additional information if requested. 12 | 13 | # Steps to Replicate 14 | If applicable, please give detailed and exact steps to reproduce your bug. If 15 | we cannot see for ourselves what you're experiencing, it becomes much more 16 | difficult to fix your bug. This may be submitted in list format.1 17 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # spade documentation build configuration file, created by 5 | # sphinx-quickstart on Sat Mar 11 00:42:47 2017. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # 20 | # import os 21 | # import sys 22 | # sys.path.insert(0, os.path.abspath('.')) 23 | 24 | 25 | # -- General configuration ------------------------------------------------ 26 | 27 | # If your documentation needs a minimal Sphinx version, state it here. 28 | # 29 | # needs_sphinx = '1.0' 30 | 31 | # Add any Sphinx extension module names here, as strings. They can be 32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 33 | # ones. 34 | extensions = ['sphinx.ext.autodoc', 35 | 'sphinx.ext.coverage', 36 | 'sphinx.ext.imgmath', 37 | 'sphinx.ext.ifconfig', 38 | 'sphinx.ext.githubpages'] 39 | 40 | # Add any paths that contain templates here, relative to this directory. 41 | templates_path = ['.templates'] 42 | 43 | # The suffix(es) of source filenames. 44 | # You can specify multiple suffix as a list of string: 45 | # 46 | # source_suffix = ['.rst', '.md'] 47 | source_suffix = '.rst' 48 | 49 | # The master toctree document. 50 | master_doc = 'index' 51 | 52 | # General information about the project. 53 | project = 'spade' 54 | copyright = '2017, Nyxxie et al.' 55 | author = 'Nyxxie et al.' 56 | 57 | # The version info for the project you're documenting, acts as replacement for 58 | # |version| and |release|, also used in various other places throughout the 59 | # built documents. 60 | # 61 | # The short X.Y version. 62 | version = '' 63 | # The full version, including alpha/beta/rc tags. 64 | release = '' 65 | 66 | # The language for content autogenerated by Sphinx. Refer to documentation 67 | # for a list of supported languages. 68 | # 69 | # This is also used if you do content translation via gettext catalogs. 70 | # Usually you set "language" from the command line for these cases. 71 | language = None 72 | 73 | # List of patterns, relative to source directory, that match files and 74 | # directories to ignore when looking for source files. 75 | # This patterns also effect to html_static_path and html_extra_path 76 | exclude_patterns = ['.build', 'Thumbs.db', '.DS_Store'] 77 | 78 | # The name of the Pygments (syntax highlighting) style to use. 79 | pygments_style = 'sphinx' 80 | 81 | # If true, `todo` and `todoList` produce output, else they produce nothing. 82 | todo_include_todos = False 83 | 84 | 85 | # -- Options for HTML output ---------------------------------------------- 86 | 87 | # The theme to use for HTML and HTML Help pages. See the documentation for 88 | # a list of builtin themes. 89 | # 90 | html_theme = 'alabaster' 91 | 92 | # Theme options are theme-specific and customize the look and feel of a theme 93 | # further. For a list of options available for each theme, see the 94 | # documentation. 95 | # 96 | # html_theme_options = {} 97 | 98 | # Add any paths that contain custom static files (such as style sheets) here, 99 | # relative to this directory. They are copied after the builtin static files, 100 | # so a file named "default.css" will overwrite the builtin "default.css". 101 | html_static_path = ['.static'] 102 | 103 | 104 | # -- Options for HTMLHelp output ------------------------------------------ 105 | 106 | # Output file base name for HTML help builder. 107 | htmlhelp_basename = 'spadedoc' 108 | 109 | 110 | # -- Options for LaTeX output --------------------------------------------- 111 | 112 | latex_elements = { 113 | # The paper size ('letterpaper' or 'a4paper'). 114 | # 115 | # 'papersize': 'letterpaper', 116 | 117 | # The font size ('10pt', '11pt' or '12pt'). 118 | # 119 | # 'pointsize': '10pt', 120 | 121 | # Additional stuff for the LaTeX preamble. 122 | # 123 | # 'preamble': '', 124 | 125 | # Latex figure (float) alignment 126 | # 127 | # 'figure_align': 'htbp', 128 | } 129 | 130 | # Grouping the document tree into LaTeX files. List of tuples 131 | # (source start file, target name, title, 132 | # author, documentclass [howto, manual, or own class]). 133 | latex_documents = [ 134 | (master_doc, 'spade.tex', 'spade Documentation', 135 | 'Nyxxie et al.', 'manual'), 136 | ] 137 | 138 | 139 | # -- Options for manual page output --------------------------------------- 140 | 141 | # One entry per manual page. List of tuples 142 | # (source start file, name, description, authors, manual section). 143 | man_pages = [ 144 | (master_doc, 'spade', 'spade Documentation', 145 | [author], 1) 146 | ] 147 | 148 | 149 | # -- Options for Texinfo output ------------------------------------------- 150 | 151 | # Grouping the document tree into Texinfo files. List of tuples 152 | # (source start file, target name, title, author, 153 | # dir menu entry, description, category) 154 | texinfo_documents = [ 155 | (master_doc, 'spade', 'spade Documentation', 156 | author, 'spade', 'One line description of project.', 157 | 'Miscellaneous'), 158 | ] 159 | 160 | 161 | 162 | -------------------------------------------------------------------------------- /docs/dev/branching.md: -------------------------------------------------------------------------------- 1 | # Branching 2 | This short document attempts to describe the branching strategy used in this 3 | project. 4 | 5 | ## Branching strategy 6 | All new additions/modifications to the codebase must be developed in branches. 7 | Upon completion, these will then be merged into master. These "development" 8 | branches should adhere to the following naming format: 9 | * `feature/descriptive-name` - For new features/modifications (see [loaf][1]). 10 | * `bugfix/descriptive-name` - For fixing errors in existing code (see [loab][2]). 11 | 12 | This model allows us to keep a clear history of what features were introduced to 13 | the mainline when, and allows us to revert code if need be. It's also fairly 14 | standard across most projects, and is basically [gitflow][3] without a develop 15 | branch. 16 | 17 | ## Releasing versions 18 | Since we merge directly into master upon feature completion, its safe to say 19 | that things might change unexpectedly for users at some point. For users that 20 | want a more consistant experience, official versions of spade will be tagged, 21 | with the most recent released version being marked with the `latest` tag. 22 | 23 | [1]: docs/dev/life_of_a_feature.md 24 | [2]: docs/dev/life_of_a_bug.md 25 | [3]: http://nvie.com/posts/a-successful-git-branching-model/ 26 | -------------------------------------------------------------------------------- /docs/dev/documenting_code.md: -------------------------------------------------------------------------------- 1 | # Documentation 2 | All methods and classes should have docstrings written for them. As spade 3 | currently uses [sphinx][1] for generating documentation, docstrings will be 4 | displayed as [reStructuredText][2]. Docstrings, therefore, may make use it's 5 | markup to add emphasis, charts, code examples, etc to their docstrings. 6 | 7 | Documentation may be generated using the Makefile in the `docs` folder, or 8 | alternately by using the command `python setup.py build_sphinx`. Generated 9 | documentation will be located in `docs/.build//`, where `` is the 10 | type of documentation that was generated (html, manpages, etc). 11 | 12 | ### Methods 13 | Docstrings for methods should describe that method's purpose, arguments, and 14 | return value at minimum. A good rule of thumb to follow is that a user should 15 | know when and how to use a method simply by looking at its signature and 16 | docstring. The following is an example of an acceptable dostring: 17 | 18 | ```python 19 | def seek(self, offset: int=0, from_what: int=0) -> int: 20 | """ 21 | Sets the cursor position relative to some position. 22 | 23 | :param offset: Offset into file relative to from_what parameter. 24 | :param from_what: Determines what the above offset is relative to. 25 | :return: Cursor position after the seek operation completes. 26 | 27 | The reference point specified by the ``from_what`` parameter should 28 | take on one of the following values: 29 | 30 | * 0 - Offset from beginning of file. 31 | * 1 - Offset from current cursor position. 32 | * 2 - Offset from end of file. 33 | 34 | The ``from_what`` parameter may be omitted, and will default to 0 35 | (beginning of file). 36 | """ 37 | ``` 38 | Method docstrings are required for all public methods, and optional (but 39 | encouraged!!) for private ones. Don't bother documenting class 'builtin' 40 | methods (e.g. `__init__`). 41 | 42 | ### Classes 43 | Docstrings for classes should describe that class's purpose in the project. A 44 | rule of thumb to go by with class docstrings is that a developer should be able 45 | to know exactly what the class is for and how it is meant to be used by reading 46 | the docstring by itself. The following is an example of an acceptable 47 | class docstring: 48 | 49 | ```python 50 | class Project(object): 51 | """Stores the state and data of a Spade session. 52 | 53 | Specifically, a project stores information on files that were opened, 54 | templates, and file metadata. Additionally, any data saved by plugins, 55 | analysis, etc is stored in a project. Projects by default store this data 56 | directly on disk in a sqlite database. 57 | """ 58 | ... 59 | ``` 60 | 61 | [1]: http://www.sphinx-doc.org 62 | [2]: http://www.sphinx-doc.org/en/stable/rest.html 63 | -------------------------------------------------------------------------------- /docs/dev/env_setup.md: -------------------------------------------------------------------------------- 1 | ## Setting up environment 2 | In order to work on spade, you'll need to set up an environment that'll allow 3 | you to make, test and submit changes. Please perform these first initial steps: 4 | * Register a github account 5 | * Fork the main spade repository 6 | * Install Python 3.4 or above 7 | 8 | For development, we also reccomend setting up a [virtual environment][1]. This 9 | is useful as it allows you to install dependencies and make spade's modules 10 | visible in an environment isolated from the rest of your python projects. The 11 | process of setting up spade using a virtual environment looks something like 12 | this: 13 | 14 | ### Linux 15 | ```shell 16 | cd # Enter project directory 17 | virtualenv venv # Create virtual environment 18 | . venv/bin/activate # Activate the virtual environment 19 | pip install -e . # Install all dependencies and add spade components to path 20 | ``` 21 | 22 | ### Mac 23 | ```shell 24 | cd # Enter project directory 25 | virtualenv venv # Create virtual environment 26 | . venv/bin/activate # Activate the virtual environment 27 | pip install -e . # Install all dependencies and add spade components to path 28 | ``` 29 | 30 | ### Windows 31 | *TODO: write this* 32 | 33 | Once your environment is configured, you are ready to start contributing. 34 | Please remember to activate your virtual environment when you want to run 35 | the development version of spade. 36 | 37 | [1]: http://python-guide-pt-br.readthedocs.io/en/latest/dev/virtualenvs/ 38 | -------------------------------------------------------------------------------- /docs/dev/getting_started.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | Spade attempts to make use of the convention and layouts popular in other 3 | projects. The hardest part about getting started will likely be getting familar 4 | enough with the codebase to understand how you might contribute an improvement 5 | or idea you have. We reccomend the following to understand what's going on: 6 | * When trying to learn about a method or class, how you learn it depends on 7 | the reason why you need to learn about it: 8 | 1. **What is it for?** All documented components should explain their 9 | purpose, so check the generated sphinx docs or the docstrings 10 | associated with that component. 11 | 2. **How do I use it?** First check out the docs for that method, and then 12 | check out the relevant tests associated with it and its usages in the 13 | codebase. 14 | 3. **How does it work?** Read the code, which should be sufficiently 15 | commented that you can understand what it's doing. 16 | As you contribute yourself, keep these assumptions of how a component will 17 | be documented in mind so that other developers can expect the same 18 | experience when reading your code. Code that isn't sufficiently documented 19 | *is a valid issue* and may be raised in the issue tracker. 20 | 21 | # Task ideas 22 | If you want to contribute but don't know where to start, here are some tasks 23 | that you can do right now without needing to be too creative: 24 | * Review open pull requests (including those in progess). 25 | * Lend your skillz to an issue in the issue tracker. 26 | * Implement features in the issue tracker (if they don't already have a pull 27 | request open). 28 | * Create new tests for cases we don't cover. You can easily assess this using 29 | pytest-cov. Check out Testing section for more info. 30 | 31 | The biggest challenge to getting started is getting to know the codebase well 32 | enough to feel comfortable contributing. Here are some low-complexity tasks 33 | that you may consider engaging in to help become familiar with spade: 34 | * Create new tests 35 | * Investigate/fix low complexity bugs 36 | * Implement appr 37 | -------------------------------------------------------------------------------- /docs/dev/life_of_a_bug.md: -------------------------------------------------------------------------------- 1 | # Life of a Bug 2 | This document describes the lifes-cycle of a bug from discovery to fix. 3 | It is meant to be useful for anyone who either wants to report a bug or anyone 4 | who wants to patch some bugs. 5 | 6 | ## Discovery 7 | When a bug is discovered, it should be submitted to the issue tracker on 8 | Github. Use the [bug report template](docs/dev/bug_template.txt) to ensure we get 9 | all the information necessary to figure out what the problem is, and please keep 10 | an eye out for any additional questions we might have. 11 | 12 | ## Bug is triaged and/or assigned 13 | After we've understood the nature and scope of the bug, it will be catagorized 14 | and eventually assigned. Alternately, if a bug is not immediately assigned 15 | anyone from the community may choose to patch it themselves. Bugs that we 16 | either can't solve or don't have the time to solve and are particularly 17 | important or valuable will get a special `[help wanted]` tag, and should be 18 | particularly noted by anyone who wants to patch bugs. 19 | 20 | ## Bug is fixed 21 | After someone has identified the cause of the bug, they should fork the repo, 22 | create a new `bugfix` branch (see [branching](docs/dev/branching.md) for more 23 | info) and start a `[wip][bugfix]` pull request to let others know they are 24 | working on that fix. This process pretty closely matches that of 25 | [creating a new feature](docs/dev/life_of_a_feature.md), so give that proccess a 26 | look for more detail. Once the fix is done, the issue will be closed and spade 27 | will be less broken! An important note **ALL BUGFIXES SHOULD BE ACCOMPANIED BY 28 | A TEST THAT DEMONSTRATES THE BUG**. This allows us to verify it is fixed both 29 | upon submission and later on when others make changes to the codebase. 30 | -------------------------------------------------------------------------------- /docs/dev/life_of_a_feature.md: -------------------------------------------------------------------------------- 1 | # Life of a Feature 2 | This document aims to describe the ideal process of converting an idea into 3 | code merged into the repo. This document is intended for anyone who wants a 4 | simple guide to follow for getting their code submitted and attempts to follow 5 | the currently popular methods for doing so. 6 | 7 | ## Starting a Feature 8 | A feature can start in one of two ways: as an issue or as a pull request. 9 | 10 | ### Issues 11 | If you have an idea for a feature but are unsure about it or don't want to 12 | implement it, Create an issue for it in the issue tracker. Before you do this, 13 | *please* make sure there isn't already an issue or open pull request for your 14 | idea. 15 | 16 | ### Pull Request 17 | If you have an idea for a feature and want to work on it, do the following: 18 | 19 | 1. Fork the spade repo 20 | 2. Create a new feature branch: `git checkout -b feature/` in 21 | your newly-forked repo. As an aside, check out [branching][4] for more 22 | info on this project's branching strategy. 23 | 3. Open a pull request in the upstream spade repo with the prefix `[wip]`. 24 | 25 | This will allow developers and reviewers to see that a feature is being worked 26 | on. The `[wip]` prefix lets reviewers know that the issue is currently being 27 | worked on and shouldn't be treated as finished. It also lets others know that 28 | you are working on a particular feature and that they probably shouldn't start 29 | on it themselves. 30 | 31 | If you're implementing a feature that started as an issue, please link it 32 | somewhere in the body of your pull request by adding `closes #`. 33 | This will update the issue timeline to reflect that you've opened a pull 34 | request and will close the issue when the feature is complete. 35 | 36 | Please try to isolate your pull request to roughly one major addition or 37 | modification of code. Large pull requests that try to do a lot of work mean 38 | larger review times and less people who can work on spade concurrently. 39 | 40 | ## Developing a Feature 41 | ### Styling 42 | In order to keep the codebase roughly homogeneous, we have a [style guide][1]. 43 | It's mostly similar to PEP8 with some additions. You can (and should) use 44 | pylint to perform a rough check on your code, though it's not perfect and you 45 | should take a look at the style guide. 46 | 47 | ### Pylint 48 | Also use pylint to perform rough error checking, since it can catch a lot of 49 | stuff that the compiler would in other languages. I've set it up to pretty much 50 | perform every check it can. Also, don't add pylint ignore comments unless you 51 | have a good reason. 52 | 53 | ### Tests 54 | Spade requires tests be created for any new code added, so please be sure to 55 | write them. This is to allow us to verify the code you wrote works, both upon 56 | submission and later on when we start modifying/replacing stuff you might 57 | depend on, refactoring, etc. Please try to keep disk writes to a minimum and 58 | try to mock out any calls to apis you don't control. Also prefer many tests 59 | that test single paths of execution over huge tests that test several, as that 60 | allows testing to be done concurrently (and thereby quicker). 61 | 62 | ### Documentation 63 | Spade also requies that feature code and usage be documented. Check out the 64 | [documenting code][2] page for more info. 65 | 66 | ## Submitting a Feature 67 | Once your contribution is ready to ship, remove the `[wip]` marker from your 68 | title and [request a maintainer to review it][3]. Please make sure that pylint 69 | doesn't complain about anything and all of the tests pass. Once your code has 70 | been reviewed and all issues have been fixed, your work will be merged. Thanks 71 | for your help! 72 | 73 | [1]: docs/dev/styleguide.md 74 | [2]: docs/dev/documenting_code.md 75 | [3]: https://github.com/blog/2291-introducing-review-requests 76 | [4]: docs/dev/documenting_code.md 77 | -------------------------------------------------------------------------------- /docs/dev/styleguide.md: -------------------------------------------------------------------------------- 1 | # Style Guide 2 | We mostly adhere to [PEP8][1], with the following additions and specifications. 3 | 4 | Table of Contents: 5 | * [General](#general) 6 | * [Tabbing](#tabbing) 7 | * [Line length](#line-length) 8 | * [Line wrapping](#line-wrapping) 9 | * [Functions](#functions) 10 | * [Type Hints](#type-hints) 11 | * [Commenting](#line-length) 12 | * [When to comment](#when-to-comment) 13 | * [Punctuation in comments](#punctuation-in-comments) 14 | * [Logical block commenting](#logical-block-commenting) 15 | * [Classes](#classes) 16 | * [Method naming](#method-naming) 17 | * [Method order](#method-order) 18 | * [Imports](#imports) 19 | * [Relative imports](#relative-imports) 20 | * [Exceptions](#exceptions) 21 | * [When to use](#when-to-use) 22 | * [Throwing plain Exception](#throwing-plain-exception) 23 | 24 | 25 | ## General 26 | 27 | ### Tabbing 28 | #### Rule 29 | Use spaces for indents. 30 | #### Reason 31 | Tabs are great because they are one byte and can be set to appear to be any 32 | number of spaces you prefer, but that same flexibility breaks style when people 33 | use spaces to align arguments and conditionals. This mixing isn't even allowed 34 | in Python3. 35 | 36 | ### Line length 37 | #### Rule 38 | Line length is limited to 80 chars. This limit may be lifted if the line 39 | contains a url, a comment, or in other specific scenarios when trying to stick 40 | to the rule produces ugly code. 41 | #### Reason 42 | Column limits are useful because they keep code from extending past a reasonable 43 | editing window. Obviously no one is programming on an 80 char terminal anymore, 44 | but this limit is still useful because it helps fit more information on your 45 | screen (documentation, more editing windows, etc). 46 | 47 | ### Line wrapping 48 | #### Rule 49 | if you need to wrap a function or conditional that goes over the 80 char limit, 50 | please adhere to the following style. Notice: 51 | 1. All wrapped lines are double indented. This is to distinquish them from 52 | the next line. 53 | 2. No words are cut off in the middle and continued on the next line. This is 54 | to increase readability. Be sure to und your wrapped string line with a 55 | space! 56 | 3. If it makes sense, you may start typing arguments on the next line. This 57 | is acceptable if proportionally the size of arguments don't match up or if 58 | a function invocation is exceptionally long and there is little room for 59 | the first argument. Avoid the latter if there are only a few arguments, 60 | however. 61 | #### Example 62 | ```python 63 | var = HugeFunctionCall(("This is a massive string that will wrap. It " 64 | "displays the value of some variable to via format, so notice how we " 65 | "enclose it in parens! Here's that value: {}.").format(value)) 66 | #do stuff 67 | ``` 68 | 69 | 70 | ## Functions 71 | 72 | ### Method Size 73 | #### Rule 74 | Avoid huge functions. Split out functionality into private or helper methods if 75 | a particular block in a function is performing a large task, even if it's only 76 | used in one specific area. 77 | 78 | ### Type Hints 79 | #### Rule 80 | Please use [type hints][2] whenever you expect an argument to be of a specific 81 | type. 82 | #### Reason 83 | Allows implicit documentation and free type checking. 84 | #### Example 85 | ```python 86 | def seek(self, offset: int=0, from_what: int=0) -> int: 87 | ... 88 | ``` 89 | 90 | 91 | ## Commenting 92 | 93 | ### When to comment 94 | #### Rule 95 | Please comment anything that wouldn't be immediately apparant to the average 96 | python programmer who has little-to-no experience with this codebase. This is 97 | mostly left to your best judgement, but please be considerate and note that it's 98 | far better to have too many comments than barely any comments. 99 | 100 | ### Punctuation in comments 101 | #### Rule 102 | Do not use periods at the end of a comment unless your comment consists of 103 | multiple sentences or is long. 104 | #### Reason 105 | This is both because most comments aren't complete sentences and because the 106 | period at the end looks bad when the comment is smaller. This is more of a best 107 | judgement kind of thing, so do what you feel is right. 108 | 109 | ### Logical block commenting 110 | #### Rule 111 | "Logical Blocks" are defined as sections of code that perform a discrete task, 112 | and are often separated by newlines. It is prefered that logical blocks are 113 | commented to explain what they are attempting to achieve. 114 | #### Reason 115 | Commenting blocks is useful because it allows someone who is reading your code 116 | to quickly determine what each "block" is intended to do without needing to 117 | actually spend time figuring it out. We shouldn't have to reverse engineer the 118 | code of a reverse engineering tool, after all :) 119 | #### Example 120 | ```python 121 | # If this isn't the first column rendered, space ourselves out from the 122 | # previous column 123 | if (start != 0): 124 | start += COLUMN_GAP 125 | 126 | # Calc width of the address bar 127 | width = BYTES_PER_ROW * self.font_width() 128 | width += (2 * TEXT_OFFSET) 129 | 130 | ... 131 | ``` 132 | 133 | 134 | ## Classes 135 | 136 | ### Method/variable naming 137 | #### Rule 138 | Please use `names_like_this()` for public methods and variables. If your thing 139 | shouldn't be used by just anyone, hint at this by prefixing your method with an 140 | underscore. DO NOT use two underscores, as that does weird name mangling stuff 141 | internally that is undesirable. 142 | 143 | ### Method order 144 | #### Rule 145 | Class methods must be declared in the following order: 146 | 1. Special class methods (`__init__`, `__str__`, etc) 147 | 2. Public class methods 148 | 3. Private class methods (prefixed with \_) 149 | 150 | Refrain from using double underscore prefixes for methods and variables. 151 | 152 | 153 | ## Imports 154 | 155 | ### Relative imports 156 | #### Rule 157 | Don't use relative imports. If you need to import code from spade, use the full 158 | path. 159 | #### Reason 160 | Looks bad and makes object location more obscure. 161 | 162 | 163 | ## Exceptions 164 | 165 | ### When to use 166 | #### Rule 167 | Use exceptions only in cases where a method failing is a potentially fatal 168 | action, where fatal is defined as the program entering an invalid state. 169 | The program crashing is FAR preferable to it functioning incorrectly and 170 | creating difficult to diagnose bugs. 171 | 172 | ### Throwing plain Exception 173 | #### Rule 174 | NEVER throw an Exception, subclass it or use an existing subclassed exception 175 | relevant to your error. 176 | 177 | [1]: https://www.python.org/dev/peps/pep-0008/#code-lay-out 178 | [2]: https://www.python.org/dev/peps/pep-0484/ 179 | -------------------------------------------------------------------------------- /docs/file.rst: -------------------------------------------------------------------------------- 1 | .. _file: 2 | 3 | File 4 | ==== 5 | 6 | .. module:: spade.core.file 7 | 8 | .. autoclass:: filemode 9 | :members: 10 | 11 | .. autoclass:: sfile 12 | :members: 13 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | :orphan: 2 | 3 | Welcome to Spade 4 | ================ 5 | 6 | Welcome to Spade's documentation. This documentation seeks to provide both a 7 | guide on how to use the various facets of Spade, as well as a reference for 8 | development using Spade's addon system. 9 | 10 | .. toctree:: 11 | :maxdepth: 2 12 | 13 | api 14 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=.build 12 | set SPHINXPROJ=spade 13 | 14 | if "%1" == "" goto help 15 | 16 | %SPHINXBUILD% >NUL 2>NUL 17 | if errorlevel 9009 ( 18 | echo. 19 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 20 | echo.installed, then set the SPHINXBUILD environment variable to point 21 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 22 | echo.may add the Sphinx directory to PATH. 23 | echo. 24 | echo.If you don't have Sphinx installed, grab it from 25 | echo.http://sphinx-doc.org/ 26 | exit /b 1 27 | ) 28 | 29 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 30 | goto end 31 | 32 | :help 33 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 34 | 35 | :end 36 | popd 37 | -------------------------------------------------------------------------------- /docs/project.rst: -------------------------------------------------------------------------------- 1 | .. _project: 2 | 3 | Project 4 | ======= 5 | 6 | .. module:: spade.core.project 7 | 8 | .. autoclass:: Project 9 | :members: 10 | -------------------------------------------------------------------------------- /pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | 3 | # A comma-separated list of package or module names from where C extensions may 4 | # be loaded. Extensions are loading into the active Python interpreter and may 5 | # run arbitrary code 6 | extension-pkg-whitelist=PyQt5 7 | 8 | # Add files or directories to the blacklist. They should be base names, not 9 | # paths. 10 | ignore=CVS,.git,venv 11 | 12 | # Add files or directories matching the regex patterns to the blacklist. The 13 | # regex matches against base names, not paths. 14 | ignore-patterns= 15 | 16 | # Python code to execute, usually for sys.path manipulation such as 17 | # pygtk.require(). 18 | #init-hook= 19 | 20 | # Use multiple processes to speed up Pylint. 21 | jobs=1 22 | 23 | # List of plugins (as comma separated values of python modules names) to load, 24 | # usually to register additional checkers. 25 | load-plugins= 26 | 27 | # Pickle collected data for later comparisons. 28 | persistent=no 29 | 30 | # Specify a configuration file. 31 | #rcfile= 32 | 33 | # Allow loading of arbitrary C extensions. Extensions are imported into the 34 | # active Python interpreter and may run arbitrary code. 35 | unsafe-load-any-extension=no 36 | 37 | # Allow optimization of some AST trees. This will activate a peephole AST 38 | # optimizer, which will apply various small optimizations. For instance, it can 39 | # be used to obtain the result of joining multiple strings with the addition 40 | # operator. Joining a lot of strings can lead to a maximum recursion error in 41 | # Pylint and this flag can prevent that. It has one side effect, the resulting 42 | # AST will be different than the one from reality. 43 | optimize-ast=no 44 | 45 | 46 | [MESSAGES CONTROL] 47 | 48 | # Only show warnings with the listed confidence levels. Leave empty to show 49 | # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED 50 | confidence= 51 | 52 | # Enable all messages and block the dumb ones below 53 | enable=all 54 | disable=locally-disabled, 55 | suppressed-message, 56 | missing-docstring, 57 | bad-whitespace, 58 | bad-continuation, 59 | duplicate-code, 60 | multiple-statements, 61 | too-few-public-methods, 62 | protected-access 63 | 64 | [REPORTS] 65 | 66 | # Python expression which should return a note less than 10 (10 is the highest 67 | # note). You have access to the variables errors warning, statement which 68 | # respectively contain the number of errors / warnings messages and the total 69 | # number of statements analyzed. This is used by the global evaluation report 70 | # (RP0004). 71 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) 72 | 73 | # Template used to display messages. This is a python new-style format string 74 | # used to format the message information. See doc for all details 75 | #msg-template= 76 | 77 | # Set the output format. Available formats are text, parseable, colorized, json 78 | # and msvs (visual studio).You can also give a reporter class, eg 79 | # mypackage.mymodule.MyReporterClass. 80 | output-format=colorized 81 | 82 | # Tells whether to display a full report or only the messages 83 | reports=no 84 | 85 | # Activate the evaluation score. 86 | score=yes 87 | 88 | 89 | [REFACTORING] 90 | 91 | # Maximum number of nested blocks for function / method body 92 | max-nested-blocks=5 93 | 94 | 95 | [VARIABLES] 96 | 97 | # List of additional names supposed to be defined in builtins. Remember that 98 | # you should avoid to define new builtins when possible. 99 | additional-builtins= 100 | 101 | # Tells whether unused global variables should be treated as a violation. 102 | allow-global-unused-variables=yes 103 | 104 | # List of strings which can identify a callback function by name. A callback 105 | # name must start or end with one of those strings. 106 | callbacks=cb_,_cb 107 | 108 | # A regular expression matching the name of dummy variables (i.e. expectedly 109 | # not used). 110 | dummy-variables-rgx=^dummy|^ignored_|^unused_ 111 | 112 | # Tells whether we should check for unused import in __init__ files. 113 | init-import=no 114 | 115 | 116 | [MISCELLANEOUS] 117 | 118 | # List of note tags to take in consideration, separated by a comma. 119 | notes=FIXME,NOTE,TODO 120 | 121 | 122 | [BASIC] 123 | 124 | # Naming hint for argument names 125 | argument-name-hint=(([a-z][a-z0-9_]{1,30})|(_[a-z0-9_]*))$ 126 | 127 | # Regular expression matching correct argument names 128 | argument-rgx=(([a-z][a-z0-9_]{1,30})|(_[a-z0-9_]*))$ 129 | 130 | # Naming hint for attribute names 131 | attr-name-hint=(([a-z][a-z0-9_]{1,30})|(_[a-z0-9_]*))$ 132 | 133 | # Regular expression matching correct attribute names 134 | attr-rgx=(([a-z][a-z0-9_]{1,30})|(_[a-z0-9_]*))$ 135 | 136 | # Bad variable names which should always be refused, separated by a comma 137 | bad-names=foo,bar,baz,toto,tutu,tata 138 | 139 | # Naming hint for class attribute names 140 | class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{1,30}|(__.*__))$ 141 | 142 | # Regular expression matching correct class attribute names 143 | class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{1,30}|(__.*__))$ 144 | 145 | # Naming hint for class names 146 | class-name-hint=[A-Z_][a-zA-Z0-9]+$ 147 | 148 | # Regular expression matching correct class names 149 | class-rgx=[A-Z_][a-zA-Z0-9]+$ 150 | 151 | # Naming hint for constant names 152 | const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ 153 | 154 | # Regular expression matching correct constant names 155 | const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ 156 | 157 | # Minimum line length for functions/classes that require docstrings, shorter 158 | # ones are exempt. 159 | docstring-min-length=-1 160 | 161 | # Naming hint for function names 162 | function-name-hint=(([a-z][a-zA-Z0-9_]{2,30})|(_[a-z0-9_]*))$ 163 | 164 | # Regular expression matching correct function names 165 | function-rgx=(([a-z][a-zA-Z0-9_]{2,30})|(_[a-z0-9_]*))$ 166 | 167 | # Good variable names which should always be accepted, separated by a comma 168 | good-names=i,j,k,f,m,h,ex,Run,_ 169 | 170 | # Include a hint for the correct naming format with invalid-name 171 | include-naming-hint=yes 172 | 173 | # Naming hint for inline iteration names 174 | inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ 175 | 176 | # Regular expression matching correct inline iteration names 177 | inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ 178 | 179 | # Naming hint for method names 180 | method-name-hint=(([a-z][a-zA-Z0-9_]{2,30})|(_[a-z0-9_]*))$ 181 | 182 | # Regular expression matching correct method names 183 | method-rgx=(([a-z][a-zA-Z0-9_]{2,30})|(_[a-z0-9_]*))$ 184 | 185 | # Colon-delimited sets of names that determine each other's naming style when 186 | # the name regexes allow several styles. 187 | name-group= 188 | 189 | # Regular expression which should only match function or class names that do 190 | # not require a docstring. 191 | no-docstring-rgx=^_ 192 | 193 | # List of decorators that produce properties, such as abc.abstractproperty. Add 194 | # to this list to register other decorators that produce valid properties. 195 | property-classes=abc.abstractproperty 196 | 197 | # Naming hint for variable names 198 | variable-name-hint=(([a-z][a-z0-9_]{1,30})|(_[a-z0-9_]*))$ 199 | 200 | # Regular expression matching correct variable names 201 | variable-rgx=(([a-zA-Z][a-z0-9_]{1,30})|(_[a-z0-9_]*))$ 202 | 203 | 204 | [LOGGING] 205 | 206 | # Logging modules to check that the string format arguments are in logging 207 | # function parameter format 208 | logging-modules=logging 209 | 210 | 211 | [SPELLING] 212 | 213 | # Spelling dictionary name. Available dictionaries: none. To make it working 214 | # install python-enchant package. 215 | spelling-dict= 216 | 217 | # List of comma separated words that should not be checked. 218 | spelling-ignore-words= 219 | 220 | # A path to a file that contains private dictionary; one word per line. 221 | spelling-private-dict-file= 222 | 223 | # Tells whether to store unknown words to indicated private dictionary in 224 | # --spelling-private-dict-file option instead of raising a message. 225 | spelling-store-unknown-words=no 226 | 227 | 228 | [FORMAT] 229 | 230 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 231 | expected-line-ending-format= 232 | 233 | # Regexp for a line that is allowed to be longer than the limit. If the line 234 | # contains a comment, import statement or a link we want to ignore it 235 | ignore-long-lines=^([^#]*#.*)|(.*https?://.*)|(from .*)|(import .*)$ 236 | 237 | # Number of spaces of indent required inside a hanging or continued line. 238 | indent-after-paren=4 239 | 240 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 241 | # tab). 242 | indent-string=' ' 243 | 244 | # Maximum number of characters on a single line. 245 | max-line-length=80 246 | 247 | # Maximum number of lines in a module 248 | max-module-lines=1000 249 | 250 | # List of optional constructs for which whitespace checking is disabled. `dict- 251 | # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. 252 | # `trailing-comma` allows a space between comma and closing bracket: (a, ). 253 | # `empty-line` allows space-only lines. 254 | no-space-check=trailing-comma,dict-separator 255 | 256 | # Allow the body of a class to be on the same line as the declaration if body 257 | # contains single statement. 258 | single-line-class-stmt=no 259 | 260 | # Allow the body of an if to be on the same line as the test if there is no 261 | # else. 262 | single-line-if-stmt=no 263 | 264 | 265 | [SIMILARITIES] 266 | 267 | # Ignore comments when computing similarities. 268 | ignore-comments=yes 269 | 270 | # Ignore docstrings when computing similarities. 271 | ignore-docstrings=yes 272 | 273 | # Ignore imports when computing similarities. 274 | ignore-imports=no 275 | 276 | # Minimum lines number of a similarity. 277 | min-similarity-lines=4 278 | 279 | 280 | [TYPECHECK] 281 | 282 | # List of decorators that produce context managers, such as 283 | # contextlib.contextmanager. Add to this list to register other decorators that 284 | # produce valid context managers. 285 | contextmanager-decorators=contextlib.contextmanager 286 | 287 | # List of members which are set dynamically and missed by pylint inference 288 | # system, and so shouldn't trigger E1101 when accessed. Python regular 289 | # expressions are accepted. 290 | generated-members= 291 | 292 | # Tells whether missing members accessed in mixin class should be ignored. A 293 | # mixin class is detected if its name ends with "mixin" (case insensitive). 294 | ignore-mixin-members=yes 295 | 296 | # This flag controls whether pylint should warn about no-member and similar 297 | # checks whenever an opaque object is returned when inferring. The inference 298 | # can return multiple potential results while evaluating a Python object, but 299 | # some branches might not be evaluated, which results in partial inference. In 300 | # that case, it might be useful to still emit no-member and other checks for 301 | # the rest of the inferred objects. 302 | ignore-on-opaque-inference=yes 303 | 304 | # List of class names for which member attributes should not be checked (useful 305 | # for classes with dynamically set attributes). This supports the use of 306 | # qualified names. 307 | ignored-classes=optparse.Values,thread._local,_thread._local 308 | 309 | # List of module names for which member attributes should not be checked 310 | # (useful for modules/projects where namespaces are manipulated during runtime 311 | # and thus existing member attributes cannot be deduced by static analysis. It 312 | # supports qualified module names, as well as Unix pattern matching. 313 | ignored-modules= 314 | 315 | # Show a hint with possible names when a member name was not found. The aspect 316 | # of finding the hint is based on edit distance. 317 | missing-member-hint=yes 318 | 319 | # The minimum edit distance a name should have in order to be considered a 320 | # similar match for a missing member name. 321 | missing-member-hint-distance=1 322 | 323 | # The total number of similar names that should be taken in consideration when 324 | # showing a hint for a missing member. 325 | missing-member-max-choices=1 326 | 327 | 328 | [DESIGN] 329 | 330 | # Maximum number of arguments for function / method 331 | max-args=5 332 | 333 | # Maximum number of attributes for a class (see R0902). 334 | max-attributes=10 335 | 336 | # Maximum number of boolean expressions in a if statement 337 | max-bool-expr=5 338 | 339 | # Maximum number of branch for function / method body 340 | max-branches=12 341 | 342 | # Maximum number of locals for function / method body 343 | max-locals=15 344 | 345 | # Maximum number of parents for a class (see R0901). 346 | max-parents=7 347 | 348 | # Maximum number of public methods for a class (see R0904). 349 | max-public-methods=20 350 | 351 | # Maximum number of return / yield for function / method body 352 | max-returns=6 353 | 354 | # Maximum number of statements in function / method body 355 | max-statements=50 356 | 357 | # Minimum number of public methods for a class (see R0903). 358 | min-public-methods=2 359 | 360 | 361 | [IMPORTS] 362 | 363 | # Allow wildcard imports from modules that define __all__. 364 | allow-wildcard-with-all=no 365 | 366 | # Analyse import fallback blocks. This can be used to support both Python 2 and 367 | # 3 compatible code, which means that the block might have code that exists 368 | # only in one or another interpreter, leading to false positives when analysed. 369 | analyse-fallback-blocks=no 370 | 371 | # Deprecated modules which should not be used, separated by a comma 372 | deprecated-modules=optparse,tkinter.tix 373 | 374 | # Create a graph of external dependencies in the given file (report RP0402 must 375 | # not be disabled) 376 | ext-import-graph= 377 | 378 | # Create a graph of every (i.e. internal and external) dependencies in the 379 | # given file (report RP0402 must not be disabled) 380 | import-graph= 381 | 382 | # Create a graph of internal dependencies in the given file (report RP0402 must 383 | # not be disabled) 384 | int-import-graph= 385 | 386 | # Force import order to recognize a module as part of the standard 387 | # compatibility libraries. 388 | known-standard-library= 389 | 390 | # Force import order to recognize a module as part of a third party library. 391 | known-third-party=enchant 392 | 393 | 394 | [CLASSES] 395 | 396 | # List of method names used to declare (i.e. assign) instance attributes. 397 | defining-attr-methods=__init__,__new__,setUp 398 | 399 | # List of member names, which should be excluded from the protected access 400 | # warning. 401 | exclude-protected=_asdict,_fields,_replace,_source,_make 402 | 403 | # List of valid names for the first argument in a class method. 404 | valid-classmethod-first-arg=cls 405 | 406 | # List of valid names for the first argument in a metaclass class method. 407 | valid-metaclass-classmethod-first-arg=mcs 408 | 409 | 410 | [EXCEPTIONS] 411 | 412 | # Exceptions that will emit a warning when being caught. Defaults to 413 | # "Exception" 414 | overgeneral-exceptions=Exception 415 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | testpaths = tests 3 | python_files=test_*.py 4 | -------------------------------------------------------------------------------- /qspade: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import sys 3 | import traceback 4 | from PyQt5.QtWidgets import QApplication 5 | from client.mainwindow import SpadeMainWindow 6 | 7 | def rungui(args): 8 | try: 9 | app = QApplication(args) 10 | w = SpadeMainWindow() 11 | w.show() 12 | return app.exec_() 13 | except Exception as e: 14 | print("Exception!") 15 | print(e) 16 | traceback.print_exc() 17 | return 1 18 | 19 | if __name__ == "__main__": 20 | sys.exit(rungui(sys.argv)) 21 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [build_sphinx] 2 | source-dir = docs 3 | build-dir = docs/.build 4 | all_files = 1 5 | 6 | [aliases] 7 | test=pytest 8 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from setuptools import setup 3 | 4 | setup( 5 | name='spade', 6 | version='0.1', 7 | description='File format reverse engineering tool.', 8 | url='https://github.com/nyxxxie/spade', 9 | author='Nyxxie et al.', 10 | author_email='nyxxxxie@gmail.com', 11 | license='GNU GPL v3', 12 | packages=['spade'], 13 | package_data={ 14 | '': [ 'qspade' ], 15 | "spade": [ ], 16 | }, 17 | install_requires=[ 18 | 'PyQt5', 19 | 'pylint', 20 | 'pyyaml', 21 | 'sqlalchemy', 22 | 'Sphinx', 23 | 'pytest' 24 | 'pytest-cov' 25 | ], 26 | setup_requires=['pytest-runner'], 27 | tests_require=['pytest'], 28 | zip_safe=False 29 | ) 30 | -------------------------------------------------------------------------------- /spade/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nyxxxie/serenity/429cd9dbea77d63e624b9b738668848208176a22/spade/__init__.py -------------------------------------------------------------------------------- /spade/core/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nyxxxie/serenity/429cd9dbea77d63e624b9b738668848208176a22/spade/core/__init__.py -------------------------------------------------------------------------------- /spade/core/file.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | class SpaceFileException(Exception): pass 4 | 5 | 6 | class SFile(object): 7 | """Wrapper over built-in file object that some spade-specific behavior. 8 | 9 | Primarily used to help a spade project track changes and status of a file. 10 | This object offers all of the functionality found in the original file, 11 | with a few extra methods modified and added to enable some spade-specific 12 | functionality. 13 | """ 14 | 15 | mode_read = "rb" 16 | mode_write = "ab" 17 | mode_rw = "ab+" 18 | 19 | def __init__(self, project, _file, path: str): 20 | self.path = path 21 | self.project = project 22 | self._closed = False 23 | self._file = _file 24 | project._register_file(path, self.sha256()) 25 | 26 | def __enter__(self): 27 | return self 28 | 29 | def __exit__(self, _type, value, tb): 30 | self.close() 31 | 32 | def __repr__(self): 33 | return "" % self.path 34 | 35 | def __str__(self): 36 | return self.__repr__() 37 | 38 | def __getattr__(self, name): 39 | """This method is a bit of a hack, so here's an explaination: 40 | 41 | tl;dr this method transparently tries to get attributes that are not 42 | defined in SFile from the built-in file object. 43 | 44 | The goal of this class is to provide a transparent wrapper over the 45 | built-in file object that allows us to hook and modify the behavior of 46 | various methods. However, since we only modify a few of the methods, we 47 | can either choose to manually implement all of the other methods that we 48 | don't really care about or we can leave some unimplemented. Leaving 49 | some methods unimplemented ruins the goal of this class being a 50 | transparent replacement, but implementing all of them means we add a 51 | bunch of repetitive crap to this class and risk missing some more 52 | niche items. To get around that, we can override this method to 53 | effectively query the underlying file object for attributes we don't 54 | have but it might. 55 | """ 56 | return getattr(self._file, name) 57 | 58 | def save(self): 59 | """Saves a file that has been modified. 60 | 61 | This is requied because, even though in the current implementation of 62 | SFile we write directly to the file on disk, we must inform the project 63 | that we've updated it. 64 | """ 65 | self.project._update_file_hash(self.path, self.sha256()) 66 | 67 | def seek(self, offset: int=0, from_what: int=0) -> int: 68 | """Sets the cursor position relative to some position. 69 | 70 | :param offset: Offset into file relative to from_what parameter. 71 | :param from_what: Determines what the above offset is relative to. 72 | :return: Cursor position after the seek operation completes. 73 | 74 | The reference point specified by the ``from_what`` parameter should 75 | take on one of the following values: 76 | 77 | * 0 - Offset from beginning of file. 78 | * 1 - Offset from current cursor position. 79 | * 2 - Offset from end of file. 80 | 81 | The ``from_what`` parameter may be omitted, and will default to 0 82 | (beginning of file). 83 | """ 84 | return self._file.seek(offset, from_what) 85 | 86 | def close(self, save: bool=True): 87 | """Closes a file. 88 | 89 | :param save: Determines if we should automatically save this file on 90 | close. Set to True by default because I'm almost 100% sure no 91 | one's going to read the docs and will complain when their 92 | projects don't reload properly. Plus, I imagine there are very 93 | few scenarios when the common user won't want to save their 94 | changes to the project. 95 | :type save: bool 96 | """ 97 | # Save file before we close it 98 | if save: 99 | self.save() 100 | 101 | # Close file and indicate that we've done so 102 | self._file.close() 103 | self._closed = True 104 | 105 | def insert(self, data: bytes) -> int: 106 | """**NOT IMPLEMENTED** 107 | Insert bytes into file starting at the current cursor position. 108 | 109 | :param data: Bytes to insert. 110 | :type data: bytes 111 | :return: Amount of bytes inserted. 112 | """ 113 | return NotImplemented 114 | 115 | def replace(self, data: bytes) -> int: 116 | """Replaces bytes in file starting at the current cursor position. 117 | 118 | :param data: Bytes to replace. 119 | :type data: bytes 120 | :return: Amount of bytes replaced. 121 | """ 122 | return self._file.write(data) 123 | 124 | def erase(self, size: int=None) -> int: 125 | """**NOT IMPLEMENTED** 126 | Deletes bytes from file. 127 | 128 | :param size: Amount of bytes to erase. If this is None or no amount 129 | specified, erase will erase all bytes after the cursor's 130 | current position. 131 | :type size: int 132 | :return: Amount of bytes erased. 133 | """ 134 | return NotImplemented 135 | 136 | def sha256(self) -> bytes: 137 | """Calculates the sha256 hash of the file. 138 | 139 | :return: SHA256 hash (in bytes). 140 | """ 141 | return hash_file(self.path) 142 | 143 | @classmethod 144 | def open(cls, project, path: str, mode: str=mode_rw): 145 | f = open(path, mode) 146 | if not f or not project: 147 | return None 148 | 149 | return cls(project, f, path) 150 | 151 | 152 | def hash_file(path: str) -> bytes: 153 | """Utility function that calculates the hash of a file. 154 | 155 | :param path: Path to the file to hash. 156 | :type path: str 157 | """ 158 | with open(path, "rb") as f: 159 | f.seek(0,0) # seek to beginning of file 160 | h = hashlib.sha256() 161 | h.update(f.read()) 162 | return h.digest() 163 | -------------------------------------------------------------------------------- /spade/core/models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nyxxxie/serenity/429cd9dbea77d63e624b9b738668848208176a22/spade/core/models/__init__.py -------------------------------------------------------------------------------- /spade/core/models/project.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.ext.declarative import declarative_base 2 | from sqlalchemy import Column, String, Binary 3 | 4 | Base = declarative_base() #pylint: disable=invalid-name 5 | 6 | class ProjectInfo(Base): 7 | __tablename__ = "project_info" 8 | key = Column(String, nullable=False, primary_key=True) 9 | value = Column(String) 10 | 11 | class ProjectFile(Base): 12 | __tablename__ = "project_files" 13 | path = Column(String, nullable=False, primary_key=True) 14 | sha256 = Column(Binary(32)) 15 | -------------------------------------------------------------------------------- /spade/core/project.py: -------------------------------------------------------------------------------- 1 | import os 2 | import datetime 3 | from sqlalchemy import create_engine 4 | from sqlalchemy.orm import sessionmaker 5 | from spade.core.file import SFile, hash_file 6 | from spade.core.models.project import Base, ProjectInfo, ProjectFile 7 | 8 | SCHEMA_VERSION = "0.1" 9 | 10 | class SpadeProjectException(Exception): pass 11 | 12 | class Project(object): 13 | """Stores the state and data of a Spade session. 14 | 15 | Specifically, a project stores information on files that were opened, 16 | templates, and file metadata. Additionally, any data saved by plugins, 17 | analysis, etc is stored in a project. Projects by default store this data 18 | directly on disk in a sqlite database. 19 | """ 20 | 21 | def __init__(self, dbfile): 22 | self._db_init(dbfile) 23 | 24 | def __str__(self): 25 | return "" % (self.db_file) 26 | 27 | def open_file(self, path: str, mode: str=SFile.mode_rw) -> SFile: 28 | """Opens a file to be tracked by this project. 29 | 30 | :param path: Path to file that should be opened. 31 | :type path: str 32 | :param mode: Mode to open file in (default: read/write). 33 | :type mode: :ref:`Filemode ` 34 | :return: A :ref:`SFile ` object corresponding to the file. 35 | """ 36 | return SFile.open(self, path, mode) 37 | 38 | def db_engine(self): 39 | """Returns the sqlalchemy engine currently in use. 40 | 41 | :return: sqlalchemy engine currently in use. 42 | """ 43 | return self._db_engine 44 | 45 | def files(self): 46 | """Returns a list of all files tracked by the project. 47 | 48 | :return: A list of all files tracked by the project. 49 | """ 50 | paths = [] 51 | for entry in self._db_get_files(): 52 | paths.append(entry.path) 53 | 54 | return paths 55 | 56 | def get_info(self, key: str=None): 57 | """Retrieves project metadata associated with a key. 58 | 59 | If no key is specified, this function will return a list of all 60 | project metadata available. 61 | 62 | :param key: Key cooresponding to metadata item to fetch. If this is 63 | None, function will return a map of all info items in the 64 | project. 65 | :type key: str 66 | :return: The value associated with a key, if given, or a map of all info 67 | items in the project. 68 | """ 69 | # Create db session 70 | Session = sessionmaker(bind=self._db_engine) 71 | session = Session() 72 | 73 | if key is None: 74 | info = {} 75 | for row in session.query(ProjectInfo): 76 | info[row.key] = row.value 77 | return info 78 | else: 79 | entry = session.query(ProjectInfo).filter_by(key=key).first() 80 | if entry is not None: 81 | return entry.value 82 | 83 | return None 84 | 85 | def _add_info(self, key, value): 86 | # Create db session 87 | Session = sessionmaker(bind=self._db_engine) 88 | session = Session() 89 | 90 | # Add info to table 91 | info = ProjectInfo(key=key, value=value) 92 | session.merge(info) 93 | session.commit() 94 | 95 | def _db_get_files(self): 96 | # Create db session 97 | Session = sessionmaker(bind=self._db_engine) 98 | session = Session() 99 | 100 | # Add info to table 101 | return session.query(ProjectFile) 102 | 103 | def _register_file(self, path, file_hash): 104 | # Create db session 105 | Session = sessionmaker(bind=self._db_engine) 106 | session = Session() 107 | 108 | # Add info to table 109 | info = ProjectFile(path=path, sha256=file_hash) 110 | session.merge(info) 111 | session.commit() 112 | 113 | def _update_file_hash(self, path, file_hash): 114 | # Create db session 115 | Session = sessionmaker(bind=self._db_engine) 116 | session = Session() 117 | 118 | entry = session.query(ProjectFile).filter_by(path=path).first() 119 | if entry is None: 120 | assert SpadeProjectException(("Can't update hash, no file " 121 | "registered at \"{}\".").format(path)) 122 | entry.sha256 = file_hash 123 | 124 | session.commit() 125 | 126 | def _db_init(self, path: str): 127 | # Create engine 128 | engine = create_engine( 129 | "sqlite:///" + path, # Create sqlite db and engine for sqlalchemy 130 | echo=False) # TODO: This should probably be commented out at some point 131 | Base.metadata.create_all(engine) # Adds all of our tables into the db 132 | self.db_file = path 133 | self._db_engine = engine 134 | 135 | # Initialize database or load info 136 | date = datetime.datetime.now() 137 | if self.get_info("schema_version") is None: 138 | self._add_info("schema_version", SCHEMA_VERSION) 139 | self._add_info("creation_datetime", date) 140 | self._add_info("update_datetime", date) 141 | else: 142 | self._db_validate() 143 | self._db_update() 144 | 145 | def _db_validate(self): 146 | # Make sure project version string is compatible with this version of spade 147 | schema_version = self.get_info("schema_version") 148 | if schema_version != SCHEMA_VERSION: 149 | raise SpadeProjectException(("Project schema version \"{}\" is " 150 | "incompatible with this version of " 151 | "spade.").format(schema_version)) 152 | 153 | # Make sure all files tracked by his project exist and match their stored hashes 154 | for entry in self._db_get_files(): 155 | # Make sure file exists 156 | if not os.path.exists(entry.path): 157 | raise SpadeProjectException("Could not find tracked file " 158 | "\"{}\".".format(entry.path)) 159 | 160 | # Make sure file hash matches 161 | if hash_file(entry.path) != entry.sha256: 162 | raise SpadeProjectException("File \"{}\" has been modified " 163 | "since last " 164 | "open.".format(entry.path)) 165 | 166 | def _db_update(self): 167 | if self.get_info("schema_version") is None: 168 | raise SpadeProjectException("Can't update uninitialized database.") 169 | 170 | date = datetime.datetime.now() 171 | self._add_info("update_datetime", date) 172 | -------------------------------------------------------------------------------- /spade/typesystem/__init__.py: -------------------------------------------------------------------------------- 1 | from spade.typesystem.manager import TypeManager 2 | typemanager = TypeManager() #pylint: disable=invalid-name 3 | 4 | # Add default types to typemanager. The __init__.py in this directory imports 5 | # all types, and each type adds itself into the typemanager object. Is this 6 | # hacky? I dunno, but it works! 7 | import spade.typesystem.types #pylint: disable=wrong-import-position 8 | -------------------------------------------------------------------------------- /spade/typesystem/manager.py: -------------------------------------------------------------------------------- 1 | class TypeManager(object): 2 | def __init__(self): 3 | self._types = [] 4 | 5 | def add_type(self, typedef): 6 | """Adds a type definition identified by a given name.""" 7 | return self._types.append(typedef) 8 | 9 | def remove_type(self, name): 10 | """Removes a type definition given its name.""" 11 | for _type in self._types: 12 | for tname in _type.__typenames__: 13 | if tname == name: 14 | return self._types.remove(tname) 15 | 16 | return None 17 | 18 | def get_type(self, name): 19 | """Gets type definition by its name.""" 20 | for _type in self._types: 21 | for tname in _type.__typenames__: 22 | if tname == name: 23 | return _type 24 | 25 | return None 26 | 27 | def types(self): 28 | """Returns the string identifiers of all types currently registered.""" 29 | return [t.typedef for t in self._types] 30 | -------------------------------------------------------------------------------- /spade/typesystem/typedef.py: -------------------------------------------------------------------------------- 1 | class SpadeTypeException(Exception): pass 2 | 3 | class TypeDef(object): 4 | def __init__(self, data=None, size=0): 5 | self._string = None 6 | self._bytes = None 7 | self._size = size 8 | self.convert(data) 9 | 10 | def convert(self, data): 11 | self._string = self.to_string(data) 12 | self._bytes = self.to_bytes(data) 13 | 14 | def __str__(self): 15 | return self.string() 16 | 17 | def string(self) -> str: 18 | return self._string 19 | 20 | def bytes(self) -> bytes: 21 | return self._bytes 22 | 23 | def size(self) -> int: 24 | return self._size 25 | 26 | def to_string(self, data) -> str: 27 | """TODO: Implement this method for your custom type.""" 28 | pass 29 | 30 | def to_bytes(self, data) -> bytes: 31 | """TODO: Implement this method for your custom type.""" 32 | pass 33 | -------------------------------------------------------------------------------- /spade/typesystem/types/__init__.py: -------------------------------------------------------------------------------- 1 | import pkgutil 2 | from importlib import import_module 3 | 4 | TYPE_AMOUNT = 0 # This is used pretty much only in tests 5 | __path__ = pkgutil.extend_path(__path__, __name__) 6 | for _,modname,_ in pkgutil.walk_packages(path=__path__, prefix=__name__+"."): 7 | import_module(modname) 8 | TYPE_AMOUNT = TYPE_AMOUNT + 1 9 | -------------------------------------------------------------------------------- /spade/typesystem/types/byte.py: -------------------------------------------------------------------------------- 1 | from spade.typesystem import typemanager 2 | from spade.typesystem.typedef import TypeDef, SpadeTypeException 3 | 4 | class Byte(TypeDef): 5 | __typenames__ = ["byte", "b"] 6 | 7 | def __init__(self, data=None): 8 | super().__init__(data, 1) 9 | 10 | def to_string(self, data) -> str: 11 | if not data: 12 | return None 13 | 14 | if isinstance(data, bytes): 15 | ret = "" 16 | for byte in data: 17 | ret += "%02x" % (byte) 18 | return ret.upper() 19 | elif isinstance(data, str): 20 | return data.upper() 21 | else: 22 | raise SpadeTypeException("Can't convert {}.".format(type(data))) 23 | 24 | def to_bytes(self, data) -> bytes: 25 | if not data: 26 | return None 27 | 28 | if isinstance(data, bytes): 29 | return data 30 | elif isinstance(data, str): 31 | return bytes.fromhex(data) 32 | else: 33 | raise SpadeTypeException("Can't convert {}.".format(type(data))) 34 | 35 | typemanager.add_type(Byte) 36 | -------------------------------------------------------------------------------- /spade/typesystem/types/char.py: -------------------------------------------------------------------------------- 1 | from spade.typesystem import typemanager 2 | from spade.typesystem.typedef import TypeDef, SpadeTypeException 3 | 4 | class Char(TypeDef): 5 | __typenames__ = ["char", "c"] 6 | 7 | def __init__(self, data=None): 8 | super().__init__(data, 1) 9 | 10 | def to_string(self, data) -> str: 11 | if not data: 12 | return None 13 | 14 | if isinstance(data, bytes): 15 | return data.decode("ascii").upper() 16 | elif isinstance(data, str): 17 | return data.upper() 18 | else: 19 | raise SpadeTypeException("Can't convert {}.".format(type(data))) 20 | 21 | def to_bytes(self, data) -> bytes: 22 | if not data: 23 | return None 24 | 25 | if isinstance(data, bytes): 26 | return data 27 | elif isinstance(data, str): 28 | return data.upper().encode("ascii") 29 | else: 30 | raise SpadeTypeException("Can't convert {}.".format(type(data))) 31 | 32 | def unprintable(self): 33 | return not self.printable() 34 | 35 | def printable(self): 36 | if self.size() == 0 or not self.bytes(): 37 | return False 38 | 39 | for char in self.bytes(): 40 | if (char >= 0x00 and char <= 0x1F) or char == 0x7F: 41 | return False 42 | 43 | return True 44 | 45 | typemanager.add_type(Char) 46 | -------------------------------------------------------------------------------- /spade/typesystem/types/int32.py: -------------------------------------------------------------------------------- 1 | import struct 2 | from spade.typesystem import typemanager 3 | from spade.typesystem.typedef import TypeDef, SpadeTypeException 4 | 5 | class Int32(TypeDef): 6 | __typenames__ = ["int32", "int", "i32", "i32le"] 7 | 8 | def __init__(self, data=None): 9 | super().__init__(data, 4) 10 | 11 | def to_string(self, data) -> str: 12 | if not data: 13 | return None 14 | 15 | if isinstance(data, bytes): 16 | if len(data) != 4: 17 | return None 18 | try: 19 | data_bytes = struct.unpack('>i', data) 20 | if data_bytes: 21 | return str(data_bytes[0]) 22 | except struct.error: 23 | #raise SpadeTypeException("Data input size {} != 4 bytes.".format(len(data))) 24 | return None 25 | raise SpadeTypeException("output of struct.unpack was None.") 26 | elif isinstance(data, str): 27 | return data 28 | else: 29 | raise SpadeTypeException("Can't convert {}.".format(type(data))) 30 | 31 | def to_bytes(self, data) -> bytes: 32 | if not data: 33 | return None 34 | 35 | if isinstance(data, bytes): 36 | if len(data) == 4: 37 | return data 38 | elif isinstance(data, str): 39 | return struct.pack(">i", int(data)) 40 | else: 41 | raise SpadeTypeException("Can't convert {}.".format(type(data))) 42 | 43 | return None 44 | 45 | typemanager.add_type(Int32) 46 | -------------------------------------------------------------------------------- /spade/typesystem/types/uint32.py: -------------------------------------------------------------------------------- 1 | import struct 2 | from spade.typesystem import typemanager 3 | from spade.typesystem.typedef import TypeDef, SpadeTypeException 4 | 5 | class UInt32(TypeDef): 6 | __typenames__ = ["uint32", "uint", "ui32", "ui32le"] 7 | 8 | def __init__(self, data=None): 9 | super().__init__(data, 4) 10 | 11 | def to_string(self, data) -> str: 12 | if not data: 13 | return None 14 | 15 | if isinstance(data, bytes): 16 | if len(data) != 4: 17 | return None 18 | try: 19 | data_bytes = struct.unpack('>I', data) 20 | if data_bytes: 21 | return str(data_bytes[0]) 22 | except struct.error: 23 | #raise SpadeTypeException("Data input size {} != 4 bytes.".format(len(data))) 24 | return None 25 | raise SpadeTypeException("output of struct.unpack was None.") 26 | elif isinstance(data, str): 27 | return data 28 | else: 29 | raise SpadeTypeException("Can't convert {}.".format(type(data))) 30 | 31 | def to_bytes(self, data) -> bytes: 32 | if not data: 33 | return None 34 | 35 | if isinstance(data, bytes): 36 | if len(data) == 4: 37 | return data 38 | elif isinstance(data, str): 39 | return struct.pack(">I", int(data)) 40 | else: 41 | raise SpadeTypeException("Can't convert {}.".format(type(data))) 42 | 43 | return None 44 | 45 | typemanager.add_type(UInt32) 46 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nyxxxie/serenity/429cd9dbea77d63e624b9b738668848208176a22/tests/__init__.py -------------------------------------------------------------------------------- /tests/core/fixtures.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pytest 3 | from shutil import copyfile 4 | from spade.core.project import Project 5 | 6 | DB_FILE = "testdb.sdb" 7 | RELATIVE_DIR = os.path.dirname(os.path.realpath(__file__)) 8 | 9 | @pytest.fixture() 10 | def testfile1(): 11 | """ 12 | This fixture creates a copy of testfile1 that can be read and written to 13 | and yields a usable path to it. It also deletes the file when the test 14 | concludes. 15 | """ 16 | # copy test file from template, yield path 17 | orig_path = os.path.join(RELATIVE_DIR, "testdata", "testfile1") 18 | path = "_testfile1" 19 | copyfile(orig_path, path) 20 | yield path 21 | if os.path.exists(path): # We might have already deleted the file in a test 22 | os.remove(path) 23 | 24 | @pytest.fixture() 25 | def testfile2(): 26 | """ 27 | This fixture creates a copy of testfile2 that can be read and written to 28 | and yields a usable path to it. It also deletes the file when the test 29 | concludes. 30 | """ 31 | # copy test file from template, yield path 32 | orig_path = os.path.join(RELATIVE_DIR, "testdata", "testfile2") 33 | path = "_testfile2" 34 | copyfile(orig_path, path) 35 | yield path 36 | if os.path.exists(path): # We might have already deleted the file in a test 37 | os.remove(path) 38 | 39 | @pytest.fixture() 40 | def project(): 41 | """ 42 | This fixture creates and yields a project for use in tests. 43 | """ 44 | project = Project(DB_FILE) 45 | yield project 46 | os.remove(DB_FILE) 47 | 48 | -------------------------------------------------------------------------------- /tests/core/test_file.py: -------------------------------------------------------------------------------- 1 | from spade.core.file import SFile 2 | from spade.core.project import Project 3 | from tests.core.fixtures import testfile1, project 4 | 5 | def testfile1_openclose1(testfile1, project): 6 | f = project.open_file(testfile1) 7 | assert f 8 | assert isinstance(f, SFile) 9 | f.close() 10 | assert f._closed 11 | 12 | def testfile1_openclose2(testfile1, project): 13 | with project.open_file(testfile1) as f: 14 | assert f 15 | assert isinstance(f, SFile) 16 | assert f._closed 17 | -------------------------------------------------------------------------------- /tests/core/test_project.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pytest 3 | from shutil import copyfile 4 | from spade.core.file import SFile 5 | from spade.core.project import Project, SpadeProjectException, SCHEMA_VERSION 6 | from tests.utils.project_sql import check_table 7 | from tests.core.fixtures import testfile1, testfile2, project, DB_FILE 8 | 9 | def test_initialization(testfile1, project): 10 | assert project is not None 11 | dbfile = project.db_file 12 | 13 | # Verify default tables exist 14 | assert check_table(dbfile, "project_info") 15 | assert check_table(dbfile, "project_files") 16 | 17 | def test_reopen(project): 18 | assert project is not None 19 | dbfile = project.db_file 20 | 21 | # Verify default tables exist 22 | assert check_table(dbfile, "project_info") 23 | assert check_table(dbfile, "project_files") 24 | 25 | # Reopen project 26 | project = Project(dbfile) 27 | assert project is not None 28 | 29 | # Verify default tables exist 30 | assert check_table(dbfile, "project_info") 31 | assert check_table(dbfile, "project_files") 32 | 33 | def test_fail_reopen_not_a_db(testfile1): 34 | caught = False 35 | try: 36 | project = Project(testfile1) # Ideally, this file shouldn't be a sqlite db 37 | except Exception as e: 38 | caught = True 39 | 40 | assert caught 41 | 42 | def test_fail_reopen_unsupported_schema_ver(project): 43 | pass # TODO: make a project with a messed up version, then try to reopen it 44 | 45 | def test_open_files(testfile1, testfile2, project): 46 | assert project is not None 47 | 48 | # Open files 49 | f1 = project.open_file(testfile1, SFile.mode_read) 50 | assert f1 is not None 51 | f2 = project.open_file(testfile2, SFile.mode_read) 52 | assert f2 is not None 53 | 54 | paths = project.files() 55 | assert len(paths) == 2 56 | assert testfile1 in paths 57 | assert testfile2 in paths 58 | 59 | def test_fail_modified_file(testfile1, testfile2, project): 60 | assert project is not None 61 | 62 | # Open file (and thereby register it in the project) 63 | f1 = project.open_file(testfile1, SFile.mode_read) 64 | assert f1 is not None 65 | f1.close() 66 | 67 | # Simulate modifying the file externally 68 | with open(testfile1, "wb+") as f: 69 | f.write(b"DO YOU BELIEVE IN SOCIETY'S LIES??") 70 | 71 | # Try to open new project and check to see if this fails 72 | caught = False 73 | try: 74 | project = Project(DB_FILE) 75 | except SpadeProjectException as e: 76 | caught = True 77 | 78 | assert caught 79 | 80 | def test_fail_deleted_file(testfile1, project): 81 | assert project is not None 82 | 83 | # Open file (and thereby register it in the project) 84 | f1 = project.open_file(testfile1, SFile.mode_read) 85 | assert f1 is not None 86 | f1.close() 87 | 88 | # Simulate an external delete 89 | os.remove(testfile1) 90 | 91 | caught = False 92 | try: 93 | project = Project(DB_FILE) 94 | except SpadeProjectException as e: 95 | caught = True 96 | 97 | assert caught 98 | 99 | def test_get_all_info(project): 100 | assert project is not None 101 | info = project.get_info() 102 | assert info is not None 103 | assert len(info) == 3 104 | assert info["schema_version"] == SCHEMA_VERSION 105 | 106 | def test_get_specific_info(project): 107 | assert project is not None 108 | version = project.get_info("schema_version") 109 | assert version is not None 110 | assert version == SCHEMA_VERSION 111 | -------------------------------------------------------------------------------- /tests/core/testdata/testfile1: -------------------------------------------------------------------------------- 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 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /tests/core/testdata/testfile2: -------------------------------------------------------------------------------- 1 | The results are unavoidable when FISH TIME 2 | -------------------------------------------------------------------------------- /tests/typesystem/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nyxxxie/serenity/429cd9dbea77d63e624b9b738668848208176a22/tests/typesystem/__init__.py -------------------------------------------------------------------------------- /tests/typesystem/fixtures.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from spade.typesystem.manager import TypeManager 3 | 4 | @pytest.fixture() 5 | def typemanager(): 6 | """ 7 | This fixture creates and yields a typemanager object for use in tests. 8 | """ 9 | mngr = TypeManager() 10 | yield mngr 11 | -------------------------------------------------------------------------------- /tests/typesystem/test_byte.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from spade.typesystem import typemanager 3 | from spade.typesystem.types.byte import Byte 4 | 5 | test_data = [ 6 | ("00", 0x00), # Smallest value 7 | ("FF", 0xFF), # 8 | ("fF", 0xFF), 9 | ("Ff", 0xFF), 10 | ("ff", 0xFF), 11 | ("CD", 0xCD), 12 | ("43", 0x43), 13 | ("C8", 0xC8), 14 | ("c8", 0xC8), 15 | ("6A", 0x6A), 16 | ("6a", 0x6A), 17 | ] 18 | 19 | # --------------------------- 20 | # INIT AND ODD CASES 21 | # --------------------------- 22 | def test_init(): 23 | byte = Byte() 24 | assert byte.size() == 1 25 | assert byte.string() is None 26 | assert byte.bytes() is None 27 | 28 | def test_none(): 29 | byte = Byte(None) 30 | assert byte.size() == 1 31 | assert byte.string() is None 32 | assert byte.bytes() is None 33 | 34 | def test_empty_bytes(): 35 | byte = Byte(bytes([])) 36 | assert byte.size() == 1 37 | assert byte.string() is None 38 | assert byte.bytes() is None 39 | 40 | def test_empty_string(): 41 | byte = Byte("") 42 | assert byte.size() == 1 43 | assert byte.string() is None 44 | assert byte.bytes() is None 45 | 46 | # --------------------------- 47 | # TO BYTE 48 | # --------------------------- 49 | @pytest.mark.parametrize("string,byte", test_data) 50 | def test_convert_to_byte(string, byte): 51 | b = Byte(string) 52 | assert b.size() == 1 53 | assert b.string() == string.upper() 54 | assert b.bytes() == bytes([byte]) 55 | 56 | # --------------------------- 57 | # TO STRING 58 | # --------------------------- 59 | @pytest.mark.parametrize("string,byte", test_data) 60 | def test_convert_to_string(string, byte): 61 | b = Byte(bytes([byte])) 62 | assert b.size() == 1 63 | assert b.string() == string.upper() 64 | assert b.bytes() == bytes([byte]) 65 | 66 | # --------------------------- 67 | # TYPESYSTEM INTEGRATION 68 | # --------------------------- 69 | def test_typemanager_added(): 70 | for name in Byte.__typenames__: 71 | assert typemanager.get_type(name) is not None 72 | -------------------------------------------------------------------------------- /tests/typesystem/test_char.py: -------------------------------------------------------------------------------- 1 | from spade.typesystem import typemanager 2 | from spade.typesystem.types.char import Char 3 | 4 | # --------------------------- 5 | # INIT AND ODD CASES 6 | # --------------------------- 7 | def test_init(): 8 | char = Char() 9 | assert char.size() == 1 10 | assert char.string() is None 11 | assert char.bytes() is None 12 | assert char.unprintable() 13 | 14 | def test_none(): 15 | char = Char(None) 16 | assert char.size() == 1 17 | assert char.string() is None 18 | assert char.bytes() is None 19 | assert char.unprintable() 20 | 21 | def test_empty_chars(): 22 | char = Char(bytes([])) 23 | assert char.size() == 1 24 | assert char.string() is None 25 | assert char.bytes() is None 26 | assert char.unprintable() 27 | 28 | def test_empty_string(): 29 | char = Char("") 30 | assert char.size() == 1 31 | assert char.string() is None 32 | assert char.bytes() is None 33 | assert char.unprintable() 34 | 35 | 36 | # --------------------------- 37 | # CONVERT A 38 | # --------------------------- 39 | def test_convert_letter_string_lower(): 40 | char = Char("A") 41 | assert char.size() == 1 42 | assert char.string() == "A" 43 | assert char.bytes() == bytes([0x41]) 44 | assert not char.unprintable() 45 | 46 | def test_convert_letter_string_lower(): 47 | char = Char("a") 48 | assert char.size() == 1 49 | assert char.string() == "A" 50 | assert char.bytes() == bytes([0x41]) 51 | assert not char.unprintable() 52 | 53 | def test_convert_letter_chars(): 54 | char = Char(bytes([0x41])) 55 | assert char.size() == 1 56 | assert char.string() == "A" 57 | assert char.bytes() == bytes([0x41]) 58 | assert not char.unprintable() 59 | 60 | 61 | # --------------------------- 62 | # CONVERT 7 63 | # --------------------------- 64 | def test_convert_number_string(): 65 | char = Char("7") 66 | assert char.size() == 1 67 | assert char.string() == "7" 68 | assert char.bytes() == bytes([0x37]) 69 | assert not char.unprintable() 70 | 71 | def test_convert_number_chars(): 72 | char = Char(bytes([0x37])) 73 | assert char.size() == 1 74 | assert char.string() == "7" 75 | assert char.bytes() == bytes([0x37]) 76 | assert not char.unprintable() 77 | 78 | 79 | # --------------------------- 80 | # CONVERT UNPRINTABLE 81 | # --------------------------- 82 | def test_convert_number_string(): 83 | char = Char("\n") 84 | assert char.size() == 1 85 | assert char.string() == "\n" 86 | assert char.bytes() == bytes([0x0A]) 87 | assert char.unprintable() 88 | 89 | def test_convert_number_chars(): 90 | char = Char(bytes([0x0A])) 91 | assert char.size() == 1 92 | assert char.string() == "\n" 93 | assert char.bytes() == bytes([0x0A]) 94 | assert char.unprintable() 95 | -------------------------------------------------------------------------------- /tests/typesystem/test_int32.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from spade.typesystem import typemanager 3 | from spade.typesystem.types.int32 import Int32 4 | 5 | # --------------------------- 6 | # INIT AND ODD CASES 7 | # --------------------------- 8 | def test_init(): 9 | int32 = Int32() 10 | assert int32.size() == 4 11 | assert int32.string() is None 12 | assert int32.bytes() is None 13 | 14 | def test_none(): 15 | int32 = Int32() 16 | assert int32.size() == 4 17 | assert int32.string() is None 18 | assert int32.bytes() is None 19 | 20 | def test_empty_bytes(): 21 | int32 = Int32(bytes([])) 22 | assert int32.size() == 4 23 | assert int32.string() is None 24 | assert int32.bytes() is None 25 | 26 | def test_empty_string(): 27 | int32 = Int32("") 28 | assert int32.size() == 4 29 | assert int32.string() is None 30 | assert int32.bytes() is None 31 | 32 | def test_too_few_bytes(): 33 | int32 = Int32(bytes([0x13, 0x37])) 34 | assert int32.size() == 4 35 | assert int32.string() is None 36 | assert int32.bytes() is None 37 | 38 | def test_too_many_bytes(): 39 | int32 = Int32(bytes([0x00, 0x00, 0x00, 0x01, 0x00])) 40 | assert int32.size() == 4 41 | assert int32.string() is None 42 | assert int32.bytes() is None 43 | #assert int32.size() == 4 44 | #assert int32.string() == "1" 45 | #assert int32.bytes() == bytes([0x00, 0x00, 0x00, 0x01]) 46 | 47 | 48 | # --------------------------- 49 | # CONVERT ZERO 50 | # --------------------------- 51 | def test_convert_zero_string(): 52 | int32 = Int32("0") 53 | assert int32.string() == "0" 54 | assert int32.bytes() == bytes([0x00, 0x00, 0x00, 0x00]) 55 | 56 | def test_convert_zero_bytes(): 57 | int32 = Int32(bytes([0x00, 0x00, 0x00, 0x00])) 58 | assert int32.string() == "0" 59 | assert int32.bytes() == bytes([0x00, 0x00, 0x00, 0x00]) 60 | 61 | 62 | # --------------------------- 63 | # CONVERT MIN 64 | # --------------------------- 65 | def test_convert_min_string(): 66 | int32 = Int32("-2147483648") 67 | assert int32.string() == "-2147483648" 68 | assert int32.bytes() == bytes([0x80, 0x00, 0x00, 0x00]) 69 | 70 | def test_convert_min_bytes(): 71 | int32 = Int32(bytes([0x80, 0x00, 0x00, 0x00])) #TODO: get binary value for this 72 | assert int32.string() == "-2147483648" 73 | assert int32.bytes() == bytes([0x80, 0x00, 0x00, 0x00]) 74 | 75 | 76 | # --------------------------- 77 | # CONVERT MAX 78 | # --------------------------- 79 | def test_convert_max_string(): 80 | int32 = Int32("2147483647") 81 | assert int32.string() == "2147483647" 82 | assert int32.bytes() == bytes([0x7F, 0xFF, 0xFF, 0xFF]) 83 | 84 | def test_convert_max_bytes(): 85 | int32 = Int32(bytes([0x7F, 0xFF, 0xFF, 0xFF])) 86 | assert int32.string() == "2147483647" 87 | assert int32.bytes() == bytes([0x7F, 0xFF, 0xFF, 0xFF]) 88 | 89 | 90 | # --------------------------- 91 | # CONVERT NEGATIVE 92 | # --------------------------- 93 | def test_convert_negative_string(): 94 | int32 = Int32("-1") 95 | assert int32.string() == "-1" 96 | assert int32.bytes() == bytes([0xFF, 0xFF, 0xFF, 0xFF]) 97 | 98 | def test_convert_negative_bytes(): 99 | int32 = Int32(bytes([0xFF, 0xFF, 0xFF, 0xFF])) 100 | assert int32.string() == "-1" 101 | assert int32.bytes() == bytes([0xFF, 0xFF, 0xFF, 0xFF]) 102 | 103 | 104 | # --------------------------- 105 | # CONVERT POSITIVE 106 | # --------------------------- 107 | def test_convert_positive_string(): 108 | int32 = Int32("1") 109 | assert int32.string() == "1" 110 | assert int32.bytes() == bytes([0x00, 0x00, 0x00, 0x01]) 111 | 112 | def test_convert_positive_bytes(): 113 | int32 = Int32(bytes([0x00, 0x00, 0x00, 0x01])) 114 | assert int32.string() == "1" 115 | assert int32.bytes() == bytes([0x00, 0x00, 0x00, 0x01]) 116 | 117 | 118 | # --------------------------- 119 | # TYPESYSTEM INTEGRATION 120 | # --------------------------- 121 | def test_typemanager_added(): 122 | for name in Int32.__typenames__: 123 | assert typemanager.get_type(name) is not None 124 | -------------------------------------------------------------------------------- /tests/typesystem/test_manager.py: -------------------------------------------------------------------------------- 1 | from spade.typesystem.manager import TypeManager 2 | from spade.typesystem.types import TYPE_AMOUNT 3 | from spade.typesystem import typemanager 4 | 5 | # --------------------------- 6 | # TypeManager TESTS 7 | # --------------------------- 8 | def test_init(): 9 | mngr = TypeManager() 10 | assert len(mngr._types) == 0 11 | 12 | 13 | # --------------------------- 14 | # typemanager TESTS 15 | # --------------------------- 16 | def test_typemanager_types_added(): 17 | assert typemanager is not None 18 | assert len(typemanager._types) == TYPE_AMOUNT 19 | -------------------------------------------------------------------------------- /tests/typesystem/test_uint32.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from spade.typesystem import typemanager 3 | from spade.typesystem.types.uint32 import UInt32 4 | 5 | # --------------------------- 6 | # INIT AND ODD CASES 7 | # --------------------------- 8 | def test_init(): 9 | uint32 = UInt32() 10 | assert uint32.size() == 4 11 | assert uint32.string() is None 12 | assert uint32.bytes() is None 13 | 14 | def test_none(): 15 | uint32 = UInt32() 16 | assert uint32.size() == 4 17 | assert uint32.string() is None 18 | assert uint32.bytes() is None 19 | 20 | def test_empty_bytes(): 21 | uint32 = UInt32(bytes([])) 22 | assert uint32.size() == 4 23 | assert uint32.string() is None 24 | assert uint32.bytes() is None 25 | 26 | def test_empty_string(): 27 | uint32 = UInt32("") 28 | assert uint32.size() == 4 29 | assert uint32.string() is None 30 | assert uint32.bytes() is None 31 | 32 | def test_too_few_bytes(): 33 | uint32 = UInt32(bytes([0x13, 0x37])) 34 | assert uint32.size() == 4 35 | assert uint32.string() is None 36 | assert uint32.bytes() is None 37 | 38 | def test_too_many_bytes(): 39 | uint32 = UInt32(bytes([0x00, 0x00, 0x00, 0x01, 0x00])) 40 | assert uint32.size() == 4 41 | assert uint32.string() is None 42 | assert uint32.bytes() is None 43 | 44 | 45 | # --------------------------- 46 | # CONVERT ZERO 47 | # --------------------------- 48 | def test_convert_zero_string(): 49 | uint32 = UInt32("0") 50 | assert uint32.size() == 4 51 | assert uint32.string() == "0" 52 | assert uint32.bytes() == bytes([0x00, 0x00, 0x00, 0x00]) 53 | 54 | def test_convert_zero_bytes(): 55 | uint32 = UInt32(bytes([0x00, 0x00, 0x00, 0x00])) 56 | assert uint32.size() == 4 57 | assert uint32.string() == "0" 58 | assert uint32.bytes() == bytes([0x00, 0x00, 0x00, 0x00]) 59 | 60 | 61 | # --------------------------- 62 | # CONVERT MIN 63 | # --------------------------- 64 | def test_convert_min_string(): 65 | uint32 = UInt32("1") 66 | assert uint32.size() == 4 67 | assert uint32.string() == "1" 68 | assert uint32.bytes() == bytes([0x00, 0x00, 0x00, 0x01]) 69 | 70 | def test_convert_min_bytes(): 71 | uint32 = UInt32(bytes([0x00, 0x00, 0x00, 0x01])) #TODO: get binary value for this 72 | assert uint32.size() == 4 73 | assert uint32.string() == "1" 74 | assert uint32.bytes() == bytes([0x00, 0x00, 0x00, 0x01]) 75 | 76 | 77 | # --------------------------- 78 | # CONVERT MAX 79 | # --------------------------- 80 | def test_convert_max_string(): 81 | uint32 = UInt32("4294967295") 82 | assert uint32.size() == 4 83 | assert uint32.string() == "4294967295" 84 | assert uint32.bytes() == bytes([0xFF, 0xFF, 0xFF, 0xFF]) 85 | 86 | def test_convert_max_bytes(): 87 | uint32 = UInt32(bytes([0xFF, 0xFF, 0xFF, 0xFF])) 88 | assert uint32.size() == 4 89 | assert uint32.string() == "4294967295" 90 | assert uint32.bytes() == bytes([0xFF, 0xFF, 0xFF, 0xFF]) 91 | 92 | 93 | # --------------------------- 94 | # TYPESYSTEM INTEGRATION 95 | # --------------------------- 96 | def test_typemanager_added(): 97 | for name in UInt32.__typenames__: 98 | assert typemanager.get_type(name) is not None 99 | -------------------------------------------------------------------------------- /tests/utils/__init__.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | def try_convert_inverse(type, str_expected: str, bytes_expected: bytes): 4 | """ 5 | Nice utility function to help test type conversions whose to_string and 6 | from_string operations are functionally inverses of each other. 7 | """ 8 | # From string to bytes 9 | b = type.from_string(str_expected) 10 | if b is None: 11 | pytest.fail("String -> Byte result was None.") 12 | 13 | if len(b) != len(bytes_expected): 14 | pytest.fail("String -> Byte result size ({}) is not the correct size ({}).".format(len(b), len(bytes_expected))) 15 | 16 | if b != bytes_expected: 17 | pytest.fail("String -> Byte result does not match what was expected [{!r} != {!r}].".format(b, bytes_expected)) 18 | 19 | # From bytes to string 20 | s = type.to_string(b) 21 | if s is None: 22 | pytest.fail("Byte -> String result was None") 23 | 24 | if len(s) != len(str_expected): 25 | pytest.fail("Byte -> String result size {} (\"{}\") is not the correct size {} (\"{}\").".format(len(s), s, len(str_expected), str_expected)) 26 | 27 | if s != str_expected.lower(): 28 | pytest.fail("Byte -> String result does not match what was expected [{!r} != {!r}].".format(s, str_expected)) 29 | -------------------------------------------------------------------------------- /tests/utils/project_sql.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | def check_table(dbfile, table_name): 4 | conn = sqlite3.connect(dbfile) 5 | c = conn.cursor() 6 | c.execute("SELECT name FROM sqlite_master WHERE name=\"%s\"" % (table_name)) 7 | all_rows = c.fetchall() 8 | conn.close() 9 | return (len(all_rows) == 1) 10 | --------------------------------------------------------------------------------