pax_global_header00006660000000000000000000000064122635120610014510gustar00rootroot0000000000000052 comment=7b33694992edaf79ba399f2e6fb254b19d1b77e4 Bear-1.4/000077500000000000000000000000001226351206100122255ustar00rootroot00000000000000Bear-1.4/.travis.yml000066400000000000000000000006441226351206100143420ustar00rootroot00000000000000language: c compiler: - gcc - clang before_install: - sudo add-apt-repository -y ppa:xav0989/libconfig - sudo apt-get update -qq install: - sudo apt-get install --allow-unauthenticated -qq python libconfig-dev script: - cmake . -DCPACK_GENERATOR="TGZ;DEB" - make all - make check - mkdir target_dir - DESTDIR=target_dir make install - make package after_success: - sudo dpkg -i ./bear-*.deb Bear-1.4/CMakeLists.txt000066400000000000000000000030011226351206100147570ustar00rootroot00000000000000cmake_minimum_required(VERSION 2.8) project(bear C) set(BEAR_VERSION "1.4") 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.") include(CPack) find_package(PkgConfig) pkg_check_modules(LIBCONFIG REQUIRED libconfig>=1.4) set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}) find_package(C99 REQUIRED) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${C99_C_FLAGS}") if (NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Release") endif() include(GNUInstallDirs) install(FILES COPYING README.md ChangeLog.md DESTINATION ${CMAKE_INSTALL_DOCDIR}) set(EAR_LIB_FILE ${CMAKE_SHARED_LIBRARY_PREFIX}ear${CMAKE_SHARED_LIBRARY_SUFFIX}) set(DEFAULT_PRELOAD_FILE ${CMAKE_INSTALL_FULL_LIBDIR}/${EAR_LIB_FILE}) set(DEFAULT_OUTPUT_FILE compile_commands.json) set(DEFAULT_CONFIG_FILE ${CMAKE_INSTALL_FULL_SYSCONFDIR}/bear.conf) add_subdirectory(src) add_subdirectory(test) add_subdirectory(doc) Bear-1.4/COPYING000066400000000000000000001045131226351206100132640ustar00rootroot00000000000000 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-1.4/ChangeLog.md000066400000000000000000000054631226351206100144060ustar00rootroot00000000000000## 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-1.4/FindC99.cmake000066400000000000000000000113561226351206100144020ustar00rootroot00000000000000# - Finds C99 standard support # This internally calls the check_c_source_compiles macro to determine the # appropriate flags for a C99 standard compilation. #============================================================================= # Copyright 2013 Ian Liu Rodrigues # # 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 . #============================================================================= include(CheckCSourceCompiles) set(C99_C_TEST_SOURCE "#include #include #include #include #include // Check varargs macros. These examples are taken from C99 6.10.3.5. #define debug(...) fprintf (stderr, __VA_ARGS__) #define showlist(...) puts (#__VA_ARGS__) #define report(test,...) ((test) ? puts (#test) : printf (__VA_ARGS__)) static void test_varargs_macros (void) { int x = 1234; int y = 5678; debug (\"Flag\"); debug (\"X = %d\\\\n\", x); showlist (The first, second, and third items.); report (x>y, \"x is %d but y is %d\", x, y); } // Check long long types. #define BIG64 18446744073709551615ull #define BIG32 4294967295ul #define BIG_OK (BIG64 / BIG32 == 4294967297ull && BIG64 % BIG32 == 0) #if !BIG_OK your preprocessor is broken; #endif #if BIG_OK #else your preprocessor is broken; #endif static long long int bignum = -9223372036854775807LL; static unsigned long long int ubignum = BIG64; struct incomplete_array { int datasize; double data[]; }; struct named_init { int number; const wchar_t *name; double average; }; typedef const char *ccp; static inline int test_restrict (ccp restrict text) { // See if C++-style comments work. // Iterate through items via the restricted pointer. // Also check for declarations in for loops. for (unsigned int i = 0; *(text+i) != '\\\\0'; ++i) continue; return 0; } // Check varargs and va_copy. static void test_varargs (const char *format, ...) { va_list args; va_start (args, format); va_list args_copy; va_copy (args_copy, args); const char *str = NULL; int number = 0; float fnumber = 0.0; while (*format) { switch (*format++) { case 's': // string str = va_arg (args_copy, const char *); break; case 'd': // int number = va_arg (args_copy, int); break; case 'f': // float fnumber = va_arg (args_copy, double); break; default: break; } } va_end (args_copy); va_end (args); number = (number != 0) && (str != NULL) && (fnumber != 0.0); } int main () { // Check bool. _Bool success = false; // Check restrict. if (test_restrict (\"String literal\") == 0) success = true; char *restrict newvar = \"Another string\"; // Check varargs. test_varargs (\"s, d' f .\", \"string\", 65, 34.234); test_varargs_macros (); // Check flexible array members. struct incomplete_array *ia = malloc (sizeof (struct incomplete_array) + (sizeof (double) * 10)); ia->datasize = 10; for (int i = 0; i < ia->datasize; ++i) ia->data[i] = i * 1.234; // Check named initializers. struct named_init ni = { .number = 34, .name = L\"Test wide string\", .average = 543.34343, }; ni.number = 58; int dynamic_array[ni.number]; dynamic_array[ni.number - 1] = 543; // work around unused variable warnings return (!success || bignum == 0LL || ubignum == 0uLL || newvar[0] == 'x' || dynamic_array[ni.number - 1] != 543); ; return 0; }") set(C99_C_FLAG_CANDIDATES " " "-std=c99" "-std=gnu99" "-c99" "-AC99" "-xc99=all" "-qlanglvl=extc99" ) if(DEFINED C99_C_FLAGS) set(C99_C_FLAG_CANDIDATES) endif(DEFINED C99_C_FLAGS) set(SAFE_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") foreach(FLAG ${C99_C_FLAG_CANDIDATES}) set(CMAKE_REQUIRED_FLAGS "${FLAG}") unset(C99_FLAG_DETECTED CACHE) message(STATUS "Try C99 C flag = [${FLAG}]") check_c_source_compiles("${C99_C_TEST_SOURCE}" C99_FLAG_DETECTED) if(C99_FLAG_DETECTED) set(C99_C_FLAGS_INTERNAL "${FLAG}") break() endif(C99_FLAG_DETECTED) endforeach(FLAG ${C99_C_FLAG_CANDIDATES}) set(CMAKE_REQUIRED_FLAGS "${SAFE_CMAKE_REQUIRED_FLAGS}") set(C99_C_FLAGS "${C99_C_FLAGS_INTERNAL}" CACHE STRING "C compiler flags for C99 standard") mark_as_advanced(C99_C_FLAGS)Bear-1.4/README.md000066400000000000000000000055121226351206100135070ustar00rootroot00000000000000Build EAR ========= Bear is a tool to generate compilation database for clang tooling. The [JSON compilation database][JSONCDB] 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. One way to get compilation database is to use `cmake` as build tool. Passing `-DCMAKE_EXPORT_COMPILE_COMMANDS=ON` to cmake generates `compile_commands.json` file into the current directory. When the project compiles with no cmake, but another build system, there is no free json file. Bear is a tool to generate such file during the build process. The concept behind Bear is to exec the original build command and intercept the `exec` calls of the build tool. To achive that Bear uses the `LD_PRELOAD` or `DYLD_INSERT_LIBRARIES` mechanisms provided by the dynamic linker. So it has two components: the library and the binary. The library defines the `exec` methods and used in every child processes. The executable sets the environment up to 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 OSs, it has been tested on FreeBSD, Linux and OS X only. ### Prerequisites 1. ANSI **C compiler** to compile the sources. 2. **cmake** to configure the build process. 3. **pkg-config** to find dependencies during configure step. 4. **make** to run the build. Makefiles are generated by `cmake`. 5. **libconfig** to parse the config file. (Version shall be greater than 1.4) ### Build commands It could be the best to build it 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 `--` separate the parameters from the build command. 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 ------------ Compiler wrappers like [ccache][CCACHE] and [distcc][DISTCC] could cause duplicates or missing items in the compilation database. Make sure you have been disabled before you run Bear. [CCACHE]: http://ccache.samba.org/ [DISTCC]: http://code.google.com/p/distcc/ 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-1.4/doc/000077500000000000000000000000001226351206100127725ustar00rootroot00000000000000Bear-1.4/doc/CMakeLists.txt000066400000000000000000000003211226351206100155260ustar00rootroot00000000000000configure_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-1.4/doc/bear.1.in000066400000000000000000000115131226351206100143730ustar00rootroot00000000000000.TH BEAR 1 "January 9, 2014" "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 achive 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 \-c \f[I]config\f[] Specify config file. Default value provided. .RS .RE .TP .B \-o \f[I]output\f[] Specify output file. Default value provided. (This option mainly for development purposes.) .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 \-s \f[I]socket\f[] Specify UNIX socket file. 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 .TP .B \-x Verbose filter dump at the end. This option dump a short statistic about the filtering. Might give some insight when the output is not what it expected or when config file were changed. .RS .RE .TP .B \-v Print out Bear version and exit. .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 achive 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? .PP Filtering has three steps. It checks the executable name agains the known compiler names. It checks any of the arguments to match as source file. (Usually done by extension match.) And checks that there is no parameter which might considered as non compilation. (Like dependency file generation, which migth cause duplicates in the output.) .PP Filters are specified in the config file. The syntax of the file defined by libconfig (http://www.hyperrealm.com/libconfig/). The filter values are extended POSIX regular expressions (http://en.wikipedia.org/wiki/Regular_expression). .PP Since the post process might be buggy, there is a way to see all exec calls. This gives opportunity to write custom post processing. The format of the non filtered output looks like this: .IP .nf \f[C] [ \ \ {\ "pid":\ "1234", \ \ \ \ "ppid":\ "100", \ \ \ \ "function":\ "execve", \ \ \ \ "directory":\ "/home/user/llvm/build", \ \ \ \ "command":\ "clang++\ \-Irelative\ \-c\ \-o\ file.o\ file.cc"\ }, \ \ ... ] \f[] .fi .PP Both output is JSON format, which means that \f[I]command\f[] field is escaped if one of the argument had space, slash or quote character. All the other fields are as it was captured. .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 socket file 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_CONFIG_FILE@ bear configuration file for post processing. .RS .RE .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 Compiler wrappers like ccache (http://ccache.samba.org/) and distcc (http://code.google.com/p/distcc/) could cause duplicates or missing items in the compilation database. Make sure you have been disabled before you run Bear. .SH COPYRIGHT .PP Copyright (C) 2012-2014 by László Nagy .SH AUTHORS László Nagy. Bear-1.4/src/000077500000000000000000000000001226351206100130145ustar00rootroot00000000000000Bear-1.4/src/AppleExportedSymbolsList000066400000000000000000000001301226351206100177120ustar00rootroot00000000000000_vfork _execv _execve _execvp _execvP _execl _execlp _execle _posix_spawn _posix_spawnp Bear-1.4/src/CMakeLists.txt000066400000000000000000000035051226351206100155570ustar00rootroot00000000000000 include(CheckFunctionExists) check_function_exists(vfork HAVE_VFORK) 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) include(CheckSymbolExists) check_symbol_exists(_NSGetEnviron crt_externs.h NEED_NSGETENVIRON) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h) include_directories(${CMAKE_CURRENT_BINARY_DIR}) add_definitions(-D_GNU_SOURCE) add_library(ear SHARED stringarray.c protocol.c environ.c execs.c) target_link_libraries(ear ${CMAKE_DL_LIBS}) set_target_properties(ear PROPERTIES COMPILE_DEFINITIONS "CLIENT") if(APPLE) # Macs have an entirely different linker. set_target_properties(ear PROPERTIES LINK_FLAGS "-Wl,-exported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/AppleExportedSymbolsList") else() set_target_properties(ear PROPERTIES LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/ExportedSymbolsList") endif() link_directories(${LIBCONFIG_LIBRARY_DIRS}) add_executable(bear stringarray.c protocol.c main.c output.c filter.c json.c) set_target_properties(bear PROPERTIES COMPILE_DEFINITIONS "SERVER") include_directories(${LIBCONFIG_INCLUDE_DIRS}) target_link_libraries(bear ${LIBCONFIG_LIBRARIES}) include(GNUInstallDirs) install(TARGETS bear ear RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) install(FILES bear.conf DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}) Bear-1.4/src/ExportedSymbolsList000066400000000000000000000003741226351206100167420ustar00rootroot00000000000000{ global: begin; end; vfork; execv; execve; execvp; execvP; execvpe; execl; execlp; execle; posix_spawn; posix_spawnp; local: *; }; Bear-1.4/src/bear.conf000066400000000000000000000024501226351206100145750ustar00rootroot00000000000000# 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-1.4/src/config.h.in000066400000000000000000000030501226351206100150350ustar00rootroot00000000000000/* 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 . */ #pragma once #cmakedefine BEAR_VERSION "@BEAR_VERSION@" #cmakedefine HAVE_VFORK #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 APPLE #cmakedefine NEED_NSGETENVIRON #cmakedefine DEFAULT_PRELOAD_FILE "@DEFAULT_PRELOAD_FILE@" #cmakedefine DEFAULT_OUTPUT_FILE "@DEFAULT_OUTPUT_FILE@" #cmakedefine DEFAULT_CONFIG_FILE "@DEFAULT_CONFIG_FILE@" #ifdef APPLE # define ENV_PRELOAD "DYLD_INSERT_LIBRARIES" # define ENV_FLAT "DYLD_FORCE_FLAT_NAMESPACE" # define EXEC_LOOP_ON_EXECVE #else # define ENV_PRELOAD "LD_PRELOAD" #endif #define ENV_OUTPUT "BEAR_OUTPUT" Bear-1.4/src/environ.c000066400000000000000000000043711226351206100146450ustar00rootroot00000000000000/* 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 . */ #include "config.h" #include "environ.h" #include "stringarray.h" #include #include #include #ifdef NEED_NSGETENVIRON #include #else // Some platforms don't provide environ in any header. extern char **environ; #endif char const * * bear_update_environ(char const * envs[], char const * key) { char const * const value = getenv(key); if (0 == value) { perror("bear: getenv"); exit(EXIT_FAILURE); } // 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; } // check the value might already correct char const * * result = envs; if ((0 != it) && ((0 == *it) || (strcmp(*it + key_length + 1, value)))) { char * env = 0; if (-1 == asprintf(&env, "%s=%s", key, value)) { perror("bear: asprintf"); exit(EXIT_FAILURE); } if (*it) { free((void *)*it); *it = env; } else result = bear_strings_append(envs, env); } return result; } char * * bear_get_environ(void) { #ifdef NEED_NSGETENVIRON // environ is not available for shared libraries have to use _NSGetEnviron() return *_NSGetEnviron(); #else return environ; #endif } Bear-1.4/src/environ.h000066400000000000000000000016161226351206100146510ustar00rootroot00000000000000/* 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 . */ #pragma once char const * * bear_update_environ(char const * * in, char const * key); char * * bear_get_environ(void); Bear-1.4/src/execs.c000066400000000000000000000251641226351206100142770ustar00rootroot00000000000000/* 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 . */ #include "config.h" #include "stringarray.h" #include "environ.h" #include "protocol.h" #include #include #include #include #include #include #include #if defined HAVE_POSIX_SPAWN || defined HAVE_POSIX_SPAWNP #include #endif static char const * * update_environment(char * const envp[]); static void report_call(char const * fun, char const * const argv[]); #ifdef EXEC_LOOP_ON_EXECVE static int already_reported = 0; # define REPORT_CALL(ARGV_) \ int const report_state = already_reported; \ if (!already_reported) { \ report_call(__func__, (char const * const *)ARGV_); \ already_reported = 1; \ } # define REPORT_FAILED_CALL(RESULT_) \ if (!report_state) { \ already_reported = 0; \ } #else # define REPORT_CALL(ARGV_) report_call(__func__, (char const * const *)ARGV_); # define REPORT_FAILED_CALL(RESULT_) #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; #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 #if defined HAVE_VFORK && defined EXEC_LOOP_ON_EXECVE pid_t vfork(void) { return fork(); } #endif #ifdef HAVE_EXECVE int execve(const char * path, char * const argv[], char * const envp[]) { REPORT_CALL(argv); int const result = call_execve(path, argv, envp); REPORT_FAILED_CALL(result); return result; } #endif #ifdef HAVE_EXECV # ifndef HAVE_EXECVE # error can not implement execv without execve # endif int execv(const char * path, char * const argv[]) { REPORT_CALL(argv); int const result = call_execve(path, argv, bear_get_environ()); REPORT_FAILED_CALL(result); return result; } #endif #ifdef HAVE_EXECVPE int execvpe(const char * file, char * const argv[], char * const envp[]) { REPORT_CALL(argv); int const result = call_execvpe(file, argv, envp); REPORT_FAILED_CALL(result); return result; } #endif #ifdef HAVE_EXECVP int execvp(const char * file, char * const argv[]) { REPORT_CALL(argv); int const result = call_execvp(file, argv); REPORT_FAILED_CALL(result); return result; } #endif #ifdef HAVE_EXECVP2 int execvP(const char * file, const char * search_path, char * const argv[]) { REPORT_CALL(argv); int const result = call_execvP(file, search_path, argv); REPORT_FAILED_CALL(result); return result; } #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); REPORT_CALL(argv); int const result = call_execve(path, (char * const *)argv, bear_get_environ()); REPORT_FAILED_CALL(result); 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); REPORT_CALL(argv); int const result = call_execvp(file, (char * const *)argv); REPORT_FAILED_CALL(result); 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); REPORT_CALL(argv); int const result = call_execve(path, (char * const *)argv, (char * const *)envp); REPORT_FAILED_CALL(result); 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]) { REPORT_CALL(argv); int const result = call_posix_spawn(pid, path, file_actions, attrp, argv, envp); REPORT_FAILED_CALL(result); return result; } #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]) { REPORT_CALL(argv); int const result = call_posix_spawnp(pid, file, file_actions, attrp, argv, envp); REPORT_FAILED_CALL(result); return result; } #endif #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 = update_environment(envp); 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 = update_environment(envp); 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"); return (*fp)(file, argv); } #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"); return (*fp)(file, search_path, 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]) { 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"); return (*fp)(pid, path, file_actions, attrp, argv, envp); } #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"); return (*fp)(pid, file, file_actions, attrp, argv, envp); } #endif static char const * * update_environment(char * const envp[]) { char const ** result = bear_strings_copy((char const * *)envp); result = bear_update_environ(result, ENV_PRELOAD); result = bear_update_environ(result, ENV_OUTPUT); #ifdef ENV_FLAT result = bear_update_environ(result, ENV_FLAT); #endif return result; } typedef void (*send_message)(char const * socket, bear_message_t const *); static void report(send_message fp, char const * socket, char const * fun, char const * const argv[]) { bear_message_t const msg = { getpid(), getppid(), fun, getcwd(NULL, 0), (char const **)argv }; (*fp)(socket, &msg); free((void *)msg.cwd); } static void report_call(char const * fun, char const * const argv[]) { char * const socket = getenv(ENV_OUTPUT); if (0 == socket) { perror("bear: getenv"); exit(EXIT_FAILURE); } report(bear_send_message, socket, fun, argv); } Bear-1.4/src/filter.c000066400000000000000000000174631226351206100144600ustar00rootroot00000000000000/* 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 . */ #include "filter.h" #include "stringarray.h" #include #include #include #include #include #define ERRBUF_SIZE 256 typedef struct regex_list_t { size_t length; regex_t * regexs; size_t total_count; size_t match_count; } regex_list_t; static void compile(config_setting_t const * array, regex_list_t * prepared); static int match(regex_list_t * prepared, char const * input); static int is_empty(regex_list_t const * prepared); static void release(regex_list_t * prepared); static config_setting_t const * get_setting(config_setting_t const *, char const *); struct bear_output_filter_t { regex_list_t compilers; regex_list_t source_files; regex_list_t cancel_parameters; }; static char const * fix_path(char const * file, char const * cwd); bear_output_filter_t * bear_filter_read_from_file(char const * file) { config_t config; config_init(&config); if (config_read_file(&config, file) == CONFIG_FALSE) { fprintf(stderr, "bear: failed to configure: '%s' in file %s at line %d\n", config_error_text(&config), config_error_file(&config), config_error_line(&config)); exit(EXIT_FAILURE); } bear_output_filter_t * const result = bear_filter_create(&config); config_destroy(&config); return result; } bear_output_filter_t * bear_filter_create(config_t const * config) { bear_output_filter_t * filter = malloc(sizeof(bear_output_filter_t)); if (0 == filter) { perror("bear: malloc"); exit(EXIT_FAILURE); } config_setting_t * const group = config_lookup(config, "filter"); if (0 == group) { fprintf(stderr, "bear: found no filter group in config file.\n"); exit(EXIT_FAILURE); } compile(get_setting(group, "compilers"), &filter->compilers); compile(get_setting(group, "source_files"), &filter->source_files); compile(get_setting(group, "cancel_parameters"), &filter->cancel_parameters); if (is_empty(&filter->compilers) || is_empty(&filter->source_files)) { fprintf(stderr, "bear: empty compilers or source files in config file will produce empty output.\n"); exit(EXIT_FAILURE); } return filter; } void bear_filter_report(bear_output_filter_t * filter) { if (0 == filter) fprintf(stderr, "bear: filtering were not enabled.\n"); else { fprintf(stderr, "bear: filtering statistic:\n"); fprintf(stderr, " total number of child processes : %zu\n", filter->compilers.total_count); fprintf(stderr, " match as compiler : %zu\n", filter->compilers.match_count); fprintf(stderr, " match as source file : %zu\n", filter->source_files.match_count); fprintf(stderr, " match on cancel parameter : %zu\n", filter->cancel_parameters.match_count); } } void bear_filter_delete(bear_output_filter_t * filter) { if (0 == filter) return; release(&filter->compilers); release(&filter->source_files); release(&filter->cancel_parameters); free((void *)filter); } char const * bear_filter_source_file(bear_output_filter_t * filter, bear_message_t const * e) { char const * result = 0; // looking for compiler name if ((e->cmd) && (e->cmd[0]) && match(&filter->compilers, e->cmd[0])) { // looking for source file for (char const * const * it = e->cmd; *it; ++it) { if ((0 == result) && match(&filter->source_files, *it)) { result = fix_path(*it, e->cwd); } else if (match(&filter->cancel_parameters, *it)) { if (result) { free((void *)result); result = 0; } break; } } } return result; } static void compile(config_setting_t const * array, regex_list_t * prepared) { prepared->total_count = 0; prepared->match_count = 0; prepared->length = config_setting_length(array); if (0 == prepared->length) { prepared->regexs = 0; return; } prepared->regexs = malloc(prepared->length * sizeof(regex_t)); regex_t * ot = prepared->regexs; for (size_t idx = 0; idx < prepared->length; ++idx, ++ot) { char const * const it = config_setting_get_string_elem(array, idx); int const result = regcomp(ot, it, REG_EXTENDED); if (0 != result) { char errbuf[ERRBUF_SIZE]; regerror(result, ot, errbuf, ERRBUF_SIZE); fprintf(stderr, "bear: regcomp failed on '%s': %s\n", it, errbuf); exit(EXIT_FAILURE); } } } static int match(regex_list_t * prepared, char const * input) { ++prepared->total_count; for (size_t idx = 0; idx < prepared->length; ++idx) { regex_t * ot = prepared->regexs + idx; if (0 == regexec(ot, input, 0, 0, 0)) { ++prepared->match_count; return 1; } } return 0; } static int is_empty(regex_list_t const * prepared) { return (prepared->length == 0); } static void release(regex_list_t * prepared) { for (size_t idx = 0; idx < prepared->length; ++idx) { regex_t * ot = prepared->regexs + idx; regfree(ot); } free((void *)prepared->regexs); } static config_setting_t const * get_setting(config_setting_t const * config, char const * name) { config_setting_t const * const result = config_setting_get_member(config, name); if (0 == result) { fprintf(stderr, "bear: could not find values for '%s' in file %s.\n", name, config_setting_source_file(config)); exit(EXIT_FAILURE); } if (! config_setting_is_array(result)) { fprintf(stderr, "bear: value for '%s' shall be array of strings in file %s at line %d.\n", name, config_setting_source_file(result), config_setting_source_line(result)); exit(EXIT_FAILURE); } size_t const size = config_setting_length(result); for (size_t idx = 0; idx < size; ++idx) { config_setting_t * const elem = config_setting_get_elem(result, idx); if (CONFIG_TYPE_STRING != config_setting_type(elem)) { fprintf(stderr, "bear: value for '%s' shall be array of strings in file %s at line %d.\n", name, config_setting_source_file(elem), config_setting_source_line(elem)); exit(EXIT_FAILURE); } } return result; } static char const * fix_path(char const * file, char const * cwd) { char * result = 0; if ('/' == file[0]) { result = strdup(file); if (0 == result) { perror("bear: strdup"); exit(EXIT_FAILURE); } } else { if (-1 == asprintf(&result, "%s/%s", cwd, file)) { perror("bear: asprintf"); exit(EXIT_FAILURE); } } return result; } Bear-1.4/src/filter.h000066400000000000000000000023521226351206100144540ustar00rootroot00000000000000/* 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 . */ #pragma once #include "protocol.h" #include typedef struct bear_output_filter_t bear_output_filter_t; bear_output_filter_t * bear_filter_read_from_file(char const * file); bear_output_filter_t * bear_filter_create(config_t const * config); void bear_filter_delete(bear_output_filter_t * filter); void bear_filter_report(bear_output_filter_t * filter); char const * bear_filter_source_file(bear_output_filter_t * filter, bear_message_t const * e); Bear-1.4/src/json.c000066400000000000000000000051521226351206100141340ustar00rootroot00000000000000/* 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 . */ #include "json.h" #include "stringarray.h" #include #include #include #include char const * * bear_json_escape_strings(char const * * raw) { for (char const * * it = raw; (raw) && (*it); ++it) { char const * const new = bear_json_escape_string(*it); if (new) { char const * const tmp = *it; *it = new; free((void *)tmp); } } return raw; } static size_t count(char const * const begin, char const * const end, int(*fp)(int)); static int needs_escape(int); char const * bear_json_escape_string(char const * raw) { size_t const length = (raw) ? strlen(raw) : 0; size_t const spaces = count(raw, raw + length, isspace); size_t const json = count(raw, raw + length, needs_escape); if ((0 == spaces) && (0 == json)) { return 0; } char * const result = malloc(length + ((0 != spaces) * 4) + json + 1); if (0 == result) { perror("bear: malloc"); exit(EXIT_FAILURE); } char * it = result; if (spaces) { *it++ = '\\'; *it++ = '\"'; } for (; (raw) && (*raw); ++raw) { if (needs_escape(*raw)) { *it++ = '\\'; } *it++ = isspace(*raw) ? ' ' : *raw; } if (spaces) { *it++ = '\\'; *it++ = '\"'; } *it = '\0'; return result; } static size_t count(char const * const begin, char const * const end, int (*fp)(int)) { size_t result = 0; for (char const * it = begin; it != end; ++it) { if (fp(*it)) ++result; } return result; } static int needs_escape(int c) { switch (c) { case '\\': case '\"': return 1; } return 0; } Bear-1.4/src/json.h000066400000000000000000000016231226351206100141400ustar00rootroot00000000000000/* 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 . */ #pragma once char const * bear_json_escape_string(char const *); char const * * bear_json_escape_strings(char const * *); Bear-1.4/src/main.c000066400000000000000000000236731226351206100141170ustar00rootroot00000000000000/* 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 . */ #include "config.h" #include "protocol.h" #include "output.h" #include "filter.h" #include #include #include #include #include #include #include typedef struct bear_commands_t { char const * config_file; char const * output_file; char const * libear_file; char const * socket_dir; char const * socket_file; char * const * unprocessed_argv; int debug; int verbose; } bear_commands_t; // variables which are used in signal handler static volatile pid_t child_pid; static volatile int child_status = EXIT_FAILURE; // forward declare the used methods static void mask_all_signals(int command); static void install_signal_handler(int signum); static void collect_messages(char const * socket, char const * output, bear_output_filter_t * filter, int sync_fd); static void update_environment(char const * key, char const * value); static void prepare_socket_file(bear_commands_t *); static void teardown_socket_file(bear_commands_t *); static void release_commands(bear_commands_t *); static void notify_child(int fd); static void wait_for_parent(int fd); static void parse(int argc, char * const argv[], bear_commands_t * commands); static void print_version(); static void print_usage(char const * const name); int main(int argc, char * const argv[]) { bear_commands_t commands = { .config_file = DEFAULT_CONFIG_FILE, .output_file = DEFAULT_OUTPUT_FILE, .libear_file = DEFAULT_PRELOAD_FILE, .socket_dir = 0, .socket_file = 0, .unprocessed_argv = 0, .debug = 0, .verbose = 0 }; int sync_fd[2]; parse(argc, argv, &commands); bear_output_filter_t * const filter = commands.debug ? 0 : bear_filter_read_from_file(commands.config_file); prepare_socket_file(&commands); // set up sync pipe if (-1 == pipe(sync_fd)) { perror("bear: pipe"); exit(EXIT_FAILURE); } // fork child_pid = fork(); if (-1 == child_pid) { perror("bear: fork"); exit(EXIT_FAILURE); } else if (0 == child_pid) { // child process close(sync_fd[1]); wait_for_parent(sync_fd[0]); update_environment(ENV_PRELOAD, commands.libear_file); update_environment(ENV_OUTPUT, commands.socket_file); #ifdef ENV_FLAT update_environment(ENV_FLAT, "1"); #endif if (-1 == execvp(*commands.unprocessed_argv, commands.unprocessed_argv)) { perror("bear: execvp"); exit(EXIT_FAILURE); } } else { // parent process install_signal_handler(SIGCHLD); install_signal_handler(SIGINT); mask_all_signals(SIG_BLOCK); close(fileno(stdin)); close(fileno(stdout)); close(sync_fd[0]); collect_messages( commands.socket_file, commands.output_file, filter, sync_fd[1]); teardown_socket_file(&commands); } if (commands.verbose) bear_filter_report(filter); bear_filter_delete(filter); release_commands(&commands); return child_status; } static void collect_messages(char const * socket_file, char const * output_file, bear_output_filter_t * filter, int sync_fd) { bear_output_t * handle = bear_open_json_output(output_file, filter); int s = bear_create_unix_socket(socket_file); notify_child(sync_fd); // receive messages bear_message_t msg; mask_all_signals(SIG_UNBLOCK); while ((child_pid) && bear_accept_message(s, &msg)) { mask_all_signals(SIG_BLOCK); bear_append_json_output(handle, &msg); bear_free_message(&msg); mask_all_signals(SIG_UNBLOCK); } mask_all_signals(SIG_BLOCK); // release resources bear_close_json_output(handle); close(s); } static void update_environment(char const * key, char const * value) { if (-1 == setenv(key, value, 1)) { perror("bear: setenv"); exit(EXIT_FAILURE); } } static void prepare_socket_file(bear_commands_t * commands) { // create temporary directory for socket if (0 == commands->socket_file) { char template[] = "/tmp/bear-XXXXXX"; char const * temp_dir = mkdtemp(template); if (0 == temp_dir) { perror("bear: mkdtemp"); exit(EXIT_FAILURE); } if (-1 == asprintf((char **)&(commands->socket_file), "%s/socket", temp_dir)) { perror("bear: asprintf"); exit(EXIT_FAILURE); } commands->socket_dir = strdup(temp_dir); if (0 == commands->socket_dir) { perror("bear: strdup"); exit(EXIT_FAILURE); } } // remove old socket file if any if ((-1 == unlink(commands->socket_file)) && (ENOENT != errno)) { perror("bear: unlink"); exit(EXIT_FAILURE); } } static void teardown_socket_file(bear_commands_t * commands) { unlink(commands->socket_file); if (commands->socket_dir) { rmdir(commands->socket_dir); } } static void release_commands(bear_commands_t * commands) { if (commands->socket_dir) { free((void *)commands->socket_dir); free((void *)commands->socket_file); } } static void parse(int argc, char * const argv[], bear_commands_t * commands) { // parse command line arguments. int opt; while ((opt = getopt(argc, argv, "c:o:l:s:ncexvh?")) != -1) { switch (opt) { case 'c': commands->config_file = optarg; break; case 'o': commands->output_file = optarg; break; case 'l': commands->libear_file = optarg; break; case 's': commands->socket_file = optarg; break; case 'n': commands->debug = 1; break; case 'x': commands->verbose = 1; break; case 'v': print_version(); exit(EXIT_SUCCESS); case 'h': print_usage(argv[0]); exit(EXIT_SUCCESS); default: /* '?' */ print_usage(argv[0]); exit(EXIT_FAILURE); } } // validate if (argc == optind) { print_usage(argv[0]); exit(EXIT_FAILURE); } commands->unprocessed_argv = &(argv[optind]); } static void handler(int signum) { switch (signum) { case SIGCHLD: { int status; while (0 > waitpid(WAIT_ANY, &status, WNOHANG)) ; child_status = WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE; child_pid = 0; break; } case SIGINT: kill(child_pid, signum); default: break; } } static void install_signal_handler(int signum) { struct sigaction action; action.sa_handler = handler; action.sa_flags = SA_NOCLDSTOP; if (0 != sigemptyset(&action.sa_mask)) { perror("bear: sigemptyset"); exit(EXIT_FAILURE); } if (0 != sigaddset(&action.sa_mask, signum)) { perror("bear: sigaddset"); exit(EXIT_FAILURE); } if (0 != sigaction(signum, &action, NULL)) { perror("bear: sigaction"); exit(EXIT_FAILURE); } } static void mask_all_signals(int command) { sigset_t signal_mask; if (0 != sigfillset(&signal_mask)) { perror("bear: sigfillset"); exit(EXIT_FAILURE); } if (0 != sigprocmask(command, &signal_mask, 0)) { perror("bear: sigprocmask"); exit(EXIT_FAILURE); } } static void notify_child(int fd) { if (-1 == write(fd, "ready", 5)) { perror("bear: write"); exit(EXIT_FAILURE); } close(fd); } static void wait_for_parent(int fd) { char buffer[5]; if (-1 == read(fd, buffer, sizeof(buffer))) { perror("bear: read"); exit(EXIT_FAILURE); } close(fd); } static void print_version() { fprintf(stdout, "Bear %s\n" "Copyright (C) 2012-2014 by László Nagy\n" "This is free software; see the source for copying conditions. " "There is NO warranty; not even for MERCHANTABILITY or FITNESS " "FOR A PARTICULAR PURPOSE.\n", BEAR_VERSION); } static void print_usage(char const * const name) { fprintf(stdout, "Usage: %s [options] -- \n" "\n" "options:\n" " -c config config file (default: %s)\n" " -o output output file (default: %s)\n" " -l libear library location (default: %s)\n" " -s socket multiplexing socket (default: randomly generated)\n" " -n disable filter, unformated output. (default: filtering)\n" " -x verbose filter dump at the end (default: disabled)\n" " -v prints Bear version and exit\n" " -h this message\n" "\n" "exit status: EXIT_FAILURE on any internal problem, " "otherwise same as the build command exit status.\n", name, DEFAULT_CONFIG_FILE, DEFAULT_OUTPUT_FILE, DEFAULT_PRELOAD_FILE); } Bear-1.4/src/output.c000066400000000000000000000067351226351206100145330ustar00rootroot00000000000000/* 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 . */ #include "output.h" #include "stringarray.h" #include "json.h" #include #include #include #include #include typedef struct bear_output_stream_t { int fd; size_t count; } bear_output_stream_t; static void stream_open(bear_output_stream_t *, char const * file); static void stream_close(bear_output_stream_t *); static void stream_separator(bear_output_stream_t *); struct bear_output_t { bear_output_stream_t stream; bear_output_filter_t * filter; }; bear_output_t * bear_open_json_output(char const * file, bear_output_filter_t * filter) { bear_output_t * handle = malloc(sizeof(bear_output_t)); if (0 == handle) { perror("bear: malloc"); exit(EXIT_FAILURE); } handle->filter = filter; stream_open(& handle->stream, file); return handle; } void bear_close_json_output(bear_output_t * handle) { stream_close(& handle->stream); free((void *)handle); } void bear_append_json_output(bear_output_t * handle, bear_message_t const * e) { bear_output_stream_t * const stream = & handle->stream; char const * const cmd = bear_strings_fold(bear_json_escape_strings(e->cmd), ' '); if (handle->filter) { char const * const src = bear_filter_source_file(handle->filter, e); if (src) { stream_separator(stream); dprintf(stream->fd, "{\n" " \"directory\": \"%s\",\n" " \"command\": \"%s\",\n" " \"file\": \"%s\"\n" "}\n", e->cwd, cmd, src); } free((void *)src); } else { stream_separator(stream); dprintf(stream->fd, "{\n" " \"pid\": \"%d\",\n" " \"ppid\": \"%d\",\n" " \"function\": \"%s\",\n" " \"directory\": \"%s\",\n" " \"command\": \"%s\"\n" "}\n", e->pid, e->ppid, e->fun, e->cwd, cmd); } free((void *)cmd); } static void stream_open(bear_output_stream_t * handle, char const * file) { handle->count = 0; handle->fd = open(file, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR); if (-1 == handle->fd) { perror("bear: open"); exit(EXIT_FAILURE); } dprintf(handle->fd, "[\n"); } static void stream_close(bear_output_stream_t * handle) { dprintf(handle->fd, "]\n"); if (-1 == close(handle->fd)) { perror("bear: close"); exit(EXIT_FAILURE); } } static void stream_separator(bear_output_stream_t * handle) { if (handle->count++) { dprintf(handle->fd, ",\n"); } } Bear-1.4/src/output.h000066400000000000000000000021241226351206100145240ustar00rootroot00000000000000/* 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 . */ #pragma once #include "protocol.h" #include "filter.h" typedef struct bear_output_t bear_output_t; bear_output_t * bear_open_json_output(char const * file, bear_output_filter_t *); void bear_append_json_output(bear_output_t * handle, bear_message_t const * e); void bear_close_json_output(bear_output_t * handle); Bear-1.4/src/protocol.c000066400000000000000000000131221226351206100150200ustar00rootroot00000000000000/* 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 . */ #include "protocol.h" #include "stringarray.h" #include #include #include #include #include #include #include #include static int init_socket(char const * file, struct sockaddr_un * addr); #ifdef SERVER static ssize_t socket_read(int fd, uint8_t * buf, ssize_t nbyte) { ssize_t sum = 0; while (sum != nbyte) { ssize_t const cur = read(fd, buf + sum, nbyte - sum); if (-1 == cur) { return cur; } sum += cur; } return sum; } static pid_t read_pid(int fd) { pid_t result = 0; if (-1 == socket_read(fd, (uint8_t *)&result, sizeof(pid_t))) { perror("bear: read pid"); exit(EXIT_FAILURE); } return result; } static char const * read_string(int fd) { size_t length = 0; if (-1 == socket_read(fd, (uint8_t *)&length, sizeof(size_t))) { perror("bear: read string length"); exit(EXIT_FAILURE); } char * result = malloc((length + 1) * sizeof(char)); if (0 == result) { perror("bear: malloc"); exit(EXIT_FAILURE); } if (length > 0) { if (-1 == socket_read(fd, (uint8_t *)result, length)) { perror("bear: read string value"); exit(EXIT_FAILURE); } } result[length] = '\0'; return result; } static char const * * read_string_array(int fd) { size_t length = 0; if (-1 == socket_read(fd, (uint8_t *)&length, sizeof(size_t))) { perror("bear: read string array length"); exit(EXIT_FAILURE); } char const * * result = malloc((length + 1) * sizeof(char const *)); if (0 == result) { perror("bear: malloc"); exit(EXIT_FAILURE); } for (size_t it = 0; it < length; ++it) { result[it] = read_string(fd); } result[length] = 0; return result; } void bear_read_message(int fd, bear_message_t * e) { e->pid = read_pid(fd); e->ppid = read_pid(fd); e->fun = read_string(fd); e->cwd = read_string(fd); e->cmd = read_string_array(fd); } void bear_free_message(bear_message_t * e) { e->pid = 0; e->ppid = 0; free((void *)e->fun); e->fun = 0; free((void *)e->cwd); e->cwd = 0; bear_strings_release(e->cmd); e->cmd = 0; } int bear_create_unix_socket(char const * file) { struct sockaddr_un addr; int s = init_socket(file, &addr); if (-1 == bind(s, (struct sockaddr *)&addr, sizeof(struct sockaddr_un))) { perror("bear: bind"); exit(EXIT_FAILURE); } if (-1 == listen(s, 0)) { perror("bear: listen"); exit(EXIT_FAILURE); } return s; } int bear_accept_message(int s, bear_message_t * msg) { int connection = accept(s, 0, 0); if (-1 != connection) { bear_read_message(connection, msg); close(connection); return 1; } return 0; } #endif #ifdef CLIENT static ssize_t socket_write(int fd, uint8_t const * buf, ssize_t nbyte) { ssize_t sum = 0; while (sum != nbyte) { ssize_t const cur = write(fd, buf + sum, nbyte - sum); if (-1 == cur) { return cur; } sum += cur; } return sum; } static void write_pid(int fd, pid_t pid) { socket_write(fd, (uint8_t const *)&pid, sizeof(pid_t)); } static void write_string(int fd, char const * message) { size_t const length = (message) ? strlen(message) : 0; socket_write(fd, (uint8_t const *)&length, sizeof(size_t)); if (length > 0) { socket_write(fd, (uint8_t const *)message, length); } } static void write_string_array(int fd, char const * const * message) { size_t const length = bear_strings_length(message); socket_write(fd, (uint8_t const *)&length, sizeof(size_t)); for (size_t it = 0; it < length; ++it) { write_string(fd, message[it]); } } void bear_write_message(int fd, bear_message_t const * e) { write_pid(fd, e->pid); write_pid(fd, e->ppid); write_string(fd, e->fun); write_string(fd, e->cwd); write_string_array(fd, e->cmd); } void bear_send_message(char const * file, bear_message_t const * msg) { struct sockaddr_un addr; int s = init_socket(file, &addr); if (-1 == connect(s, (struct sockaddr *)&addr, sizeof(struct sockaddr_un))) { perror("bear: connect"); exit(EXIT_FAILURE); } bear_write_message(s, msg); close(s); } #endif static int init_socket(char const * file, struct sockaddr_un * addr) { int const s = socket(AF_UNIX, SOCK_STREAM, 0); if (-1 == s) { perror("bear: socket"); exit(EXIT_FAILURE); } memset((void *)addr, 0, sizeof(struct sockaddr_un)); addr->sun_family = AF_UNIX; strncpy(addr->sun_path, file, sizeof(addr->sun_path) - 1); return s; } Bear-1.4/src/protocol.h000066400000000000000000000025051226351206100150300ustar00rootroot00000000000000/* 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 . */ #pragma once #include typedef struct bear_message_t { pid_t pid; pid_t ppid; char const * fun; char const * cwd; char const * * cmd; } bear_message_t; #ifdef SERVER void bear_read_message(int fd, bear_message_t * e); void bear_free_message(bear_message_t * e); int bear_create_unix_socket(char const * socket); int bear_accept_message(int fd, bear_message_t * e); #endif #ifdef CLIENT void bear_write_message(int fd, bear_message_t const * e); void bear_send_message(char const * socket, bear_message_t const * e); #endif Bear-1.4/src/stringarray.c000066400000000000000000000100461226351206100155260ustar00rootroot00000000000000/* 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 . */ #include "stringarray.h" #include #include #include #include #ifdef CLIENT 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; } 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; } char const ** bear_strings_append(char const ** const in, char const * const e) { if (0 == e) return in; 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; } 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; } #endif void bear_strings_release(char const ** in) { for (char const * const * it = in; (it) && (*it); ++it) { free((void *)*it); } free((void *)in); } #ifdef SERVER char const * bear_strings_find(char const * const * in, char const * const e) { if (0 == e) return 0; for (char const * const * it = in; (it) && (*it); ++it) { if (0 == strcmp(e, *it)) return *it; } return 0; } char const * bear_strings_fold(char const * const * in, char const separator) { // calculate the needed size size_t size = 0; for (char const * const * it = in; (it) && (*it); ++it) size += strlen(*it) + 1; // allocate memory once char * result = (0 != size) ? malloc(size * sizeof(char)) : 0; if (0 == result) { perror("bear: malloc"); exit(EXIT_FAILURE); } // copy each row to the result char * result_ptr = result; for (char const * const * it = in; (it) && (*it); ++it) { size_t const it_size = strlen(*it); strncpy(result_ptr, *it, it_size); result_ptr += it_size; *result_ptr++ = separator; } // replace the last separator to terminating zero *--result_ptr = '\0'; return result; } #endif Bear-1.4/src/stringarray.h000066400000000000000000000024751226351206100155420ustar00rootroot00000000000000/* 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 . */ #pragma once #include #ifdef CLIENT #include char const ** bear_strings_build(char const * arg, va_list *ap); char const ** bear_strings_copy(char const ** const in); char const ** bear_strings_append(char const ** in, char const * e); size_t bear_strings_length(char const * const * in); #endif void bear_strings_release(char const **); #ifdef SERVER char const * bear_strings_find(char const * const * in, char const * e); char const * bear_strings_fold(char const * const * in, char const sep); #endif Bear-1.4/test/000077500000000000000000000000001226351206100132045ustar00rootroot00000000000000Bear-1.4/test/CMakeLists.txt000066400000000000000000000004041226351206100157420ustar00rootroot00000000000000enable_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(config_failures) Bear-1.4/test/config_failures/000077500000000000000000000000001226351206100163435ustar00rootroot00000000000000Bear-1.4/test/config_failures/CMakeLists.txt000066400000000000000000000007711226351206100211100ustar00rootroot00000000000000find_package(PythonInterp) set(BEAR_EXE ${CMAKE_CURRENT_BINARY_DIR}/../../src/bear) if(PYTHONINTERP_FOUND) add_custom_target(run_config_failure_test COMMAND python ${CMAKE_CURRENT_SOURCE_DIR}/run.py --sut ${BEAR_EXE} --test-cases ${CMAKE_CURRENT_SOURCE_DIR}/tests COMMENT "Running config failure tests") add_dependencies(run_config_failure_test ear) add_dependencies(run_config_failure_test bear) add_test(NAME run_config_failure_test COMMAND make run_config_failure_test) endif() Bear-1.4/test/config_failures/run.py000077500000000000000000000036751226351206100175370ustar00rootroot00000000000000#!/bin/env python from os import listdir from os.path import isdir, join import subprocess import logging import re def _test(bear, path): config = '{}/config'.format(path) cmd = [bear, '-c', config, '--', 'true'] logging.debug('executing {}'.format(cmd)) child = subprocess.Popen(cmd, stderr=subprocess.PIPE) child.wait() return child.stderr.read() def _read(path): file = '{}/output'.format(path) logging.debug('reading {}'.format(file)) with open(file, "r") as fd: return fd.read() def _evaulate(bear, path): result = _test(bear, path) regex = re.compile(_read(path).encode()) if (None == regex.match(result)): logging.error('failed test: {}'.format(path)) logging.info('stderr: {}'.format(result)) return False return True def main(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument("--sut", metavar='FILE', required=True, help="SUT executable") parser.add_argument("--test-cases", metavar='DIRECTORY', required=True, help="where the tests files are") parser.add_argument('--log-level', metavar='LEVEL', choices='DEBUG INFO WARN ERROR'.split(), default='INFO', help="Choose a level from DEBUG, INFO (default), \ WARN or ERROR") args = parser.parse_args() logging.basicConfig(format='%(levelname)s: %(message)s', level=args.log_level) bear = args.sut parent = args.test_cases subdirs = [ join(parent,d) for d in listdir(parent) if isdir(join(parent,d)) ] results = [ _evaulate(bear, t) for t in subdirs ] return all(results) if __name__ == '__main__': import sys if (main()): sys.exit(0) else: sys.exit(1) Bear-1.4/test/config_failures/tests/000077500000000000000000000000001226351206100175055ustar00rootroot00000000000000Bear-1.4/test/config_failures/tests/broken_regex/000077500000000000000000000000001226351206100221575ustar00rootroot00000000000000Bear-1.4/test/config_failures/tests/broken_regex/config000066400000000000000000000002661226351206100233530ustar00rootroot00000000000000filter: { compilers = [ "compiler?*(+" ]; source_files = [ ".*\\.[cC]([cC]|\\+\\+|xx|pp|p)?$" ]; cancel_parameters = [ "^-M" ]; }; Bear-1.4/test/config_failures/tests/broken_regex/output000066400000000000000000000000411226351206100234350ustar00rootroot00000000000000bear: regcomp failed on '.*': .* Bear-1.4/test/config_failures/tests/empty_array/000077500000000000000000000000001226351206100220415ustar00rootroot00000000000000Bear-1.4/test/config_failures/tests/empty_array/config000066400000000000000000000002321226351206100232260ustar00rootroot00000000000000filter: { compilers = []; source_files = [ ".*\\.[cC]([cC]|\\+\\+|xx|pp|p)?$" ]; cancel_parameters = [ "^-M" ]; }; Bear-1.4/test/config_failures/tests/empty_array/output000066400000000000000000000001211226351206100233160ustar00rootroot00000000000000bear: empty compilers or source files in config file will produce empty output\. Bear-1.4/test/config_failures/tests/missing_array/000077500000000000000000000000001226351206100223545ustar00rootroot00000000000000Bear-1.4/test/config_failures/tests/missing_array/config000066400000000000000000000002051226351206100235410ustar00rootroot00000000000000filter: { source_files = [ ".*\\.[cC]([cC]|\\+\\+|xx|pp|p)?$" ]; cancel_parameters = [ "^-M" ]; }; Bear-1.4/test/config_failures/tests/missing_array/output000066400000000000000000000000731226351206100236370ustar00rootroot00000000000000bear: could not find values for 'compilers' in file (.*)\. Bear-1.4/test/config_failures/tests/missing_file/000077500000000000000000000000001226351206100221555ustar00rootroot00000000000000Bear-1.4/test/config_failures/tests/missing_file/output000066400000000000000000000001031226351206100234320ustar00rootroot00000000000000bear: failed to configure: 'file I/O error' in file (.*) at line 0 Bear-1.4/test/config_failures/tests/missing_format_group/000077500000000000000000000000001226351206100237425ustar00rootroot00000000000000Bear-1.4/test/config_failures/tests/missing_format_group/config000066400000000000000000000000421226351206100251260ustar00rootroot00000000000000# comment correct_syntax = true; Bear-1.4/test/config_failures/tests/missing_format_group/output000066400000000000000000000000551226351206100252250ustar00rootroot00000000000000bear: found no filter group in config file\. Bear-1.4/test/config_failures/tests/non_string_array/000077500000000000000000000000001226351206100230635ustar00rootroot00000000000000Bear-1.4/test/config_failures/tests/non_string_array/config000066400000000000000000000002571226351206100242570ustar00rootroot00000000000000filter: { compilers = [ 1, 2, 3 ]; source_files = [ ".*\\.[cC]([cC]|\\+\\+|xx|pp|p)?$" ]; cancel_parameters = [ "^-M" ]; }; Bear-1.4/test/config_failures/tests/non_string_array/output000066400000000000000000000001171226351206100243450ustar00rootroot00000000000000bear: value for 'compilers' shall be array of strings in file (.*) at line 4\. Bear-1.4/test/config_failures/tests/syntax_problem/000077500000000000000000000000001226351206100225535ustar00rootroot00000000000000Bear-1.4/test/config_failures/tests/syntax_problem/config000066400000000000000000000000531226351206100237410ustar00rootroot00000000000000# comment filter: { compilers := [ } } Bear-1.4/test/config_failures/tests/syntax_problem/output000066400000000000000000000001101226351206100240260ustar00rootroot00000000000000bear: failed to configure: 'syntax error' in file (.*)/config at line 3 Bear-1.4/test/end-to-end/000077500000000000000000000000001226351206100151365ustar00rootroot00000000000000Bear-1.4/test/end-to-end/CMakeLists.txt000066400000000000000000000042471226351206100177050ustar00rootroot00000000000000message(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}/../../src/bear) set(BEAR_LIB ${CMAKE_CURRENT_BINARY_DIR}/../../src/${EAR_LIB_FILE}) set(BEAR_CFG ${CMAKE_CURRENT_SOURCE_DIR}/bear.conf) if(PYTHONINTERP_FOUND) add_custom_target(run_shell_test COMMAND ${BEAR_EXE} -c ${BEAR_CFG} -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_dependencies(run_shell_test bear) add_test(NAME run_shell_test COMMAND make run_shell_test) endif() if(PYTHONINTERP_FOUND AND SCONS_FOUND) add_custom_target(run_scons_test COMMAND ${BEAR_EXE} -c ${BEAR_CFG} -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_dependencies(run_scons_test bear) 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 ${BEAR_EXE} -c ${BEAR_CFG} -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_dependencies(run_qmake_test bear) add_test(NAME run_qmake_test COMMAND make run_qmake_test) endif() Bear-1.4/test/end-to-end/SConstruct000066400000000000000000000006641226351206100171760ustar00rootroot00000000000000env = Environment() 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-1.4/test/end-to-end/bear.conf000066400000000000000000000024471226351206100167250ustar00rootroot00000000000000# 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-1.4/test/end-to-end/bin/000077500000000000000000000000001226351206100157065ustar00rootroot00000000000000Bear-1.4/test/end-to-end/bin/bin.pro000066400000000000000000000002171226351206100172000ustar00rootroot00000000000000TEMPLATE = app TARGET = some_app INCLUDEPATH += ../lib LIBS += -L../lib -lsome_lib HEADERS += boo.h++ SOURCES += boo.c++ SOURCES += far.cxx Bear-1.4/test/end-to-end/bin/boo.c++000066400000000000000000000005351226351206100167620ustar00rootroot00000000000000#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-1.4/test/end-to-end/bin/boo.h++000066400000000000000000000000601226351206100167600ustar00rootroot00000000000000#ifndef boo_h #define boo_h void t1(); #endif Bear-1.4/test/end-to-end/bin/far.cxx000066400000000000000000000001151226351206100171770ustar00rootroot00000000000000#include #include "boo.h++" void b1() { t1(); acme::t1(); } Bear-1.4/test/end-to-end/compile.sh000077500000000000000000000011771226351206100171330ustar00rootroot00000000000000#!/bin/sh set -o nounset set -o errexit set -o xtrace g++ -c -fPIC -I"$1/lib" "$1/lib/foo.cpp" -o /dev/null g++ -c -fPIC -I"$1/lib" "$1/lib/bar.cc" -o /dev/null g++ -M -I"$1/lib" "$1/lib/foo.cpp" -o /dev/null g++ -MM -I"$1/lib" "$1/lib/foo.cpp" -o /dev/null g++ -MM -MG -I"$1/lib" "$1/lib/bar.cc" -o /dev/null g++ -I"$1/lib" "$1/lib/bar.cc" -M -o /dev/null # add noise to the compilation... true echo "gcc -invocation -look -like this.c" (g++ -c -I"$1/lib" -I"$1/bin" "$1/bin/boo.c++" -o /dev/null) (g++ -c -I"$1/lib" -I"$1/bin" "$1/bin/far.cxx" -o /dev/null) # add noise to the compilation... echo "g++ -c bin/boo.cpp -o /dev/null" Bear-1.4/test/end-to-end/lib/000077500000000000000000000000001226351206100157045ustar00rootroot00000000000000Bear-1.4/test/end-to-end/lib/bar.cc000066400000000000000000000000771226351206100167630ustar00rootroot00000000000000#include "foo.h" namespace acme { void b1() { t1(); } } Bear-1.4/test/end-to-end/lib/foo.cpp000066400000000000000000000004471226351206100172000ustar00rootroot00000000000000#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-1.4/test/end-to-end/lib/foo.h000066400000000000000000000001051226351206100166340ustar00rootroot00000000000000#ifndef foo_h #define foo_h namespace acme { void t1(); } #endif Bear-1.4/test/end-to-end/lib/lib.pro000066400000000000000000000001311226351206100171670ustar00rootroot00000000000000TEMPLATE = lib TARGET = some_lib HEADERS += foo.h SOURCES += foo.cpp SOURCES += bar.cc Bear-1.4/test/end-to-end/qmake.pro000066400000000000000000000001001226351206100167450ustar00rootroot00000000000000TEMPLATE = subdirs CONFIG -= qt SUBDIRS += lib SUBDIRS += bin Bear-1.4/test/end-to-end/validate_and_count.py000077500000000000000000000001531226351206100213350ustar00rootroot00000000000000#!/bin/env python import json import sys if __name__ == '__main__': print(len(json.load(sys.stdin))) Bear-1.4/test/exec_anatomy/000077500000000000000000000000001226351206100156605ustar00rootroot00000000000000Bear-1.4/test/exec_anatomy/CMakeLists.txt000066400000000000000000000006271226351206100204250ustar00rootroot00000000000000add_executable(exec_anatomy EXCLUDE_FROM_ALL main.c) add_definitions(-D_GNU_SOURCE) include_directories(${CMAKE_CURRENT_BINARY_DIR}/../../src) 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) add_dependencies(exec_anatomy bear) Bear-1.4/test/exec_anatomy/main.c000066400000000000000000000147041226351206100167560ustar00rootroot00000000000000/* 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 . */ #include "config.h" #include #include #include #include #include #if defined HAVE_POSIX_SPAWN || defined HAVE_POSIX_SPAWNP #include #endif // ..:: environment access fixer - begin ::.. #ifdef NEED_NSGETENVIRON #include #else extern char **environ; #endif char ** getenviron() { #ifdef NEED_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() { cwd = getcwd(NULL, 0); fd = fopen("expected.json", "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; cwd = NULL; } void expected_out(const char *cmd, 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\": \"%s -c %s\",\n", cmd, file); fprintf(fd, " \"file\": \"%s/%s\"\n", cwd, file); fprintf(fd, "}\n"); } // ..:: test fixtures - end ::.. typedef void (*exec_fun)(); void wait_for(pid_t child) { int status; if (-1 == waitpid(child, &status, 0)) { perror("wait"); exit(EXIT_FAILURE); } int exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE; if (exit_code) { fprintf(stderr, "children process has non zero exit code\n"); exit(EXIT_FAILURE); } } void fork_fun(exec_fun f) { pid_t child = fork(); if (-1 == child) { perror("fork"); exit(EXIT_FAILURE); } else if (0 == child) { (*f)(); fprintf(stderr, "children process failed to exec\n"); exit(EXIT_FAILURE); } else { wait_for(child); } } #ifdef HAVE_EXECV void call_execv() { char * const compiler = "/usr/bin/cc"; char * const argv[] = { "cc", "-c", "execv.c", 0 }; execv(compiler, argv); } #endif #ifdef HAVE_EXECVE void call_execve() { char * const compiler = "/usr/bin/cc"; char * const argv[] = { compiler, "-c", "execve.c", 0 }; char * const envp[] = { "THIS=THAT", 0 }; execve(compiler, argv, envp); } #endif #ifdef HAVE_EXECVP void call_execvp() { char * const compiler = "cc"; char * const argv[] = { "cc", "-c", "execvp.c", 0 }; execvp(compiler, argv); } #endif #ifdef HAVE_EXECVP2 void call_execvP() { char * const compiler = "cc"; char * const argv[] = { "cc", "-c", "execvP.c", 0 }; execvP(compiler, _PATH_DEFPATH, argv); } #endif #ifdef HAVE_EXECVPE void call_execvpe() { char * const compiler = "cc"; char * const argv[] = { "/usr/bin/cc", "-c", "execvpe.c", 0 }; char * const envp[] = { "THIS=THAT", 0 }; execvpe(compiler, argv, envp); } #endif #ifdef HAVE_EXECL void call_execl() { char * const compiler = "/usr/bin/cc"; execl(compiler, "cc", "-c", "execl.c", (char *)0); } #endif #ifdef HAVE_EXECLP void call_execlp() { char * const compiler = "cc"; execlp(compiler, "cc", "-c", "execlp.c", (char *)0); } #endif #ifdef HAVE_EXECLE void call_execle() { char * const compiler = "/usr/bin/cc"; char * const envp[] = { "THIS=THAT", 0 }; execle(compiler, compiler, "-c", "execle.c", (char *)0, envp); } #endif #ifdef HAVE_EXECLE void call_execle_and_printenv() { char * const envp[] = { "THIS=THAT", 0 }; char * const pe = "/usr/bin/printenv"; execle(pe, "printenv", (char *)0, envp); } #endif #ifdef HAVE_POSIX_SPAWN void call_posix_spawn() { char * const argv[] = { "cc", "-c", "posix_spawn.c", 0 }; pid_t child; if (0 != posix_spawn(&child, "/usr/bin/cc", 0, 0, argv, getenviron())) { perror("posix_spawn"); exit(EXIT_FAILURE); } wait_for(child); } #endif #ifdef HAVE_POSIX_SPAWNP void call_posix_spawnp() { char * const argv[] = { "cc", "-c", "posix_spawnp.c", 0 }; pid_t child; if (0 != posix_spawnp(&child, "cc", 0, 0, argv, getenviron())) { perror("posix_spawnp"); exit(EXIT_FAILURE); } wait_for(child); } #endif int main() { expected_out_open(); #ifdef HAVE_EXECV fork_fun(call_execv); expected_out("cc", "execv.c"); #endif #ifdef HAVE_EXECVE fork_fun(call_execve); expected_out("/usr/bin/cc", "execve.c"); #endif #ifdef HAVE_EXECVP fork_fun(call_execvp); expected_out("cc", "execvp.c"); #endif #ifdef HAVE_EXECVP2 fork_fun(call_execvP); expected_out("cc", "execvP.c"); #endif #ifdef HAVE_EXECVPE fork_fun(call_execvpe); expected_out("/usr/bin/cc", "execvpe.c"); #endif #ifdef HAVE_EXECL fork_fun(call_execl); expected_out("cc", "execl.c"); #endif #ifdef HAVE_EXECLP fork_fun(call_execlp); expected_out("cc", "execlp.c"); #endif #ifdef HAVE_EXECLE fork_fun(call_execle); expected_out("/usr/bin/cc", "execle.c"); #endif #ifdef HAVE_POSIX_SPAWN call_posix_spawn(); expected_out("cc", "posix_spawn.c"); #endif #ifdef HAVE_POSIX_SPAWNP call_posix_spawnp(); expected_out("cc", "posix_spawnp.c"); #endif #ifdef HAVE_EXECLE fork_fun(call_execle_and_printenv); #endif expected_out_close(); return 0; } Bear-1.4/test/exec_anatomy/run.sh.in000077500000000000000000000006641226351206100174360ustar00rootroot00000000000000#!/bin/sh set -o nounset set -o errexit BEAR_EXE="@CMAKE_CURRENT_BINARY_DIR@/../../src/bear" BEAR_LIB="@CMAKE_CURRENT_BINARY_DIR@/../../src/@EAR_LIB_FILE@" BEAR_CFG="@CMAKE_CURRENT_SOURCE_DIR@/../../src/bear.conf" touch execve.c execv.c execvpe.c execvp.c execl.c execlp.c execle.c execvP.c posix_spawn.c posix_spawnp.c ${BEAR_EXE} -c ${BEAR_CFG} -l ${BEAR_LIB} -s ./socket -- ./exec_anatomy diff expected.json compile_commands.json Bear-1.4/test/result_code/000077500000000000000000000000001226351206100155145ustar00rootroot00000000000000Bear-1.4/test/result_code/CMakeLists.txt000066400000000000000000000002331226351206100202520ustar00rootroot00000000000000configure_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-1.4/test/result_code/run.sh.in000077500000000000000000000007011226351206100172620ustar00rootroot00000000000000#!/bin/sh set -o nounset set -o errexit BEAR_EXE="@CMAKE_CURRENT_BINARY_DIR@/../../src/bear" BEAR_LIB="@CMAKE_CURRENT_BINARY_DIR@/../../src/@EAR_LIB_FILE@" BEAR_CFG="@CMAKE_CURRENT_SOURCE_DIR@/../../src/bear.conf" set +o errexit ${BEAR_EXE} -c ${BEAR_CFG} -l ${BEAR_LIB} -s ./socket -- false rc=$? set -o errexit if [ 0 = $rc ]; then echo "exit code was not captured" && false fi ${BEAR_EXE} -c ${BEAR_CFG} -l ${BEAR_LIB} -s ./socket -- true Bear-1.4/test/unit_test/000077500000000000000000000000001226351206100152225ustar00rootroot00000000000000Bear-1.4/test/unit_test/CMakeLists.txt000066400000000000000000000007721226351206100177700ustar00rootroot00000000000000link_directories(${LIBCONFIG_LIBRARY_DIRS}) add_executable(unit_test EXCLUDE_FROM_ALL main.c ../../src/stringarray.c ../../src/protocol.c ../../src/json.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-1.4/test/unit_test/main.c000066400000000000000000000137251226351206100163220ustar00rootroot00000000000000/* 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() { char const * input_const[] = { "this", "is my", "message=\"shit\\gold\"", "with\tall the\rbad\nwhitespaces", 0 }; char const ** input = bear_strings_copy(input_const); char const ** result = bear_json_escape_strings(input); char const * expected[] = { "this", "\\\"is my\\\"", "message=\\\"shit\\\\gold\\\"", "\\\"with all the bad whitespaces\\\"", 0 }; assert_stringarray_equals(expected, result); bear_strings_release(input); } 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(); test_protocol(); return 0; }