commit 7a8eb69bf9c775a2dbe250a72d0f06786be0aeb9 Author: Tracy Rust Date: Sun Dec 10 23:14:52 2023 -0500 Relicensing the code and removing it from github. Prev commit March 2020 diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..1fd130c --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,88 @@ +#This file is part of the IVD project and is licensed under the terms of the + +cmake_minimum_required(VERSION 3.12) + +project(Reprodyne LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(REPRODYNE_MAJOR_VERSION 1) +set(REPRODYNE_MINOR_VERSION 0) +set(REPRODYNE_PATCH_VERSION 0) + +set(REPRODYNE_API_VERSION ${REPRODYNE_MAJOR_VERSION}.${REPRODYNE_MINOR_VERSION}) +set(REPRODYNE_VERSION ${REPRODYNE_API_VERSION}.${REPRODYNE_PATCH_VERSION}) + +set(REPRODYNE_USER_INCLUDE_DIRS ${CMAKE_INSTALL_PREFIX}/include/reprodyne${REPRODYNE_API_VERSION}) + +add_library(reprodyne +user-include/reprodyne.h + +errorstuff.h + +scopehandlers.h +scopehandlers.cpp + +scopecontainers.h +scopecontainers.cpp + +fileformat.h +programhandlers.h +programhandlers.cpp + +reprodyne.cpp + +${CMAKE_CURRENT_BINARY_DIR}/schema_generated.h +) + +set_target_properties(reprodyne PROPERTIES PUBLIC_HEADER "${PROJECT_SOURCE_DIR}/user-include/reprodyne.h") +target_compile_definitions(reprodyne PUBLIC REPRODYNE_AVAILABLE) +target_include_directories(reprodyne PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) + +find_package(ZLIB REQUIRED) + +find_package(Flatbuffers REQUIRED) +find_package(OpenSSL REQUIRED) +find_package(Catch2) + +target_link_libraries(reprodyne ${ZLIB_LIBRARIES}) +target_link_libraries(reprodyne ${OPENSSL_CRYPTO_LIBRARY}) + +add_custom_command(DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/schema.fbs + COMMAND flatbuffers::flatc --cpp ${CMAKE_CURRENT_SOURCE_DIR}/schema.fbs + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/schema_generated.h ) + +if(DEFINED Catch2_FOUND) + add_executable(reprodyne_tests + tests/catchmain.cpp + tests/oopsiewhoopsie.h + + tests/tests.cpp + tests/videotests.cpp + ) + target_link_libraries(reprodyne_tests reprodyne) +endif() + + + +install(TARGETS reprodyne EXPORT reprodyne-targets + ARCHIVE + DESTINATION lib/reprodyne${REPRODYNE_VERSION} + PUBLIC_HEADER + DESTINATION ${REPRODYNE_USER_INCLUDE_DIRS}) + +include(CMakePackageConfigHelpers) + +write_basic_package_version_file(reprodyne-config-version.cmake + VERSION ${REPRODYNE_VERSION} + COMPATIBILITY SameMajorVersion) + +configure_file(reprodyne-config.cmake.in + ${CMAKE_BINARY_DIR}/reprodyne-config.cmake @ONLY) + +install(FILES ${CMAKE_BINARY_DIR}/reprodyne-config.cmake ${CMAKE_BINARY_DIR}/reprodyne-config-version.cmake + DESTINATION lib/cmake/reprodyne${REPRODYNE_VERSION}) + +install(EXPORT reprodyne-targets + DESTINATION lib/cmake/reprodyne${REPRODYNE_VERSION}) diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3dfeccd --- /dev/null +++ b/README.md @@ -0,0 +1,248 @@ +# Reprodyne +Reprodyne is a C/C++ library for automating manual tests. + +Generally speaking, real world data is both easier and faster to generate, and more interesting to test against, than artificial test conditions written in sterile environments. Reproducibility, however, is limited. Reprodyne attempts to solve this problem by "recording" manual tests to later be played back automatically. + +Reprodyne is not meant to *replace* existing test frameworks, but rather to augment their capabilities. It should be possible, at least in theory, to integrate it with any test framework. + +From a high level, Reprodyne works by transforming non-deterministic funtions into deterministic ones, and saving their results for testing. "Interceptors" capture indeterminate values in record mode and resupply them in playback mode. "Validators" save values produced by the program in record mode, and compares against them in playback mode, signaling a playback failure if anything is different. + +The Reprodyne API is defined entirely as a set of preprocessor macros, so that once you're done testing, they gracefully expand into no-ops and there is no longer a need to link against the library. + +![Demo gif of Reprodyne](demo.gif) + +# Build/Install +#### Required toolchain: +- C++ compiler with C++17 support +- CMake >= 3.12 + +#### The following libraries must be available to CMake: +- ZLIB +- Flatbuffers +- OpenSSL/Crypto +- Catch2 (Optional. Required for testing Reprodyne itself) + +Reprodyne follows standard CMake usage e.g. from your build directory: + + cmake REPRODYNE-SOURCE-DIR + cmake --build . + sudo cmake --install . + +Reprodyne will be installed in the following directories: + + /usr/local/lib + /usr/local/include + +You can optionally provide a prefix for the install path: + + cmake --install . --prefix THE-DIRECTORY-YOU-WANT + +Which will of course prefix the install path as such: + + THE-DIRECTORY-YOU-WANT/usr/local/lib + THE-DIRECTORY-YOU-WANT/usr/local/include + +--- +**Note**: If you want to explore the code for the library itself, you will probably want to build it first as the source calls generated header code and your tools might get mad at you if it doesn't exist yet. + + +## Running The Library Tests + +Simply run the "reprodyne_tests" executable located in the build directory: + + ./reprodyne_tests + +## Including Reprodyne in Your Projects +### CMake Examples + + #Exact match for major version 1, and minimum minor/patch verion 0 + find_package(reprodyne 1.0.0 REQUIRED) + + target_link_library(YOUR-TARGET reprodyne) + +If it is found then the include director(ies) will be in REPRODYNE_INCLUDE_DIRS: + + target_include_directories(YOUR-TARGET ${REPRODYNE_INCLUDE_DIRS}) + +To toggle usage of the library macros, define REPRODYNE_AVAILABLE: + + target_compile_definitions(YOUR-TARGET PRIVATE REPRODYNE_AVAILABLE) + +--- +### And for The Love of God + +Please don't do this: + + + +Minor versions should be backwards compatible, and with this you are hardcoding an exact minor version requirement. + +With or without CMake, you should be including reprodyne as such: + + + +If you're not using CMake do whatever you have to do to point your non-CMake peasant-build system to the directory containing the appropriate version of this header. + +# How it Works/Theory + +As far as I can see, there are two ways to use Reprodyne. You can either integrate the interceptors and validators directly into your codebase (Which has first-class support, that is why the macros can compile into no-ops), or you can write mocks that use them behind the scenes. I will not dictate what the "correct" approach is, as this is a decision best left to the particular developer(s) of a given project. + + + +## Scopes, Frames and Subscope Keys oh my! + +Data in Reprodyne is aligned by the combination of the the current *frame*, *scope*, and *subscope*. + +Playback data is bound to a *scope*, which is represented by a pointer. The idea is that for a given scope you have a set of indeterminates going in, and values coming out, independent of the order of execution of any other scope currently being executed. This reduces coupling between the tests and the absolute order of execution. + +Frames are the synchronization mechanism for scopes. The intention being that for a given go-round of the program's *main outer loop*, all scopes should be done processing whatever it is that they are responsible for, *for a given iteration*. Again, frames are *only* to be marked at a high level of the program. + +Subscopes follow the same rules as scopes except: They are addressed by a their parent scope and a string key. A given scope (Which is most commonly just an object) might have several things going on where the order of execution is not *inherently* serial. In this case, we don't want Reprodyne to enforce the order of execution, otherwise it would limit our ability to refactor. To solve this problem, the order of execution is only tracked on the subscope level. This prevents tight coupling of the tests to arbitrary design decisions that don't affect the result we care about. One nice side-benefit of this is that naming the subscope allows Reprodyne to tell you exactly what part of the scope failed and to a limited extent, how. + +You may think that an object should only do one thing, and that anything else should be handled by other objects. Child objects, perhaps. This was actually the driving motivion *for* subscopes. Working this way, you simply register the scope of a primary object, and then any child objects use subscopes, this way the *hierarchy* of excution is preserved but not the order of the subscopes. You could track the addresses of all these child objects, but that could become unwieldy, it's hard enough to guarantee the order of allocation of a bunch of root objects, much less all of their children, grandchildren, etc... + +## Interceptors and Validators + +In record mode, an intercept function takes a value, saves it against the scope/subscope pair, along with the frame ID, and then returns it to your code like nothing ever happened. + +In playback mode, it is exactly the same *interface,* but the intercepted value is discarded and Reprodyne attempts to retrieve one saved previously to be returned so your code runs exactly as it did in record mode. + +Care must be taken to ensure that you intercept all *true* indeterminate values. Otherwise you'll get "almost deterministic" behaviour. + +If anything is amiss with the number of calls to a given scope, or there is a difference in frame ID or the like, then a playback error will be raised. + +Validators are just like interceptors, but they return nothing, and in playback mode they attempt to compare the provided value against the stored one. + +Errors are likewise the same for validators but they will additionally raise a playback error if the stored value is different from the provided one. + +Currently, interceptors can intercept doubles and validators can validate strings and hashes of bitmaps. This will be extended in the future. + +# Learn by Example + +There are two classes of functions in Reprodyne. Functions intended to be called by the test administration code, and functions intended to be called within the code under test. + +Your code under test might look something like this: + + #include + #include + #include "someruntimeclass.h" + #include "somesortofsystemeventheader.h" + + void processSomething() + { + SomeRuntimeClass rt; + + while(rt.yupStillRunning()) + { + reprodyne_mark_frame(); + + const auto eventCode = reprodyne_intercept_double(&rt, "System Event", getSystemEvent()); + + rt.reactToSystemEvent(eventCode); + + std::cout << rt.resultString() << std::endl; + + reprodyne_validate_string(&rt, "Processing Result", rt.resultString()); + } + } + +--- + +There are four states this code could be under when executed: + +- Reprodyne is not compiled in, and the calls are no-ops. +- You're in record mode and the values are being captured, a test failure is not possible, this is where you test the executable manually to verify that it is functioning as intended. +- You're in playback mode and the values are being intercepted/validated, a playback failure will be raised if there is an issue. +- Reprodyne is compiled in but the setup code hasn't been called by the test setup code. This will fail. + + +For record mode, you probably want a custom executable for generating the test data, where the main function might look something like this: + + #include + + void processSomething(); + + int main(int argc, char** argv) + { + reprodyne_record(); + + processSomething(); + + reprodyne_save("PATH-TO-SAVE-TEST-DATA.x3th"); + + return 0; + } + +**NOTE:** The file extension is somewhat arbitrary, Reprodyne is able to recognize one of it's own. + +--- + +Then to execute the test: + + void test() + { + reprodyne_play("PATH-TO-SAVED-TEST-DATA.rep"); + + processSomething(); + + reprodyne_assert_complete_read(); //Make sure the process didn't exit early. + } + +--- + +### Making Reprodyne Available to Your Code + +Reprodyne macros expand to no-ops by default. In order to use Reprodyne you must define the following: + + REPRODYNE_AVAILABLE + +It is recommended that this be defined by your build system/compiler, as it needs to be defined everywhere Reprodyne is used, not just in your test code but your code under test. + +## Gotchas + +reprodyne_open_scope tracks *the temporal position of objects.* That is, Reprodyne saves the *order in which the scopes are opened.* The actual values of the pointers is irrelevant. The only requirement is that scopes *must* be opened in the same order every time. + +One pernicious edge-case that may not seem obvious is that it is possible for pointers to be re-used for different objects (E.g. a memory pool). If a pointer is already tracked during a call to reprodyne_open_scope, Reprodyne will *shadow* it with a new scope. It is possible that a pointer is reused in one run of the application and not another, or in record mode but not in subsequent playbacks. Again, this is fine because the scopes only track the *temporal location* of the pointers and the actual address is irrelevant. They could all be null pointers or arbitrary integers so long as they *represent* one and only one scope at a time and that those scopes are always represented in the same order. + +You must call mark frame at least once, even if you have a case where the "frame" model doesn't make sense. + +## Custom Playback Failure Handling and Exception/Longjmp Safety + +It may be convienient to provide a custom playback failure handler to help weave Reprodyne into whatever test framework/ungodly mess you are dealing with. But it's not recommended unless you have to. Reprodyne by default prints a message to stderr and then aborts the executable, which most test frameworks should be able to handle out of the box. But read on if you must... + +It is safe to longjmp out of the custom playback failure handler. The only hard rule is that it cannot simply return, if it tries, the application will then terminate. + +Exceptions... Well, they work on my machine. + +Reprodyne will not catch any user exceptions from that handler and the code path for the error handler is written to be longjmp safe, so of course it won't leak given an exception, but I am in no position to guarantee whether or not an exception from a binary with an incompatible exception model will pass through without causing a fuss; it might work, it might not. + +If you run into issues with C++ exceptions, I'd recommend just using setjmp/longjmp if you must retrieve control in this way. + +# Reprodyne is no Testing Panacea + +Reprodyne is not a replacement for traditional testing, it's an alternative method for when it makes sense to do things differently. + +If you don't play your cards right, it can be very easy to break your tests without invalidating your code. Although... That happens with traditional testing as well, just perhaps not as easily. + +An example of a false positive test failure would be if you manage to remove extraneous iterations from your main loop, invalidating the playback data. Even for a single frame this will invalidate everything. The closer you can map your calls to Reprodyne to the semantic, unchangeable meaning of your operations, the better. But this isn't necessarily easy. + +I've tried to make it as flexible as possible and in the future with more experience using it, I hope to make it more so. For now at least, I feel as though the benefits of Reprodyne already outweigh these concerns in certain situations. + + +# Reference Documentation and Getting Help + +For reference, the reprodyne.h header documents all of the interface calls and is a short read. If you have any questions after that, feel free to open an issue in the tracker with the "question" label. + + +# Contributing +Contributions are welcome, but please open an issue with the "Proposal" label in the issue tracker to begin discussion before beginning work on anything non-trivial. I would hate for you to waste effort on something I can't pull because it's not how I want to proceed. + +Alternatively, you can contact me directly (tracy@enesda.com) and I'll manage the issue for you. + +# Credits +Created and developed by Tracy Rust (tracy@enesda.com) + +Reprodyne was originally developed for use in end-to-end testing of the IVD gui framework. I present it here for anyone whom it may benefit~ + +# License +Reprodyne is licensed under the terms of the LGPL-3.0-only. diff --git a/demo.gif b/demo.gif new file mode 100644 index 0000000..6a76f52 Binary files /dev/null and b/demo.gif differ diff --git a/errorstuff.h b/errorstuff.h new file mode 100644 index 0000000..c616767 --- /dev/null +++ b/errorstuff.h @@ -0,0 +1,30 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + + +#pragma once + +#include + +namespace reprodyne +{ + +class PlaybackError : public std::runtime_error +{ + const int code; + + //Yeah yeah I know about strings and exceptions, and in this case I'll take + // my chances (This is never thrown on memory error, and memory errors never happen...). + const std::string dynamicErr; + +public: + PlaybackError(const int code, const std::string dynamicErr): + code(code), + dynamicErr(dynamicErr), + std::runtime_error(dynamicErr.c_str()) + {} + + int getCode() const + { return code; } +}; + +}//reprodyne diff --git a/fileformat.h b/fileformat.h new file mode 100644 index 0000000..7f8a193 --- /dev/null +++ b/fileformat.h @@ -0,0 +1,83 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + + +#pragma once + +#include + +namespace reprodyne +{ +namespace FileFormat +{ + +//For 8 * 8 == 64 bit or enough for a 138,547,332 terrabyte file or versions... Should be enough for everybody. +//Integers are stored little endian because I felt like it +const int intSize = 8; + +//"x3th", encoded as ascii. Manually, because I don't trust locales. +const int signatureOffset = 0; +const int signatureSize = 4; +const char fileSignature[signatureSize] = {0x78, 0x33, 0x74, 0x68}; + +const int versionOffset = signatureOffset + signatureSize; +const int versionSize = intSize; + +const int currentFileFormatVersion = 0x01; //Good thing we used a 64 bit integer for this + +const int uncompressedSizeOffset = versionOffset + versionSize; +const int uncompressedSizeSize = intSize; + +const int compressedDataRegionOffset = uncompressedSizeOffset + uncompressedSizeSize; + +const int reservedRangeSize = compressedDataRegionOffset; + +inline uint64_t readInteger(unsigned char* pos) +{ + uint64_t ret = 0; + for(int i = 0; i != intSize; ++i) ret = uint64_t(pos[i]) << i * 8 | ret; + return ret; +} + +inline void writeInteger(unsigned char* pos, const uint64_t val) +{ + for(int i = 0; i != intSize; ++i) + pos[i] = val >> i * 8; +} + +inline void writeVersion(unsigned char* fileStart) +{ + writeInteger(&fileStart[versionOffset], currentFileFormatVersion); +} + +inline bool checkVersion(unsigned char* fileStart) +{ + return readInteger(&fileStart[versionOffset]) == currentFileFormatVersion; +} + +inline void writeSignature(unsigned char* fileStart) +{ + for(int i = 0; i != signatureSize; ++i) + fileStart[i] = fileSignature[i]; +} + +inline bool checkSignature(unsigned char* fileStart) +{ + return std::string(reinterpret_cast(fileStart), signatureSize) + == std::string(&fileSignature[0], signatureSize); +} + +inline uint64_t readUncompressedSize(unsigned char* fileStart) +{ + return readInteger(&fileStart[uncompressedSizeOffset]); +} + +inline void writeBoringStuffToReservedRegion(unsigned char* filesStart, const uint64_t uncompressedSize) +{ + writeSignature(filesStart); + writeVersion(filesStart); + writeInteger(&filesStart[uncompressedSizeOffset], uncompressedSize); +} + +}//FileFormat +}//reprodyne + diff --git a/lexcompare.h b/lexcompare.h new file mode 100644 index 0000000..5d3534e --- /dev/null +++ b/lexcompare.h @@ -0,0 +1,354 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + + +#ifndef RUSTUTILS_LEXCOMPARE +#define RUSTUTILS_LEXCOMPARE + +#include + +//Once upon a time I thought 7 outta be enough. But it proved insufficient, so then I made it 17. +//... Then that wasn't enough... So now it's 22... + +#define RUSTUTILS_MACRO_OVERLOAD(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, MACRO, ...) MACRO + +#define RUSTUTILS_UNPACK_FINAL(object, field) object . field + +#define RUSTUTILS_UNPACK22(object, field22, field21, field20, field19, field18, field17, field16, field15, field14, field13, field12, field11, field10, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field22) , \ + RUSTUTILS_UNPACK_FINAL(object, field21) , \ + RUSTUTILS_UNPACK_FINAL(object, field20) , \ + RUSTUTILS_UNPACK_FINAL(object, field19) , \ + RUSTUTILS_UNPACK_FINAL(object, field18) , \ + RUSTUTILS_UNPACK_FINAL(object, field17) , \ + RUSTUTILS_UNPACK_FINAL(object, field16) , \ + RUSTUTILS_UNPACK_FINAL(object, field15) , \ + RUSTUTILS_UNPACK_FINAL(object, field14) , \ + RUSTUTILS_UNPACK_FINAL(object, field13) , \ + RUSTUTILS_UNPACK_FINAL(object, field12) , \ + RUSTUTILS_UNPACK_FINAL(object, field11) , \ + RUSTUTILS_UNPACK_FINAL(object, field10) , \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK21(object, field21, field20, field19, field18, field17, field16, field15, field14, field13, field12, field11, field10, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field21) , \ + RUSTUTILS_UNPACK_FINAL(object, field20) , \ + RUSTUTILS_UNPACK_FINAL(object, field19) , \ + RUSTUTILS_UNPACK_FINAL(object, field18) , \ + RUSTUTILS_UNPACK_FINAL(object, field17) , \ + RUSTUTILS_UNPACK_FINAL(object, field16) , \ + RUSTUTILS_UNPACK_FINAL(object, field15) , \ + RUSTUTILS_UNPACK_FINAL(object, field14) , \ + RUSTUTILS_UNPACK_FINAL(object, field13) , \ + RUSTUTILS_UNPACK_FINAL(object, field12) , \ + RUSTUTILS_UNPACK_FINAL(object, field11) , \ + RUSTUTILS_UNPACK_FINAL(object, field10) , \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK20(object, field20, field19, field18, field17, field16, field15, field14, field13, field12, field11, field10, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field20) , \ + RUSTUTILS_UNPACK_FINAL(object, field19) , \ + RUSTUTILS_UNPACK_FINAL(object, field18) , \ + RUSTUTILS_UNPACK_FINAL(object, field17) , \ + RUSTUTILS_UNPACK_FINAL(object, field16) , \ + RUSTUTILS_UNPACK_FINAL(object, field15) , \ + RUSTUTILS_UNPACK_FINAL(object, field14) , \ + RUSTUTILS_UNPACK_FINAL(object, field13) , \ + RUSTUTILS_UNPACK_FINAL(object, field12) , \ + RUSTUTILS_UNPACK_FINAL(object, field11) , \ + RUSTUTILS_UNPACK_FINAL(object, field10) , \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK19(object, field19, field18, field17, field16, field15, field14, field13, field12, field11, field10, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field19) , \ + RUSTUTILS_UNPACK_FINAL(object, field18) , \ + RUSTUTILS_UNPACK_FINAL(object, field17) , \ + RUSTUTILS_UNPACK_FINAL(object, field16) , \ + RUSTUTILS_UNPACK_FINAL(object, field15) , \ + RUSTUTILS_UNPACK_FINAL(object, field14) , \ + RUSTUTILS_UNPACK_FINAL(object, field13) , \ + RUSTUTILS_UNPACK_FINAL(object, field12) , \ + RUSTUTILS_UNPACK_FINAL(object, field11) , \ + RUSTUTILS_UNPACK_FINAL(object, field10) , \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK18(object, field18, field17, field16, field15, field14, field13, field12, field11, field10, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field18) , \ + RUSTUTILS_UNPACK_FINAL(object, field17) , \ + RUSTUTILS_UNPACK_FINAL(object, field16) , \ + RUSTUTILS_UNPACK_FINAL(object, field15) , \ + RUSTUTILS_UNPACK_FINAL(object, field14) , \ + RUSTUTILS_UNPACK_FINAL(object, field13) , \ + RUSTUTILS_UNPACK_FINAL(object, field12) , \ + RUSTUTILS_UNPACK_FINAL(object, field11) , \ + RUSTUTILS_UNPACK_FINAL(object, field10) , \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK17(object, field17, field16, field15, field14, field13, field12, field11, field10, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field17) , \ + RUSTUTILS_UNPACK_FINAL(object, field16) , \ + RUSTUTILS_UNPACK_FINAL(object, field15) , \ + RUSTUTILS_UNPACK_FINAL(object, field14) , \ + RUSTUTILS_UNPACK_FINAL(object, field13) , \ + RUSTUTILS_UNPACK_FINAL(object, field12) , \ + RUSTUTILS_UNPACK_FINAL(object, field11) , \ + RUSTUTILS_UNPACK_FINAL(object, field10) , \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK16(object, field16, field15, field14, field13, field12, field11, field10, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field16) , \ + RUSTUTILS_UNPACK_FINAL(object, field15) , \ + RUSTUTILS_UNPACK_FINAL(object, field14) , \ + RUSTUTILS_UNPACK_FINAL(object, field13) , \ + RUSTUTILS_UNPACK_FINAL(object, field12) , \ + RUSTUTILS_UNPACK_FINAL(object, field11) , \ + RUSTUTILS_UNPACK_FINAL(object, field10) , \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK15(object, field15, field14, field13, field12, field11, field10, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field15) , \ + RUSTUTILS_UNPACK_FINAL(object, field14) , \ + RUSTUTILS_UNPACK_FINAL(object, field13) , \ + RUSTUTILS_UNPACK_FINAL(object, field12) , \ + RUSTUTILS_UNPACK_FINAL(object, field11) , \ + RUSTUTILS_UNPACK_FINAL(object, field10) , \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK14(object, field14, field13, field12, field11, field10, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field14) , \ + RUSTUTILS_UNPACK_FINAL(object, field13) , \ + RUSTUTILS_UNPACK_FINAL(object, field12) , \ + RUSTUTILS_UNPACK_FINAL(object, field11) , \ + RUSTUTILS_UNPACK_FINAL(object, field10) , \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK13(object, field13, field12, field11, field10, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field13) , \ + RUSTUTILS_UNPACK_FINAL(object, field12) , \ + RUSTUTILS_UNPACK_FINAL(object, field11) , \ + RUSTUTILS_UNPACK_FINAL(object, field10) , \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK12(object, field12, field11, field10, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field12) , \ + RUSTUTILS_UNPACK_FINAL(object, field11) , \ + RUSTUTILS_UNPACK_FINAL(object, field10) , \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK11(object, field11, field10, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field11) , \ + RUSTUTILS_UNPACK_FINAL(object, field10) , \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK10(object, field10, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field10) , \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK9(object, field9, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field9) , \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK8(object, field8, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field8) , \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK7(object, field7, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field7) , \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK6(object, field6, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field6) , \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK5(object, field5, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field5) , \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK4(object, field4, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field4) , \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK3(object, field3, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field3) , \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK2(object, field2, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field2) , \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK1(object, field1) \ + RUSTUTILS_UNPACK_FINAL(object, field1) + +#define RUSTUTILS_UNPACK(object, fields...) \ + RUSTUTILS_MACRO_OVERLOAD(fields, \ + RUSTUTILS_UNPACK22, \ + RUSTUTILS_UNPACK21, \ + RUSTUTILS_UNPACK20, \ + RUSTUTILS_UNPACK19, \ + RUSTUTILS_UNPACK18, \ + RUSTUTILS_UNPACK17, \ + RUSTUTILS_UNPACK16, \ + RUSTUTILS_UNPACK15, \ + RUSTUTILS_UNPACK14, \ + RUSTUTILS_UNPACK13, \ + RUSTUTILS_UNPACK12, \ + RUSTUTILS_UNPACK11, \ + RUSTUTILS_UNPACK10, \ + RUSTUTILS_UNPACK9, \ + RUSTUTILS_UNPACK8, \ + RUSTUTILS_UNPACK7, \ + RUSTUTILS_UNPACK6, \ + RUSTUTILS_UNPACK5, \ + RUSTUTILS_UNPACK4, \ + RUSTUTILS_UNPACK3, \ + RUSTUTILS_UNPACK2, \ + RUSTUTILS_UNPACK1)(object, fields) + + +#define RUSTUTILS_DEFINE_COMP(type, fields...) \ + friend bool operator<(const type & left, const type & right) \ + { \ + return std::tie(RUSTUTILS_UNPACK(left, fields)) < \ + std::tie(RUSTUTILS_UNPACK(right, fields)); \ + } \ + friend bool operator!=(const type & left, const type & right) \ + { \ + return left < right || right < left; \ + } \ + friend bool operator==(const type & left, const type & right) \ + { \ + return !(left != right); \ + } + +#endif // RUSTUTILS_LEXCOMPARE diff --git a/programhandlers.cpp b/programhandlers.cpp new file mode 100644 index 0000000..889aeb5 --- /dev/null +++ b/programhandlers.cpp @@ -0,0 +1,78 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + + +#include "programhandlers.h" + +#include +#include + +#include "fileformat.h" + +namespace reprodyne +{ + +void ProgramRecorder::save(const char* path) +{ + { + auto ordinalScopes = scopes.pop(); + + //TODO: move to ScopeRecorder? + std::vector> builtOrdinalEntries; + for(auto keyedScopeHandler : ordinalScopes) + builtOrdinalEntries.push_back(keyedScopeHandler.buildOrdinalScopeFlatbuffer(builder)); + + builder.Finish(reprodyne::CreateTapeContainer(builder, builder.CreateVector(builtOrdinalEntries))); + } + + //0 + to make damn sure the upper bits are zeroed + uint64_t compressionRegionSize = 0 + compressBound(builder.GetSize()); + std::vector outputBuffer(reprodyne::FileFormat::reservedRangeSize + compressionRegionSize); + + reprodyne::FileFormat::writeBoringStuffToReservedRegion(&outputBuffer[0], compressionRegionSize); + + if(compress(&outputBuffer[reprodyne::FileFormat::compressedDataRegionOffset], + &compressionRegionSize, + builder.GetBufferPointer(), + builder.GetSize()) + != Z_OK) //Heard of A-okay? Yeah well this is like that but not really + { + throw std::runtime_error("Some problem with zlib"); + } + + const int finalFileSize = reprodyne::FileFormat::reservedRangeSize + compressionRegionSize; + std::ofstream(path, std::ios_base::binary).write(reinterpret_cast(&outputBuffer[0]), finalFileSize); + + builder = flatbuffers::FlatBufferBuilder(); //reset just in case +} + +ProgramPlayer::ProgramPlayer(const char* path) +{ + std::ifstream file(path, std::ios_base::binary); + auto tempBuffer = std::vector(std::istreambuf_iterator(file), {}); + + if(tempBuffer.size() < reprodyne::FileFormat::reservedRangeSize) + throw std::runtime_error("Bad file, too small to even hold the reserved region..."); + + if(!reprodyne::FileFormat::checkSignature(&tempBuffer[0])) + throw std::runtime_error("Unrecognized file signature."); + + if(!reprodyne::FileFormat::checkVersion(&tempBuffer[0])) + throw std::runtime_error("File is not compatible with this version of reprodyne."); + + uint64_t destBuffSize = reprodyne::FileFormat::readUncompressedSize(&tempBuffer[0]); + loadedBuffer = std::vector(destBuffSize); + + //READ MOTHERGUCGKer + const int compressedRegionSize = tempBuffer.size() - reprodyne::FileFormat::reservedRangeSize; + const auto stat = + uncompress(&loadedBuffer[0], &destBuffSize, + &tempBuffer[reprodyne::FileFormat::compressedDataRegionOffset], compressedRegionSize); + + if(stat == Z_MEM_ERROR) throw std::runtime_error("Not enough memory for zlib."); + if(stat == Z_BUF_ERROR) throw std::runtime_error("Data corrupt or incomplete."); + if(stat != Z_OK) throw std::runtime_error("Some unknown error occurred during decompression."); + + scopes.load(reprodyne::GetTapeContainer(&loadedBuffer[0])->ordinalScopeTape()); +} + +}//reprodyne diff --git a/programhandlers.h b/programhandlers.h new file mode 100644 index 0000000..e0433fe --- /dev/null +++ b/programhandlers.h @@ -0,0 +1,77 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + + +#pragma once + +#include "scopecontainers.h" + +namespace reprodyne +{ + +template +class Program +{ + std::optional frameCounter; + +protected: + ScopeContainer scopes; + +public: + Program() {} + Program(ScopeContainer cont): scopes(cont) {} + + void openScope(void* ptr) + { scopes.openScope(ptr); } + + void markFrame() + { + if(!frameCounter) frameCounter = 0; + else ++(*frameCounter); + } + + unsigned int readFrameId() + { + if(!frameCounter) + throw std::logic_error("Call to intercept before reprodyne_mark_frame is forbidden."); + return *frameCounter; + } + + template + T intercept(void* scopePtr, const char* subscopeKey, const T indeterminate) + { return scopes.at(scopePtr).intercept(readFrameId(), subscopeKey, indeterminate); } + + template + void serialize(void* scopePtr, const char* subscopeKey, const Ts... serialValue) + { scopes.at(scopePtr).serialize(readFrameId(), subscopeKey, serialValue...); } + + void assertCompleteRead() + { scopes.assertCompleteRead(); } +}; + + + + +class ProgramRecorder : public Program +{ + flatbuffers::FlatBufferBuilder builder; + +public: + ProgramRecorder(): Program(ScopeContainerRecorder(builder)) {} + + void save(const char* path); +}; + + + +class ProgramPlayer : public Program +{ + std::vector loadedBuffer; + +public: + ProgramPlayer(const char* path); +}; + + + + +}//reprodyne diff --git a/reprodyne-config.cmake.in b/reprodyne-config.cmake.in new file mode 100644 index 0000000..9f15b4c --- /dev/null +++ b/reprodyne-config.cmake.in @@ -0,0 +1,3 @@ +include(${CMAKE_CURRENT_LIST_DIR}/reprodyne-targets.cmake) + +set(REPRODYNE_INCLUDE_DIRS "@REPRODYNE_USER_INCLUDE_DIRS@") diff --git a/reprodyne.cpp b/reprodyne.cpp new file mode 100644 index 0000000..bf0ef7e --- /dev/null +++ b/reprodyne.cpp @@ -0,0 +1,237 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + + +#include + + +#include + +#include "user-include/reprodyne.h" + +#include "programhandlers.h" + + +std::unique_ptr recorder; +std::unique_ptr player; + +reprodyne_playback_failure_handler playbackErrorHandler = nullptr; +std::string jumpSafeString; + +//(re: using std::strings in exceptions) +//Playing it on the loose and easy with these exceptions because they are playback, +// not memory errors. And it's prettier this way~ + + +//We need to catch all exceptions and deal with them here because you don't want +// the library to leak through a C boundary. And as such, we want to be longjmp safe. +static void handlePlaybackErrorException(const reprodyne::PlaybackError& e) +{ + if(!playbackErrorHandler) + { + std::cerr << "Reprodyne PLAYBACK FAILURE (No handler provided): " << e.what() << std::endl << std::flush; + std::terminate(); + } + + jumpSafeString = e.what(); //what() references an std::string, so it's not safe beyond this point. + playbackErrorHandler(e.getCode(), jumpSafeString.c_str()); + std::terminate(); //If you don't do it, I will. +} + +static void handleRuntimeErrrr(const char* what) +{ + std::cerr << "Reprodyne runtime error: " << what << std::endl; + std::terminate(); +} + +static void unknownErrorDie() +{ + std::terminate(); +} + +//Uniform exception handler so that we can translate to C-safe errors consistently. +template +static T safeBlock(std::function thingamajigulator) +{ + try + { return thingamajigulator(); } + catch(const reprodyne::PlaybackError& e) + { handlePlaybackErrorException(e); } + catch(const std::runtime_error& e) + { handleRuntimeErrrr(e.what()); } //"eh, what??" + catch(...) + { + //fucc + unknownErrorDie(); + } + + std::terminate(); //Why won't you fuCKING DIE ALREADY?!? +} + +template<> +void safeBlock(std::function thingamajigulator) +{ + try + { thingamajigulator(); } + catch(const reprodyne::PlaybackError& e) + { handlePlaybackErrorException(e); } + catch(const std::runtime_error& e) + { handleRuntimeErrrr(e.what()); } + catch(...) + { + //fucc + unknownErrorDie(); + } +} + +//Generic reset so I can have n-number of player types and swap between them arbitrarily +static void reset() +{ + recorder.reset(); + player.reset(); +} + +extern "C" +{ + +void reprodyne_do_not_call_this_function_directly_set_playback_failure_handler(reprodyne_playback_failure_handler handler) +{ playbackErrorHandler = handler; /*Not my problem anymore...*/ } + +void reprodyne_do_not_call_this_function_directly_record() +{ + safeBlock([&] + { + reset(); + recorder = std::make_unique(); + }); +} + +void reprodyne_do_not_call_this_function_directly_save(const char* path) +{ + safeBlock([&] + { + if(!recorder) throw std::logic_error("bad doG! No!"); + recorder->save(path); + }); +} + +void reprodyne_do_not_call_this_function_directly_play(const char* path) +{ + safeBlock([&] + { + reset(); + player = std::make_unique(path); + }); +} + +void reprodyne_do_not_call_this_function_directly_assert_complete_read() +{ + safeBlock([&] + { + if(!player) throw std::logic_error("Cannot assert complete read in record mode"); + player->assertCompleteRead(); + }); +} + +void reprodyne_do_not_call_this_function_directly_mark_frame() +{ + safeBlock([&] + { + if(recorder) recorder->markFrame(); + else if(player) player->markFrame(); + }); +} + +void reprodyne_do_not_call_this_function_directly_open_scope(void* ptr) +{ + safeBlock([&] + { + if(recorder) recorder->openScope(ptr); + else if(player) player->openScope(ptr); + }); +} + +void reprodyne_do_not_call_this_function_directly_write_indeterminate(void* scopePtr, const char* key, double indeterminate) +{ + safeBlock([&] + { + if(!recorder) throw std::logic_error("Bad mode. Expected record"); + recorder->intercept(scopePtr, key, indeterminate); + }); +} + +double reprodyne_do_not_call_this_function_directly_read_indeterminate(void* scopePtr, const char* subscopeKey) +{ + return safeBlock([&] + { + if(!player) throw std::logic_error("Bad mode. Expected player"); + return player->intercept(scopePtr, subscopeKey, 0); //Value is ignored for read. + }); +} + +double reprodyne_do_not_call_this_function_directly_intercept_double(void* scopePtr, const char* scopeKey, const double indeterminate) +{ + return safeBlock([&]() + { + if(recorder) return recorder->intercept(scopePtr, scopeKey, indeterminate); + else if(player) return player->intercept(scopePtr, scopeKey, indeterminate); + + throw std::logic_error("die"); + }); +} + +void reprodyne_do_not_call_this_function_directly_validate_string(void* scopePtr, const char* subScopeKey, const char* call) +{ + return safeBlock([&] + { + //God I wish I had lisp macros... + if(recorder) recorder->serialize(scopePtr, subScopeKey, call); + else if(player) player->serialize(scopePtr, subScopeKey, call); + else throw std::logic_error("die"); + }); +} + +void reprodyne_do_not_call_this_function_directly_validate_bitmap_hash(void* scope, + const char* key, + const unsigned int width, + const unsigned int height, + const unsigned int stride, + void* bytes) +{ + safeBlock([&] + { + //I like my typos sometimes + auto errorHahnDler = [&](const char* msg) + { + //This is only safe because jumpSafeString is only otherwise used by + // the playback error handler. Even still, I don't like this... + jumpSafeString = msg; + jumpSafeString += " in validate bitmap hash function!"; + jumpSafeString += " Subscope key: "; + jumpSafeString += key; + throw std::runtime_error(jumpSafeString.c_str()); + }; + + if(height < 1) errorHahnDler("Useless height"); + if(width < 1) errorHahnDler("Useless width"); + if(stride < width) errorHahnDler("Stride smaller than width"); + if(!bytes) errorHahnDler("NULL data pointer"); + + //int8_t because that's how flatbuffers likes it, I ain't judge. + std::vector hash(SHA256_DIGEST_LENGTH); + + //unsigned char because that's how OpenSSL likes it, I ain't judge. + std::vector clippedImageRegion; + clippedImageRegion.reserve(width * height); + + for(int h = 0; h != height; ++h) + for(int w = 0; w != width; ++w) + clippedImageRegion.push_back(reinterpret_cast(bytes)[h * stride + w]); + + SHA256(&clippedImageRegion[0], clippedImageRegion.size(), reinterpret_cast(&hash[0])); + + if(recorder) recorder->serialize(scope, key, width, height, hash); //Variadic templates are badass. + else if(player) player->serialize(scope, key, width, height, hash); + }); +} + +} //extern "C" diff --git a/schema.fbs b/schema.fbs new file mode 100644 index 0000000..31c3254 --- /dev/null +++ b/schema.fbs @@ -0,0 +1,49 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + + +file_identifier "X3TH"; + +file_extension "x3th"; + +namespace reprodyne; + +table IndeterminateDoubleEntry +{ + frameId:uint; + val:double; +} + +table ValidationStringEntry +{ + frameId:uint; + str:string; +} + +table ValidationVideoSHA256Entry +{ + frameId:uint; + width:uint; + height:uint; + sha256:[byte]; +} + +table KeyedScopeTapeEntry +{ + key:string (key); + + indeterminateDoubles:[IndeterminateDoubleEntry]; + validationStrings:[ValidationStringEntry]; + validationVideoSHA256Hashes:[ValidationVideoSHA256Entry]; +} + +table OrdinalScopeTapeEntry +{ + keyedScopeTape: [KeyedScopeTapeEntry]; +} + +table TapeContainer +{ + ordinalScopeTape:[OrdinalScopeTapeEntry]; +} + +root_type TapeContainer; diff --git a/scopecontainers.cpp b/scopecontainers.cpp new file mode 100644 index 0000000..1a5fe2f --- /dev/null +++ b/scopecontainers.cpp @@ -0,0 +1,53 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + LGPL-3.0-only + +#include "scopecontainers.h" + +#include "user-include/reprodyne.h" + +namespace reprodyne +{ + +ScopeHandlerRecorder& ScopeContainerRecorder::at(void* ptr) +{ + auto ordinalIterator = ordinalMap.find(ptr); + if(ordinalIterator == ordinalMap.end()) + throw PlaybackError(REPRODYNE_STAT_UNREGISTERED_SCOPE, "Unregistered scope!"); + + return storedScope.at(ordinalIterator->second); +} + + + + +void ScopeContainerPlayer::openScope(void* ptr) +{ + if(ordinalPosition == myRootBuffer->end()) throw std::runtime_error("Ordinal scope buffer overread"); + + auto it = scopeMap.find(ptr); + + if(it != scopeMap.end()) + { + try + { + it->second.assertCompletReed(); + } + catch(const PlaybackError& e) + { + //Current interface doesn't expect such eager playback errors, so we stash it for now~ + deferredCompleteReadErrors.push_back(e); + } + } + + scopeMap.insert_or_assign(ptr, ScopeHandlerPlayer(*ordinalPosition)); + ++ordinalPosition; +} + +ScopeHandlerPlayer& ScopeContainerPlayer::at(void* ptr) +{ + auto it = scopeMap.find(ptr); + if(it == scopeMap.end()) throw PlaybackError(REPRODYNE_STAT_UNREGISTERED_SCOPE, "Unregistered scope!"); + return it->second; +} + +}//reprodyne diff --git a/scopecontainers.h b/scopecontainers.h new file mode 100644 index 0000000..98c4978 --- /dev/null +++ b/scopecontainers.h @@ -0,0 +1,73 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + + +#pragma once + +#include "scopehandlers.h" + +#include "errorstuff.h" + +namespace reprodyne +{ + +class ScopeContainerRecorder +{ + flatbuffers::FlatBufferBuilder& builder; + + std::vector storedScope; + std::map ordinalMap; + +public: + ScopeContainerRecorder(flatbuffers::FlatBufferBuilder& builder): builder(builder) {} + + void openScope(void* ptr) + { + storedScope.emplace_back(builder); + ordinalMap[ptr] = storedScope.size() - 1; + } + + ScopeHandlerRecorder& at(void* ptr); + + std::vector pop() + { + ordinalMap.clear(); + return std::move(storedScope); + } +}; + + + + +class ScopeContainerPlayer +{ +public: + typedef flatbuffers::Vector> BufferType; + +private: + const BufferType* myRootBuffer; + BufferType::const_iterator ordinalPosition; + + std::map scopeMap; + + std::vector deferredCompleteReadErrors; + +public: + void openScope(void *ptr); + + ScopeHandlerPlayer& at(void* ptr); + + void load(const BufferType* rootBeer) + { + myRootBuffer = rootBeer; + ordinalPosition = myRootBuffer->begin(); + } + + void assertCompleteRead() + { + for(auto& e : deferredCompleteReadErrors) throw e; //Only the first one but that's cool too. + for(auto pair : scopeMap) pair.second.assertCompletReed(); + } +}; + + +}//reprodyne diff --git a/scopehandlers.cpp b/scopehandlers.cpp new file mode 100644 index 0000000..df31fa9 --- /dev/null +++ b/scopehandlers.cpp @@ -0,0 +1,148 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + + +#include "scopehandlers.h" + +#include "user-include/reprodyne.h" //For the codes; +#include "errorstuff.h" + +namespace reprodyne +{ + +flatbuffers::Offset ScopeHandlerRecorder::buildOrdinalScopeFlatbuffer(flatbuffers::FlatBufferBuilder& builder) +{ + std::vector> keyedEntries; + for(auto pair : subScopes) + { + const auto subScopeEntry = pair.second; + const auto subscopeKey = builder.CreateString(pair.first); + + keyedEntries.push_back(reprodyne::CreateKeyedScopeTapeEntry(builder, + subscopeKey, + builder.CreateVector(subScopeEntry.theDubbles), + builder.CreateVector(subScopeEntry.serialStrings), + builder.CreateVector(subScopeEntry.validationVideoHash))); + } + + return reprodyne::CreateOrdinalScopeTapeEntry(builder, builder.CreateVectorOfSortedTables(&keyedEntries)); +} + + + + +const KeyedScopeTapeEntry* ScopeHandlerPlayer::getKeyedEntry(const char* subscopeKey) +{ + auto entry = myBuffer->keyedScopeTape()->LookupByKey(subscopeKey); + if(!entry) + { + std::string msg = "Tape empty for key: \""; + msg += subscopeKey; + msg += "\"\n"; + throw PlaybackError(REPRODYNE_STAT_EMPTY_TAPE, msg); + } + return entry; +} + +void ScopeHandlerPlayer::checkReadPastEnd(const int size, const int pos) +{ if(size == pos) throw PlaybackError(REPRODYNE_STAT_TAPE_PAST_END, "Read past end"); } + +void ScopeHandlerPlayer::checkFrame(const unsigned int frameId1, const unsigned int frameId2, const char* moreSpecifically) +{ + std::string msg = "Frame ID mismatch!"; + msg += moreSpecifically; + msg.push_back('\n'); + + if(frameId1 != frameId2) throw PlaybackError(REPRODYNE_STAT_FRAME_MISMATCH, msg); +} + +double ScopeHandlerPlayer::intercept(const unsigned int frameId, const char* subscopeKey, const double indeterminate) +{ + auto entry = getKeyedEntry(subscopeKey); + const auto ordinal = readPosMap[entry].indeterminateDoublePos++; + + checkReadPastEnd(entry->indeterminateDoubles()->size(), ordinal); + + auto indeterminateEntry = entry->indeterminateDoubles()->Get(ordinal); + + checkFrame(indeterminateEntry->frameId(), frameId, "Indeterminates out of order!"); + + return indeterminateEntry->val(); +} + +void ScopeHandlerPlayer::serialize(const unsigned int frameId, const char* subscopeKey, const char* val) +{ + auto entry = getKeyedEntry(subscopeKey); + const auto ordinal = readPosMap[entry].validationStringPos++; + + checkReadPastEnd(entry->validationStrings()->size(), ordinal); + + auto serialEntry = entry->validationStrings()->Get(ordinal); + + checkFrame(serialEntry->frameId(), frameId, "Serialized calls out of order!"); + + if(std::string(val) != serialEntry->str()->str()) + { + std::string msg = "Stored call mismatch! Program produced: "; + msg += val; + msg.push_back('\n'); + msg += "Was expecting: \n"; + msg += serialEntry->str()->str(); + msg.push_back('\n'); + throw PlaybackError(REPRODYNE_STAT_VALIDATION_FAIL, msg); + } +} + +void ScopeHandlerPlayer::serialize(const unsigned int frameId, + const char* subscopeKey, + const unsigned int width, + const unsigned int height, + std::vector hash) +{ + auto entry = getKeyedEntry(subscopeKey); + const auto ordinal = readPosMap[entry].validationVideoHashPos++; + + checkReadPastEnd(entry->validationVideoSHA256Hashes()->size(), ordinal); + + auto serialEntry = entry->validationVideoSHA256Hashes()->Get(ordinal); + + checkFrame(serialEntry->frameId(), frameId, "Validation video frame out of order!"); + + if(!std::equal(hash.begin(), hash.end(), serialEntry->sha256()->begin(), serialEntry->sha256()->end())) + throw PlaybackError(REPRODYNE_STAT_VALIDATION_FAIL, "Stored video hash mismatch!"); +} + +void ScopeHandlerPlayer::assertCompletReed() //I'm, bored okay? +{ + for(const KeyedScopeTapeEntry* entry : *myBuffer->keyedScopeTape()) + { + const std::string subscopeKey = entry->key()->str(); + auto readPosIterator = readPosMap.find(entry); + + auto assertEntry = [&](const LastReadPos& pos) + { + auto generateErrorMsg = [&](const std::string type) + { + std::string ret; + ret = type; + ret = " tape not read to complete for sub scope key: "; + ret = subscopeKey; + return ret; + }; + + if(entry->indeterminateDoubles()->size() != pos.indeterminateDoublePos) + throw PlaybackError(REPRODYNE_STAT_PROG_TAPE_INCOMPLETE_READ, generateErrorMsg("Program")); + + if(entry->validationStrings()->size() != pos.validationStringPos) + throw PlaybackError(REPRODYNE_STAT_CALL_TAPE_INCOMPLETE_READ, generateErrorMsg("Call")); + if(entry->validationVideoSHA256Hashes()->size() != pos.validationVideoHashPos) + throw PlaybackError(REPRODYNE_STAT_CALL_TAPE_INCOMPLETE_READ, generateErrorMsg("Video hash")); + }; + + if(readPosIterator == readPosMap.end()) assertEntry(LastReadPos()); //Empty read pos because we haven't read anything, obvs + else assertEntry(readPosIterator->second); + } +} + + + +}//reprodyne diff --git a/scopehandlers.h b/scopehandlers.h new file mode 100644 index 0000000..4e77a34 --- /dev/null +++ b/scopehandlers.h @@ -0,0 +1,105 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + +#pragma once + +#include +#include +#include + +#include "schema_generated.h" + + +namespace reprodyne +{ + +class ScopeHandlerRecorder +{ + flatbuffers::FlatBufferBuilder& builder; + + struct SubScopeEntry + { + std::vector> theDubbles; + std::vector> serialStrings; + std::vector> validationVideoHash; + }; + + std::map subScopes; + +public: + ScopeHandlerRecorder(flatbuffers::FlatBufferBuilder& builder): builder(builder) {} //builder builder builder + + double intercept(const unsigned int frameId, const char* subscopeKey, const double indeterminate) + { + subScopes[subscopeKey].theDubbles.push_back(CreateIndeterminateDoubleEntry(builder, + frameId, + indeterminate)); + return indeterminate; + } + + //int intercept(const unsigned int frameId, const char* subscopeKey, const int indeterminate) + //{ return saveValue(subScopes[subscopeKey].theInts, frameId, indeterminate); } + + void serialize(const unsigned int frameId, const char* subscopeKey, const char* val) + { + subScopes[subscopeKey].serialStrings.push_back(CreateValidationStringEntry(builder, + frameId, + builder.CreateString(val))); + } + + void serialize(const unsigned int frameId, + const char* subscopeKey, + const int unsigned width, + const unsigned int height, + std::vector hash) + { + subScopes[subscopeKey].validationVideoHash.push_back(CreateValidationVideoSHA256Entry(builder, + frameId, + width, + height, + builder.CreateVector(hash))); + } + + + flatbuffers::Offset buildOrdinalScopeFlatbuffer(flatbuffers::FlatBufferBuilder& builder); +}; + + +class ScopeHandlerPlayer +{ +public: + typedef const OrdinalScopeTapeEntry BufferType; + +private: + const BufferType* myBuffer; + + struct LastReadPos + { + int indeterminateDoublePos = 0; + int validationStringPos = 0; + int validationVideoHashPos = 0; + }; + + std::map readPosMap; + + const KeyedScopeTapeEntry* getKeyedEntry(const char* subscopeKey); + + void checkReadPastEnd(const int size, const int pos); + void checkFrame(const unsigned int frameId1, const unsigned int frameId2, const char* moreSpecifically); + +public: + ScopeHandlerPlayer(BufferType* buf): myBuffer(buf) {} + + double intercept(const unsigned int frameId, const char* subscopeKey, const double indeterminate); + //int intercept(const unsigned int frameId, const char* subscopeKey, const int indeterminate); + + void serialize(const unsigned int frameId, const char* subscopeKey, const char* val); + void serialize(const unsigned int frameId, + const char* subscopeKey, + const unsigned int width, + const unsigned int height, + std::vector hash); + + void assertCompletReed(); +}; + +}//reprodyne diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..de3cf73 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,8 @@ +# Maintainer's notes +These tests are ugly, but should be effective for now. + +In the future I would like to generalize them, so that any future interceptors or validators can be tested by adding a couple of lines of code. + +Currently, there is duplication between the validation tests in tests.cpp and videotests.cpp. I want to make it generic but I don't have the time. + +Also, as is stated in videotests.cpp, a lot of scope stuff isn't done with them in particular. Again, it shouldn't be a problem, but a more robust testing solution would allow for this easily. diff --git a/tests/catchmain.cpp b/tests/catchmain.cpp new file mode 100644 index 0000000..4ed06df --- /dev/null +++ b/tests/catchmain.cpp @@ -0,0 +1,2 @@ +#define CATCH_CONFIG_MAIN +#include diff --git a/tests/oopsiewhoopsie.h b/tests/oopsiewhoopsie.h new file mode 100644 index 0000000..cb90d78 --- /dev/null +++ b/tests/oopsiewhoopsie.h @@ -0,0 +1,22 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + + +#pragma once + +#include +#include + +//Common test code, no namespace because it's just for testing and not for +// the library itself. + +class OopsieWhoopsie : public std::exception +{ +public: + OopsieWhoopsie(const int code): code(code) {} + const int code; +}; + +inline double time() +{ + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); +} diff --git a/tests/tests.cpp b/tests/tests.cpp new file mode 100644 index 0000000..6cf9ac2 --- /dev/null +++ b/tests/tests.cpp @@ -0,0 +1,422 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + + +#include + +#include "../user-include/reprodyne.h" + +#include "oopsiewhoopsie.h" + +const auto testDataPath = "reprodyne-test-data.rep"; + + +void code_gobbling_error_handler(const int code, const char*) +{ + throw OopsieWhoopsie(code); +} + +std::vector generateList() +{ + //Tried this in a lambda but gcc is too clever for it's own good. + return std::initializer_list({time(), time(), time(), time()}); +} + +TEST_CASE("Big ugly test group") +{ + reprodyne_record(); + reprodyne_mark_frame(); + + int scope1; //Only used for their addresses + int scope2; + + reprodyne_open_scope(&scope1); + reprodyne_open_scope(&scope2); + + + auto interceptHelper = [&](void* scope, std::string key, auto list, std::vector validationSet) + { + for(int i = 0; i != list.size(); ++i) + { + const double rep = reprodyne_intercept_double(scope, key.c_str(), list[i]); + + if(validationSet.size()) REQUIRE(validationSet[i] == rep); + } + }; + + auto callHelper = [&](void* scope, std::string key, auto list) + { + for(const double i : list) + reprodyne_validate_string(scope, key.c_str(), std::string("pretendFunctionCall(" + std::to_string(i) + ");").c_str()); + }; + + + const auto originalSetScope1 = generateList(); + const auto originalSetScope2 = generateList(); + + //Consequently, this tests that the original values are returned + interceptHelper(&scope1, "the-wan", originalSetScope1, originalSetScope1); + reprodyne_mark_frame(); + interceptHelper(&scope2, "the-wan", originalSetScope2, originalSetScope2); + callHelper(&scope2, "the-wan", originalSetScope2); + + { + reprodyne_save(testDataPath); + reprodyne_play(testDataPath); //Automatically re-initializes everything, don't worry~ + + reprodyne_set_playback_failure_handler(&code_gobbling_error_handler); + + reprodyne_mark_frame(); + } + SECTION("Correct interception") + { + int rescope2; + int rescope1; + + reprodyne_open_scope(&rescope1); + reprodyne_open_scope(&rescope2); + + SECTION("Discard supplied indeterminates, returning originals") + { + //These new values are intercepted and replaced + const auto secondSetScope1 = generateList(); + const auto secondSetScope2 = generateList(); + + interceptHelper(&rescope1, "the-wan", secondSetScope1, originalSetScope1); + reprodyne_mark_frame(); + interceptHelper(&rescope2, "the-wan", secondSetScope2, originalSetScope2); + callHelper(&rescope2, "the-wan", originalSetScope2); + + reprodyne_assert_complete_read(); + } + } + SECTION("Mismatched frame") + { + reprodyne_open_scope(&scope1); + reprodyne_open_scope(&scope2); + + interceptHelper(&scope1, "the-wan", originalSetScope1, {}); + + /*MARK FRAME MISSING*/ + + try + { + interceptHelper(&scope2, "the-wan", originalSetScope2, {}); + FAIL("Intercept didn't fail with mismatched frame calls"); + } + catch(const OopsieWhoopsie& oops) + { + REQUIRE(oops.code == REPRODYNE_STAT_FRAME_MISMATCH); + SUCCEED(); + } + } + SECTION("Read past the end") + { + reprodyne_open_scope(&scope1); + reprodyne_open_scope(&scope2); + + interceptHelper(&scope1, "the-wan", originalSetScope1, {}); + + try + { + interceptHelper(&scope1, "the-wan", originalSetScope1, {}); + FAIL("Read past end didn't fail correctly"); + } + catch(const OopsieWhoopsie& oops) + { + REQUIRE(oops.code == REPRODYNE_STAT_TAPE_PAST_END); + } + } + SECTION("Call mismatch") + { + reprodyne_open_scope(&scope1); + reprodyne_open_scope(&scope2); + + interceptHelper(&scope1, "the-wan", originalSetScope1, {}); + reprodyne_mark_frame(); + interceptHelper(&scope2, "the-wan", originalSetScope2, {}); + + try + { + reprodyne_validate_string(&scope2, "the-wan", "wrongo"); + FAIL("Mismatched Call not detected."); + } + catch(const OopsieWhoopsie& oops) + { + //Check da oophs code + REQUIRE(oops.code == REPRODYNE_STAT_VALIDATION_FAIL); + } + } + SECTION("Incomplete program read") + { + reprodyne_open_scope(&scope1); + reprodyne_open_scope(&scope2); + + interceptHelper(&scope1, "the-wan", originalSetScope1, {}); + reprodyne_mark_frame(); + + try + { + reprodyne_assert_complete_read(); + FAIL("Reprodyne should have aborted on incomplete program read."); + } + catch(const OopsieWhoopsie& oops) + { + REQUIRE(oops.code == REPRODYNE_STAT_PROG_TAPE_INCOMPLETE_READ); + } + } + SECTION("Incomplete call read") + { + reprodyne_open_scope(&scope1); + reprodyne_open_scope(&scope2); + + interceptHelper(&scope1, "the-wan", originalSetScope1, {}); + reprodyne_mark_frame(); + interceptHelper(&scope2, "the-wan", originalSetScope2, {}); + + /*SERIALIZE CALL MISSING*/ + + try + { + reprodyne_assert_complete_read(); + FAIL("Reprodyne should have aborted on incomplete call read."); + } + catch(const OopsieWhoopsie& oops) + { + REQUIRE(oops.code == REPRODYNE_STAT_CALL_TAPE_INCOMPLETE_READ); + } + } +} + +TEST_CASE("Scope override") +{ + reprodyne_record(); + reprodyne_mark_frame(); + int scope; + + reprodyne_open_scope(&scope); + reprodyne_intercept_double(&scope, "n", 42); + + reprodyne_open_scope(&scope); + reprodyne_intercept_double(&scope, "n", 240); //Dyslexics be blazin' like + + reprodyne_save(testDataPath); + reprodyne_play(testDataPath); + + reprodyne_mark_frame(); + + auto validate = [](void* scope1, void* scope2) + { + reprodyne_open_scope(scope1); + REQUIRE(reprodyne_intercept_double(scope1, "n", 4839) == 42); + + reprodyne_open_scope(scope2); + REQUIRE(reprodyne_intercept_double(scope2, "n", 43894389) == 240); + + SECTION("Assert complete read for overriden scope") + { + reprodyne_assert_complete_read(); + } + }; + + SECTION("Playback override with one pointer") + { + int scopee; + validate(&scopee, &scopee); + } + SECTION("Playback override with two pointers") + { + int scope1; + int scope2; + validate(&scope1, &scope2); + } + + SECTION("Assert complete read after clobbering incompletely read scope") + { + int scope1; + + reprodyne_open_scope(&scope1); + reprodyne_open_scope(&scope1); //CLOBBER + + REQUIRE(reprodyne_intercept_double(&scope1, "n", 43894389) == 240); + + try + { + reprodyne_assert_complete_read(); + FAIL("Reprodyne should have aborted on incomplete indeterminate read."); + } + catch(const OopsieWhoopsie& oops) + { + REQUIRE(oops.code == REPRODYNE_STAT_PROG_TAPE_INCOMPLETE_READ); + } + } +} + +TEST_CASE("Invalid scope key") +{ + reprodyne_record(); + reprodyne_mark_frame(); + + int scope; + reprodyne_open_scope(&scope); + + reprodyne_save(testDataPath); + reprodyne_play(testDataPath); + + //TODO: make a test for this without these two lines? Whatever condition that is... Too busy to think r/n + reprodyne_mark_frame(); + reprodyne_open_scope(&scope); + + reprodyne_set_playback_failure_handler(&code_gobbling_error_handler); + + try + { + reprodyne_intercept_double(&scope, "notta", 42); + FAIL("Intercept with bad key in playback mode didn't fail"); + } + catch(const OopsieWhoopsie& oops) + { + REQUIRE(oops.code == REPRODYNE_STAT_EMPTY_TAPE); + } +} + +TEST_CASE("Validation and program tape different sizes, larger program tape") +{ + reprodyne_record(); + reprodyne_mark_frame(); + + double up; + reprodyne_open_scope(&up); + reprodyne_intercept_double(&up, "key", 42); + reprodyne_intercept_double(&up, "key", 42); + + reprodyne_validate_string(&up, "ee", "ffff"); + + reprodyne_save(testDataPath); + reprodyne_play(testDataPath); + reprodyne_mark_frame(); + reprodyne_open_scope(&up); + + reprodyne_intercept_double(&up, "key", 42); + reprodyne_intercept_double(&up, "key", 42); + + reprodyne_validate_string(&up, "ee", "ffff"); + + reprodyne_assert_complete_read(); + + SUCCEED("If we made it this far it worked"); +} + +TEST_CASE("Validation and program tape different sizes, larger validation tape") +{ + reprodyne_record(); + reprodyne_mark_frame(); + + double up; + reprodyne_open_scope(&up); + reprodyne_intercept_double(&up, "key", 42); + + reprodyne_validate_string(&up, "ee", "ffff"); + reprodyne_validate_string(&up, "ee", "ffff"); + + reprodyne_save(testDataPath); + reprodyne_play(testDataPath); + reprodyne_mark_frame(); + reprodyne_open_scope(&up); + + reprodyne_intercept_double(&up, "key", 42); + + reprodyne_validate_string(&up, "ee", "ffff"); + reprodyne_validate_string(&up, "ee", "ffff"); + + reprodyne_assert_complete_read(); + + SUCCEED("If we made it this far it worked"); +} + +TEST_CASE("Graceful handling of saved file with no entries") +{ + reprodyne_record(); + reprodyne_save(testDataPath); + reprodyne_play(testDataPath); + reprodyne_set_playback_failure_handler(&code_gobbling_error_handler); + + try + { + double up; + reprodyne_mark_frame(); + reprodyne_intercept_double(&up, "fdsfd", 34243); + } + catch(const OopsieWhoopsie& oops) + { + //This is really all we can get to I think... + REQUIRE(oops.code == REPRODYNE_STAT_UNREGISTERED_SCOPE); + } +} + +TEST_CASE("Unregistered scope") +{ + int s; + reprodyne_record(); + reprodyne_mark_frame(); + reprodyne_open_scope(&s); + + reprodyne_set_playback_failure_handler(&code_gobbling_error_handler); + + double up; + + SECTION("Write indeterminate with bad scope") + { + try + { + reprodyne_intercept_double(&up, "fj", 43); + FAIL("Unregistered scope accepted in indeterminate write"); + } + catch(const OopsieWhoopsie& oops) + { + REQUIRE(oops.code == REPRODYNE_STAT_UNREGISTERED_SCOPE); + } + } + SECTION("Serialize with bad scope") + { + try + { + reprodyne_validate_string(&up, "fjfjfjasdfdas", "CEREAL"); + FAIL("Unregistered scope accepted in serialize write"); + } + catch(const OopsieWhoopsie& oops) + { + REQUIRE(oops.code == REPRODYNE_STAT_UNREGISTERED_SCOPE); + } + } + SECTION("Reads") + { + reprodyne_save(testDataPath); + reprodyne_play(testDataPath); + reprodyne_mark_frame(); + + SECTION("Read indeterminate with bad scope") + { + try + { + reprodyne_intercept_double(&up, "bep", 3); + FAIL("Unregistered scope accepted in indeterminate read"); + } + catch(const OopsieWhoopsie& oops) + { + REQUIRE(oops.code == REPRODYNE_STAT_UNREGISTERED_SCOPE); + } + } + SECTION("Read stored call with bad scope") + { + try + { + reprodyne_validate_string(&up, "bep", ""); + FAIL("Unregistered scope accepted for serialize read"); + } + catch(const OopsieWhoopsie& oops) + { + REQUIRE(oops.code == REPRODYNE_STAT_UNREGISTERED_SCOPE); + } + } + } +} diff --git a/tests/videotests.cpp b/tests/videotests.cpp new file mode 100644 index 0000000..82ac098 --- /dev/null +++ b/tests/videotests.cpp @@ -0,0 +1,268 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + + +#include + +#include + +#include "../user-include/reprodyne.h" + +#include "oopsiewhoopsie.h" + +//Was going to test scope handling but honestly I think it's well +// enough covered by the other validation tests. It's handling is generic +// after all. Sure, this means we don't have "proper" blackbox testing, but be realistic. + + +const auto videoTestDataPath = "reprodyne-video-test-data.rep"; +const char* basicKey = "vidboi"; + +struct Bitmap +{ + std::vector data; + int width; + int stride; + int height; +}; + + +void readyRecord() +{ + reprodyne_record(); + reprodyne_mark_frame(); + reprodyne_open_scope(nullptr); +} + +void readyPlay() +{ + reprodyne_save(videoTestDataPath); + reprodyne_play(videoTestDataPath); + reprodyne_mark_frame(); + reprodyne_open_scope(nullptr); +} + +Bitmap generateBitmap(const int width, const int height) +{ + Bitmap b = {std::vector(width * height), width, width, height}; + for(auto& byte : b.data) byte = time(); //Random enough for gooberment wonk. + + //TODO: Honestly, this probably shouldn't be random. You want validation tests to be + // deterministic. Random data belongs in fuzz testing... + + return b; +} + +auto bitmap1 = generateBitmap(2000, 2000); +auto bitmap2 = generateBitmap(2000, 2000); +auto bitmap3 = generateBitmap(2000, 2000); + +void validateHelper(Bitmap& bitbap, const char* key = basicKey) +{ + SECTION("Test Bitmap Sanity Check") + { + //Just quickly make sure that each bitmap is actually unique, + // as the tests depend heavily on that fact. + //Not a seperate test because I want each test that depends on + // them to fail if they're not unique. + + auto compare = [&](Bitmap& other) + { + if(&bitbap == &other) return; + + REQUIRE(bitbap.data.size() == other.data.size()); + + auto mit = bitbap.data.begin(); + auto oit = other.data.begin(); + + while(mit != bitbap.data.end() && oit != other.data.end()) + { + REQUIRE(*mit != *oit); + ++mit; + ++oit; + } + }; + + //TODO: Uh... There's no call... + } + + reprodyne_validate_bitmap_hash(nullptr, + key, + bitbap.width, + bitbap.height, + bitbap.stride, + &bitbap.data[0]); +} + +void validationFail(const int code, const char* testFailureMsg, std::function fun) +{ + try + { + fun(); + FAIL(testFailureMsg); + } + catch(OopsieWhoopsie& e) + { + REQUIRE(e.code == code); + } +} + + +TEST_CASE("Standard video validation") +{ + readyRecord(); + + SECTION("One frame") + { + validateHelper(bitmap1); + readyPlay(); + validateHelper(bitmap1); + reprodyne_assert_complete_read(); + SUCCEED(); + } + SECTION("Three identical frames") + { + validateHelper(bitmap1); + validateHelper(bitmap1); + validateHelper(bitmap1); + readyPlay(); + validateHelper(bitmap1); + validateHelper(bitmap1); + validateHelper(bitmap1); + reprodyne_assert_complete_read(); + SUCCEED(); + } + SECTION("Three distinct frames") + { + validateHelper(bitmap1); + validateHelper(bitmap2); + validateHelper(bitmap3); + readyPlay(); + validateHelper(bitmap1); + validateHelper(bitmap2); + validateHelper(bitmap3); + reprodyne_assert_complete_read(); + SUCCEED(); //SUCC SEED + } + SECTION("Variable input frame dimensions") + { + auto bitmap2butsmaller = bitmap2; + --bitmap2butsmaller.width; + auto bitmap3butsmaller = bitmap3; + ----bitmap3butsmaller.width; + + validateHelper(bitmap1); + validateHelper(bitmap2butsmaller); + validateHelper(bitmap3butsmaller); + readyPlay(); + validateHelper(bitmap1); + validateHelper(bitmap2butsmaller); + validateHelper(bitmap3butsmaller); + reprodyne_assert_complete_read(); + SUCCEED(); + } + SECTION("Padded area changed") + { + auto bitmapWithStride = bitmap1; + bitmapWithStride.width -= 10; + + auto bitmapWidthDiffStride = bitmapWithStride; + + //Change stride value for each row + for(int h = 0; h != bitmapWidthDiffStride.height; ++h) + { + //Not = time() because it needs to be DIFFERENT, not random... + bitmapWidthDiffStride.data[h * bitmapWidthDiffStride.stride + bitmapWidthDiffStride.width]++; + } + + validateHelper(bitmapWithStride); + readyPlay(); + validateHelper(bitmapWidthDiffStride); + reprodyne_assert_complete_read(); + SUCCEED(); + } +} + + +TEST_CASE("Video frame failure conditions") +{ + auto reconfigureBitmap1validate = [](const int code, + const char* testFailureMsg, + std::function reconfigurator) + { + validationFail(code, testFailureMsg, [reconfigurator]() + { + Bitmap bcopy = bitmap1; + reconfigurator(bcopy); + validateHelper(bcopy); + }); + }; + + //TODO: test bad dimensions... But results in a runtime error and it harder to test + // FIX: Define a playback error code for it so that it can be tested easily? + + SECTION("Playback mode") + { + readyRecord(); + validateHelper(bitmap1); + readyPlay(); + + SECTION("Input video frame mismatch") + { + validationFail(REPRODYNE_STAT_VALIDATION_FAIL, + "Accepted input was different from recorded", + []() { validateHelper(bitmap2); }); + } + SECTION("Video input overflow/read past end") + { + validationFail(REPRODYNE_STAT_TAPE_PAST_END, + "Read past end successfully", + []() + { + validateHelper(bitmap1); + validateHelper(bitmap1); + }); + } + SECTION("Video input underflow/incomplete read") + { + validationFail(REPRODYNE_STAT_CALL_TAPE_INCOMPLETE_READ, + "Incomplete read succesfully asserted, oops", + []() { reprodyne_assert_complete_read(); }); + } + SECTION("Input frame dimensions are different") + { + SECTION("Width") + { + reconfigureBitmap1validate(REPRODYNE_STAT_VALIDATION_FAIL, + "Accepted frame with too small a width", + [](Bitmap& bip) { --bip.width; }); + } + SECTION("Height") + { + reconfigureBitmap1validate(REPRODYNE_STAT_VALIDATION_FAIL, + "Accepted frame with too small a height", + [](Bitmap& bip) { --bip.height; }); + } + + + //We'll just assume that if it can do either, it can do both + + //We're also not testing whether we get a mismatch when width/height > recorded. + //This is just a judgement call and so chosen because the test helpers are done + // with the assumption that the max size is the same as the default size of the bitmaps. + //If we need to test this condition (Which would only fail on an absolutely assanine implementation) + // then it should just be in it's own test case because it has to break that assumption. + } + } + SECTION("Playback on empty tape") + { + readyRecord(); + readyPlay(); + + validationFail(REPRODYNE_STAT_EMPTY_TAPE, + "Read worked empty tape succesfully", + []() + { + validateHelper(bitmap1); + }); + } +} diff --git a/user-include/reprodyne.h b/user-include/reprodyne.h new file mode 100644 index 0000000..78b32c4 --- /dev/null +++ b/user-include/reprodyne.h @@ -0,0 +1,124 @@ +//This file is part of the reprodyne project and is licensed under the terms of the LGPL-3.0-only + + +#ifndef REPRODYNE_H +#define REPRODYNE_H + +#define REPRODYNE_STAT_FRAME_MISMATCH 100 +#define REPRODYNE_STAT_VALIDATION_FAIL 101 +#define REPRODYNE_STAT_EMPTY_TAPE 102 +#define REPRODYNE_STAT_TAPE_PAST_END 103 +#define REPRODYNE_STAT_CALL_TAPE_INCOMPLETE_READ 104 +#define REPRODYNE_STAT_PROG_TAPE_INCOMPLETE_READ 105 +#define REPRODYNE_STAT_UNREGISTERED_SCOPE 106 + +typedef void(*reprodyne_playback_failure_handler)(const int code, const char* msg); + +#ifdef REPRODYNE_AVAILABLE + +//Set the playback handler (Using the above function signature) +// that will be called if there's anything fishy with the playback. May also be called +// if something illegal happens in record mode. +#define reprodyne_set_playback_failure_handler(handler) \ + reprodyne_do_not_call_this_function_directly_set_playback_failure_handler(handler) + +//Called to initialize recording. +#define reprodyne_record() reprodyne_do_not_call_this_function_directly_record() + +//Save recording to path. File extension doesn't matter. +#define reprodyne_save(path) reprodyne_do_not_call_this_function_directly_save(path) + +//Called to initialize playback. +#define reprodyne_play(path) reprodyne_do_not_call_this_function_directly_play(path) + +//Mark a "frame", this must be called before any validator or interceptors. Suggested +// to be called at the top of a main loop, if applicable. Otherwise once at the beginning of +// the procedure. +#define reprodyne_mark_frame() reprodyne_do_not_call_this_function_directly_mark_frame() + +//Register a scope. Must be done before using said scope in interceptors or validators. +//A reused pointer will shadow it's previous scope. Pointer reuse need not be deterministic +// (They can be reused in one run but not another, for example), only the order of allocation, +// and what the pointer represents at any given time is important. +#define reprodyne_open_scope(scope) reprodyne_do_not_call_this_function_directly_open_scope(scope) + +//Intercept a double against the scope/key pair. +#define reprodyne_intercept_double(scope, key, val) \ + reprodyne_do_not_call_this_function_directly_intercept_double(scope, key, val) + +//Validate a string against the scope/key pair. +#define reprodyne_validate_string(scope, key, call) \ + reprodyne_do_not_call_this_function_directly_validate_string(scope, key, call) + +//Validate a bitmap against a scope/key pair by taking a hash. +// NOTE: Width and stride represent the width of you data in *BYTES* +//It's fine if the stride is the same size as the width, this should be useful for generic data. +//The data in the padded region is ignored. +#define reprodyne_validate_bitmap_hash(scope, key, width, height, stride, bytes) \ + reprodyne_do_not_call_this_function_directly_validate_bitmap_hash(scope, key, width, height, stride, bytes) + +//Make sure that the program didn't terminate early, and that all the validation +// and indeterminate tapes have been read to completion. Only makes sense in playback mode. +#define reprodyne_assert_complete_read() reprodyne_do_not_call_this_function_directly_assert_complete_read() + + +//If you believe lower case macros are evil... I'm sorry. +//I just... I can't yell this much... +/*-------------------------------Implementation junk beyond this point-------------------------------*/ +#ifdef __cplusplus +extern "C" { +#endif + +void reprodyne_do_not_call_this_function_directly_set_playback_failure_handler(reprodyne_playback_failure_handler handler); + +void reprodyne_do_not_call_this_function_directly_record(); +void reprodyne_do_not_call_this_function_directly_save(const char* path); + +void reprodyne_do_not_call_this_function_directly_play(const char* path); + +void reprodyne_do_not_call_this_function_directly_mark_frame(); +void reprodyne_do_not_call_this_function_directly_open_scope(void* scope); + +double reprodyne_do_not_call_this_function_directly_intercept_double(void* scope, + const char* key, + double val); + +void reprodyne_do_not_call_this_function_directly_validate_string(void* scope, const char* key, const char* cereal); + +void reprodyne_do_not_call_this_function_directly_validate_bitmap_hash(void* scope, + const char* key, + const unsigned int width, + const unsigned int height, + const unsigned int stride, + void* bytes); + +void reprodyne_do_not_call_this_function_directly_assert_complete_read(); + +#ifdef __cplusplus +} //extern "C" +#endif + +#else + +#define reprodyne_set_playback_failure_handler(handler) ((void)0) + +#define reprodyne_mode_play() ((void)0) +#define reprodyne_mode_record() ((void)0) + +#define reprodyne_record() ((void)0) +#define reprodyne_save(path) ((void)0) +#define reprodyne_play(path) ((void)0) + +#define reprodyne_assert_complete_read() ((void)0) + +#define reprodyne_open_scope(scope) ((void)0) +#define reprodyne_mark_frame() ((void)0) + +#define reprodyne_intercept_double(scope, key, val) val + +#define reprodyne_validate_string(scope, key, call) ((void)0) +#define reprodyne_validate_bitmap_hash(scope, key, width, height, stride, bytes) ((void)0) + + +#endif //REPRODYNE_AVAILABLE +#endif //REPRODYNE_H