pax_global_header00006660000000000000000000000064126606100300014504gustar00rootroot0000000000000052 comment=e6791d1217ca8c4d1d709ebd1bb7f3ffec3248bc Bear-2.1.5/000077500000000000000000000000001266061003000123625ustar00rootroot00000000000000Bear-2.1.5/.travis.yml000066400000000000000000000005771266061003000145040ustar00rootroot00000000000000language: python python: - "2.7" - "3.2" - "3.3" - "3.4" - "3.5" - "pypy" sudo: false addons: apt: packages: - cmake - scons - qt4-qmake install: - pip install pep8 script: - pep8 bear/main.py.in - cmake . -DCPACK_GENERATOR="TGZ;DEB" - make all - make check - mkdir target_dir - DESTDIR=target_dir make install - make package Bear-2.1.5/CMakeLists.txt000066400000000000000000000030631266061003000151240ustar00rootroot00000000000000cmake_minimum_required(VERSION 2.8) SET (CMAKE_OSX_ARCHITECTURES "i386;x86_64" CACHE STRING "Rogue") project(bear C) set(BEAR_VERSION "2.1.5") set(CPACK_PACKAGE_NAME "bear") set(CPACK_PACKAGE_CONTACT "László Nagy") set(CPACK_PACKAGE_VENDOR ${CPACK_PACKAGE_CONTACT}) set(CPACK_PACKAGE_VERSION ${BEAR_VERSION}) set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "BuildEAR") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/COPYING") set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md") set(CPACK_PACKAGING_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX}) set(CPACK_RPM_PACKAGE_RELEASE "1%{?dist}") set(CPACK_RPM_PACKAGE_LICENSE "GPLv3") set(CPACK_RPM_PACKAGE_GROUP "Development/Tools") set(CPACK_RPM_PACKAGE_URL "http://github.com/rizsotto/Bear") set(CPACK_RPM_PACKAGE_DESCRIPTION "Bear is a tool to generate compilation database for clang tooling.") set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON) include(CPack) include(GNUInstallDirs) install(FILES COPYING README.md ChangeLog.md DESTINATION ${CMAKE_INSTALL_DOCDIR}) include(CheckCCompilerFlag) check_c_compiler_flag("-std=c99" C99_SUPPORTED) if (C99_SUPPORTED) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99") endif() add_definitions(-D_GNU_SOURCE) list(APPEND CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE) if (NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Release") endif() set(EAR_LIB_FILE ${CMAKE_SHARED_LIBRARY_PREFIX}ear${CMAKE_SHARED_LIBRARY_SUFFIX}) set(DEFAULT_PRELOAD_FILE ${CMAKE_INSTALL_FULL_LIBDIR}/${EAR_LIB_FILE}) add_subdirectory(libear) add_subdirectory(bear) add_subdirectory(test) add_subdirectory(doc) Bear-2.1.5/COPYING000066400000000000000000001045131266061003000134210ustar00rootroot00000000000000 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 . Bear-2.1.5/ChangeLog.md000066400000000000000000000124011266061003000145310ustar00rootroot00000000000000## 2.1.5 (2016.02.16) Bugfixes: - Stop filtering out `-m` options (@joshtriplett, #115) - Updated man page bugs section (#114) ## 2.1.4 (2016.02.14) Bugfixes: - Make paths to sources and include files absolute. (@svenpanne, #111) - Extend known issues section of documentation (#112, #108, #105, #102) ## 2.1.3 (2016.01.13) Bugfixes: - warnings are not filtered from output (@velkyel, #106) - support universal binaries (32 and 64) on x86 OS X (@DeanoC, #101) ## 2.1.2 (2015.10.01) Bugfixes: - Fix escaping quotes for shell too. (@zauguin, #88) ## 2.1.1 (2015.08.31) Bugfixes: - Fix iterator next method usage (@drvink, #97) ## 2.1.0 (2015.08.08) Features: - Ignore preprocessor flags for dependency generation (@jonthn, #74) - Exclude irrelevant files names in command (@wweic, #94) - Support MetaWare toolkit (@twpedersen, #95) - Use docker build for travis-ci Bugfixes: - Get rid of cmake warnings on osx (@emlai, #90) - Protect report generation in multithread build systems (@smoofra, #93) ## 2.0.4 (2015-06-16) Bugfixes: - Fix crash when make with -j option (@minhyuk, #87) ## 2.0.3 (2015-04-04) Bugfixes: - Fix passing of arguments to mkdtemp (@kljohann, #75) - Empty output when compiler used to link. (@QuaziRandom, #80) - Bad escape of strings in compilation database. (@jumapico, #81) ## 2.0.2 (2015-02-08) Bugfixes: - Address Sanitizer error fixed. - Fix some typos in man page (@sebastinas, #72) ## 2.0.1 (2015-01-23) Bugfixes: - Double free problem fixed when descrutor called multiple times. ## 2.0 (2015-01-20) Features: - Rewrite command `bear` from C to Python. - Simplified build process with a single module for `libear`. Bugfixes: - Work with empty environment (#69, @YorkZ) - Filter out redundant entries (#66, @HongxuChen) - Append to existing compilation database (#63, @p0rnfl4k3s) ## 1.4.4 (2015-01-09) Features: - Improve escaping logic (#67, #68, @SpecLad) - Reword README file to be more english (#64, @libnoon) ## 1.4.3 (2014-07-11) Features: - Automatically generate Debian package dependency list with cpack (#62, @bbannier) ## 1.4.2 (2014-05-19) Features: - cross compilers recognised by bear (@nolange) ## 1.4.1 (2014-05-09) Bugfixes: - fix output entries have c14n file path (#61, @nickhutchinson) - fix error message on missing config file (#60, @viraptor) - extend README file based on user feedbacks (#54, #55, #56, #59, @btorpey, @breser, @vguerra) ## 1.4 (2014-01-12) Bugfixes: - fix typo in the README.md (#48, @breser) - fix typo in the man page (#49, @sebastinas) - fix cmake file to honor given CFLAGS (#50, @sebastinas) - fix execle causes segfault on 32 bit systems (#51, #52, @breser, @sebastinas) ## 1.3 (2013-12-18) Features: - set empty cancel parameter list as default (#39, #43) - implement verbose filter message at the end of the run (#41) Bugfixes: - fix process stops when ctrl-z pressed (#40, @bbannier) - fix non filtered output option renamed from debug (#44, @mikemccracken) - fix broken build on OS X (#46, @breser) - fix documentation (@mlq) - fix posix_spawn* call not implemented (#43, @agentsim, @apoluektov) ## 1.2 (2013-10-01) Features: - dependency file generation compiler calls are _optionally_ filtered (#35, @lonico) - use config file for compiler call filtering parameters (#38, @lonico, @peti) Bugfixes: - fix end-to-end test on OS X (#37, @smmckay) - fix memory leaks detected by static analyser ## 1.1 (2013-08-01) Features: - dependency file generation compiler calls `-M` are filtered (#35, @chrta) - smaller memory footprint (less allocation, code went for places when it is called) - add version query to command line Bugfixes: - fix memory leaks detected by static analyser ## 1.0 (2013-06-27) Features: - change license to GPLv3 Bugfixes: - fix process syncronization problem (#33, @blowback) - fix malloc/realloc usage (#34, @mlq) ## 0.5 (2013-06-09) Features: - use temporary directory for default socket (#29, @sebastinas) Bugfixes: - fix bashism in test (#27, @sebastinas) - fix temporary socket dir problem introduce by new code (#31, @lukedirtwalker) - fix bug introduced by report filtering (#32, @lukedirtwalker) ## 0.4 (2013-04-26) Features: - man page generation is optional (#18, @Sarcasm) - port to OS X (#24, @breser) Bugfixes: - fix json output on whitespaces (#19) - fix socket reading problem (#20, @brucestephens) - improved signal handling (#21) - build system checks for available `exec` functions (#22) ## 0.3 (2013-01-09) Features: - query known compilers which are play roles in filtering (#10) - query recognised source file extensions which are filtering (#11) - man page added (#12) - pacage generation target added to `cmake` (#15) Bugfixes: - fix child process termination problem - test added: build result propagation check ## 0.2 (2013-01-01) Features: - add debug output Bugfixes: - test added: unit test, end-to-end test and full `exec` family coverage (#4) - `scons` does pass empty environment to child processes (#9) - fix `execle` overriding bug (#13) - fix json output (#14) ## 0.1 (2012-11-17) Features: - first working version - [Travis CI](https://travis-ci.org/rizsotto/Bear) hook set up Bear-2.1.5/README.md000066400000000000000000000073431266061003000136500ustar00rootroot00000000000000Build EAR ========= Bear is a tool that generates a compilation database for clang tooling. The [JSON compilation database][JSONCDB] is used in the clang project to provide information on how a single compilation unit is processed. With this, it is easy to re-run the compilation with alternate programs. One way to get a compilation database is to use `cmake` as the build tool. Passing `-DCMAKE_EXPORT_COMPILE_COMMANDS=ON` to cmake generates the `compile_commands.json` file into the current directory. For non-cmake projects, use Bear. Bear generates the json file during the build process. The concept behind Bear is to execute the original build command and intercept the `exec` calls issued by the build tool. To achieve that, Bear uses the `LD_PRELOAD` or `DYLD_INSERT_LIBRARIES` mechanisms provided by the dynamic linker. Bear has two components: the library and the binary. The library redefines the `exec` methods to be used by all child processes. The executable enables the use of the library for child processes and writes the output file. [JSONCDB]: http://clang.llvm.org/docs/JSONCompilationDatabase.html How to build ------------ Bear should be quite portable on UNIX operating systems. It has been tested on FreeBSD, GNU/Linux and OS X. ### Prerequisites 1. an ANSI **C compiler**, to compile the sources. 2. **cmake**, to configure the build process. 3. **make**, to run the build. The makefiles are generated by `cmake`. 4. **python** is a runtime dependency. The `bear` command is written in Python. (version >= 2.7) ### Build commands Ideally, you should build Bear in a separate build directory. cmake $BEAR_SOURCE_DIR make all make install # to install make check # to run tests make package # to make packages You can configure the build process with passing arguments to cmake. How to use ---------- After installation the usage is like this: bear make The output file called `compile_commands.json` found in current directory. For more options you can check the man page or pass `--help` parameter. Known issues ------------ ### Environment overriding caused problems Because Bear uses `LD_PRELOAD` or `DYLD_INSERT_LIBRARIES` environment variables, it does not append to it, but overrides it. So builds which are using these variables might not work. (I don't know any build tool which does that, but please let me know if you do.) ### Empty compilation database on OS X Captain or Fedora Security extension/modes on different operating systems might disable library preloads. This case Bear behaves normaly, but the result compilation database will be empty. (Please make sure it's not the case when reporting bugs.) Notable examples for enabled security modes are: OS X 10.11 (check with `csrutil status | grep 'System Integrity Protection'`), and Fedora, CentOS, RHEL (check with `sestatus | grep 'SELinux status'`). Workaround could be to disable the security feature while running Bear. (This might involve reboot of your computer, so might be heavy workaround.) The other option could be to use tools which are using compiler wrappers. (It inject a fake compiler which does record the compiler invocation and calls the real compiler too.) An example for such tool might be [scan-build][scanbuild]. The build system shall respect `CC` and `CXX` environment variables. [scanbuild]: https://github.com/rizsotto/scan-build Problem reports --------------- If you find a bug in this documentation or elsewhere in the program or would like to propose an improvement, please use the project's [github issue tracker][ISSUES]. Please describing the bug and where you found it. If you have a suggestion how to fix it, include that as well. Patches are also welcome. [ISSUES]: https://github.com/rizsotto/Bear/issues Bear-2.1.5/bear/000077500000000000000000000000001266061003000132735ustar00rootroot00000000000000Bear-2.1.5/bear/CMakeLists.txt000066400000000000000000000003141266061003000160310ustar00rootroot00000000000000configure_file(${CMAKE_CURRENT_SOURCE_DIR}/main.py.in ${CMAKE_CURRENT_BINARY_DIR}/bear) include(GNUInstallDirs) install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/bear DESTINATION ${CMAKE_INSTALL_BINDIR}) Bear-2.1.5/bear/main.py.in000066400000000000000000000331051266061003000152000ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2012-2014 by László Nagy # This file is part of Bear. # # Bear is a tool to generate compilation database for clang tooling. # # Bear 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. # # Bear 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 . """ This module is responsible to capture the compiler invocation of any build process. The result of that should be a compilation database. This implementation is using the LD_PRELOAD or DYLD_INSERT_LIBRARIES mechanisms provided by the dynamic linker. The related library is implemented in C language and can be found under 'libear' directory. The 'libear' library is capturing all child process creation and logging the relevant information about it into separate files in a specified directory. The input of the library is therefore the output directory which is passed as an environment variable. This module implements the build command execution with the 'libear' library and the post-processing of the output files, which will condensates into a (might be empty) compilation database. """ import argparse import subprocess import json import sys import os import os.path import re import shlex import itertools import tempfile import shutil import contextlib import logging def main(): try: parser = create_parser() args = parser.parse_args() level = logging.WARNING - min(logging.WARNING, (10 * args.verbose)) logging.basicConfig(format='bear: %(message)s', level=level) logging.debug(args) if not args.build: parser.print_help() return 0 return capture(args) except KeyboardInterrupt: return 1 except Exception: logging.exception("Something unexpected had happened.") return 127 def capture(args): """ The entry point of build command interception. """ @contextlib.contextmanager def temporary_directory(**kwargs): name = tempfile.mkdtemp(**kwargs) try: yield name finally: shutil.rmtree(name) def post_processing(commands): # run post processing only if that was requested if not args.raw_entries: # create entries from the current run current = itertools.chain.from_iterable( # creates a sequence of entry generators from an exec, # but filter out non compiler calls before. (format_entry(x) for x in commands if compiler_call(x))) # read entries from previous run if args.append and os.path.exists(args.cdb): with open(args.cdb) as handle: previous = iter(json.load(handle)) else: previous = iter([]) # filter out duplicate entries from both duplicate = duplicate_check(entry_hash) return (entry for entry in itertools.chain(previous, current) if os.path.exists(entry['file']) and not duplicate(entry)) return commands with temporary_directory(prefix='bear-', dir=tempdir()) as tmpdir: # run the build command environment = setup_environment(tmpdir, args.libear) logging.info('run build in environment: %s', environment) exit_code = subprocess.call(args.build, env=environment) logging.info('build finished with exit code: %s', exit_code) # read the intercepted exec calls commands = (parse_exec_trace(os.path.join(tmpdir, filename)) for filename in sorted(os.listdir(tmpdir))) # do post processing entries = post_processing(itertools.chain.from_iterable(commands)) # dump the compilation database with open(args.cdb, 'w+') as handle: json.dump(list(entries), handle, sort_keys=True, indent=4) return exit_code def setup_environment(destination, ear_library_path): """ Sets up the environment for the build command. It sets the required environment variables and execute the given command. The exec calls will be logged by the 'libear' preloaded library or by the 'wrapper' programs. """ environment = dict(os.environ) environment.update({'BEAR_OUTPUT': destination}) if sys.platform == 'darwin': environment.update({ 'DYLD_INSERT_LIBRARIES': ear_library_path, 'DYLD_FORCE_FLAT_NAMESPACE': '1' }) else: environment.update({'LD_PRELOAD': ear_library_path}) return environment def parse_exec_trace(filename): """ Parse the file generated by the 'libear' preloaded library. Given filename points to a file which contains the basic report generated by the interception library or wrapper command. A single report file _might_ contain multiple process creation info. """ GS = chr(0x1d) RS = chr(0x1e) US = chr(0x1f) logging.debug('parse exec trace file: %s', filename) with open(filename, 'r') as handler: content = handler.read() for group in filter(bool, content.split(GS)): records = group.split(RS) yield { 'pid': records[0], 'ppid': records[1], 'function': records[2], 'directory': records[3], 'command': records[4].split(US)[:-1] } def format_entry(entry): """ Generate the desired fields for compilation database entries. """ def abspath(name): """ Create normalized absolute path from input filename. """ fullname = name if os.path.isabs( name) else os.path.join(entry['directory'], name) return os.path.normpath(fullname) logging.debug('format this command: %s', entry['command']) atoms = classify_parameters(entry['command'], abspath) if atoms['action'] <= Action.Compile: for source in atoms['files']: compiler = 'c++' if atoms['c++'] else 'cc' command = [compiler, '-c'] + atoms['compile_options'] + [source] logging.debug('formated as: %s', command) yield { 'directory': entry['directory'], 'command': shell_escape(command), 'file': abspath(source) } def shell_escape(command): """ Takes a command as list and returns a string. """ def needs_quote(word): """ Returns true if worduments needs to be protected by quotes. Previous implementation was shlex.split method, but that's not good for this job. Currently is running through the string with a basic state checking. """ reserved = {' ', '$', '%', '&', '(', ')', '[', ']', '{', '}', '*', '|', '<', '>', '@', '?', '!'} state = 0 for current in word: if state == 0 and current in reserved: return True elif state == 0 and current == '\\': state = 1 elif state == 1 and current in reserved | {'\\'}: state = 0 elif state == 0 and current == '"': state = 2 elif state == 2 and current == '"': state = 0 elif state == 0 and current == "'": state = 3 elif state == 3 and current == "'": state = 0 return state != 0 def escape(word): """ Do protect argument if that's needed. """ table = {'\\': '\\\\', '"': '\\"'} escaped = ''.join([table.get(c, c) for c in word]) return '"' + escaped + '"' if needs_quote(word) else escaped return " ".join([escape(arg) for arg in command]) def is_source(filename): """ A predicate to decide the filename is a source file or not. """ accepted = { '.c', '.cc', '.cp', '.cpp', '.cxx', '.c++', '.m', '.mm', '.i', '.ii', '.mii' } __, ext = os.path.splitext(filename) return ext.lower() in accepted def compiler_call(entry): """ A predicate to decide the entry is a compiler call or not. """ patterns = [ re.compile(r'^([^/]*/)*c(c|\+\+)$'), re.compile(r'^([^/]*/)*([^-]*-)*[mg](cc|\+\+)(-\d+(\.\d+){0,2})?$'), re.compile(r'^([^/]*/)*([^-]*-)*clang(\+\+)?(-\d+(\.\d+){0,2})?$'), re.compile(r'^([^/]*/)*llvm-g(cc|\+\+)$'), ] executable = entry['command'][0] return any((pattern.match(executable) for pattern in patterns)) def entry_hash(entry): """ Implement unique hash method for compilation database entries. """ # For faster lookup in set filename is reverted filename = entry['file'][::-1] # For faster lookup in set directory is reverted directory = entry['directory'][::-1] # On OS X the 'cc' and 'c++' compilers are wrappers for # 'clang' therefore both call would be logged. To avoid # this the hash does not contain the first word of the # command. command = ' '.join(shlex.split(entry['command'])[1:]) return '<>'.join([filename, directory, command]) def duplicate_check(method): """ Predicate to detect duplicated entries. Unique hash method can be use to detect duplicates. Entries are represented as dictionaries, which has no default hash method. This implementation uses a set datatype to store the unique hash values. This method returns a method which can detect the duplicate values. """ def predicate(entry): hash_value = predicate.unique(entry) if hash_value not in predicate.state: predicate.state.add(hash_value) return False return True predicate.unique = method predicate.state = set() return predicate def tempdir(): """ Return the default temorary directory. """ from os import getenv return getenv('TMPDIR', getenv('TEMP', getenv('TMP', '/tmp'))) def create_parser(): """ Parser factory method. """ parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '--version', action='version', version='%(prog)s @BEAR_VERSION@') parser.add_argument( '--verbose', '-v', action='count', default=0, help="""enable verbose output from '%(prog)s'. A second '-v' increases verbosity.""") parser.add_argument( '--cdb', '-o', metavar='', default="compile_commands.json", help="""The JSON compilation database.""") parser.add_argument( '--append', '-a', action='store_true', help="""appends new entries to existing compilation database.""") testing = parser.add_argument_group('advanced options') testing.add_argument( '--disable-filter', '-n', dest='raw_entries', action='store_true', help="""disable filter, unformated output.""") testing.add_argument( '--libear', '-l', dest='libear', default="@DEFAULT_PRELOAD_FILE@", action='store', help="""specify libear file location.""") parser.add_argument( dest='build', nargs=argparse.REMAINDER, help="""command to run.""") return parser class Action(object): """ Enumeration class for compiler action. """ Link, Compile, Ignored = range(3) def classify_parameters(command, abspath): """ Parses the command line arguments of the given invocation. """ def take(values, key, iterator): current = values.get(key, []) values.update({key: current + [iterator]}) def action(values, value): current = values.get('action', value) values.update({'action': max(current, value)}) state = { 'action': Action.Link, 'files': [], 'compile_options': [], 'c++': cplusplus_compiler(command[0]) } args = iter(command[1:]) for arg in args: # compiler action parameters are the most important ones... if arg == '-c': action(state, Action.Compile) elif arg in {'-E', '-S', '-cc1', '-M', '-MM', '-###'}: action(state, Action.Ignored) # some preprocessor parameters are ignored... elif arg in {'-MD', '-MMD', '-MG', '-MP'}: pass elif arg in {'-MF', '-MT', '-MQ'}: next(args) # linker options are ignored... elif arg in {'-static', '-shared', '-s', '-rdynamic'}: pass elif re.match(r'^-[lL].+', arg): pass elif arg in {'-l', '-L', '-u', '-z', '-T', '-Xlinker'}: next(args) # parameters which looks source file are taken... elif re.match(r'^[^-].+', arg) and is_source(arg): take(state, 'files', abspath(arg)) # and consider everything else as compile option. else: # make include paths absolute match = re.match(r'^(-I)(.+)', arg) if match: arg = match.group(1) + abspath(match.group(2)) take(state, 'compile_options', arg) return state def cplusplus_compiler(name): """ Returns true when the compiler name refer to a C++ compiler. """ match = re.match(r'^([^/]*/)*(\w*-)*(\w+\+\+)(-(\d+(\.\d+){0,3}))?$', name) return False if match is None else True if __name__ == "__main__": sys.exit(main()) Bear-2.1.5/doc/000077500000000000000000000000001266061003000131275ustar00rootroot00000000000000Bear-2.1.5/doc/CMakeLists.txt000066400000000000000000000003211266061003000156630ustar00rootroot00000000000000configure_file(${CMAKE_CURRENT_SOURCE_DIR}/bear.1.in ${CMAKE_CURRENT_BINARY_DIR}/bear.1) include(GNUInstallDirs) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/bear.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1) Bear-2.1.5/doc/bear.1.in000066400000000000000000000077371266061003000145450ustar00rootroot00000000000000.TH BEAR 1 "February 16, 2016" "Bear User Manuals" .SH NAME .PP bear \- build ear .SH SYNOPSIS .PP bear [\f[I]options\f[]] [\f[I]build commands\f[]] .SH DESCRIPTION .PP Bear is a tool to generate compilation database for clang tooling. .PP The JSON compilation database (http://clang.llvm.org/docs/JSONCompilationDatabase.html) is used in clang project to provide information how a single compilation unit was processed. When that is available then it is easy to re\-run the compilation with different programs. .PP Bear execs the original build command and intercept the \f[C]exec\f[] calls. To achieve that Bear uses the \f[C]LD_PRELOAD\f[] or \f[C]DYLD_INSERT_LIBRARIES\f[] mechanisms provided by the dynamic linker. There is a library which defines the \f[C]exec\f[] methods and used in every child processes of the build command. The executable itself sets the environment up to child processes and writes the output file. .SH OPTIONS .TP .B \-o \f[I]output\f[], \-\-cdb \f[I]output\f[] Specify output file. Default value provided. .RS .RE .TP .B \-a, \-\-append Use previously generated output file and append the new entries to it. This way you can run bear continuously during work, and it keeps the compilation database up to date. File deletion and addition are both considered. But build process change (modifying compiler flags) will cause duplicate entries. .RS .RE .TP .B \-v, \-\-verbose Make bear more verbose. .RS .RE .TP .B \-l \f[I]library\f[] Specify the preloaded library location. Default value provided. (This option mainly for development purposes.) .RS .RE .TP .B \-n Disable filter. The output is also a \f[I]JSON\f[] formated file. But the result is not a compilation database. It contains all available information of the \f[C]exec\f[] calls. (This option mainly for development purposes.) .RS .RE .SH OUTPUT .PP There are two version of output formats. One is defined by the clang tooling. This goes like this: .IP .nf \f[C] [ \ \ {\ "directory":\ "/home/user/llvm/build", \ \ \ \ "command":\ "clang++\ \-Irelative\ \-c\ \-o\ file.o\ file.cc", \ \ \ \ "file":\ "file.cc"\ }, \ \ ... ] \f[] .fi .PP To achieve this bear has to run some filtering and formating. Build tools exec many commands during the build process. Bear has to find was that a compiler call, and what was the source file? The other output format is generated by the \f[C]\-n\f[] flag. (This output is not formalized, it's used to debug bear itself.) .SH EXIT STATUS .PP Bear exit status is the exit status of the build command. Except when bear crashes, then it sets to non zero. .SH ENVIRONMENT .TP .B BEAR_OUTPUT The place of the temporary files where client shall report \f[C]exec\f[] calls. Value set by bear, overrides previous value for child processes. .RS .RE .TP .B LD_PRELOAD Used by the dynamic loader on Linux, FreeBSD and other UNIX OS. Value set by bear, overrides previous value for child processes. .RS .RE .TP .B DYLD_INSERT_LIBRARIES Used by the dynamic loader on OS X. Value set by bear, overrides previous value for child processes. .RS .RE .TP .B DYLD_FORCE_FLAT_NAMESPACE Used by the dynamic loader on OS X. Value set by bear, overrides previous value for child processes. .RS .RE .SH FILES .TP .B @DEFAULT_PRELOAD_FILE@ bear library to implement \f[C]exec\f[] calls. .RS .RE .SH SEE ALSO .PP ld.so(8), exec(3) .SH BUGS .PP Because Bear uses LD_PRELOAD or DYLD_INSERT_LIBRARIES environment variables, it does not append to it, but overrides it. So builds which are using these variables might not work. (I don't know any build tool which does that, but please let me know if you do.) .PP Security extension/modes on different operating systems might disable library preloads. This case Bear behaves normaly, but the result compilation database will be empty. (Please make sure it's not the case when reporting bugs.) Notable examples for enabled security modes are: SIP on OS X Captain and SELinux on Fedora, CentOS, RHEL. .SH COPYRIGHT .PP Copyright (C) 2012-2016 by László Nagy .SH AUTHORS László Nagy. Bear-2.1.5/libear/000077500000000000000000000000001266061003000136205ustar00rootroot00000000000000Bear-2.1.5/libear/CMakeLists.txt000066400000000000000000000024221266061003000163600ustar00rootroot00000000000000set(CMAKE_MACOSX_RPATH 1) include(CheckFunctionExists) include(CheckSymbolExists) check_function_exists(execve HAVE_EXECVE) check_function_exists(execv HAVE_EXECV) check_function_exists(execvpe HAVE_EXECVPE) check_function_exists(execvp HAVE_EXECVP) check_function_exists(execvP HAVE_EXECVP2) check_function_exists(execl HAVE_EXECL) check_function_exists(execlp HAVE_EXECLP) check_function_exists(execle HAVE_EXECLE) check_function_exists(posix_spawn HAVE_POSIX_SPAWN) check_function_exists(posix_spawnp HAVE_POSIX_SPAWNP) check_symbol_exists(_NSGetEnviron crt_externs.h HAVE_NSGETENVIRON) find_package(Threads REQUIRED) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_library(ear SHARED ear.c) target_link_libraries(ear ${CMAKE_DL_LIBS}) if(THREADS_HAVE_PTHREAD_ARG) set_property(TARGET ear PROPERTY COMPILE_OPTIONS "-pthread") set_property(TARGET ear PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread") endif() if(CMAKE_THREAD_LIBS_INIT) target_link_libraries(ear "${CMAKE_THREAD_LIBS_INIT}") endif() set_target_properties(ear PROPERTIES INSTALL_RPATH "@loader_path/${CMAKE_INSTALL_LIBDIR}") include(GNUInstallDirs) install(TARGETS ear LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) Bear-2.1.5/libear/config.h.in000066400000000000000000000010201266061003000156340ustar00rootroot00000000000000/* -*- coding: utf-8 -*- // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. */ #pragma once #cmakedefine HAVE_EXECVE #cmakedefine HAVE_EXECV #cmakedefine HAVE_EXECVPE #cmakedefine HAVE_EXECVP #cmakedefine HAVE_EXECVP2 #cmakedefine HAVE_EXECL #cmakedefine HAVE_EXECLP #cmakedefine HAVE_EXECLE #cmakedefine HAVE_POSIX_SPAWN #cmakedefine HAVE_POSIX_SPAWNP #cmakedefine HAVE_NSGETENVIRON #cmakedefine APPLE Bear-2.1.5/libear/ear.c000066400000000000000000000434771266061003000145520ustar00rootroot00000000000000/* Copyright (C) 2012-2015 by László Nagy This file is part of Bear. Bear is a tool to generate compilation database for clang tooling. Bear 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. Bear 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 . */ /** * This file implements a shared library. This library can be pre-loaded by * the dynamic linker of the Operating System (OS). It implements a few function * related to process creation. By pre-load this library the executed process * uses these functions instead of those from the standard library. * * The idea here is to inject a logic before call the real methods. The logic is * to dump the call into a file. To call the real method this library is doing * the job of the dynamic linker. * * The only input for the log writing is about the destination directory. * This is passed as environment variable. */ #include "config.h" #include #include #include #include #include #include #include #include #if defined HAVE_POSIX_SPAWN || defined HAVE_POSIX_SPAWNP #include #endif #if defined HAVE_NSGETENVIRON #include static char **environ; #else extern char **environ; #endif #define ENV_OUTPUT "BEAR_OUTPUT" #ifdef APPLE # define ENV_FLAT "DYLD_FORCE_FLAT_NAMESPACE" # define ENV_PRELOAD "DYLD_INSERT_LIBRARIES" # define ENV_SIZE 3 #else # define ENV_PRELOAD "LD_PRELOAD" # define ENV_SIZE 2 #endif #define DLSYM(TYPE_, VAR_, SYMBOL_) \ union { \ void *from; \ TYPE_ to; \ } cast; \ if (0 == (cast.from = dlsym(RTLD_NEXT, SYMBOL_))) { \ perror("bear: dlsym"); \ exit(EXIT_FAILURE); \ } \ TYPE_ const VAR_ = cast.to; typedef char const * bear_env_t[ENV_SIZE]; static int bear_capture_env_t(bear_env_t *env); static void bear_release_env_t(bear_env_t *env); static char const **bear_update_environment(char *const envp[], bear_env_t *env); static char const **bear_update_environ(char const **in, char const *key, char const *value); static void bear_report_call(char const *fun, char const *const argv[]); static char const **bear_strings_build(char const *arg, va_list *ap); static char const **bear_strings_copy(char const **const in); static char const **bear_strings_append(char const **in, char const *e); static size_t bear_strings_length(char const *const *in); static void bear_strings_release(char const **); static bear_env_t env_names = { ENV_OUTPUT , ENV_PRELOAD #ifdef ENV_FLAT , ENV_FLAT #endif }; static bear_env_t initial_env = { 0 , 0 #ifdef ENV_FLAT , 0 #endif }; static int initialized = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static void on_load(void) __attribute__((constructor)); static void on_unload(void) __attribute__((destructor)); #ifdef HAVE_EXECVE static int call_execve(const char *path, char *const argv[], char *const envp[]); #endif #ifdef HAVE_EXECVP static int call_execvp(const char *file, char *const argv[]); #endif #ifdef HAVE_EXECVPE static int call_execvpe(const char *file, char *const argv[], char *const envp[]); #endif #ifdef HAVE_EXECVP2 static int call_execvP(const char *file, const char *search_path, char *const argv[]); #endif #ifdef HAVE_POSIX_SPAWN static int call_posix_spawn(pid_t *restrict pid, const char *restrict path, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *restrict attrp, char *const argv[restrict], char *const envp[restrict]); #endif #ifdef HAVE_POSIX_SPAWNP static int call_posix_spawnp(pid_t *restrict pid, const char *restrict file, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *restrict attrp, char *const argv[restrict], char *const envp[restrict]); #endif /* Initialization method to Captures the relevant environment variables. */ static void on_load(void) { pthread_mutex_lock(&mutex); #ifdef HAVE_NSGETENVIRON environ = *_NSGetEnviron(); #endif if (!initialized) initialized = bear_capture_env_t(&initial_env); pthread_mutex_unlock(&mutex); } static void on_unload(void) { pthread_mutex_lock(&mutex); bear_release_env_t(&initial_env); initialized = 0; pthread_mutex_unlock(&mutex); } /* These are the methods we are try to hijack. */ #ifdef HAVE_EXECVE int execve(const char *path, char *const argv[], char *const envp[]) { bear_report_call(__func__, (char const *const *)argv); return call_execve(path, argv, envp); } #endif #ifdef HAVE_EXECV #ifndef HAVE_EXECVE #error can not implement execv without execve #endif int execv(const char *path, char *const argv[]) { bear_report_call(__func__, (char const *const *)argv); return call_execve(path, argv, environ); } #endif #ifdef HAVE_EXECVPE int execvpe(const char *file, char *const argv[], char *const envp[]) { bear_report_call(__func__, (char const *const *)argv); return call_execvpe(file, argv, envp); } #endif #ifdef HAVE_EXECVP int execvp(const char *file, char *const argv[]) { bear_report_call(__func__, (char const *const *)argv); return call_execvp(file, argv); } #endif #ifdef HAVE_EXECVP2 int execvP(const char *file, const char *search_path, char *const argv[]) { bear_report_call(__func__, (char const *const *)argv); return call_execvP(file, search_path, argv); } #endif #ifdef HAVE_EXECL #ifndef HAVE_EXECVE #error can not implement execl without execve #endif int execl(const char *path, const char *arg, ...) { va_list args; va_start(args, arg); char const **argv = bear_strings_build(arg, &args); va_end(args); bear_report_call(__func__, (char const *const *)argv); int const result = call_execve(path, (char *const *)argv, environ); bear_strings_release(argv); return result; } #endif #ifdef HAVE_EXECLP #ifndef HAVE_EXECVP #error can not implement execlp without execvp #endif int execlp(const char *file, const char *arg, ...) { va_list args; va_start(args, arg); char const **argv = bear_strings_build(arg, &args); va_end(args); bear_report_call(__func__, (char const *const *)argv); int const result = call_execvp(file, (char *const *)argv); bear_strings_release(argv); return result; } #endif #ifdef HAVE_EXECLE #ifndef HAVE_EXECVE #error can not implement execle without execve #endif // int execle(const char *path, const char *arg, ..., char * const envp[]); int execle(const char *path, const char *arg, ...) { va_list args; va_start(args, arg); char const **argv = bear_strings_build(arg, &args); char const **envp = va_arg(args, char const **); va_end(args); bear_report_call(__func__, (char const *const *)argv); int const result = call_execve(path, (char *const *)argv, (char *const *)envp); bear_strings_release(argv); return result; } #endif #ifdef HAVE_POSIX_SPAWN int posix_spawn(pid_t *restrict pid, const char *restrict path, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *restrict attrp, char *const argv[restrict], char *const envp[restrict]) { bear_report_call(__func__, (char const *const *)argv); return call_posix_spawn(pid, path, file_actions, attrp, argv, envp); } #endif #ifdef HAVE_POSIX_SPAWNP int posix_spawnp(pid_t *restrict pid, const char *restrict file, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *restrict attrp, char *const argv[restrict], char *const envp[restrict]) { bear_report_call(__func__, (char const *const *)argv); return call_posix_spawnp(pid, file, file_actions, attrp, argv, envp); } #endif /* These are the methods which forward the call to the standard implementation. */ #ifdef HAVE_EXECVE static int call_execve(const char *path, char *const argv[], char *const envp[]) { typedef int (*func)(const char *, char *const *, char *const *); DLSYM(func, fp, "execve"); char const **const menvp = bear_update_environment(envp, &initial_env); int const result = (*fp)(path, argv, (char *const *)menvp); bear_strings_release(menvp); return result; } #endif #ifdef HAVE_EXECVPE static int call_execvpe(const char *file, char *const argv[], char *const envp[]) { typedef int (*func)(const char *, char *const *, char *const *); DLSYM(func, fp, "execvpe"); char const **const menvp = bear_update_environment(envp, &initial_env); int const result = (*fp)(file, argv, (char *const *)menvp); bear_strings_release(menvp); return result; } #endif #ifdef HAVE_EXECVP static int call_execvp(const char *file, char *const argv[]) { typedef int (*func)(const char *file, char *const argv[]); DLSYM(func, fp, "execvp"); char **const original = environ; char const **const modified = bear_update_environment(original, &initial_env); environ = (char **)modified; int const result = (*fp)(file, argv); environ = original; bear_strings_release(modified); return result; } #endif #ifdef HAVE_EXECVP2 static int call_execvP(const char *file, const char *search_path, char *const argv[]) { typedef int (*func)(const char *, const char *, char *const *); DLSYM(func, fp, "execvP"); char **const original = environ; char const **const modified = bear_update_environment(original, &initial_env); environ = (char **)modified; int const result = (*fp)(file, search_path, argv); environ = original; bear_strings_release(modified); return result; } #endif #ifdef HAVE_POSIX_SPAWN static int call_posix_spawn(pid_t *restrict pid, const char *restrict path, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *restrict attrp, char *const argv[restrict], char *const envp[restrict]) { typedef int (*func)(pid_t *restrict, const char *restrict, const posix_spawn_file_actions_t *, const posix_spawnattr_t *restrict, char *const *restrict, char *const *restrict); DLSYM(func, fp, "posix_spawn"); char const **const menvp = bear_update_environment(envp, &initial_env); int const result = (*fp)(pid, path, file_actions, attrp, argv, (char *const *restrict)menvp); bear_strings_release(menvp); return result; } #endif #ifdef HAVE_POSIX_SPAWNP static int call_posix_spawnp(pid_t *restrict pid, const char *restrict file, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *restrict attrp, char *const argv[restrict], char *const envp[restrict]) { typedef int (*func)(pid_t *restrict, const char *restrict, const posix_spawn_file_actions_t *, const posix_spawnattr_t *restrict, char *const *restrict, char *const *restrict); DLSYM(func, fp, "posix_spawnp"); char const **const menvp = bear_update_environment(envp, &initial_env); int const result = (*fp)(pid, file, file_actions, attrp, argv, (char *const *restrict)menvp); bear_strings_release(menvp); return result; } #endif /* this method is to write log about the process creation. */ static void bear_report_call(char const *fun, char const *const argv[]) { static int const GS = 0x1d; static int const RS = 0x1e; static int const US = 0x1f; if (!initialized) return; pthread_mutex_lock(&mutex); const char *cwd = getcwd(NULL, 0); if (0 == cwd) { perror("bear: getcwd"); exit(EXIT_FAILURE); } char const * const out_dir = initial_env[0]; size_t const path_max_length = strlen(out_dir) + 32; char filename[path_max_length]; if (-1 == snprintf(filename, path_max_length, "%s/%d.cmd", out_dir, getpid())) { perror("bear: snprintf"); exit(EXIT_FAILURE); } FILE * fd = fopen(filename, "a+"); if (0 == fd) { perror("bear: fopen"); exit(EXIT_FAILURE); } fprintf(fd, "%d%c", getpid(), RS); fprintf(fd, "%d%c", getppid(), RS); fprintf(fd, "%s%c", fun, RS); fprintf(fd, "%s%c", cwd, RS); size_t const argc = bear_strings_length(argv); for (size_t it = 0; it < argc; ++it) { fprintf(fd, "%s%c", argv[it], US); } fprintf(fd, "%c", GS); if (fclose(fd)) { perror("bear: fclose"); exit(EXIT_FAILURE); } free((void *)cwd); pthread_mutex_unlock(&mutex); } /* update environment assure that chilren processes will copy the desired * behaviour */ static int bear_capture_env_t(bear_env_t *env) { int status = 1; for (size_t it = 0; it < ENV_SIZE; ++it) { char const * const env_value = getenv(env_names[it]); char const * const env_copy = (env_value) ? strdup(env_value) : env_value; (*env)[it] = env_copy; status &= (env_copy) ? 1 : 0; } return status; } static void bear_release_env_t(bear_env_t *env) { for (size_t it = 0; it < ENV_SIZE; ++it) { free((void *)(*env)[it]); (*env)[it] = 0; } } static char const **bear_update_environment(char *const envp[], bear_env_t *env) { char const **result = bear_strings_copy((char const **)envp); for (size_t it = 0; it < ENV_SIZE && (*env)[it]; ++it) result = bear_update_environ(result, env_names[it], (*env)[it]); return result; } static char const **bear_update_environ(char const *envs[], char const *key, char const * const value) { // find the key if it's there size_t const key_length = strlen(key); char const **it = envs; for (; (it) && (*it); ++it) { if ((0 == strncmp(*it, key, key_length)) && (strlen(*it) > key_length) && ('=' == (*it)[key_length])) break; } // allocate a environment entry size_t const value_length = strlen(value); size_t const env_length = key_length + value_length + 2; char *env = malloc(env_length); if (0 == env) { perror("bear: malloc [in env_update]"); exit(EXIT_FAILURE); } if (-1 == snprintf(env, env_length, "%s=%s", key, value)) { perror("bear: snprintf"); exit(EXIT_FAILURE); } // replace or append the environment entry if (it && *it) { free((void *)*it); *it = env; return envs; } return bear_strings_append(envs, env); } /* util methods to deal with string arrays. environment and process arguments * are both represented as string arrays. */ static char const **bear_strings_build(char const *const arg, va_list *args) { char const **result = 0; size_t size = 0; for (char const *it = arg; it; it = va_arg(*args, char const *)) { result = realloc(result, (size + 1) * sizeof(char const *)); if (0 == result) { perror("bear: realloc"); exit(EXIT_FAILURE); } char const *copy = strdup(it); if (0 == copy) { perror("bear: strdup"); exit(EXIT_FAILURE); } result[size++] = copy; } result = realloc(result, (size + 1) * sizeof(char const *)); if (0 == result) { perror("bear: realloc"); exit(EXIT_FAILURE); } result[size++] = 0; return result; } static char const **bear_strings_copy(char const **const in) { size_t const size = bear_strings_length(in); char const **const result = malloc((size + 1) * sizeof(char const *)); if (0 == result) { perror("bear: malloc"); exit(EXIT_FAILURE); } char const **out_it = result; for (char const *const *in_it = in; (in_it) && (*in_it); ++in_it, ++out_it) { *out_it = strdup(*in_it); if (0 == *out_it) { perror("bear: strdup"); exit(EXIT_FAILURE); } } *out_it = 0; return result; } static char const **bear_strings_append(char const **const in, char const *const e) { size_t size = bear_strings_length(in); char const **result = realloc(in, (size + 2) * sizeof(char const *)); if (0 == result) { perror("bear: realloc"); exit(EXIT_FAILURE); } result[size++] = e; result[size++] = 0; return result; } static size_t bear_strings_length(char const *const *const in) { size_t result = 0; for (char const *const *it = in; (it) && (*it); ++it) ++result; return result; } static void bear_strings_release(char const **in) { for (char const *const *it = in; (it) && (*it); ++it) { free((void *)*it); } free((void *)in); } Bear-2.1.5/test/000077500000000000000000000000001266061003000133415ustar00rootroot00000000000000Bear-2.1.5/test/CMakeLists.txt000066400000000000000000000005331266061003000161020ustar00rootroot00000000000000enable_testing() set(CMAKE_CTEST_COMMAND ctest -V) add_custom_target(check COMMAND ${CMAKE_CTEST_COMMAND}) #add_subdirectory(unit_test) add_subdirectory(end-to-end) add_subdirectory(exec_anatomy) add_subdirectory(result_code) add_subdirectory(bug74) add_subdirectory(bug80) add_subdirectory(bug81) add_subdirectory(bug88) add_subdirectory(bug94) Bear-2.1.5/test/bug74/000077500000000000000000000000001266061003000142715ustar00rootroot00000000000000Bear-2.1.5/test/bug74/CMakeLists.txt000066400000000000000000000002231266061003000170260ustar00rootroot00000000000000configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/run.sh.in ${CMAKE_CURRENT_BINARY_DIR}/run.sh @ONLY) add_test(NAME run_bug74 COMMAND ./run.sh) Bear-2.1.5/test/bug74/foo.c000066400000000000000000000000341266061003000152150ustar00rootroot00000000000000int foo() { return 0; } Bear-2.1.5/test/bug74/run.sh.in000077500000000000000000000006131266061003000160410ustar00rootroot00000000000000#!/bin/sh set -o nounset set -o errexit BEAR_EXE="@CMAKE_CURRENT_BINARY_DIR@/../../bear/bear" BEAR_LIB="@CMAKE_CURRENT_BINARY_DIR@/../../libear/@EAR_LIB_FILE@" RUN_TEST="cc -c -MMD @CMAKE_CURRENT_SOURCE_DIR@/foo.c" python ${BEAR_EXE} -l ${BEAR_LIB} --cdb out.json sh -c "$RUN_TEST" test `grep "command" out.json | wc -l` -eq 1 test `cat out.json | grep "command" | grep "MMD" | wc -l` -eq 0 Bear-2.1.5/test/bug80/000077500000000000000000000000001266061003000142665ustar00rootroot00000000000000Bear-2.1.5/test/bug80/CMakeLists.txt000066400000000000000000000002231266061003000170230ustar00rootroot00000000000000configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/run.sh.in ${CMAKE_CURRENT_BINARY_DIR}/run.sh @ONLY) add_test(NAME run_bug80 COMMAND ./run.sh) Bear-2.1.5/test/bug80/build.mk000066400000000000000000000002621266061003000157160ustar00rootroot00000000000000SRC:=empty.c OBJ:=empty.o EXE:=empty test-in-one: $(SRC) cc -o $(EXE) $(SRC) test-in-two: $(SRC) cc -c $(SRC) cc -o $(EXE) $(OBJ) .PHONY: clean clean: rm -f $(OBJ) $(EXE) Bear-2.1.5/test/bug80/empty.c000066400000000000000000000000351266061003000155660ustar00rootroot00000000000000int main() { return 0; } Bear-2.1.5/test/bug80/run.sh.in000077500000000000000000000007471266061003000160460ustar00rootroot00000000000000#!/bin/sh set -o nounset set -o errexit BEAR_EXE="@CMAKE_CURRENT_BINARY_DIR@/../../bear/bear" BEAR_LIB="@CMAKE_CURRENT_BINARY_DIR@/../../libear/@EAR_LIB_FILE@" RUN_MAKE="make -C @CMAKE_CURRENT_SOURCE_DIR@ -f build.mk" python ${BEAR_EXE} -l ${BEAR_LIB} --cdb one.json $RUN_MAKE test-in-one $RUN_MAKE clean test `grep "command" one.json | wc -l` -eq 1 python ${BEAR_EXE} -l ${BEAR_LIB} --cdb two.json $RUN_MAKE test-in-two $RUN_MAKE clean test `grep "command" two.json | wc -l` -eq 1 Bear-2.1.5/test/bug81/000077500000000000000000000000001266061003000142675ustar00rootroot00000000000000Bear-2.1.5/test/bug81/CMakeLists.txt000066400000000000000000000002231266061003000170240ustar00rootroot00000000000000configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/run.sh.in ${CMAKE_CURRENT_BINARY_DIR}/run.sh @ONLY) add_test(NAME run_bug81 COMMAND ./run.sh) Bear-2.1.5/test/bug81/build.mk000066400000000000000000000001331266061003000157140ustar00rootroot00000000000000all: $(CXX) -DEXPORT="extern \"C\"" -o hello hello.cxx .PHONY: clean clean: rm -f hello Bear-2.1.5/test/bug81/hello.cxx000066400000000000000000000001421266061003000161130ustar00rootroot00000000000000#include EXPORT void foo(void) { printf("Hello world!\n"); } int main() { foo(); } Bear-2.1.5/test/bug81/run.sh.in000077500000000000000000000005261266061003000160420ustar00rootroot00000000000000#!/bin/sh set -o nounset set -o errexit BEAR_EXE="@CMAKE_CURRENT_BINARY_DIR@/../../bear/bear" BEAR_LIB="@CMAKE_CURRENT_BINARY_DIR@/../../libear/@EAR_LIB_FILE@" RUN_MAKE="make -C @CMAKE_CURRENT_SOURCE_DIR@ -f build.mk" python ${BEAR_EXE} -l ${BEAR_LIB} --cdb one.json $RUN_MAKE test `grep "command" one.json | wc -l` -eq 1 $RUN_MAKE clean Bear-2.1.5/test/bug88/000077500000000000000000000000001266061003000142765ustar00rootroot00000000000000Bear-2.1.5/test/bug88/CMakeLists.txt000066400000000000000000000002231266061003000170330ustar00rootroot00000000000000configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/run.sh.in ${CMAKE_CURRENT_BINARY_DIR}/run.sh @ONLY) add_test(NAME run_bug88 COMMAND ./run.sh) Bear-2.1.5/test/bug88/run.sh.in000077500000000000000000000011141266061003000160430ustar00rootroot00000000000000#!/bin/sh set -o nounset set -o errexit BEAR_EXE="@CMAKE_CURRENT_BINARY_DIR@/../../bear/bear" BEAR_LIB="@CMAKE_CURRENT_BINARY_DIR@/../../libear/@EAR_LIB_FILE@" RUN_TEST='cc "-DKEY=\"value with spaces\"" @CMAKE_CURRENT_SOURCE_DIR@/spaces.c -o space' python ${BEAR_EXE} -l ${BEAR_LIB} --cdb out.json sh -c "$RUN_TEST" [ "$(./space)" = "value with spaces" ] && echo "compiled correctly" [ "$(cat out.json | grep command | wc -l)" -eq 1 ] && echo "command captured" [ "$(cat out.json | grep command | sed 's/\s/\n/g' | uniq | grep -c -e \\\\\\\")" -eq 2 ] && echo "3 backslash is there" Bear-2.1.5/test/bug88/spaces.c000066400000000000000000000001641266061003000157210ustar00rootroot00000000000000#include static const char * const value = KEY; int main() { printf("%s\n", value); return 0; } Bear-2.1.5/test/bug94/000077500000000000000000000000001266061003000142735ustar00rootroot00000000000000Bear-2.1.5/test/bug94/CMakeLists.txt000066400000000000000000000002231266061003000170300ustar00rootroot00000000000000configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/run.sh.in ${CMAKE_CURRENT_BINARY_DIR}/run.sh @ONLY) add_test(NAME run_bug94 COMMAND ./run.sh) Bear-2.1.5/test/bug94/bar.c000066400000000000000000000000341266061003000152000ustar00rootroot00000000000000int bar() { return 0; } Bear-2.1.5/test/bug94/foo.c000066400000000000000000000000341266061003000152170ustar00rootroot00000000000000int foo() { return 0; } Bear-2.1.5/test/bug94/run.sh.in000077500000000000000000000007531266061003000160500ustar00rootroot00000000000000#!/bin/sh set -o nounset set -o errexit BEAR_EXE="@CMAKE_CURRENT_BINARY_DIR@/../../bear/bear" BEAR_LIB="@CMAKE_CURRENT_BINARY_DIR@/../../libear/@EAR_LIB_FILE@" RUN_TEST="cc -c @CMAKE_CURRENT_SOURCE_DIR@/foo.c @CMAKE_CURRENT_SOURCE_DIR@/bar.c" python ${BEAR_EXE} -l ${BEAR_LIB} --cdb out.json sh -c "$RUN_TEST" test `grep "command" out.json | wc -l` -eq 2 test `cat out.json | grep "command" | grep "foo.c" | wc -l` -eq 1 test `cat out.json | grep "command" | grep "bar.c" | wc -l` -eq 1 Bear-2.1.5/test/end-to-end/000077500000000000000000000000001266061003000152735ustar00rootroot00000000000000Bear-2.1.5/test/end-to-end/CMakeLists.txt000066400000000000000000000040161266061003000200340ustar00rootroot00000000000000message(STATUS "Looking for scons") find_program(SCONS_EXECUTABLE NAMES scons PATHS ENV SCONS_PATH) if (SCONS_EXECUTABLE) set(SCONS_FOUND 1) message(STATUS "Looking for scons -- found") endif() message(STATUS "Looking for qmake") find_program(QMAKE_EXECUTABLE NAMES qmake qmake-qt4 PATHS ENV QMAKE_PATH) if (QMAKE_EXECUTABLE) set(QMAKE_FOUND 1) message(STATUS "Looking for qmake -- found") endif() find_package(PythonInterp) set(BEAR_EXE ${CMAKE_CURRENT_BINARY_DIR}/../../bear/bear) set(BEAR_LIB ${CMAKE_CURRENT_BINARY_DIR}/../../libear/${EAR_LIB_FILE}) if(PYTHONINTERP_FOUND) add_custom_target(run_shell_test COMMAND python ${BEAR_EXE} -vvv -l ${BEAR_LIB} -o shell.json ${CMAKE_CURRENT_SOURCE_DIR}/compile.sh ${CMAKE_CURRENT_SOURCE_DIR} COMMAND test `python ${CMAKE_CURRENT_SOURCE_DIR}/validate_and_count.py < shell.json` -eq 4 COMMENT "Running module tests with shell") add_dependencies(run_shell_test ear) add_test(NAME run_shell_test COMMAND make run_shell_test) endif() if(PYTHONINTERP_FOUND AND PYTHON_VERSION_MAJOR EQUAL 2 AND SCONS_FOUND) add_custom_target(run_scons_test COMMAND python ${BEAR_EXE} -vvv -l ${BEAR_LIB} -o scons.json ${SCONS_EXECUTABLE} -Y ${CMAKE_CURRENT_SOURCE_DIR} COMMAND ${SCONS_EXECUTABLE} -Y ${CMAKE_CURRENT_SOURCE_DIR} -c COMMAND test `python ${CMAKE_CURRENT_SOURCE_DIR}/validate_and_count.py < scons.json` -eq 4 COMMENT "Running module tests with scons") add_dependencies(run_scons_test ear) add_test(NAME run_scons_test COMMAND make run_scons_test) endif() if(PYTHONINTERP_FOUND AND QMAKE_FOUND) add_custom_target(run_qmake_test COMMAND ${QMAKE_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/qmake.pro COMMAND python ${BEAR_EXE} -vvv -l ${BEAR_LIB} -o qmake.json make COMMAND make distclean COMMAND test `python ${CMAKE_CURRENT_SOURCE_DIR}/validate_and_count.py < qmake.json` -eq 4 COMMENT "Running module tests with qmake") add_dependencies(run_qmake_test ear) add_test(NAME run_qmake_test COMMAND make run_qmake_test) endif() Bear-2.1.5/test/end-to-end/SConstruct000066400000000000000000000007301266061003000173250ustar00rootroot00000000000000env = Environment() env['CXX'] = 'c++' env['CC'] = 'cc' env.Append(CPPDEFINES={'RELEASE_BUILD' : 'First release \"quoted\"'}) some_lib = env.SharedLibrary(target="some_lib", source=["lib/foo.cpp", "lib/bar.cc"]) some_app = env.Program(target="some_app", source=["bin/far.cxx", "bin/boo.c++"], CPPPATH=Split('#lib'), LIBPATH=['.'], LIBS=['some_lib']) Bear-2.1.5/test/end-to-end/bear.conf000066400000000000000000000024471266061003000170620ustar00rootroot00000000000000# Configuration file for Bear. # The file read by libconfig library. For syntax, check out the info page. # `info libconfig` # Filter applied on every child process execution. (a.k.a. call) # # The call will be presented in the output iff: # - match a compiler, # - match a source file, # - and does not match any cancel parameter. # # The match string shall be an extended POSIX regex. # Which is implemented in your OS libc, with all the features and bugs. # # http://en.wikipedia.org/wiki/Regular_expression # filter: { # If any of these regex match to the first argument, # it will be considered as a match on compiler. (must not be empty array.) compilers = [ "^([^/]*/)*c(c|\\+\\+)$", "^([^/]*/)*g(cc|\\+\\+)(-[34].[0-9])?$", "^([^/]*/)*clang(-[23].[0-9])?$", "^([^/]*/)*clang(\\+\\+)(-[23].[0-9])?$", "^([^/]*/)*llvm-g(cc|\\+\\+)$" ]; # If any of these regex match to any of the arguments, the first match # will be considered as source file. (must not be empty array) source_files = [ ".*\\.[cC]([cC]|\\+\\+|xx|pp|p)?$" ]; # If any of these regex match to any of the arguments, # the call won't presented in the output. (can be empty array.) cancel_parameters = [ "^-M", "^-cc1$" ]; }; Bear-2.1.5/test/end-to-end/bin/000077500000000000000000000000001266061003000160435ustar00rootroot00000000000000Bear-2.1.5/test/end-to-end/bin/bin.pro000066400000000000000000000002171266061003000173350ustar00rootroot00000000000000TEMPLATE = app TARGET = some_app INCLUDEPATH += ../lib LIBS += -L../lib -lsome_lib HEADERS += boo.h++ SOURCES += boo.c++ SOURCES += far.cxx Bear-2.1.5/test/end-to-end/bin/boo.c++000066400000000000000000000005351266061003000171170ustar00rootroot00000000000000#include "boo.h++" #include void t2(int i); void t1() { for (int i = 0; i < 100; ++i) { if (98 == i) { t2(i); break; } } } void t2(int i) { if (9 == i) { int k = i + 9; ++k; return; } acme::t1(); } int main() { t1(); return 0; } Bear-2.1.5/test/end-to-end/bin/boo.h++000066400000000000000000000000601266061003000171150ustar00rootroot00000000000000#ifndef boo_h #define boo_h void t1(); #endif Bear-2.1.5/test/end-to-end/bin/far.cxx000066400000000000000000000001151266061003000173340ustar00rootroot00000000000000#include #include "boo.h++" void b1() { t1(); acme::t1(); } Bear-2.1.5/test/end-to-end/compile.sh000077500000000000000000000006401266061003000172620ustar00rootroot00000000000000#!/bin/sh set -o nounset set -o errexit set -o xtrace c++ -c -fPIC -I"$1/lib" "$1/lib/foo.cpp" -o /dev/null c++ -c -fPIC -I"$1/lib" "$1/lib/bar.cc" -o /dev/null (c++ -c -I"$1/lib" -I"$1/bin" "$1/bin/./boo.c++" -o /dev/null) (c++ -c -I"$1/lib" -I"$1/bin" "$1/bin/../bin/far.cxx" -o /dev/null) # add noise to the compilation... true echo "gcc -invocation -look -like this.c" echo "c++ -c bin/boo.cpp -o /dev/null" Bear-2.1.5/test/end-to-end/lib/000077500000000000000000000000001266061003000160415ustar00rootroot00000000000000Bear-2.1.5/test/end-to-end/lib/bar.cc000066400000000000000000000000771266061003000171200ustar00rootroot00000000000000#include "foo.h" namespace acme { void b1() { t1(); } } Bear-2.1.5/test/end-to-end/lib/foo.cpp000066400000000000000000000004471266061003000173350ustar00rootroot00000000000000#include "foo.h" namespace acme { void t2(int i); void t1() { for (int i = 0; i < 100; ++i) { if (98 == i) { t2(i); break; } } } void t2(int i) { if (9 == i) { int k = i + 9; --k; return; } } } Bear-2.1.5/test/end-to-end/lib/foo.h000066400000000000000000000001051266061003000167710ustar00rootroot00000000000000#ifndef foo_h #define foo_h namespace acme { void t1(); } #endif Bear-2.1.5/test/end-to-end/lib/lib.pro000066400000000000000000000001311266061003000173240ustar00rootroot00000000000000TEMPLATE = lib TARGET = some_lib HEADERS += foo.h SOURCES += foo.cpp SOURCES += bar.cc Bear-2.1.5/test/end-to-end/qmake.pro000066400000000000000000000001001266061003000171020ustar00rootroot00000000000000TEMPLATE = subdirs CONFIG -= qt SUBDIRS += lib SUBDIRS += bin Bear-2.1.5/test/end-to-end/validate_and_count.py000077500000000000000000000001571266061003000214760ustar00rootroot00000000000000#!/usr/bin/env python import json import sys if __name__ == '__main__': print(len(json.load(sys.stdin))) Bear-2.1.5/test/exec_anatomy/000077500000000000000000000000001266061003000160155ustar00rootroot00000000000000Bear-2.1.5/test/exec_anatomy/CMakeLists.txt000066400000000000000000000005271266061003000205610ustar00rootroot00000000000000add_executable(exec_anatomy EXCLUDE_FROM_ALL main.c) include_directories(${CMAKE_CURRENT_BINARY_DIR}/../../libear) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/run.sh.in ${CMAKE_CURRENT_BINARY_DIR}/run.sh @ONLY) add_test(NAME run_exec_anatomy COMMAND ./run.sh) add_dependencies(check exec_anatomy) add_dependencies(exec_anatomy ear) Bear-2.1.5/test/exec_anatomy/json_diff.py000077500000000000000000000012641266061003000203360ustar00rootroot00000000000000#!/usr/bin/env python import sys import json def main(): try: lhs = {pretty(entry) for entry in load(sys.argv[1])} rhs = {pretty(entry) for entry in load(sys.argv[2])} if len(lhs - rhs): for e in lhs - rhs: print('> {0}'.format(e)) for e in rhs - lhs: print('< {0}'.format(e)) return 40 return 0 except Exception as ex: print(ex) return 50 def load(filename): with open(filename, 'r') as handler: return json.load(handler) def pretty(entry): return str(sorted(entry.items(), key=lambda x: x[0])) if __name__ == '__main__': sys.exit(main()) Bear-2.1.5/test/exec_anatomy/main.c000066400000000000000000000150471266061003000171140ustar00rootroot00000000000000/* -*- coding: utf-8 -*- // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. */ #include "config.h" #include #include #include #include #include #if defined HAVE_POSIX_SPAWN || defined HAVE_POSIX_SPAWNP #include #endif // ..:: environment access fixer - begin ::.. #ifdef HAVE_NSGETENVIRON #include #else extern char **environ; #endif char **get_environ() { #ifdef HAVE_NSGETENVIRON return *_NSGetEnviron(); #else return environ; #endif } // ..:: environment access fixer - end ::.. // ..:: test fixtures - begin ::.. static char const *cwd = NULL; static FILE *fd = NULL; static int need_comma = 0; void expected_out_open(const char *expected) { cwd = getcwd(NULL, 0); fd = fopen(expected, "w"); if (!fd) { perror("fopen"); exit(EXIT_FAILURE); } fprintf(fd, "[\n"); need_comma = 0; } void expected_out_close() { fprintf(fd, "]\n"); fclose(fd); fd = NULL; free((void *)cwd); cwd = NULL; } void expected_out(const char *file) { if (need_comma) fprintf(fd, ",\n"); else need_comma = 1; fprintf(fd, "{\n"); fprintf(fd, " \"directory\": \"%s\",\n", cwd); fprintf(fd, " \"command\": \"cc -c %s/%s\",\n", cwd, file); fprintf(fd, " \"file\": \"%s/%s\"\n", cwd, file); fprintf(fd, "}\n"); } void create_source(char *file) { FILE *fd = fopen(file, "w"); if (!fd) { perror("fopen"); exit(EXIT_FAILURE); } fprintf(fd, "typedef int score;\n"); fclose(fd); } typedef void (*exec_fun)(); void wait_for(pid_t child) { int status; if (-1 == waitpid(child, &status, 0)) { perror("wait"); exit(EXIT_FAILURE); } if (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE) { fprintf(stderr, "children process has non zero exit code\n"); exit(EXIT_FAILURE); } } #define FORK(FUNC) \ { \ pid_t child = fork(); \ if (-1 == child) { \ perror("fork"); \ exit(EXIT_FAILURE); \ } else if (0 == child) { \ FUNC fprintf(stderr, "children process failed to exec\n"); \ exit(EXIT_FAILURE); \ } else { \ wait_for(child); \ } \ } // ..:: test fixtures - end ::.. #ifdef HAVE_EXECV void call_execv() { char *const file = "execv.c"; char *const compiler = "/usr/bin/cc"; char *const argv[] = {"cc", "-c", file, 0}; expected_out(file); create_source(file); FORK(execv(compiler, argv);) } #endif #ifdef HAVE_EXECVE void call_execve() { char *const file = "execve.c"; char *const compiler = "/usr/bin/cc"; char *const argv[] = {compiler, "-c", file, 0}; char *const envp[] = {"THIS=THAT", 0}; expected_out(file); create_source(file); FORK(execve(compiler, argv, envp);) } #endif #ifdef HAVE_EXECVP void call_execvp() { char *const file = "execvp.c"; char *const compiler = "cc"; char *const argv[] = {compiler, "-c", file, 0}; expected_out(file); create_source(file); FORK(execvp(compiler, argv);) } #endif #ifdef HAVE_EXECVP2 void call_execvP() { char *const file = "execv_p.c"; char *const compiler = "cc"; char *const argv[] = {compiler, "-c", file, 0}; expected_out(file); create_source(file); FORK(execvP(compiler, _PATH_DEFPATH, argv);) } #endif #ifdef HAVE_EXECVPE void call_execvpe() { char *const file = "execvpe.c"; char *const compiler = "cc"; char *const argv[] = {"/usr/bin/cc", "-c", file, 0}; char *const envp[] = {"THIS=THAT", 0}; expected_out(file); create_source(file); FORK(execvpe(compiler, argv, envp);) } #endif #ifdef HAVE_EXECL void call_execl() { char *const file = "execl.c"; char *const compiler = "/usr/bin/cc"; expected_out(file); create_source(file); FORK(execl(compiler, "cc", "-c", file, (char *)0);) } #endif #ifdef HAVE_EXECLP void call_execlp() { char *const file = "execlp.c"; char *const compiler = "cc"; expected_out(file); create_source(file); FORK(execlp(compiler, compiler, "-c", file, (char *)0);) } #endif #ifdef HAVE_EXECLE void call_execle() { char *const file = "execle.c"; char *const compiler = "/usr/bin/cc"; char *const envp[] = {"THIS=THAT", 0}; expected_out(file); create_source(file); FORK(execle(compiler, compiler, "-c", file, (char *)0, envp);) } #endif #ifdef HAVE_POSIX_SPAWN void call_posix_spawn() { char *const file = "posix_spawn.c"; char *const compiler = "cc"; char *const argv[] = {compiler, "-c", file, 0}; expected_out(file); create_source(file); pid_t child; if (0 != posix_spawn(&child, "/usr/bin/cc", 0, 0, argv, get_environ())) { perror("posix_spawn"); exit(EXIT_FAILURE); } wait_for(child); } #endif #ifdef HAVE_POSIX_SPAWNP void call_posix_spawnp() { char *const file = "posix_spawnp.c"; char *const compiler = "cc"; char *const argv[] = {compiler, "-c", file, 0}; expected_out(file); create_source(file); pid_t child; if (0 != posix_spawnp(&child, "cc", 0, 0, argv, get_environ())) { perror("posix_spawnp"); exit(EXIT_FAILURE); } wait_for(child); } #endif int main(int argc, char *const argv[]) { if (argc != 2) exit(EXIT_FAILURE); expected_out_open(argv[1]); #ifdef HAVE_EXECV call_execv(); #endif #ifdef HAVE_EXECVE call_execve(); #endif #ifdef HAVE_EXECVP call_execvp(); #endif #ifdef HAVE_EXECVP2 call_execvP(); #endif #ifdef HAVE_EXECVPE call_execvpe(); #endif #ifdef HAVE_EXECL call_execl(); #endif #ifdef HAVE_EXECLP call_execlp(); #endif #ifdef HAVE_EXECLE call_execle(); #endif #ifdef HAVE_POSIX_SPAWN call_posix_spawn(); #endif #ifdef HAVE_POSIX_SPAWNP call_posix_spawnp(); #endif expected_out_close(); return 0; } Bear-2.1.5/test/exec_anatomy/run.sh.in000077500000000000000000000006421266061003000175670ustar00rootroot00000000000000#!/bin/sh set -o nounset set -o errexit BEAR_EXE="@CMAKE_CURRENT_BINARY_DIR@/../../bear/bear" BEAR_LIB="@CMAKE_CURRENT_BINARY_DIR@/../../libear/@EAR_LIB_FILE@" touch execve.c execv.c execvpe.c execvp.c execl.c execlp.c execle.c execv_p.c posix_spawn.c posix_spawnp.c python ${BEAR_EXE} -l ${BEAR_LIB} ./exec_anatomy expected.json python "@CMAKE_CURRENT_SOURCE_DIR@/json_diff.py" expected.json compile_commands.json Bear-2.1.5/test/result_code/000077500000000000000000000000001266061003000156515ustar00rootroot00000000000000Bear-2.1.5/test/result_code/CMakeLists.txt000066400000000000000000000002331266061003000204070ustar00rootroot00000000000000configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/run.sh.in ${CMAKE_CURRENT_BINARY_DIR}/run.sh @ONLY) add_test(NAME result_code_check COMMAND ./run.sh) Bear-2.1.5/test/result_code/run.sh.in000077500000000000000000000005351266061003000174240ustar00rootroot00000000000000#!/bin/sh set -o nounset set -o errexit BEAR_EXE="@CMAKE_CURRENT_BINARY_DIR@/../../bear/bear" BEAR_LIB="@CMAKE_CURRENT_BINARY_DIR@/../../libear/@EAR_LIB_FILE@" set +o errexit python ${BEAR_EXE} -l ${BEAR_LIB} false rc=$? set -o errexit if [ 0 = $rc ]; then echo "exit code was not captured" && false fi python ${BEAR_EXE} -l ${BEAR_LIB} true Bear-2.1.5/test/unit_test/000077500000000000000000000000001266061003000153575ustar00rootroot00000000000000Bear-2.1.5/test/unit_test/CMakeLists.txt000066400000000000000000000010051266061003000201130ustar00rootroot00000000000000link_directories(${LIBCONFIG_LIBRARY_DIRS}) add_executable(unit_test EXCLUDE_FROM_ALL main.c ../../src/stringarray.c ../../src/protocol.c ../../src/stringtransform.c ../../src/environ.c ) add_definitions(-D_GNU_SOURCE) add_definitions(-DCLIENT -DSERVER) include_directories(../../src ${CMAKE_CURRENT_BINARY_DIR}/../../src) include_directories(${LIBCONFIG_INCLUDE_DIRS}) target_link_libraries(unit_test ${LIBCONFIG_LIBRARIES}) add_test(unit_test ./unit_test) add_dependencies(check unit_test) Bear-2.1.5/test/unit_test/main.c000066400000000000000000000153161266061003000164550ustar00rootroot00000000000000/* Copyright (C) 2012-2014 by László Nagy This file is part of Bear. Bear is a tool to generate compilation database for clang tooling. Bear 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. Bear 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 . */ #undef NDEBUG #include #include #include #include #include #include #include #include #include #include #include #include void assert_stringarray_equals(char const ** const lhs, char const ** const rhs) { assert(bear_strings_length(lhs) == bear_strings_length(rhs)); size_t const length = bear_strings_length(lhs); for (size_t i = 0; i < length; ++i) { assert(0 == strcmp(lhs[i], rhs[i])); } } void test_strings_length() { char const * input[] = { "this", "is", "my", "message", 0 }; assert(4 == bear_strings_length(input)); assert(2 == bear_strings_length(input + 2)); assert(0 == bear_strings_length(0)); } void test_strings_fold() { char const * input[] = { "this", "is", "my", "message", 0 }; char const * const expected = "this\x1fis\x1fmy\x1fmessage"; char const * const result = bear_strings_fold(input, '\x1f'); assert((0 == strcmp(expected, result)) && "bear_strings_fold failed"); free((void *)result); } void test_strings_append() { char const ** result = 0; char const * const this = "this"; char const * const that = "that"; result = bear_strings_append(result, this); assert(1 == bear_strings_length(result)); assert(this == result[0]); assert(0 == result[1]); result = bear_strings_append(result, that); assert(2 == bear_strings_length(result)); assert(this == result[0]); assert(that == result[1]); assert(0 == result[2]); free((void *)result); } void test_strings_find() { char const * input[] = { "this", "is", "my", "message", 0 }; assert(input[0] == bear_strings_find(input, "this")); assert(input[2] == bear_strings_find(input, "my")); assert(0 == bear_strings_find(input, "th")); assert(0 == bear_strings_find(input, "messa")); } void test_strings_copy() { char const * input[] = { "this", "is", "my", "message", 0 }; char const ** result = bear_strings_copy(input); assert_stringarray_equals(input, result); assert(input != result); bear_strings_release(result); } char const ** bear_strings_build_stdarg_driver(char const * arg, ...) { va_list args; va_start(args, arg); char const ** result = bear_strings_build(arg, &args); va_end(args); return result; } void test_strings_build() { char const ** result = bear_strings_build_stdarg_driver("this", "is", "my", "message", 0); char const * expected[] = { "this", "is", "my", "message", 0 }; assert_stringarray_equals(expected, result); bear_strings_release(result); } void test_env_insert() { char const * input[] = { "HOME=/home/user", "BEAR_OUTPUT=/tmp/socket", "LD_PRELOAD_NOW=what_is_this", 0 }; char const ** result = bear_strings_copy(input); setenv("BEAR_OUTPUT", "/tmp/other_socket", 1); setenv("LD_PRELOAD", "/tmp/other_lib", 1); setenv("HOME", "/home/user", 1); result = bear_update_environ(result, "HOME"); result = bear_update_environ(result, "BEAR_OUTPUT"); result = bear_update_environ(result, "LD_PRELOAD"); char const * expected[] = { "HOME=/home/user", "BEAR_OUTPUT=/tmp/other_socket", "LD_PRELOAD_NOW=what_is_this", "LD_PRELOAD=/tmp/other_lib", 0 }; assert_stringarray_equals(expected, result); bear_strings_release(result); } void test_json_escape() { char const * input[] = { "no escaping for this one", "symbolic: BS \b FF \f LF \n CR \r HT \t slash \\ quote \"", "numeric: BEL \a VT \v ESC \x1b", "mix: \a \b c", 0 }; char const ** result = bear_strings_copy(input); bear_strings_transform(result, bear_string_json_escape); char const * expected[] = { "no escaping for this one", "symbolic: BS \\b FF \\f LF \\n CR \\r HT \\t slash \\\\ quote \\\"", "numeric: BEL \\u0007 VT \\u000b ESC \\u001b", "mix: \\u0007 \\b c", 0 }; assert_stringarray_equals(expected, result); bear_strings_release(result); } void test_shell_escape() { char const * input[] = { "$no_escaping(\r)", "escaped:\"\\", "quoted: \t\n", "quoted\\and escaped", "", 0 }; char const ** result = bear_strings_copy(input); bear_strings_transform(result, bear_string_shell_escape); char const * expected[] = { "$no_escaping(\r)", "escaped:\\\"\\\\", "\"quoted: \t\n\"", "\"quoted\\\\and escaped\"", "\"\"", 0 }; assert_stringarray_equals(expected, result); bear_strings_release(result); } void assert_messages_equals(bear_message_t const * lhs, bear_message_t const * rhs) { assert(lhs->pid == rhs->pid); assert(lhs->ppid == rhs->ppid); assert(0 == strcmp(lhs->fun, rhs->fun)); assert(0 == strcmp(lhs->cwd, rhs->cwd)); assert_stringarray_equals(lhs->cmd, rhs->cmd); } void test_protocol() { char const * cmds[] = { "this", "that", 0 }; bear_message_t input = { 9, 1, "exec", "/tmp", cmds }; bear_message_t result; { int fds[2]; pipe(fds); bear_write_message(fds[1], &input); bear_read_message(fds[0], &result); } assert_messages_equals(&input, &result); bear_free_message(&result); } int main() { test_strings_length(); test_strings_fold(); test_strings_append(); test_strings_find(); test_strings_copy(); test_strings_build(); test_env_insert(); test_json_escape(); test_shell_escape(); test_protocol(); return 0; }