pax_global_header00006660000000000000000000000064125472256240014523gustar00rootroot0000000000000052 comment=fcef533525875fb4c8bdf7f011b67396d9d305b4 termdebug-2.2+dfsg/000077500000000000000000000000001254722562400142635ustar00rootroot00000000000000termdebug-2.2+dfsg/COPYING000066400000000000000000001045131254722562400153220ustar00rootroot00000000000000 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 . termdebug-2.2+dfsg/Changelog000066400000000000000000000024721254722562400161020ustar00rootroot00000000000000Version 2.2: - Fixed bug in configure script which prevented compilation with pthreads Version 2.1: - Fixed incorrect output of window_size directive in tdrerecord - Fixed several print formatting issues - Reset the terminal to blocking mode after exit - Fixed several build issues with different combinations of available libraries Version 2.0: - Added visual comparison mode, which emulates a terminal and compares the emulated outputs - Added a program to compare two recordings - Changed handling of expect in tdreplay, such that it now waits for the amount of time specified by the next send or window_size event - Added optional minimum delay to send events and window_size events to force a wait even if the key delay setting causes a smaller wait - Fixed incorrect printing of line numbers in parse errors Version 1.2: - Added an option to tdrecord to prevent clearing of the DISPLAY environment variable - Fixed handling of octal escapes in strings for octal numbers starting with 4 through 7 - Fixed handling of unknown escape sequences in strings - Fixed handling of -- for tdrecord Version 1.1: - Added code to reset terminal to sane values after abort when replaying in display mode Version 1.0: - Initial release termdebug-2.2+dfsg/Makefile.in000066400000000000000000000036301254722562400163320ustar00rootroot00000000000000# Copyright (C) 2006-2010,2012-2013 G.P. Halkes # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, as # published by the Free Software Foundation. # # 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 . .POSIX: # C-compiler flags CFLAGS=-O2 -Isrc CONFIGFLAGS= CONFIGLIBS= INSTALL=install SILENTCC=@echo '[CC]' $< ; SILENTLD=@echo '[LD]' $@ ; prefix=/usr/local bindir=$(prefix)/bin docdir=$(prefix)/share/doc/termdebug mandir=$(prefix)/share/man OBJECTS=src/input_lex.o src/common.o src/replay.o src/view.o src/rerecord.o src/compare.o src/record.o src/input.o OPTOBJECTS= all: termdebug .PHONY: all clean install clean: rm -rf src/*.o dist-clean: clean rm -rf tdrecord tdreplay tdrerecord tdview tdcompare config.log Makefile .c.o: $(SILENTCC) $(CC) $(CFLAGS) $(CONFIGFLAGS) -c -o $@ $< termdebug: $(OBJECTS) $(OPTOBJECTS) $(SILENTLD) $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJECTS) $(OPTOBJECTS) $(LDLIBS) $(CONFIGLIBS) # Macros to make DESTDIR support more readable _bindir=$(DESTDIR)$(bindir) _docdir=$(DESTDIR)$(docdir) _mandir=$(DESTDIR)$(mandir) install: all $(INSTALL) -d "$(_bindir)" $(INSTALL) termdebug "$(_bindir)" cd "$(_bindir)" && ln -s termdebug tdrecord cd "$(_bindir)" && ln -s termdebug tdreplay cd "$(_bindir)" && ln -s termdebug tdrerecord cd "$(_bindir)" && ln -s termdebug tdview cd "$(_bindir)" && ln -s termdebug tdcompare $(INSTALL) -d "$(_mandir)/man1" $(INSTALL) -m 644 man/*.1 "$(_mandir)/man1" $(INSTALL) -d "$(_docdir)" $(INSTALL) -m 644 README COPYING Changelog "$(_docdir)" termdebug-2.2+dfsg/README000066400000000000000000000053071254722562400151500ustar00rootroot00000000000000Introduction ============ Termdebug is a set of utilities to record and replay the input and output of a terminal program. Its main goal is to aid in developing and debugging terminal programs. Other programs such as termrec/termplay, nethack-recorder/player and script/scriptreplay only record the output. However, when debugging an interactive terminal program, the input is often more important than the output. Motivation ========== When developing an interactive terminal program, bugs can be very hard to track down, as a specific sequence of actions may have triggered the bug. Usually one stumbles upon a bug when doing undirected testing, and it is unclear which sequence of actions triggered it. Moreover, it is often hard, if not impossible, to recreate such a sequence from memory. Termdebug allows you to record the input and output of your testing sessions such that if you stumble upon a bug, you have a record of what you did. This record can then be replayed to the program to recreate the exact circumstances that triggered the bug. A second use of termdebug is testsuites for interactive terminal programs. The tdreplay program can verify that the output of the program is the same as the recorded output. By building a set of testcases with known output you can verify that changes to the program don't affect the output behaviour of the program, or only those parts of the behaviour that you intended. Utilities ========= tdrecord Starts a program and records its input and output. tdreplay Starts a program and replays the input of a recording. tdview Shows the output of a recording. tdrerecord Starts a program and replays the input of a recording, recording the input and output to create a new recording. tdcompare Compares two recordings. Prerequisites and Installation ============================== Termdebug can provide optional (but recommended) functionality. This requires at least ncurses, to add a visual comparison mode. If further iconv, libunistring, Cairo and Pango are installed, pictures can be generated of the visual differences. Finally, if pthread is available, tdreplay will also include the option to generate a sequence of pictures showing the progression of the terminal output. To compile and install termdebug: $ ./configure or $ ./configure --prefix=/usr (see ./configure --help for more tuning options) $ make all $ make install Reporting Bugs ============== If you think you have found a bug, please check that you are using the latest version of termdebug [http://os.ghalkes.nl/termdebug.html]. When reporting bugs, please include a minimal example that demonstrates the problem. Author ====== Gertjan Halkes termdebug-2.2+dfsg/config.pkg000066400000000000000000000344331254722562400162420ustar00rootroot00000000000000# Copyright (C) 2010,2012-2013 G.P. Halkes # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, as # published by the Free Software Foundation. # # 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 . EXTENSIONS="c pkgconfig_dep verbose_compile" checkfunction() { CHECKFOR="$1" CODE="$2" shift 2 { while [ $# -ne 0 ] do if [ "x$1" = "x--" ] then shift break fi echo "#include $1" shift done cat < .config.c clean .config.o .config test_link "${CHECKFOR}" "$@" } config() { unset CONFIGFLAGS CONFIGLIBS # Test for all required functionality cat > .config.c < #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { char *args[2]; struct timeval tv; struct winsize wsz; struct timespec ts; int fd[2]; struct sigaction sa; sigset_t ss; struct termios tios; execvp("test", args); fcntl(0, F_SETFL, 0); fileno(stdin); fork(); getcwd(args[0], 0); gettimeofday(&tv, NULL); ioctl(0, TIOCGWINSZ, &wsz); isatty(0); kill(0, SIGTERM); localtime((time_t) 0); nanosleep(&ts, &ts); pipe(fd); read(0, args[0], 1); write(0, args[0], 1); close(0); setenv("NAME", "VALUE", 1); unsetenv("NAME"); sigaction(SIGWINCH, &sa, &sa); sigemptyset(&ss); sigaddset(&ss, SIGCHLD); sigprocmask(SIG_UNBLOCK, &ss, NULL); sleep(3); snprintf(args[0], 1, "foo%d", 1); tcgetattr(0, &tios); tcsetattr(0, TCSAFLUSH, &tios); umask((mode_t) 0077); unlink("PATH"); waitpid(0, fd, WNOHANG | WUNTRACED); basename("foo"); } EOF clean .config.o test_link "required functions" || { check_message_result "Testing required functions seperatly for debugging purposes" checkfunction "execvp" 'char *args[2]; execvp("test", args);' "" checkfunction "fcntl" "fcntl(0, F_SETFL, 0);" "" "" checkfunction "fileno" "fileno(stdin);" "" checkfunction "fork" "fork();" "" checkfunction "getcwd" 'char *args[2]; getcwd(args[0], 0);' "" checkfunction "gettimeofday" "struct timeval tv; gettimeofday(&tv, NULL);" "" "" checkfunction "ioctl" "struct winsize wsz; ioctl(0, TIOCGWINSZ, &wsz);" "" checkfunction "isatty" "isatty(0);" "" checkfunction "kill" "kill(0, SIGTERM);" "" "" checkfunction "localtime" "localtime((time_t) 0);" "" checkfunction "nanosleep" "struct timespec ts; nanosleep(&ts, &ts);" "" checkfunction "pipe" "int fd[2]; pipe(fd);" "" checkfunction "read" "char *args[2]; read(0, args[0], 1);" "" checkfunction "write" "char *args[2]; write(0, args[0], 1);" "" checkfunction "close" "close(0);" "" checkfunction "setenv" 'setenv("NAME", "VALUE", 1);' "" checkfunction "unsetenv" 'unsetenv("NAME");' "" checkfunction "sigaction" "struct sigaction sa; sigaction(SIGWINCH, &sa, &sa);" "" checkfunction "sigemptyset" "sigset_t ss; sigemptyset(&ss);" "" checkfunction "sigaddset" "sigset_t ss; sigaddset(&ss, SIGCHLD);" "" checkfunction "sigprocmask" "sigset_t ss; sigprocmask(SIG_UNBLOCK, &ss, NULL);" "" "" checkfunction "sleep" "sleep(3);" "" checkfunction "snprintf" 'char *args[2]; snprintf(args[0], 1, "foo%d", 1);' "" checkfunction "tcgetattr" "struct termios tios; tcgetattr(0, &tios);" "" "" checkfunction "tcsetattr" "struct termios tios; tcsetattr(0, TCSAFLUSH, &tios);" "" "" checkfunction "umask" "umask((mode_t) 0077);" "" "" checkfunction "unlink" 'unlink("PATH");' "" checkfunction "waitpid" "int fd[2]; waitpid(0, fd, WNOHANG | WUNTRACED);" "" "" checkfunction "basename" 'basename("foo");' "" check_message_result "!! A required function is not available." exit 1 } checkfunction "strdup" "strdup(\"foo\");" "" && CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_STRDUP" if checkfunction "poll" "struct pollfd fds[1]; fds[0].events = POLLIN; poll(fds, 1, 1);" "" then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_POLL" else if checkfunction "select in sys/select.h" "fd_set readfds; struct timeval timeout; select(&readfds, NULL, NULL, NULL, &timeout);" "" "" then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_SYS_SELECT_H" elif not checkfunction "select in old header files" "fd_set readfds; struct timeval timeout; select(&readfds, NULL, NULL, NULL, &timeout);" "" "" "" "" then check_message_result "!! Could not find select" exit 1 fi fi unset NEED_LIBUTIL if checkfunction "openpty in pty.h" "int a; struct winsize wsz; openpty(&a, &a, NULL, NULL, &wsz);" "" "" -- "TESTLIBS=-lutil" then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_OPENPTY" NEED_LIBUTIL=1 elif checkfunction "openpty in util.h" "int a; struct winsize wsz; openpty(&a, &a, NULL, NULL, &wsz);" "" "" "" "" "" -- "TESTLIBS=-lutil" then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_OPENPTY -DOPENPTY_IN_UTIL_H" NEED_LIBUTIL=1 elif checkfunction "openpty in libutil.h" "int a; struct winsize wsz; openpty(&a, &a, NULL, NULL, &wsz);" "" "" "" "" "" -- "TESTLIBS=-lutil" then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_OPENPTY -DOPENPTY_IN_LIBUTIL_H" NEED_LIBUTIL=1 else cat > .config.c < #include #include int main(int argc, char *argv[]) { grantpt(0); unlockpt(0); ptsname(0); open("foo", O_RDWR | O_NOCTTY); } EOF clean .config.o test_link "required functions for openpty work-around" || { check_message_result "Testing required functions seperatly for debugging purposes" checkfunction "grantpt" "grantpt(0);" "" checkfunction "unlockpt" "unlockpt(0);" "" checkfunction "ptsname" "ptsname(0);" "" checkfunction "open" 'open("foo", O_RDWR | O_NOCTTY);' "" "" check_message_result "!! Did not find any method to open a new pseudo terminal." exit 1 } if checkfunction "posix_openpt" "posix_openpt(O_RDWR | O_NOCTTY);" "" "" then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_POSIX_OPENPT" else check_message "Checking for /dev/ptmx... " if not [ -c "/dev/ptmx" ] then check_message_result "no" check_message_result "!! Did not find a method to open a new pseudo terminal." exit 1 fi check_message_result "yes" fi fi if checkfunction "login_tty in utmp.h" "login_tty(0);" "" -- "TESTLIBS=-lutil" then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_LOGIN_TTY" NEED_LIBUTIL=1 elif checkfunction "login_tty in util.h" "login_tty(0);" "" "" -- "TESTLIBS=-lutil" then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_LOGIN_TTY -DLOGIN_TTY_IN_UTIL_H" NEED_LIBUTIL=1 elif checkfunction "login_tty in libutil.h" "login_tty(0);" "" "" "" "" -- "TESTLIBS=-lutil" then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_LOGIN_TTY -DLOGIN_TTY_IN_LIBUTIL_H" NEED_LIBUTIL=1 else cat > .config.c < int main(int argc, char *argv[]) { dup2(0, 1); setsid(); } EOF clean .config.o test_link "required functions for login_tty work-around" || { check_message_result "Testing required functions seperatly for debugging purposes" checkfunction "dup2" "dup2(0, 1);" "" checkfunction "setsid" "unlockpt(0);" "" check_message_result "!! Did not find a method to open a new pseudo terminal." exit 1 } fi if checkfunction "forkpty in pty.h" "int a; struct winsize wsz; forkpty(&a, NULL, NULL, &wsz);" "" "" -- "TESTLIBS=-lutil" then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_FORKPTY" NEED_LIBUTIL=1 elif checkfunction "forkpty in util.h" "int a; struct winsize wsz; forkpty(&a, NULL, NULL, &wsz);" "" "" "" "" "" -- "TESTLIBS=-lutil" then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_FORKPTY -DFORKPTY_IN_UTIL_H" NEED_LIBUTIL=1 elif checkfunction "forkpty in libutil.h" "int a; struct winsize wsz; forkpty(&a, NULL, NULL, &wsz);" "" "" "" "" "" -- "TESTLIBS=-lutil" then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_FORKPTY -DFORKPTY_IN_LIBUTIL_H" NEED_LIBUTIL=1 fi [ "x${NEED_LIBUTIL}" = "x1" ] && CONFIGLIBS="${CONFIGLIBS} -lutil" unset CURSES_FOUND CURSES_LIBS CURSES_FLAGS cat > .config.c < #include #include int main(int argc, char *argv[]) { setupterm(NULL, 1, NULL); putp(tigetstr("smacs")); return 0; } EOF clean .config.o if pkgconfig tinfo CURSES test_link ; then CURSES_FOUND=1 elif pkgconfig ncurses CURSES test_link ; then CURSES_FOUND=1 elif test_compile "curses header file" ; then if test_link "terminfo access functions in -ltinfo" "TESTLIBS=-ltinfo" ; then CURSES_LIBS="-ltinfo" CURSES_FOUND=1 elif test_link "curses library in -lcurses" "TESTLIBS=-lcurses" ; then CURSES_LIBS="-lcurses" CURSES_FOUND=1 else if test_link "ncurses library in -lncurses" "TESTLIBS=-lncurses" ; then CURSES_LIBS="-lncurses" CURSES_FOUND=1 fi fi fi if [ "${CURSES_FOUND}" = 1 ] ; then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_CURSES ${CURSES_FLAGS}" CONFIGLIBS="${CONFIGLIBS} ${CURSES_LIBS}" OPTOBJECTS="${OPTOBJECTS} src/curses_handling.o" KEEPGOING=1 else check_message_result "!! Warning: compiling without curses. This means visual compare will not be available. Install the curses development package if you wish to compile with curses." KEEPGOING=0 fi if [ $KEEPGOING = 1 ] ; then clean_c cat > .config.c < #include int main(int argc, char *argv[]) { int32_t c; char nul; uc_is_general_category_withtable(c, UC_CATEGORY_MASK_Cs); uc_width(c, &nul); return 0; } EOF if test_link "libunistring" TESTLIBS="-lunistring" ; then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_UNISTRING" CONFIGLIBS="${CONFIGLIBS} -lunistring" OPTOBJECTS="${OPTOBJECTS} src/window.o src/write_stringlist.o" else check_message_result "!! Warning: compiling without libunistring. This means visual compare will not be available." KEEPGOING=0 fi fi if [ $KEEPGOING = 1 ] ; then clean_c cat > .config.c < #include int main(int argc, char *argv[]) { cairo_surface_write_to_png(NULL, NULL); return 0; } EOF pkgconfig cairo CAIRO test_link || KEEPGOING=0 fi if [ $KEEPGOING = 1 ] ; then clean_c cat > .config.c < #include int main(int argc, char *argv[]) { PangoFontDescription *font_desc = pango_font_description_new(); return 0; } EOF pkgconfig pangocairo PANGOCAIRO test_link || KEEPGOING=0 fi if [ $KEEPGOING = 1 ] ; then clean_c cat > .config.c < int main(int argc, char *argv[]) { iconv_t handle = iconv_open("UTF-8", "ISO-8859-1"); return 0; } EOF if test_link "iconv" ; then ICONVLIBS= elif test_link "iconv in -liconv" TESTLIBS="-liconv" ; then ICONVLIBS=-liconv else KEEPGOING=0 fi fi if [ $KEEPGOING = 1 ] ; then CONFIGFLAGS="${CONFIGFLAGS} -DHAVE_CAIRO ${CAIRO_FLAGS} ${PANGOCAIRO_FLAGS}" CONFIGLIBS="${CONFIGLIBS} -DHAVE_CAIRO ${CAIRO_LIBS} ${PANGOCAIRO_LIBS} -lunistring ${ICONVLIBS}" OPTOBJECTS="${OPTOBJECTS} src/write_image.o" else check_message_result "!! Warning: compiling without cairo. This means that no images can be generated from tdreplay and tdcompare." fi if [ $KEEPGOING = 1 ] ; then clean_c unset PTHREADFLAGS PTHREADLIBS PTHREAD_NOT_FOUND=0 cat > .config.c < #include pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_t thread; void *thread_func(void *arg) { (void) arg; return NULL; } int main(int argc, char *argv[]) { void *result; pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); pthread_cond_wait(&cond, &mutex); pthread_create(&thread, NULL, thread_func, NULL); pthread_join(thread, &result); return 0; } EOF if not test_compile "pthreads" ; then PTHREAD_NOT_FOUND=1 check_message_result "!! Can not find flags to compile with pthreads. Image writing will be done on main thread. See config.log for compile details." else test_compile "-pthread flag" && PTHREADFLAGS=-pthread # Libtool sometimes adds -nostdlib, which then requires that -lpthread is specified # separately. Therefore, we first test for -pthread -lpthread, then for # -pthread, then -lpthread and if all else fails without anything if [ -n "${PTHREADFLAGS}" ] && test_link "pthreads in ${PTHREADFLAGS} -lpthread" "TESTLIBS=${PTHREADFLAGS} -lpthread" ; then PTHREADLIBS="${PTHREADFLAGS} -lpthread" elif [ -n "${PTHREADFLAGS}" ] && test_link "pthreads in ${PTHREADFLAGS}" "TESTLIBS=${PTHREADFLAGS}" ; then PTHREADLIBS="${PTHREADFLAGS}" elif test_link "pthreads in -lpthread" TESTLIBS=-lpthread ; then PTHREADLIBS=-lpthread elif test_link "pthreads in standard library" "TESTLIBS=" ; then : else PTHREAD_NOT_FOUND=1 check_message_result "!! Can not find flags to link with pthreads. tdreplay will not provide -P/--picture-series. See config.log for compile details." fi fi if [ "$PTHREAD_NOT_FOUND" = 0 ] ; then CONFIGFLAGS="${CONFIGFLAGS} ${PTHREADFLAGS}" CONFIGLIBS="${CONFIGLIBS} ${PTHREADLIBS}" OPTOBJECTS="${OPTOBJECTS} src/picture_queue.o" fi fi create_makefile "CONFIGFLAGS=${CONFIGFLAGS}" "CONFIGLIBS=${CONFIGLIBS}" "OPTOBJECTS=${OPTOBJECTS}" } termdebug-2.2+dfsg/configure000077500000000000000000000271151254722562400162000ustar00rootroot00000000000000#!/bin/sh # Copyright (C) 2006-2007,2009,2011 G.P. Halkes # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, as # published by the Free Software Foundation. # # 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 . # Set zsh to emulate sh (otherwise all kinds of eval's wont work) [ -n "${ZSH_VERSION}" ] && emulate sh #============================== # Functions #============================== error() { echo "$*" [ -n "$DUMP_LOG" ] && cat config.log exit 1 } not() { if "$@" ; then false else true fi } check() { if not "$@" ; then error "Error executing $*. Aborting." fi } check_message() { printf "$*" echo "----------------------------------" >> config.log echo "$*" >> config.log } check_message_result() { echo "$*" echo "$*" >> config.log } clean() { rm -rf "$@" >/dev/null 2>&1 } test_make() { printf "%s" "Running: ${MAKE} -f .Makefile" >> config.log for ARG in "$@" do printf " '%s'" "${ARG}" >> config.log done echo >> config.log "${MAKE}" -f .Makefile "$@" } test_install() { clean .foo check_message "Checking for working install ($*)... " if test_make "INSTALL=$*" "install" >> config.log 2>&1 ; then check_message_result "yes" true else check_message_result "no" false fi } test_and_set() { SETTING="$4${5+ }$5" if $1 "$2${SETTING+ in }${SETTING}" "TESTFLAGS=$4" "TESTLIBS=$5" ; then eval "${3}_FLAGS=\"$4\"" eval "${3}_LIBS=\"$5\"" true else false fi } add_replace_settings() { for SETTING do echo "/^${SETTING%%=*}/s/^/# Disabled by configure: /" echo "/\.POSIX/a\\ ${SETTING}" done } replace_default() { if [ -n "$2" ] ; then echo "/^$1=/c\\ $1=$2" fi } insert() { [ -n "$2" ] && echo "/^\\.POSIX:/a\\ $1=$2" } create_makefile() { for _INSTALL in ${TEST_INSTALL} do # Don't test the sun install program, because it is dangerous. if [ "`uname`" = "SunOS" ] && [ "$_INSTALL" = "install" ] ; then continue fi test_install "${_INSTALL}" && INSTALL="${_INSTALL}" && break done if [ -z "${INSTALL}" ] ; then check_message_result "!! No working install program found. The install target will not work." fi { echo '/\.POSIX/a\ # Settings from configure script' replace_default prefix "${PREFIX}" for INSTALLDIR in ${INSTALLDIRS} do [ -n "`eval echo \\${option_${INSTALLDIR}}`" ] && replace_default "${INSTALLDIR}" "`eval echo \\${option_${INSTALLDIR}}`" done replace_default INSTALL "${INSTALL}" insert LDFLAGS "${LDFLAGS}" insert LDLIBS "${LDLIBS}" for EXT in ${EXTENSIONS} do sed_rules_${EXT} done add_replace_settings "$@" [ -n "${SEDEXTRA}" ] && ${SEDEXTRA} } > .sedscript for MAKEFILE in ${MAKEFILES:-Makefile} do echo "----------------------------------">> config.log check_message_result "Creating ${MAKEFILE}" cat ${MAKEFILE}.in | sed -f .sedscript > ${MAKEFILE} done clean .sedscript .Makefile .foo .config_base for EXT in ${EXTENSIONS} do clean_${EXT} done exit 0 } #============================== # Setup #============================== unset LINKRULE COMPILERULE USERRULES USERHELP EXTENSIONS SWITCHES PRECHECKFUNC INSTALLDIRS DUMP_LOG . ./config.pkg for MAKEFILE in ${MAKEFILES:-Makefile} do [ -f ${MAKEFILE}.in ] || error "${MAKEFILE}.in does not exist" grep "^\\.POSIX:" ${MAKEFILE}.in > /dev/null || error "${MAKEFILE}.in does not contain .POSIX target" done #@INCLUDE_START [ "${EXTENSIONS}" = "c pkgconfig_dep verbose_compile" ] || error "EXTENSIONS changed after running merge_config. Run merge_config again." SUFFIXES="${SUFFIXES} .c .o" [ -z "${LINKRULE}" ] && LINKRULE='$(CC) $(CFLAGS) $(LDFLAGS) -o $@ .config.o $(LDLIBS) $(TESTLIBS)' [ -z "${COMPILERULE}" ] && COMPILERULE='$(CC) $(CFLAGS) $(TESTFLAGS) -c -o $@ $<' clean_c() { clean .config .config.o .config.c } show_help_c() { if [ "$1" = VARIABLES ] ; then cat < .config.c <> config.log 2>&1 ; then check_message_result "yes" true else check_message_result "no" echo "Source of the failed compile:" >> config.log nl -ba .config.c >> config.log false fi } test_link() { clean .config check_message "Checking for $1... " shift if test_make "$@" .config >> config.log 2>&1 ; then check_message_result "yes" true else check_message_result "no" echo "Source of the failed compile:" >> config.log nl -ba .config.c >> config.log false fi } touch_c() { [ -f .config.c ] && touch .config.c } unset HASPKGCONFIG show_help_pkgconfig_dep() { : } print_rules_pkgconfig_dep() { : } clean_pkgconfig_dep() { : } basic_test_pkgconfig_dep() { : } sed_rules_pkgconfig_dep() { : } pkgconfig() { if [ -z "${HASPKGCONFIG}" ] ; then check_message "Checking for pkg-config... " echo "Running: pkg-config --variable pc_path pkg-config" >> .config.log if pkg-config --variable pc_path pkg-config > /dev/null 2>>config.log ; then check_message_result "yes" HASPKGCONFIG=yes else check_message_result "no" HASPKGCONFIG=no fi fi PKGNAME="${1%/*}" PKGVERSION="${1##*/}" if [ "${PKGVERSION}" = "$1" ] ; then unset PKGVERSION else PKGVERSION=" >= $PKGVERSION" fi if [ "${HASPKGCONFIG}" = no ] ; then check_message_result "Skipping check for $PKGNAME pkg-config because pkg-config is unavailable" return 2 fi unset "${2}_FLAGS" "${2}_LIBS" check_message "Checking for $PKGNAME$PKGVERSION pkg-config... " echo "Running: pkg-config --print-errors --exists $PKGNAME$PKGVERSION" >> config.log if not pkg-config --exists $PKGNAME $PKGVERSION 2>>config.log >/dev/null ; then check_message_result "no" return 1 fi check_message_result "yes" if [ $# -ge 3 ] ; then if $3 "$PKGNAME pkg-config compile" "TESTFLAGS=\`pkg-config --cflags $PKGNAME\`" "TESTLIBS=\`pkg-config --libs $PKGNAME\`" 2>>config.log ; then eval "${2}_FLAGS"="\"\\\`pkg-config --cflags $PKGNAME\\\`\"" eval "${2}_LIBS"="\"\\\`pkg-config --libs $PKGNAME\\\`\"" else return 1 fi [ $# -ge 4 ] && eval $4="\"\${$4:+\${$4}, }$PKGNAME$PKGVERSION\"" fi return 0 } SWITCHES="${SWITCHES} -verbose-compile" clean_verbose_compile() { : } show_help_verbose_compile() { if [ "$1" = OPTIONS ] ; then cat <] [=] --dump-log Dump config.log to stdout on error --prefix= Prefix for installation [/usr/local] EOF for INSTALLDIR in ${INSTALLDIRS} do case "${INSTALLDIR}" in bindir) echo ' --bindir= Binaries directory [/bin]' ;; sbindir) echo ' --sbindir= System binaries directory [/sbin]' ;; libdir) echo ' --libdir= Library directory [/lib]' ;; includedir) echo ' --includedir= Include file directory [/include]' ;; datadir) echo ' --datadir= Directory for data [/share]' ;; mandir) echo ' --mandir= Manual page directory [/share/man]' ;; infodir) echo ' --infodir= Info page directory [/share/man]' ;; docdir) echo ' --docdir= Document dir [/share/doc/-]' ;; esac done [ -n "${USERINSTALLDIRSHELP}" ] && echo "${USERINSTALLDIRSHELP}" for EXT in ${EXTENSIONS} do show_help_$EXT OPTIONS done cat < INSTALL The install program to use LDFLAGS Linker flags to use (default determined by make) LDLIBS Extra libraries to link EOF for EXT in ${EXTENSIONS} do show_help_$EXT VARIABLES done [ -n "${USERHELP}" ] && { echo ; echo "Package specific settings" ; ${USERHELP} ; } cat <&2 ;; --*) unset _match for _switch in ${_SWITCHES} do case "${PARAM}" in --with-${_switch}) _name=`echo "${_switch}" | sed 's/-/_/g'` eval with_${_name}="yes" _match="1" break ;; --without-${_switch}) _name=`echo "${_switch}" | sed 's/-/_/g'` eval with_${_name}="no" _match="1" break ;; esac done [ -z "${_match}" ] && echo "WARNING: ignoring unknown parameter: ${PARAM}" >&2 ;; *=*) name="${PARAM%%=*}" value="${PARAM#*=}" eval "${name}"="\"${value}\"" ;; *) error "Error on commandline: ${PARAM}" ;; esac done if [ -n "${INSTALL}" ] ; then TEST_INSTALL="${INSTALL}" unset INSTALL else TEST_INSTALL="install ./install.sh" fi echo "Configuration test log created at `date`" > config.log echo "-- configure called with $0 $@" >> config.log clean config.log .Makefile .sedscript .config_base for EXT in ${EXTENSIONS} do clean_${EXT} done { echo ".POSIX:" [ -z "${LDFLAGS}" ] || echo "LDFLAGS=${LDFLAGS}" [ -z "${LDLIBS}" ] || echo "LDLIBS=${LDLIBS}" [ -z "${SUFFIXES}" ] || echo ".SUFFIXES: ${SUFFIXES}" [ -z "${USERRULES}" ] || ${USERRULES} cat < .Makefile echo "Using settings:" >> config.log grep '^[[:upper:]_]\+=' .Makefile >> config.log [ -n "${MAKE}" ] || MAKE=make [ -z "${PRECHECKFUNC}" ] || ${PRECHECKFUNC} check_message "Checking for working make (${MAKE})... " if test_make .config_base >> config.log 2>&1 ; then check_message_result "yes" else check_message_result "no" error "${MAKE} failed. See config.log for errors." fi for EXT in ${EXTENSIONS} do basic_test_${EXT} done config error "Error in config.pkg. Cannot continue." termdebug-2.2+dfsg/install.sh000077500000000000000000000060521254722562400162730ustar00rootroot00000000000000#!/bin/sh # Copyright (C) 2009 G.P. Halkes # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3, as # published by the Free Software Foundation. # # 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 . # Set zsh to emulate sh (otherwise all kinds of eval's wont work) [ -n "${ZSH_VERSION}" ] && emulate sh unset directory sources dest mode owner group strip # Provide an alternative to ! not() { if "$@" ; then false else true fi } # Default mode for install is rwxr-xr-x mode="0755" while [ $# -gt 0 ] do case "$1" in -d) directory="1" ;; -m) mode="$2" shift ;; -m*) mode=`echo "$1" | sed 's/^-m//'` ;; -o) owner="$2" shift ;; -o*) owner=`echo "$1" | sed 's/^-o//'` ;; -g) group="$2" shift ;; -g*) group=`echo "$1" | sed 's/^-g//'` ;; -s) strip=1 ;; *) break ;; esac shift done if [ "1" = "${directory}" ] ; then if [ $# -eq 0 ] ; then echo "No directory names supplied" >&2 exit 1 fi # Create directories while [ $# -gt 0 ] do if [ ! -d "$1" ] ; then # Find name of dir to apply chown/chgrp -R to, i.e., the first part # of the path that does not yet exist. firstDir="$1" testDir=`dirname "$1"` while [ ! -d "${testDir}" ] ; do firstDir="${testDir}" testDir=`dirname "${firstDir}"` done # Make the directory if not mkdir -p "$1" ; then exit 1 fi if not chmod -R "${mode}" "${firstDir}" ; then exit 1 fi # Set owner and group, if specified if [ -n "${owner}" ] ; then if not chown -R "${owner}" "${firstDir}" ; then exit 1 fi fi if [ -n "${group}" ] ; then if not chgrp -R "${group}" "${firstDir}" ; then exit 1 fi fi fi shift done exit fi if [ $# -lt 2 ] ; then echo "No destination and/or source(s) supplied" >&2 exit 1 fi install_file() { if [ -d "$2" ] ; then echo "Cannot install $2: directory in the way" >&2 exit 1 fi # Copy file if not cp "$1" "$2" ; then exit 1 fi # Set attributes if [ -n "${mode}" ] ; then if not chmod "${mode}" "$2" ; then exit 1 fi fi if [ -n "${owner}" ] ; then if not chown "${owner}" "$2" ; then exit 1 fi fi if [ -n "${group}" ] ; then if not chgrp "${group}" "$2" ; then exit 1 fi fi if [ -n "${strip}" ] ; then if not strip "$2" ; then exit 1 fi fi } eval dest="\"\${$#}\"" if [ -d "${dest}" ] ; then # Loop over all sources, but do not process destination as source while [ $# -gt 1 ] do install_file "$1" "${dest}/`basename \"$1\"`" shift done elif [ $# -eq 2 ] ; then install_file "$1" "${dest}" else echo "Multiple sources specified, but destination is not a directory" >&2 exit 1 fi termdebug-2.2+dfsg/man/000077500000000000000000000000001254722562400150365ustar00rootroot00000000000000termdebug-2.2+dfsg/man/tdcompare.1000066400000000000000000000073731254722562400171100ustar00rootroot00000000000000.\" Generated by manscript from tdcompare.1.txt .TH "TDCOMPARE" "1" "2013/03/03" "2.2" "termdebug" .SH NAME tdcompare \- compare two recordings of a terminal program .SH SYNOPSIS \fBtdcompare\fR [\fIOPTIONS\fR]... \fIOLD\fR \fINEW\fR .SH DESCRIPTION \fBtdcompare\fR compares two recordings of a terminal program to determine whether they represent the same output. The comparison can be both at the input/output level, or at the visual level. When comparing at the input/output level, the difference will be reported as line numbers in the \fIOLD\fR and \fINEW\fR files. For visual comparisons, a textual description of the first difference can be produced, and a picture of the first different terminal state can be written (if \fBtermdebug\fR was compiled with Cairo support). .PP \fBtdcompare\fR is useful to verify that a new recording of the same program produced the same result. To do on-line verification, use \fBtdreplay\fR(1) instead. .SH OPTIONS \fBtdcompare\fR accepts the following options: .PP .TP \fB\-h\fR, \fB\-\-help\fR Display a short help message. .TP \fB\-V\fR, \fB\-\-version\fR Print version and copyright information. .TP \fB\-v\fR, \fB\-\-visual\-compare\fR Check for visual equality, rather than exact input/output behaviour. (Requires a build with ncurses support.) .TP \fB\-D\fR, \fB\-\-describe\fR Write a description of the first visual difference encountered. Only useful with \fB\-v\fR/\fB\-\-visual\-compare\fR. (Requires a build with ncurses support.) .TP \fB\-p\fR \fIname\fR, \fB\-\-picture\fR=\fIname\fR Write a picture of the difference to \fIname\fR. Only useful with \fB\-v\fR/\fB\-\-visual\-compare\fR. (Requires a build with ncurses and Cairo support.) .TP \fB\-f\fR \fIfont\fR, \fB\-\-font\fR=\fIfont\fR Use \fIfont\fR to show text in generated pictures. Only useful with \fB\-p\fR/\fB\-\-picture\fR or \fB\-P\fR/\fB\-\-picture\-series\fR. (Requires a build with ncurses and Cairo support.) .TP \fB\-W\fR \fIwidth\fR, \fB\-\-cell\-width\fR=\fIwidth\fR Use cells of \fIwidth\fR pixels wide in generated pictures. Only useful with \fB\-p\fR/\fB\-\-picture\fR or \fB\-P\fR/\fB\-\-picture\-series\fR. (Requires a build with ncurses and Cairo support.) .TP \fB\-H\fR \fIheight\fR, \fB\-\-cell\-height\fR=\fIheight\fR Use cells of \fIheight\fR pixels wide in generated pictures. Only useful with \fB\-p\fR/\fB\-\-picture\fR or \fB\-P\fR/\fB\-\-picture\-series\fR. (Requires a build with ncurses and Cairo support.) .TP \fB\-P\fR \fIname\fR, \fB\-\-picture\-series\fR=\fIname\fR Create a series of pictures, representing the different visual steps in the client interface, using \fIname\fR as the file name template. \fIname\fR is a \fBprintf\fR(3) format string, where a single d-type conversion is required. (Requires a build with ncurses and Cairo support.) .TP \fB\-s\fR, \fB\-\-stop\-on\-difference\fR Stop when the first visual difference is found. Only valid with \fB\-P\fR/\fB\-\-picture\-series\fR. .PP To stop \fBtdcompare\fR from interpreting file names that start with a dash as options, one can specify a double dash (\-\-) after which tdreplay will interpret any following arguments as files to read. .SH BUGS If you think you have found a bug, please check that you are using the latest version of \fBtermdebug\fR . When reporting bugs, please include a minimal example that demonstrates the problem. .SH AUTHOR G.P. Halkes .SH COPYRIGHT Copyright \(co 2010,2012\-2013 G.P. Halkes .br \fBtermdebug\fR is licensed under the GNU General Public License version 3. .br For more details on the license, see the file COPYING in the documentation directory. On Un*x systems this is usually /usr/share/doc/termdebug. .SH SEE\ ALSO \fBtermdebug\fR(1), \fBtdrecord\fR(1), \fBtdrerecord\fR(1), \fBtdview\fR(1), \fBtdreplay\fR(1) .RS .ft CW termdebug-2.2+dfsg/man/tdrecord.1000066400000000000000000000044351254722562400167340ustar00rootroot00000000000000.\" Generated by manscript from tdrecord.1.txt .TH "TDRECORD" "1" "2013/03/03" "2.2" "termdebug" .SH NAME tdrecord \- record input and output of a terminal program .SH SYNOPSIS \fBtdrecord\fR [\fIOPTIONS\fR]... \fICLIENT\fR [\fICLIENT OPTIONS\fR]... .SH DESCRIPTION \fBtdrecord\fR records the input and output of client. The recording can later be replayed using \fBtdreplay\fR(1) to compare behaviour of different versions of client. Without options, \fBtdrecord\fR will create the recording in the file tdrecord-\fIyear\fR\-\fImonth\fR\-\fIday\fR@\fIhour\fR:\fIminute\fR:\fIsecond\fR. .SH OPTIONS \fBtdrecord\fR accepts the following options: .PP .TP \fB\-h\fR, \fB\-\-help\fR Display a short help message. .TP \fB\-V\fR, \fB\-\-version\fR Print version and copyright information. .TP \fB\-d\fR \fIdir\fR, \fB\-\-directory\fR=\fIdir\fR Create the recording in directory \fIdir\fR. This option can not be used together with the \fB\-o\fR/\fB\-\-output\fR option. .TP \fB\-e\fR \fIvars\fR, \fB\-\-environment\fR=\fIvars\fR Save the environment variables indicated by the comma-separated list \fIvars\fR to the recording. These will be set on replay. .TP \fB\-o\fR \fIfile\fR, \fB\-\-output\fR=\fIfile\fR Save the output in \fIfile\fR. This option can not be used together with the \fB\-d\fR/\fB\-\-directory\fR option. .TP \fB\-X\fR, \fB\-\-allow\-x11\fR Don't clear the DISPLAY environment variable, to allow communication with X11. .PP To stop \fBtdrecord\fR from interpreting file names that start with a dash as options, one can specify a double dash (\-\-) after which \fBtdrecord\fR will interpret any following arguments as the client and its options. .SH BUGS If you think you have found a bug, please check that you are using the latest version of \fBtermdebug\fR . When reporting bugs, please include a minimal example that demonstrates the problem. .SH AUTHOR G.P. Halkes .SH COPYRIGHT Copyright \(co 2010,2012\-2013 G.P. Halkes .br \fBtermdebug\fR is licensed under the GNU General Public License version 3. .br For more details on the license, see the file COPYING in the documentation directory. On Un*x systems this is usually /usr/share/doc/termdebug. .SH SEE\ ALSO \fBtermdebug\fR(1), \fBtdreplay\fR(1), \fBtdrerecord\fR(1), \fBtdview\fR(1), \fBtdcompare\fR(1) termdebug-2.2+dfsg/man/tdreplay.1000066400000000000000000000114701254722562400167470ustar00rootroot00000000000000.\" Generated by manscript from tdreplay.1.txt .TH "TDREPLAY" "1" "2013/03/03" "2.2" "termdebug" .SH NAME tdreplay \- replay input to a terminal program .SH SYNOPSIS \fBtdreplay\fR [\fIOPTIONS\fR] \fIRECORDING\fR .SH DESCRIPTION \fBtdreplay\fR replays the input from a recording to the terminal program named in the recording. This allows verification that the program behaviour has not changed, or confirmation that it has. .SH OPTIONS \fBtdreplay\fR accepts the following options: .PP .TP \fB\-h\fR, \fB\-\-help\fR Display a short help message. .TP \fB\-V\fR, \fB\-\-version\fR Print version and copyright information. .TP \fB\-a\fR \fIcmd\fR, \fB\-\-alert\fR=\fIcmd\fR Execute \fIcmd\fR when a difference is detected between the recorded output and the output generated by replaying the input back to the program. The environment variable REASON contains a message about what sort of difference was detected. A useful command is 'xmessage "$REASON"'. .TP \fB\-d\fR, \fB\-\-display\fR Show the output of the running program on the current terminal. The default is to only verify that the program behaves as recorded without showing the output. .TP \fB\-e\fR \fIaction\fR, \fB\-\-on\-error\fR=\fIaction\fR Set the action to take when a difference is detected between the recorded and the actual output. Possible values for \fIaction\fR are interact, continue and abort. When the \fIaction\fR is interact, \fBtdreplay\fR will allow the user to interact with the program. When the \fIaction\fR is continue, \fBtdreplay\fR will continue as if no difference was detected. This can be dangerous as the input is no longer in sync with the output. Depending on the possible actions of the program being run this can cause data corruption. .TP \fB\-k\fR \fIdelay\fR, \fB\-\-key\-delay\fR=\fIdelay\fR Set the delay for sending a the next keys to \fIdelay\fR. Delay may be either a fixed number of miliseconds, or it may be specified as / (slash) followed by a divisor. When a divisor is specified, all key delays specified in the recording will be divided by the divisor. .TP \fB\-l\fR \fIlog\fR, \fB\-\-log\fR=\fIlog\fR Write a log of the events to \fIlog\fR. This may be useful in figuring out what the difference between the recorded and the actual output is. .TP \fB\-R\fR, \fB\-\-no\-resize\fR Do not try to resize the output terminal by sending a resize command sequence. .TP \fB\-v\fR, \fB\-\-visual\-compare\fR Check for visual equality, rather than exact input/output behaviour. (Requires a build with ncurses support.) .TP \fB\-D\fR, \fB\-\-describe\fR Write a description of the first visual difference encountered. Only useful with \fB\-v\fR/\fB\-\-visual\-compare\fR. (Requires a build with ncurses support.) .TP \fB\-p\fR \fIname\fR, \fB\-\-picture\fR=\fIname\fR Write a picture of the difference to \fIname\fR. Only useful with \fB\-v\fR/\fB\-\-visual\-compare\fR. (Requires a build with ncurses and Cairo support.) .TP \fB\-f\fR \fIfont\fR, \fB\-\-font\fR=\fIfont\fR Use \fIfont\fR to show text in generated pictures. Only useful with \fB\-p\fR/\fB\-\-picture\fR or \fB\-P\fR/\fB\-\-picture\-series\fR. (Requires a build with ncurses and Cairo support.) .TP \fB\-W\fR \fIwidth\fR, \fB\-\-cell\-width\fR=\fIwidth\fR Use cells of \fIwidth\fR pixels wide in generated pictures. Only useful with \fB\-p\fR/\fB\-\-picture\fR or \fB\-P\fR/\fB\-\-picture\-series\fR. (Requires a build with ncurses and Cairo support.) .TP \fB\-H\fR \fIheight\fR, \fB\-\-cell\-height\fR=\fIheight\fR Use cells of \fIheight\fR pixels wide in generated pictures. Only useful with \fB\-p\fR/\fB\-\-picture\fR or \fB\-P\fR/\fB\-\-picture\-series\fR. (Requires a build with ncurses and Cairo support.) .TP \fB\-P\fR \fIname\fR, \fB\-\-picture\-series\fR=\fIname\fR Create a series of pictures, representing the different visual steps in the client interface, using \fIname\fR as the file name template. \fIname\fR is a \fBprintf\fR(3) format string, where a single d-type conversion is required. (Requires a build with ncurses, Cairo and Pthread support.) .PP To stop \fBtdreplay\fR from interpreting file names that start with a dash as options, one can specify a double dash (\-\-) after which \fBtdreplay\fR will interpret any following arguments as files to read. .SH BUGS If you think you have found a bug, please check that you are using the latest version of \fBtermdebug\fR . When reporting bugs, please include a minimal example that demonstrates the problem. .SH AUTHOR G.P. Halkes .SH COPYRIGHT Copyright \(co 2010,2012\-2013 G.P. Halkes .br \fBtermdebug\fR is licensed under the GNU General Public License version 3. .br For more details on the license, see the file COPYING in the documentation directory. On Un*x systems this is usually /usr/share/doc/termdebug. .SH SEE\ ALSO \fBtermdebug\fR(1), \fBtdrecord\fR(1), \fBtdrerecord\fR(1), \fBtdview\fR(1), \fBtdcompare\fR(1) termdebug-2.2+dfsg/man/tdrerecord.1000066400000000000000000000053101254722562400172540ustar00rootroot00000000000000.\" Generated by manscript from tdrerecord.1.txt .TH "TDRERECORD" "1" "2013/03/03" "2.2" "termdebug" .SH NAME tdrerecord \- rerecord output of a terminal program .SH SYNOPSIS \fBtdrerecord\fR [OPTIONS] \fIRECORDING\fR .SH DESCRIPTION \fBtdrerecord\fR re-records the output of a terminal program, by replaying the input from a recording. This allows a new recording to created based on the same input, after modifying the behaviour of the program. Without options, \fBtdrerecord\fR will create the recording in the file tdrecord-\fIyear\fR\-\fImonth\fR\-\fIday\fR@\fIhour\fR:\fIminute\fR:\fIsecond\fR. .PP \fBNote\fR that \fBtdrerecord\fR does \fBnot\fR check whether the output conforms to the recorded output. This can be dangerous as the input may not be in sync with the output. Depending on the possible actions of the program being run this can cause data corruption. .SH OPTIONS \fBtdrerecord\fR accepts the following options: .PP .TP \fB\-h\fR, \fB\-\-help\fR Display a short help message. .TP \fB\-V\fR, \fB\-\-version\fR Print version and copyright information. .TP \fB\-d\fR \fIdir\fR, \fB\-\-directory\fR=\fIdir\fR Create the recording in directory \fIdir\fR. This option can not be used together with the \fB\-o\fR/\fB\-\-output\fR option. .TP \fB\-o\fR \fIfile\fR, \fB\-\-output\fR=\fIfile\fR Save the output in \fIfile\fR. This option can not be used togehter with the \fB\-d\fR/\fB\-\-directory\fR option. .TP \fB\-l\fR, \fB\-\-no\-strip\-location\-reports\fR Do not remove ANSI cursor location reports from the recorded client input. These reports are normally generated on request by the client program. Including these in the client input will result in duplicate location reports which is likely to confuse the client. However, in some cases it may be necessary to retain these strings (e.g. if they were not generated in response to a client request). .PP To stop \fBtdrerecord\fR from interpreting file names that start with a dash as options, one can specify a double dash (\-\-) after which \fBtdrerecord\fR will interpret any following arguments as files to read. .SH BUGS If you think you have found a bug, please check that you are using the latest version of \fBtermdebug\fR . When reporting bugs, please include a minimal example that demonstrates the problem. .SH AUTHOR G.P. Halkes .SH COPYRIGHT Copyright \(co 2010,2012\-2013 G.P. Halkes .br \fBtermdebug\fR is licensed under the GNU General Public License version 3. .br For more details on the license, see the file COPYING in the documentation directory. On Un*x systems this is usually /usr/share/doc/termdebug. .SH SEE\ ALSO \fBtermdebug\fR(1), \fBtdrecord\fR(1), \fBtdreplay\fR(1), \fBtdview\fR(1), \fBtdcompare\fR(1) termdebug-2.2+dfsg/man/tdview.1000066400000000000000000000033531254722562400164260ustar00rootroot00000000000000.\" Generated by manscript from tdview.1.txt .TH "TDVIEW" "1" "2013/03/03" "2.2" "termdebug" .SH NAME tdview \- show recorded output of a terminal program .SH SYNOPSIS \fBtdview\fR [OPTIONS] \fIRECORDING\fR .SH DESCRIPTION \fBtdview\fR shows the recorded output of a terminal program. The recording can be made by either \fBtdrecord\fR(1) or \fBtdrerecord\fR(1). .SH OPTIONS \fBtdview\fR accepts the following options: .PP .TP \fB\-h\fR, \fB\-\-help\fR Display a short help message. .TP \fB\-V\fR, \fB\-\-version\fR Print version and copyright information. .TP \fB\-k\fR\fIdelay\fR, \fB\-\-key\-delay\fR=\fIdelay\fR Set the delay for sending a the next keys to \fIdelay\fR. Delay may be either a fixed number of miliseconds, or it may be specified as / (slash) followed by a divisor. When a divisor is specified, all key delays specified in the recording will be divided by the divisor. .PP To stop \fBtdview\fR from interpreting file names that start with a dash as options, one can specify a double dash (\-\-) after which \fBtdview\fR will interpret any following arguments as files to read. .SH BUGS If you think you have found a bug, please check that you are using the latest version of \fBtermdebug\fR . When reporting bugs, please include a minimal example that demonstrates the problem. .SH AUTHOR G.P. Halkes .SH COPYRIGHT Copyright \(co 2010,2012\-2013 G.P. Halkes .br \fBtermdebug\fR is licensed under the GNU General Public License version 3. .br For more details on the license, see the file COPYING in the documentation directory. On Un*x systems this is usually /usr/share/doc/termdebug. .SH SEE\ ALSO \fBtermdebug\fR(1), \fBtdrecord\fR(1), \fBtdreplay\fR(1), \fBtdrerecord\fR(1), \fBtdcompare\fR(1) termdebug-2.2+dfsg/man/termdebug.1000066400000000000000000000074621254722562400171070ustar00rootroot00000000000000.\" Generated by manscript from termdebug.1.txt .TH "TERMDEBUG" "1" "2013/03/03" "2.2" "termdebug" .SH NAME termdebug \- utilities for debugging interactive terminal programs. .SH DESCRIPTION \fBtermdebug\fR is a set of utilities to record and replay the input and output of terminal programs. Its main goal is to aid in developing and debugging terminal programs. Other programs such as termrec/termplay, nethack-recorder/player and script/scriptreplay only record the output. However, when debugging an interactive terminal program, the input is often as important as the output. .PP \fBtermdebug\fR consists of the following utilities: .PP .TP \fBtdrecord\fR Starts a program and records its input and output. .TP \fBtdreplay\fR Starts a program and replays the input of a recording. .TP \fBtdview\fR Shows the output of a recording. .TP \fBtdrerecord\fR Starts a program and replays the input of a recording, recording the input and output to create a new recording. .TP \fBtdcompare\fR Compares two recordings to determine if there are differences. The reported differences can be either on the exact input/output behaviour, or on the visual behaviour. .SH GRAMMAR The recordings made with the \fBtermdebug\fR utilities use a simple format. Each recording consists of a set of directives with arguments. White space is not important. The language supports line comments which start at # and run to the end of the line. The only other elements are numbers (a sequence of digits) and strings. Strings start and end with a double qoute, and use C-style escaping. The following directives are known: .PP .TP \fBenv\fR \fIname\fR \fIvalue\fR Set the value of environment variable \fIname\fR to \fIvalue\fR. \fIname\fR and \fIvalue\fR are strings. All env directives must appear before the start directive. .TP \fBwindow_size\fR \fIcolumns\fR \fIlines\fR [\fIdelay\fR [\fB>\fR \fImin_delay\fR]] Set the terminal window size to \fIcolumns\fR by lines_. May be specified both before and after the start directive. On optional \fIdelay\fR in milliseconds may be specified. Furthermore, \fImin_delay\fR may be specified to force a wait of at least \fImin_delay\fR milliseconds regardless of program options changing the key delay. .TP \fBstart\fR \fIclient\fR [\fIargument\fR+] The start directive indicates the \fIclient\fR to start. Zero or more \fIargument\fRs for the \fIclient\fR may be specified. \fIclient\fR and \fIargument\fR are strings. .TP \fBrequire_version\fR \fIversion\fR Tell the interpreter that the script langauge version must be \fIversion\fR. The current version is 1. .PP The following directives may only appear after the start directive: .PP .TP \fBexpect\fR \fIstring\fR+ Indicate what output to expect. One or more \fIstring\fRs may be specified. .TP \fBsend\fR (\fIdelay\fR \fIstring\fR [\fB>\fR \fImin_delay\fR)+ Specify one or more key \fIstring\fRs to send to the client program. \fIdelay\fR is the delay in miliseconds to wait before sending \fIstring\fR. Furthermore, \fImin_delay\fR may be specified to force a wait of at least \fImin_delay\fR milliseconds regardless of program options changing the key delay. .TP \fBexpect_exit\fR \fIstatus\fR Signal that the client should stop at this point, returning \fIstatus\fR. .TP \fBexpect_suspend\fR Indicate that the client should suspend itself at this point. .TP \fBinteract\fR Indicate the interaction with the user should be started at this point. Any directives after this point will be ignored. .SH AUTHOR G.P. Halkes .SH COPYRIGHT Copyright \(co 2010,2012 G.P. Halkes .br \fBtermdebug\fR is licensed under the GNU General Public License version 3. .br For more details on the license, see the file COPYING in the documentation directory. On Un*x systems this is usually /usr/share/doc/termdebug. .SH SEE\ ALSO \fBtdrecord\fR(1), \fBtdreplay\fR(1), \fBtdrerecord\fR(1), \fBtdview\fR(1) termdebug-2.2+dfsg/src/000077500000000000000000000000001254722562400150525ustar00rootroot00000000000000termdebug-2.2+dfsg/src/common.c000066400000000000000000000502271254722562400165140ustar00rootroot00000000000000/* Copyright (C) 2010,2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_SYS_SELECT_H #include #endif #include "common.h" int signal_pipe[2]; static const char controlMap[] = "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]_^"; static struct termios saved; static struct timeval timestamp; static Type last_type = TYPE_NONE; /** Alert the user of a fatal error and quit. @param fmt The format string for the message. See fprintf(3) for details. @param ... The arguments for printing. */ void fatal(const char *fmt, ...) { va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); //FIXME: should we always do this? Standard error is not always visible... /* char *fmtBuffer, *msgBuffer; va_start(args, fmt); asprintf(&fmtBuffer, "xmessage \"%s\"", fmt, args); vasprintf(&msgBuffer, fmtBuffer, args); system(msgBuffer); va_end(args); */ exit(EXIT_FAILURE); } void safe_write(int fd, const void *buffer, size_t size) { while (size) { ssize_t result = write(fd, buffer, size); if (result < 0) { if (errno == EINTR || errno == EAGAIN) continue; fatal("Error writing data: %s\n", strerror(errno)); } buffer += result; size -= result; } } ssize_t safe_read(int fd, char *buffer, size_t size) { size_t todo = size; while (todo) { ssize_t result = read(fd, buffer, todo); if (result < 0) { if (errno == EINTR) continue; else if (errno == EAGAIN) return size - todo; fatal("Error reading data: %s\n", strerror(errno)); } buffer += result; todo -= result; } return size; } void write_echo(const unsigned char *buffer, size_t size) { size_t write_from = 0, i; char ctrl[2] = { '^', 0 }; for (i = 0; i < size; i++) { /* FIXME: some of the control characters should be interpreted or sent to the terminal, depending on the terminal settings. C-D (4) should not be printed at all return (13) and newline (10) should be printed depending on the NL to CR mapping tab (9) should be sent to the terminal C-U, C-W seem to kill the line if (buffer[i] < 32 && buffer[i] != 4 && buffer[i] != 10 && buffer[i] != 9 && buffer[i] != 13 && buffer[i] != 21 && buffer[i] != 23 && buffer[i] != 28) { */ if (buffer[i] < 32 && buffer[i] != 4 && buffer[i] != 9 && buffer[i] != 10 && buffer[i] != 13) { if (i > write_from) safe_write(STDOUT_FILENO, buffer + write_from, i - write_from); write_from = i + 1; ctrl[1] = controlMap[buffer[i]]; safe_write(STDOUT_FILENO, ctrl, 2); } } if (i > write_from) safe_write(STDOUT_FILENO, buffer + write_from, i - write_from); } void copy_attrs_to_terminal(int from) { struct termios attrs; if (tcgetattr(from, &attrs) < 0) return; attrs.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSADRAIN, &attrs); } void set_non_block(int fd, const char *descr, td_bool value) { int flags; if ((flags = fcntl(fd, F_GETFL)) < 0) fatal("Could not get flags for %s\n", descr); if (value) flags |= O_NONBLOCK; else flags &= ~O_NONBLOCK; if (fcntl(fd, F_SETFL, flags) < 0) fatal("Could not set flags for %s\n", descr); } FILE *open_output(char **name, const char *directory) { FILE *retval; mode_t oldUmask; /* If no name is given, create one */ if (*name == NULL) { char nameBuffer[1024]; time_t seconds; struct tm *local; seconds = time(NULL); local = localtime(&seconds); if (!local) fatal("Error getting localtime\n"); strftime(nameBuffer, 1024, "tdrecord-%Y-%m-%d@%H:%M:%S", local); *name = strdup(nameBuffer); if (*name == NULL) fatal("Out of memory\n"); /* Use directory if one is supplied */ if (directory != NULL) { snprintf(nameBuffer, 1024, "%s/%s", directory, *name); free(*name); *name = strdup(nameBuffer); if (*name == NULL) fatal("Out of memory\n"); } } oldUmask = umask((mode_t) 0077); if ((retval = fopen(*name, "w")) == NULL) fatal("Could not open output %s: %s\n", *name, strerror(errno)); umask(oldUmask); return retval; } void install_signal_handler(int sig, void (*handler)(int), const char *descr) { static td_bool pipe_initialised = td_false; struct sigaction sa; sigset_t sigs; if (!pipe_initialised) { if (pipe(signal_pipe) < 0) fatal("Could not open pipe: %s\n", strerror(errno)); pipe_initialised = td_true; } /* Set signal handler to catch sig */ sa.sa_handler = handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; if (sigaction(sig, &sa, NULL) < 0) fatal("Could not set signal handler for %s: %s\n", descr, strerror(errno)); sigemptyset(&sigs); sigaddset(&sigs, sig); if (sigprocmask(SIG_UNBLOCK, &sigs, NULL) < 0) fatal("Could not block %s: %s\n", descr, strerror(errno)); } void sigwinch_handler(int param) { char signal_byte = SIGNAL_WINCH; (void) param; safe_write(signal_pipe[PIPE_WRITE], &signal_byte, 1); } void sigchld_handler(int param) { char signal_byte = SIGNAL_CHILD; (void) param; safe_write(signal_pipe[PIPE_WRITE], &signal_byte, 1); } void save_tty(void) { /* Get terminal attributes. */ if (tcgetattr(STDIN_FILENO, &saved) < 0) fatal("Could not get terminal settings: %s\n", strerror(errno)); atexit(reset_tty); } void reset_tty(void) { tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved); set_non_block(STDIN_FILENO, "terminal", td_false); } int timevaldiff(struct timeval origin, struct timeval now) { return (now.tv_usec - origin.tv_usec) / 1000 + (now.tv_sec - origin.tv_sec) * 1000; } void init_timestamp(void) { gettimeofday(×tamp, NULL); } int get_elapsed(void) { struct timeval now; int retval; gettimeofday(&now, NULL); retval = timevaldiff(timestamp, now); timestamp = now; return retval; } void write_record(FILE *output, Type dir, int delay, int min_delay, unsigned char *buffer, ssize_t length) { int i; if (last_type != dir) { if (last_type == TYPE_OUTPUT) fputc('"', output); if (last_type != TYPE_NONE) fputc('\n', output); fprintf(output, "%s", dir == TYPE_OUTPUT ? "expect " : "send"); if (dir == TYPE_OUTPUT) fputc('"', output); last_type = dir; } if (dir == TYPE_INPUT) { fprintf(output, " %d ", delay); if (min_delay > 0) fprintf(output, ">%d ", min_delay); fputc('"', output); } for (i = 0; i < length; i++) { if (buffer[i] == '\r' && dir == TYPE_OUTPUT) { /* FIXME: don't start a new string here because it may become an empty string. */ fputs("\\r\"\n\t\"", output); } else if (!isprint(buffer[i])) { fprintf(output, "\\%03o", buffer[i]); } else if (buffer[i] == '"' || buffer[i] == '\\') { fputc('\\', output); fputc(buffer[i], output); } else { fputc(buffer[i], output); } } if (dir == TYPE_INPUT) fputc('"', output); } void copy_fd(int from, int to, Type dir, FILE *output) { unsigned char buffer[1024]; ssize_t result; struct termios backup; td_bool restore = td_true; if (dir == TYPE_INPUT) { /* Temporarily disable ECHO on the terminal to prevent duplicate output. Note that the "to" terminal in this case is the pty connected to the client program. */ if (tcgetattr(to, &backup) < 0 || !(backup.c_lflag & ECHO)) { /* If we can't read the attributes, we can't restore them at the end either. And if echo is disabled anyway, we don't have to. */ restore = td_false; } else { struct termios noecho = backup; noecho.c_lflag &= ~ECHO; tcsetattr(to, TCSANOW, &noecho); } } repeat: while ((result = read(from, buffer, sizeof(buffer))) > 0) { /* Record copied data to file. */ if (output != NULL) write_record(output, dir, dir == TYPE_INPUT ? get_elapsed() : 0, 0, buffer, result); /* Simulate ECHO flag on terminal. The ECHO flag has been disabled because we can't get a signal when the client program changes the terminal settings. This means that the first character typed will have the old ECHO settings and may echo when it is not desired. However, if the client program does want the ECHO flag we must now provide... */ if (dir == TYPE_INPUT && restore) write_echo(buffer, result); safe_write(to, buffer, result); } if (result < 0) { if (errno == EINTR) { goto repeat; } else if (errno != EAGAIN) { if (dir == TYPE_INPUT) fatal("Error reading data from terminal or pty: %s\n", strerror(errno)); } } if (dir == TYPE_INPUT && restore) tcsetattr(to, TCSANOW, &backup); } int interact_loop(int master, pid_t pid, FILE *output, int timeout) { port_pollfd fdset[3]; struct winsize wsz; int status; int remaining_timeout = timeout; struct timeval start; fdset[0].fd = STDIN_FILENO; fdset[0].events = PORT_POLLIN; fdset[1].fd = master; fdset[1].events = PORT_POLLIN; fdset[2].fd = signal_pipe[PIPE_READ]; fdset[2].events = PORT_POLLIN; copy_attrs_to_terminal(STDIN_FILENO); if (timeout >= 0) gettimeofday(&start, NULL); while (1) { int result; result = port_poll(fdset, 3, remaining_timeout); if (result == -1) { if (errno != EINTR) fatal("Error during poll: %s\n", strerror(errno)); } if (result == 0) return -1; copy_attrs_to_terminal(master); if (fdset[1].revents & PORT_POLLIN) copy_fd(master, STDOUT_FILENO, TYPE_OUTPUT, output); copy_attrs_to_terminal(master); if (fdset[0].revents & PORT_POLLIN) copy_fd(STDIN_FILENO, master, TYPE_INPUT, output); /* Check if a signal handler has been called since the last check. */ if (fdset[2].revents & PORT_POLLIN) { HANDLE_SIG_BYTES() case SIGNAL_CHILD: if (waitpid(pid, &status, WNOHANG | WUNTRACED) == pid) { if (WIFSTOPPED(status)) { if (output != NULL) { if (last_type == TYPE_OUTPUT) fputs("\"\n", output); fprintf(output, "expect_suspend\n"); last_type = TYPE_NONE; } printf("Process has stopped. Will send continue signal in 3 seconds\n"); sleep(3); kill(pid, SIGCONT); if (timeout >=0) timeout += 3000; } else { goto end; } } break; case SIGNAL_WINCH: if (ioctl(STDIN_FILENO, TIOCGWINSZ, &wsz) < 0) fatal("Error obtaining window size: %s\n", strerror(errno)); if (output != NULL) { if (last_type == TYPE_OUTPUT) fputs("\"\n", output); fprintf(output, "window_size %d %d %d\n", wsz.ws_col, wsz.ws_row, get_elapsed()); last_type = TYPE_NONE; } if (ioctl(master, TIOCSWINSZ, &wsz) < 0) fatal("Error setting window size: %s\n", strerror(errno)); break; END_HANDLE } if (timeout >= 0) { struct timeval now; gettimeofday(&now, NULL); remaining_timeout = timeout - timevaldiff(start, now); if (remaining_timeout <= 0) return -1; } } end: /* Copy any remaining data */ copy_attrs_to_terminal(master); copy_fd(master, STDOUT_FILENO, TYPE_OUTPUT, output); if (output != NULL) { if (last_type == TYPE_OUTPUT) fputs("\"\n", output); fprintf(output, "expect_exit %d\n", WEXITSTATUS(status)); } return status; } void write_escaped_string(FILE *out, const char *string, size_t length) { size_t i; fputc('"', out); for (i = 0; i < length; i++, string++) { if (!isprint(*string)) { fprintf(out, "\\%03o", (unsigned char) *string); } else if (*string == '\\' || *string == '"') { fputc('\\', out); fputc(*string, out); } else { fputc(*string, out); } } fputs("\"", out); } td_bool detect_resize_capable(void) { /* Only way to check whether the terminal is resize capable is to check the TERM environment variable. Unfortunately, this is not 100% sure. For example, xterm only allows this when "XTerm*allowWindowOps" resource is set to td_true. */ const char *term = getenv("TERM"); if (term == NULL) return td_false; return strcmp(term, "xterm") == 0 || strcmp(term, "rxvt") == 0 || strcmp(term, "Eterm") == 0; } pid_t start_client(ExpNode *client, int fd, FILE *log_file) { pid_t result; StringListNode *ptr; int argc = 0; char **argv; if (log_file != NULL) { /* Log the start attempt */ fprintf(log_file, "Starting client:"); ptr = client->un.args; while (ptr != NULL) { fprintf(log_file, " %s", ptr->string); ptr = ptr->next; } fprintf(log_file, "\n"); fflush(log_file); } /* Start the client */ if ((result = fork()) < 0) fatal("Error executing fork: %s\n", strerror(errno)); else if (result != 0) return result; if (port_login_tty(fd) < 0) fatal("Error executing login_tty: %s\n", strerror(errno)); ptr = client->un.args; while (ptr != NULL) { argc++; ptr = ptr->next; } if ((argv = malloc(sizeof(char *) * (argc + 1))) == NULL) fatal("Could not allocate client argument array: %s\n", strerror(errno)); ptr = client->un.args; argc = 0; while (ptr != NULL) { argv[argc++] = ptr->string; ptr = ptr->next; } argv[argc] = NULL; /* Don't want program to communicate with X11 server for modifier states. */ unsetenv("DISPLAY"); execvp(argv[0], argv); fatal("execvp failed: %s\n", strerror(errno)); return 0; } char *getcwd_wrapper(void) { size_t cwdBufferLength = 1024; char *cwdBuffer, *retval; if ((cwdBuffer = malloc(cwdBufferLength)) == NULL) return strdup(""); repeat_getcwd: retval = getcwd(cwdBuffer, cwdBufferLength); if (retval != NULL) return retval; if (errno == ERANGE) { char *newCwdBuffer; if (SIZE_MAX / 2 > cwdBufferLength) { free(cwdBuffer); return strdup(""); } cwdBufferLength <<= 1; newCwdBuffer = realloc(cwdBuffer, cwdBufferLength); if (newCwdBuffer == NULL) { free(cwdBuffer); return strdup(""); } goto repeat_getcwd; } free(cwdBuffer); /* FIXME: report _which_ error */ return strdup(""); } void check_script(const char *file_name, ExpNode *script) { int current_check_version = 0; for (; script != NULL; script = script->next) { switch (script->type) { case EXP_START: case EXP_INTERACT: case EXP_ENV: case EXP_EXPECT: case EXP_EXPECT_EXIT: case EXP_EXPECT_SUSPEND: /* Ignore stuff that isn't relavant to simply checking the script. */ break; case EXP_SEND: { StringListNode *string; if (current_check_version >= 2) break; for (string = script->un.args; string != NULL; string = string->next) { if (string->min_delay > 0) { fprintf(stderr, "%s:%d: WARNING: minimum delay construct is not supported in script version 1. " "Please add 'require_version 2' to your script.\n", file_name, script->line); break; } } break; } case EXP_WINDOW_SIZE: if (script->un.size.min_delay > 0) fprintf(stderr, "%s:%d: WARNING: minimum delay construct is not supported in script version 1. " "Please add 'require_version 2' to your script.\n", file_name, script->line); break; case EXP_REQUIRE_VERSION: if (script->un.number > CURRENT_SCRIPT_VERSION) fatal("Script requires an unsupported script version.\n"); current_check_version = script->un.number; break; default: fatal("Internal error\n"); } } } #ifndef HAVE_OPENPTY int port_openpty(int *master, int *slave, struct winsize *wsz) { char *slave_name; int save_errno; # ifdef HAVE_POSIX_OPENPT *master = posix_openpt(O_RDWR | O_NOCTTY); # else *master = open("/dev/ptmx", O_RDWR | O_NOCTTY); # endif if (*master == -1) return -1; if (grantpt (*master) == -1 || unlockpt (*master) == -1 || (slave_name = ptsname(*master)) == NULL || (*slave = open(slave_name, O_RDWR | O_NOCTTY)) == -1) { save_errno = errno; goto error_end_close_master; } if (wsz == NULL || ioctl(*master, TIOCSWINSZ, wsz) != -1) return 0; /* ioctl failed. */ save_errno = errno; close(*slave); error_end_close_master: close(*master); errno = save_errno; return -1; } #endif #ifndef HAVE_LOGIN_TTY int port_login_tty(int fd) { if (setsid() == -1) return -1; if (ioctl(fd, TIOCSCTTY, 0) == -1) return -1; if (dup2(fd, STDIN_FILENO) == -1) return -1; if (dup2(fd, STDOUT_FILENO) == -1) return -1; if (dup2(fd, STDOUT_FILENO) == -1) return -1; close(fd); return 0; } #endif #ifndef HAVE_FORKPTY pid_t port_forkpty(int *master, struct winsize *wsz) { pid_t pid; int slave, save_errno; if (port_openpty(master, &slave, wsz) == -1) return -1; if ((pid = fork()) == -1) { save_errno = errno; goto error_end_close; } if (pid != 0) return pid; if (port_login_tty(slave) == -1) { save_errno = errno; goto error_end_close; } return 0; error_end_close: close(slave); close(*master); errno = save_errno; return -1; } #endif #ifndef HAVE_POLL int port_poll(port_pollfd *fds, port_nfds_t nfds, int timeout) { fd_set readfds, writefds, exceptfds; struct timeval _timeout; port_nfds_t i; int maxfd = 0, result; FD_ZERO(&readfds); FD_ZERO(&writefds); FD_ZERO(&exceptfds); for (i = 0; i < nfds; i++) { if (fds[i].events & PORT_POLLIN) FD_SET(fds[i].fd, &readfds); if (fds[i].events & PORT_POLLOUT) FD_SET(fds[i].fd, &writefds); if (fds[i].events & PORT_POLLERR) FD_SET(fds[i].fd, &exceptfds); if (fds[i].events != 0 && fds[i].fd > maxfd) maxfd = fds[i].fd; } _timeout.tv_sec = timeout / 1000; _timeout.tv_usec = (timeout % 1000) * 1000; result = select(maxfd + 1, &readfds, &writefds, &exceptfds, timeout < 0 ? NULL : &_timeout); if (result == -1) return -1; if (result == 0) return 0; result = 0; for (i = 0; i < nfds; i++) { fds[i].revents = 0; if (FD_ISSET(fds[i].fd, &readfds)) fds[i].revents |= PORT_POLLIN; if (FD_ISSET(fds[i].fd, &writefds)) fds[i].revents |= PORT_POLLOUT; if (FD_ISSET(fds[i].fd, &exceptfds)) fds[i].revents |= PORT_POLLERR; if (fds[i].revents != 0) result++; } return result; } #endif #ifndef HAVE_STRDUP char *port_strdup(const char *s) { char *result = malloc(strlen(s) + 1); if (result == NULL) return NULL; strcpy(result, s); return result; } #endif const char *get_script_env(const ExpNode *script, const char *name) { for (; script != NULL; script = script->next) { if (script->type == EXP_ENV && strcmp(script->un.args->string, name) == 0) return script->un.args->next->string; } return NULL; } /* Check if a format string contains exactly 1 d-type conversion. */ td_bool check_fmt(const char *str) { td_bool percent_seen = td_false; td_bool conversion_seen = td_false; for (; *str != 0; str++) { if (*str == '%') { if (percent_seen) return td_false; if (str[1] == '%') { str++; continue; } percent_seen = td_true; } else if (percent_seen) { if (*str == 'd') { percent_seen = td_false; if (conversion_seen) return td_false; conversion_seen = td_true; } else if (*str < '0' || *str > '9') { return td_false; } } } return !percent_seen && conversion_seen; } int tdrecord_main(int argc, char *argv[]); int tdrerecord_main(int argc, char *argv[]); int tdreplay_main(int argc, char *argv[]); int tdview_main(int argc, char *argv[]); int tdcompare_main(int argc, char *argv[]); int main(int argc, char *argv[]) { char *name = basename(argv[0]); if (strcmp(name, "tdrecord") == 0) return tdrecord_main(argc, argv); if (strcmp(name, "tdreplay") == 0) return tdreplay_main(argc, argv); if (strcmp(name, "tdrerecord") == 0) return tdrerecord_main(argc, argv); if (strcmp(name, "tdview") == 0) return tdview_main(argc, argv); if (strcmp(name, "tdcompare") == 0) return tdcompare_main(argc, argv); fprintf(stderr, "Please use the tdrecord, tdreplay, tdrerecord, tdview, tdcompare symlinks instead of running this executable\n"); return 0; } termdebug-2.2+dfsg/src/common.h000066400000000000000000000154071254722562400165220ustar00rootroot00000000000000/* Copyright (C) 2010,2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 . */ #ifndef COMMON_H #define COMMON_H #include #include #include #include #include #include "replay.h" /* This should be automatically determined from the repository [and is, by the mkdist.sh script] */ #define VERSION_STRING "2.2" #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) #ifndef MIN #define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif /* Define a td_bool type */ typedef enum { td_false, td_true } td_bool; /* Exit program with message, in response to an error. */ #ifdef __GNUC__ void fatal(const char *fmt, ...) __attribute__((format(printf, 1, 2))); #else void fatal(const char *fmt, ...); #endif /* Write to file descriptor, retrying if interrupted by a signal. */ void safe_write(int fd, const void *buffer, size_t size); /* Read from file descriptor, retrying if interrupted by a signal. */ ssize_t safe_read(int fd, char *buffer, size_t size); /* Echo characters to screen, interpreting control characters as ^X. */ void write_echo(const unsigned char *buffer, size_t size); /* Copy the attributes from a file descriptor (pseudo tty) to the actual terminal. */ void copy_attrs_to_terminal(int from); void set_non_block(int fd, const char *descr, td_bool value); /* Open the output file. If *name == NULL, a file is created in directory (if != NULL) or in the cwd. */ FILE *open_output(char **name, const char *directory); void install_signal_handler(int sig, void (*handler)(int), const char *descr); /* Calculate the difference between two timeval structs in miliseconds. */ int timevaldiff(struct timeval origin, struct timeval now); /* Values for bytes sent over the signal_pipe. */ enum { SIGNAL_CHILD, SIGNAL_WINCH }; /* Give the pipe fd's names. */ enum { PIPE_READ, PIPE_WRITE }; extern int signal_pipe[2]; void sigwinch_handler(int param); void sigchld_handler(int param); void save_tty(void); void reset_tty(void); #define HANDLE_SIG_BYTES() { char signal_byte; \ while (safe_read(signal_pipe[PIPE_READ], &signal_byte, 1) == 1) { \ switch (signal_byte) { #define END_HANDLE default: break; }}} /* Directions for copying bytes to/from terminal. NONE is used only for keeping track of the last direction output to file. */ typedef enum { TYPE_NONE, TYPE_INPUT, TYPE_OUTPUT } Type; void init_timestamp(void); /* Write a set of bytes to the output file. */ void write_record(FILE *output, Type dir, int delay, int min_delay, unsigned char *buffer, ssize_t length); /* Copy bytes between tty and pseudo tty, recording the events to output. */ void copy_fd(int from, int to, Type dir, FILE *output); /* Main loop for interactive operation of the child program. */ int interact_loop(int master, pid_t pid, FILE *output, int timeout); /* Write a string to out, using escaping to ensure that it can be read back. */ void write_escaped_string(FILE *out, const char *string, size_t length); /* Check if the current terminal is capable of resizing initiated by a program. */ td_bool detect_resize_capable(void); /* Start the child program. */ pid_t start_client(ExpNode *client, int fd, FILE *log_file); /* getcwd which allocates a large enough buffer. */ char *getcwd_wrapper(void); #define CURRENT_SCRIPT_VERSION 2 void check_script(const char *file_name, ExpNode *script); /* Portable implementation wrappers for openpty, login_tty, forkpty, poll and strdup. Note that these only provide the arguments actually used in the termdebug programs. */ #ifdef HAVE_OPENPTY #if defined(OPENPTY_IN_UTIL_H) #include #include #include #include #elif defined(OPENPTY_IN_LIBUTIL_H) #include #include #include #include #else #include #endif #define port_openpty(_a, _b, _c) openpty((_a), (_b), NULL, NULL, (_c)) #else #include #include int port_openpty(int *master, int *slave, struct winsize *wsz); #endif #ifdef HAVE_LOGIN_TTY #if defined(LOGIN_TTY_IN_UTIL_H) #include #include #elif defined(LOGIN_TTY_IN_LIBUTIL_H) #include #include #include #include #else #include #endif #define port_login_tty(_a) login_tty((_a)) #else int port_login_tty(int fd); #endif #ifdef HAVE_FORKPTY #if defined(FORKPTY_IN_UTIL_H) #include #include #include #include #elif defined(FORKPTY_IN_LIBUTIL_H) #include #include #include #include #else #include #endif #define port_forkpty(_a, _b) forkpty((_a), NULL, NULL, (_b)) #else #include #include pid_t port_forkpty(int *master, struct winsize *wsz); #endif #ifdef HAVE_POLL #include typedef struct pollfd port_pollfd; typedef nfds_t port_nfds_t; #define PORT_POLLIN POLLIN #define PORT_POLLOUT POLLOUT #define PORT_POLLERR POLLERR #define port_poll(_a, _b, _c) poll((_a), (_b), (_c)) #else typedef struct { int fd; short events, revents; } port_pollfd; typedef size_t port_nfds_t; #define PORT_POLLIN (1<<0) #define PORT_POLLOUT (1<<1) #define PORT_POLLERR (1<<2) int port_poll(port_pollfd *fds, port_nfds_t nfds, int timeout); #endif #ifdef HAVE_STRDUP #include #define port_strdup(_a) strdup(_a) #else char *port_strdup(const char *s); #endif /* Retrieve an environment variable from a script. */ const char *get_script_env(const ExpNode *script, const char *name); td_bool check_fmt(const char *str); /* Unfortunately, the system(3) call has been marked as warn_unused_result in some distributions. In our case, we don't care about whether the program we are trying to start actually succeeded, or whether the fork failed. There is nothing we can do about it, and we don't have a good fall back. The only way to stop GCC whining about ignoring the result, is by assigning to a variable, or using the result in some other way. However, if we simply assign the variable, GCC will start whining about the fact that the assigned value is never used. Sigh. So we explicitly tell it to ignore that, by casting it to a void. */ #ifdef __GNUC__ #define ignore_result(x) do { __typeof__(x) _ignore = x; (void) _ignore; } while (0) #else #define ignore_result(x) x #endif #endif termdebug-2.2+dfsg/src/compare.c000066400000000000000000000267331254722562400166570ustar00rootroot00000000000000/* Copyright (C) 2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 #include #include #include #include #include #include #include "common.h" #include "optionMacros.h" #include "replay.h" #include "input.h" #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) #include "write_stringlist.h" #endif static const char *inputA, *inputB; static ExpNode *scriptA, *scriptB; static td_bool stop_on_difference; #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) static td_bool describe; static td_bool visual_compare; static window_t *winA, *winB; #ifdef HAVE_CAIRO static const char *picture_name; static const char *picture_series; #endif #endif // FIXME: add option to check equality of sent strings as well static void printUsage(void) { printf("Usage: tdcompare [OPTIONS] \n"); #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) printf(" -v, --visual-compare Check for visual equality\n"); printf(" -D, --describe Print a description of the first\n" " difference found\n"); #ifdef HAVE_CAIRO printf(" -p, --picture= Write a picture of the differences to\n" " \n"); printf(" -f, --font= Use to show text in picture.\n"); printf(" -W, --cell-width= Use as cell width in picture.\n"); printf(" -H, --cell-height= Use as cell width in picture.\n"); printf(" -P, --picture-series= Create a series of picutes use as\n" " template\n"); printf(" -s, --stop-on-difference Stop when the first visual difference is\n" " found\n"); #endif #endif printf(" -V, --version Print version and copyright information\n"); exit(EXIT_SUCCESS); } static PARSE_FUNCTION(parse_options) OPTIONS OPTION('h', "help", NO_ARG) printUsage(); END_OPTION OPTION('V', "version", NO_ARG) fputs("tdcompare " VERSION_STRING "\nCopyright (C) 2013 G.P. Halkes\nLicensed under the GNU General Public License version 3\n", stdout); /* @copyright */ exit(0); END_OPTION OPTION('v', "visual-compare", NO_ARG) #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) visual_compare = td_true; #else fatal("termdebug was built without (n)curses and/or libunistring, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION OPTION('D', "describe", NO_ARG) #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) describe = td_true; #else fatal("termdebug was built without (n)curses and/or libunistring, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION OPTION('p', "picture", REQUIRED_ARG) #ifdef HAVE_CAIRO picture_name = optArg; #else fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION OPTION('f', "font", REQUIRED_ARG) #ifdef HAVE_CAIRO option_font = optArg; #else fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION OPTION('W', "cell-width", REQUIRED_ARG) #ifdef HAVE_CAIRO PARSE_INT(cell_width, 6, 16); #else fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION OPTION('H', "cell-heigth", REQUIRED_ARG) #ifdef HAVE_CAIRO PARSE_INT(cell_width, 6, 24); #else fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION OPTION('P', "picture-series", REQUIRED_ARG) #ifdef HAVE_CAIRO if (!check_fmt(optArg)) fatal(OPTFMT " argument must have exactly one d-type printf conversion\n", OPTPRARG); picture_series = optArg; #else fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION OPTION('s', "stop-on-difference", NO_ARG) #ifdef HAVE_CAIRO stop_on_difference = td_true; #else fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION DOUBLE_DASH NO_MORE_OPTIONS; END_OPTION fatal("Unknown option " OPTFMT "\n", OPTPRARG); NO_OPTION if (inputA != NULL) { if (inputB != NULL) fatal("More than two recordings specified\n"); inputB = optcurrent; } else { inputA = optcurrent; } END_OPTIONS if (inputA == NULL || inputB == NULL) fatal("Two recordings should be specified\n"); #ifdef HAVE_CAIRO if (picture_series == NULL) stop_on_difference = td_true; #else stop_on_difference = td_true; #endif END_FUNCTION #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) static td_bool advance_script(ExpNode **script, window_t *win) { while (*script != NULL) { switch ((*script)->type) { case EXP_START: case EXP_INTERACT: case EXP_ENV: /* Ignore stuff that isn't relavant to simply viewing the replay. */ break; case EXP_EXPECT: win_write_stringlist(win, (*script)->un.args); break; case EXP_SEND: *script = (*script)->next; return td_true; case EXP_EXPECT_EXIT: *script = (*script)->next; return td_true; case EXP_WINDOW_SIZE: win_resize(win, (*script)->un.size.rows, (*script)->un.size.columns); *script = (*script)->next; return td_true; case EXP_EXPECT_SUSPEND: win_set_paint(win, 0, 0); win_clrtobot(win); return td_true; case EXP_REQUIRE_VERSION: break; default: fatal("Internal error\n"); } *script = (*script)->next; } return td_false; } static void do_visual_compare(void) { td_bool difference_reported = td_false; const char *winAterm, *winBterm; int step_count = 0; init_attr_map(); if ((winA = win_new(24, 80)) == NULL) fatal("Out of memory\n"); if ((winB = win_new(24, 80)) == NULL) fatal("Out of memory\n"); winAterm = get_script_env(scriptA, "TERM"); winBterm = get_script_env(scriptB, "TERM"); if (winAterm == NULL) fatal("Recording %s does not contain a TERM environment variable\n", inputA); if (winBterm == NULL) fatal("Recording %s does not contain a TERM environment variable\n", inputB); if (strcmp(winAterm, winBterm) != 0) fatal("Recordings have a different TERM environment variable\n"); setup_ti_strings(winAterm, get_script_env(scriptA, "LANG")); while (td_true) { if (!advance_script(&scriptA, winA)) break; if (!advance_script(&scriptB, winB)) break; #ifdef HAVE_CAIRO if (picture_series != NULL) { char output_name_buffer[1024]; snprintf(output_name_buffer, sizeof(output_name_buffer), picture_series, step_count); win_write_image(winA, winB, output_name_buffer); } #endif if (!win_compare(winA, winB, describe ? stderr : NULL)) { #ifdef HAVE_CAIRO if (picture_name != NULL) { win_write_image(winA, winB, picture_name); picture_name = NULL; } #endif if (!difference_reported) { fprintf(stderr, "Recordings have different results\n"); difference_reported = td_true; } /* stop_on_difference will be set to false if picture_series == NULL. */ if (stop_on_difference) exit(EXIT_FAILURE); describe = td_false; } step_count++; } if (scriptA != scriptB && !difference_reported) fatal("Recordings have different results\n"); free_attr_map(); } #endif static ExpNode *find_start(ExpNode *script) { for (; script != NULL && script->type != EXP_START; script = script->next) {} return script; } static void compare_expects(void) { StringListNode *stringA = scriptA->un.args; StringListNode *stringB = scriptB->un.args; int stringA_offset = 0; int stringB_offset = 0; int min_length; while (1) { min_length = MIN(stringA->length - stringA_offset, stringB->length - stringB_offset); /* FIXME: explain which string and at which offset */ if (memcmp(stringA->string + stringA_offset, stringB->string + stringB_offset, min_length) != 0) fatal("Different strings expected at %d/%d\n", scriptA->line, scriptB->line); stringA_offset += min_length; if (stringA->length <= stringA_offset) { stringA = stringA->next; stringA_offset = 0; } stringB_offset += min_length; if (stringB->length <= stringB_offset) { stringB = stringB->next; stringB_offset = 0; } if (stringA == NULL && stringB == NULL) { scriptA = scriptA->next; scriptB = scriptB->next; return; } if (stringA == NULL) { /* FIXME: explain which string and at which offset */ if (scriptA->next->type != EXP_EXPECT) fatal("Different strings expected at %d/%d\n", scriptA->line, scriptB->line); scriptA = scriptA->next; stringA = scriptA->un.args; } if (stringB == NULL) { /* FIXME: explain which string and at which offset */ if (scriptB->next->type != EXP_EXPECT) fatal("Different strings expected at %d/%d\n", scriptA->line, scriptB->line); scriptB = scriptB->next; stringB = scriptB->un.args; } } } static void compare(void) { static const char *exp2string[] = { "start", "env", "window_size", "expect", "send", "expect_exit", "interact", "expect_suspend", "require_version" }; scriptA = find_start(scriptA); scriptB = find_start(scriptB); if (scriptA == NULL) fatal("Recording '%s' does not have a start directive\n", inputA); if (scriptB == NULL) fatal("Recording '%s' does not have a start directive\n", inputB); while (scriptA != NULL && scriptB != NULL) { if (scriptA->type != scriptB->type) fatal("Recordings have different actions (%s/%s) at line %d/%d\n", exp2string[scriptA->type], exp2string[scriptB->type], scriptA->line, scriptB->line); switch (scriptA->type) { case EXP_START: case EXP_INTERACT: /* Ignore stuff that isn't relavant to simply viewing the replay. */ break; case EXP_EXPECT: compare_expects(); break; case EXP_SEND: break; case EXP_WINDOW_SIZE: if (scriptA->un.size.columns != scriptB->un.size.columns || scriptA->un.size.rows != scriptB->un.size.rows) fatal("Recordings set different window size (%dx%d/%dx%d) at line %d/%d\n", scriptA->un.size.columns, scriptA->un.size.rows, scriptB->un.size.columns, scriptB->un.size.rows, scriptA->line, scriptB->line); break; case EXP_EXPECT_EXIT: if (scriptA->un.number != scriptB->un.number) fatal("Expecting different exit value (%d/%d) at line %d/%d\n", scriptA->un.number, scriptB->un.number, scriptA->line, scriptB->line); break; case EXP_EXPECT_SUSPEND: break; default: fatal("Internal error\n"); } scriptA = scriptA->next; scriptB = scriptB->next; } } int tdcompare_main(int argc, char *argv[]) { parse_options(argc, argv); reset_lexer(inputA); parse(); scriptA = script; script = NULL; reset_lexer(inputB); parse(); scriptB = script; #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) if (visual_compare) do_visual_compare(); else #endif compare(); return EXIT_SUCCESS; } termdebug-2.2+dfsg/src/curses_handling.c000066400000000000000000000031451254722562400203710ustar00rootroot00000000000000/* Copyright (C) 2010,2012-2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 . */ /* We have all this in a separate file, because the curses header files clutter up the name space too much with macros and what not. This also means we have to duplicate some of the stuf from common.h. */ #include #include #ifdef HAVE_STRDUP #include #define port_strdup(_a) strdup(_a) #else char *port_strdup(const char *s); #endif void reset_tty(void); char *get_ti_string(const char *name) { char *result = tigetstr(name); if (result == (char *) 0 || result == (char *) -1) return NULL; return port_strdup(result); } int get_ti_bool(const char *name) { return tigetflag(name); } void sanitize_term(void) { char *tistr; int errret; if (setupterm(NULL, 1, &errret) == ERR) return; tistr = get_ti_string("rmcup"); if (tistr != NULL) putp(tistr); tistr = get_ti_string("rmacs"); if (tistr != NULL) putp(tistr); tistr = get_ti_string("cvvis"); if (tistr != NULL) putp(tistr); } void call_setupterm(const char *name) { setupterm(name, 1, 0); } termdebug-2.2+dfsg/src/curses_handling.h000066400000000000000000000014641254722562400204000ustar00rootroot00000000000000/* Copyright (C) 2010,2012 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 . */ #ifndef CURSES_HANDLING_H #define CURSES_HANDLING_H char *get_ti_string(const char *name); int get_ti_bool(const char *name); void call_setupterm(const char *name); void sanitize_term(void); #endif termdebug-2.2+dfsg/src/input.c000066400000000000000000000463541254722562400163710ustar00rootroot00000000000000/* THIS FILE HAS BEEN AUTOMATICALLY GENERATED BY LLnextgen. DO NOT EDIT */ #define LL_NTERMINALS 13 #define LL_NSETS 2 #define LL_SSETS 4 #define LLinset(LLx) (LLsets[LLx*LL_SSETS + (LLcsymb/8)] & (1<<(LLcsymb & 7))) #define LL_SCANDONE(LLx) if (LLsymb != LLx) LLerror(LLx); static int LLscnt[LL_NSETS+1], LLtcnt[LL_NTERMINALS]; static int LLcsymb; #include static const char LLsets[] = { '\xFE', '\x0C', '\x00', '\x00', '\x00', '\x13', '\x00', '\x00', 0 }; static const int LLindex[] = { 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; int LLsymb; static int LLreissue; int yylex(void); static int LLlexerWrapper(void) { if (LLreissue == -2 /* LL_NEW_TOKEN */) { return yylex(); } else { int LLretval = LLreissue; LLreissue = -2 /* LL_NEW_TOKEN */; return LLretval; } } void LLmessage(int); static void LLread(void) { LLcsymb = LLindex[(LLsymb = LLlexerWrapper()) + 1]; } static int LLskip(void) { int LL_i; if (LLcsymb >= 0) { if (LLtcnt[LLcsymb] != 0) return 0; for (LL_i = 0; LL_i < LL_NSETS; LL_i++) if (LLscnt[LL_i] != 0 && LLinset(LL_i)) return 0; } for (;;) { LLmessage(0 /* LL_DELETE */); while ((LLcsymb = LLindex[(LLsymb = LLlexerWrapper()) + 1]) < 0) LLmessage(0 /* LL_DELETE */); if (LLtcnt[LLcsymb] != 0) return 1; for (LL_i = 0; LL_i < LL_NSETS; LL_i++) if (LLscnt[LL_i] != 0 && LLinset(LL_i)) return 1; } } static void LLerror(int LLtoken) { if (LLtoken == 256 /* EOFILE */) { LLmessage(-1 /* LL_MISSINGEOF */); while (LLindex[(LLsymb = LLlexerWrapper()) + 1] != 0) /*NOTHING*/ ; return; } LLtcnt[LLindex[LLtoken + 1]]++; LLskip(); LLtcnt[LLindex[LLtoken + 1]]--; if (LLsymb != LLtoken) { LLreissue = LLsymb; LLmessage(LLtoken); } } static const char *LLsymbolTable[] = { "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "'!'", "'\"'", "'#'", "'$'", "'%'", "'&'", "'\''", "'('", "')'", "'*'", "'+'", "','", "'-'", "'.'", "'/'", "'0'", "'1'", "'2'", "'3'", "'4'", "'5'", "'6'", "'7'", "'8'", "'9'", "':'", "';'", "'<'", "'='", "'>'", "'?'", "'@'", "'A'", "'B'", "'C'", "'D'", "'E'", "'F'", "'G'", "'H'", "'I'", "'J'", "'K'", "'L'", "'M'", "'N'", "'O'", "'P'", "'Q'", "'R'", "'S'", "'T'", "'U'", "'V'", "'W'", "'X'", "'Y'", "'Z'", "'['", "'\\'", "']'", "'^'", "'_'", "'`'", "'a'", "'b'", "'c'", "'d'", "'e'", "'f'", "'g'", "'h'", "'i'", "'j'", "'k'", "'l'", "'m'", "'n'", "'o'", "'p'", "'q'", "'r'", "'s'", "'t'", "'u'", "'v'", "'w'", "'x'", "'y'", "'z'", "'{'", "'|'", "'}'", "'~'", "", "'\x80'", "'\x81'", "'\x82'", "'\x83'", "'\x84'", "'\x85'", "'\x86'", "'\x87'", "'\x88'", "'\x89'", "'\x8A'", "'\x8B'", "'\x8C'", "'\x8D'", "'\x8E'", "'\x8F'", "'\x90'", "'\x91'", "'\x92'", "'\x93'", "'\x94'", "'\x95'", "'\x96'", "'\x97'", "'\x98'", "'\x99'", "'\x9A'", "'\x9B'", "'\x9C'", "'\x9D'", "'\x9E'", "'\x9F'", "'\xA0'", "'\xA1'", "'\xA2'", "'\xA3'", "'\xA4'", "'\xA5'", "'\xA6'", "'\xA7'", "'\xA8'", "'\xA9'", "'\xAA'", "'\xAB'", "'\xAC'", "'\xAD'", "'\xAE'", "'\xAF'", "'\xB0'", "'\xB1'", "'\xB2'", "'\xB3'", "'\xB4'", "'\xB5'", "'\xB6'", "'\xB7'", "'\xB8'", "'\xB9'", "'\xBA'", "'\xBB'", "'\xBC'", "'\xBD'", "'\xBE'", "'\xBF'", "'\xC0'", "'\xC1'", "'\xC2'", "'\xC3'", "'\xC4'", "'\xC5'", "'\xC6'", "'\xC7'", "'\xC8'", "'\xC9'", "'\xCA'", "'\xCB'", "'\xCC'", "'\xCD'", "'\xCE'", "'\xCF'", "'\xD0'", "'\xD1'", "'\xD2'", "'\xD3'", "'\xD4'", "'\xD5'", "'\xD6'", "'\xD7'", "'\xD8'", "'\xD9'", "'\xDA'", "'\xDB'", "'\xDC'", "'\xDD'", "'\xDE'", "'\xDF'", "'\xE0'", "'\xE1'", "'\xE2'", "'\xE3'", "'\xE4'", "'\xE5'", "'\xE6'", "'\xE7'", "'\xE8'", "'\xE9'", "'\xEA'", "'\xEB'", "'\xEC'", "'\xED'", "'\xEE'", "'\xEF'", "'\xF0'", "'\xF1'", "'\xF2'", "'\xF3'", "'\xF4'", "'\xF5'", "'\xF6'", "'\xF7'", "'\xF8'", "'\xF9'", "'\xFA'", "'\xFB'", "'\xFC'", "'\xFD'", "'\xFE'", "'\xFF'", "", "env", "start", "window_size", "expect", "send", "expect_exit", "interact", "number", "string", "expect_suspend", "require_version"}; const char *LLgetSymbol(int LLtoken) { if (LLtoken < -1 || LLtoken > 267 /* == LL_MAXTOKNO */) return (char *) 0; return LLsymbolTable[LLtoken+1]; } #include "input.h" #line 18 "input.g" #include #include #include #include "replay.h" #include "common.h" static td_bool start_parsed; static td_bool first_directive; ExpNode *script; extern int line_number; extern const char *file_name; extern char *yytext; void LLmessage(int class) { switch (class) { case LL_MISSINGEOF: fatal("%s:%d: Unexpected %s at end of file\n", file_name, line_number, LLgetSymbol(LLsymb)); case LL_DELETE: fatal("%s:%d: Unexpected %s\n", file_name, line_number, LLgetSymbol(LLsymb)); default: fatal("%s:%d: Expected %s before %s\n", file_name, line_number, LLgetSymbol(class), LLgetSymbol(LLsymb)); } } void *safe_calloc(size_t size) { void *retval = calloc(1, size); if (retval == NULL) fatal("Out of memory while reading script\n"); return retval; } char *safe_strdup_remove_quotes(const char *string) { size_t size; char *retval = strdup(string + 1); if (retval == NULL) fatal("Out of memory while reading script\n"); if ((size = strlen(retval)) > 0) retval[size - 1] = 0; return retval; } /** Convert a string from the input format to an internally usable string. @param string A @a Token with the string to be converted. @param descr A description of the string to be included in error messages. @return The length of the resulting string. The use of this function processes escape characters. The converted characters are written in the original string. */ static size_t parseEscapes(char *string) { size_t maxReadPosition = strlen(string); size_t readPosition = 0, writePosition = 0; size_t i; while(readPosition < maxReadPosition) { if (string[readPosition] == '\\') { readPosition++; if (readPosition == maxReadPosition) fatal("Interal error\n"); switch(string[readPosition++]) { case 'n': string[writePosition++] = '\n'; break; case 'r': string[writePosition++] = '\r'; break; case '\'': string[writePosition++] = '\''; break; case '\\': string[writePosition++] = '\\'; break; case 't': string[writePosition++] = '\t'; break; case 'b': string[writePosition++] = '\b'; break; case 'f': string[writePosition++] = '\f'; break; case 'a': string[writePosition++] = '\a'; break; case 'v': string[writePosition++] = '\v'; break; case '?': string[writePosition++] = '\?'; break; case '"': string[writePosition++] = '"'; break; case 'x': { /* Hexadecimal escapes */ unsigned int value = 0; /* Read at most two characters, or as many as are valid. */ for (i = 0; i < 2 && (readPosition + i) < maxReadPosition && isxdigit(string[readPosition + i]); i++) { value <<= 4; if (isdigit(string[readPosition + i])) value += (int) (string[readPosition + i] - '0'); else value += (int) (tolower(string[readPosition + i]) - 'a') + 10; if (value > UCHAR_MAX) fatal("%s:%d: Invalid hexadecimal escape sequence\n", file_name, line_number); } readPosition += i; if (i == 0) fatal("%s:%d: Invalid hexadecimal escape sequence\n", file_name, line_number); string[writePosition++] = (char) value; break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { /* Octal escapes */ int value = (int)(string[readPosition - 1] - '0'); size_t maxIdx = string[readPosition - 1] < '4' ? 2 : 1; for (i = 0; i < maxIdx && readPosition + i < maxReadPosition && string[readPosition + i] >= '0' && string[readPosition + i] <= '7'; i++) value = value * 8 + (int)(string[readPosition + i] - '0'); readPosition += i; string[writePosition++] = (char) value; break; } default: string[writePosition++] = string[readPosition - 1]; break; } } else { string[writePosition++] = string[readPosition++]; } } /* Terminate string. */ string[writePosition] = 0; return writePosition; } #line 323 "input.c" static void LL0_input(void); static ExpNode * LL1_command(void); static void LL0_input(void){ #line 190 "input.g" ExpNode * #line 329 "input.c" command; memset(&command, 0, sizeof(command)); { #line 172 "input.g" ExpNode **current = &script; start_parsed = td_false; first_directive = td_true; #line 339 "input.c" LLscnt[0]++; switch (LLcsymb) { case 1:/* ENV */ case 2:/* START */ case 3:/* WINDOW_SIZE */ case 4:/* EXPECT */ case 5:/* SEND */ case 6:/* EXPECT_EXIT */ case 7:/* INTERACT */ case 10:/* EXPECT_SUSPEND */ case 11:/* REQUIRE_VERSION */ break; default: LLskip(); break; } LLscnt[0]--; LLscnt[0]++; goto LL_0; for (;;) { LL_1: switch (LLcsymb) { default: if (LLskip()) goto LL_1; break; case 0:/* */ break; case 1:/* ENV */ case 2:/* START */ case 3:/* WINDOW_SIZE */ case 4:/* EXPECT */ case 5:/* SEND */ case 6:/* EXPECT_EXIT */ case 7:/* INTERACT */ case 10:/* EXPECT_SUSPEND */ case 11:/* REQUIRE_VERSION */ LL_0: LLscnt[0]++; command = LL1_command(); #line 179 "input.g" { *current = command; current = &(*current)->next; first_directive = td_false; } #line 383 "input.c" continue; } LLscnt[0]--; break; } #line 185 "input.g" { check_script(file_name, script); } #line 393 "input.c" } } static ExpNode * LL1_command(void){ #line 190 "input.g" ExpNode * #line 399 "input.c" LLretval; memset(&LLretval, 0, sizeof(LLretval)); { #line 190 "input.g" StringListNode **next; LLretval = safe_calloc(sizeof(ExpNode)); next = &LLretval->un.args; #line 409 "input.c" LL_0: switch (LLcsymb) { case 1:/* ENV */ LLscnt[0]--; LLtcnt[9]++; LLtcnt[9]++; LL_SCANDONE(257);/* ENV */ LLread(); LLtcnt[9]--; LL_SCANDONE(265);/* STRING */ #line 197 "input.g" { if (start_parsed) fatal("%s:%d: env directive after start directive\n", file_name, line_number); LLretval->type = EXP_ENV; LLretval->line = line_number; *next = safe_calloc(sizeof(StringListNode)); (*next)->string = safe_strdup_remove_quotes(yytext); next = &(*next)->next; } #line 430 "input.c" LLread(); LLtcnt[9]--; LL_SCANDONE(265);/* STRING */ #line 207 "input.g" { *next = safe_calloc(sizeof(StringListNode)); (*next)->string = safe_strdup_remove_quotes(yytext); (*next)->length = parseEscapes((*next)->string); } #line 440 "input.c" LLread(); break; case 11:/* REQUIRE_VERSION */ LLscnt[0]--; LLtcnt[8]++; LL_SCANDONE(267);/* REQUIRE_VERSION */ LLread(); LLtcnt[8]--; LL_SCANDONE(264);/* NUMBER */ #line 215 "input.g" { if (!first_directive) fatal("%s:%d: require_version directive should be the first directive in the recording\n", file_name, line_number); LLretval->type = EXP_REQUIRE_VERSION; LLretval->line = line_number; LLretval->un.number = atoi(yytext); if (LLretval->un.number < 1) fatal("%s:%d: lowest possible require_version is 1\n", file_name, line_number); } #line 460 "input.c" LLread(); break; case 2:/* START */ LLscnt[0]--; LLtcnt[9]++; LL_SCANDONE(258);/* START */ #line 226 "input.g" { if (start_parsed) fatal("%s:%d: Multiple start directives specified\n", file_name, line_number); start_parsed = td_true; LLretval->type = EXP_START; LLretval->line = line_number; } #line 475 "input.c" LLread(); switch (LLcsymb) { case 9:/* STRING */ break; default: LLskip(); break; } LLtcnt[9]--; LLtcnt[9]++; goto LL_1; for (;;) { LL_2: switch (LLcsymb) { default: if (LLskip()) goto LL_2; break; case 0:/* */ case 1:/* ENV */ case 2:/* START */ case 3:/* WINDOW_SIZE */ case 4:/* EXPECT */ case 5:/* SEND */ case 6:/* EXPECT_EXIT */ case 7:/* INTERACT */ case 10:/* EXPECT_SUSPEND */ case 11:/* REQUIRE_VERSION */ break; case 9:/* STRING */ LL_1: LL_SCANDONE(265);/* STRING */ #line 235 "input.g" { *next = safe_calloc(sizeof(StringListNode)); (*next)->string = safe_strdup_remove_quotes(yytext); (*next)->length = parseEscapes((*next)->string); next = &(*next)->next; } #line 512 "input.c" LLread(); continue; } LLtcnt[9]--; break; } break; case 3:/* WINDOW_SIZE */ LLscnt[0]--; LLtcnt[8]++; LLtcnt[8]++; LLtcnt[8]++; LL_SCANDONE(259);/* WINDOW_SIZE */ LLread(); LLtcnt[8]--; LL_SCANDONE(264);/* NUMBER */ #line 245 "input.g" { LLretval->type = EXP_WINDOW_SIZE; LLretval->line = line_number; LLretval->un.size.columns = atoi(yytext); } #line 535 "input.c" LLread(); LLtcnt[8]--; LL_SCANDONE(264);/* NUMBER */ #line 251 "input.g" { LLretval->un.size.rows = atoi(yytext); } #line 543 "input.c" LLread(); LL_3: switch (LLcsymb) { default: if (LLskip()) goto LL_3; LLtcnt[8]--; break; case 0:/* */ case 1:/* ENV */ case 2:/* START */ case 3:/* WINDOW_SIZE */ case 4:/* EXPECT */ case 5:/* SEND */ case 6:/* EXPECT_EXIT */ case 7:/* INTERACT */ case 10:/* EXPECT_SUSPEND */ case 11:/* REQUIRE_VERSION */ LLtcnt[8]--; break; case 8:/* NUMBER */ LLtcnt[8]--; LLtcnt[12]++; LL_SCANDONE(264);/* NUMBER */ #line 256 "input.g" { LLretval->un.size.delay = atoi(yytext); } #line 571 "input.c" LLread(); LL_4: switch (LLcsymb) { default: if (LLskip()) goto LL_4; LLtcnt[12]--; break; case 0:/* */ case 1:/* ENV */ case 2:/* START */ case 3:/* WINDOW_SIZE */ case 4:/* EXPECT */ case 5:/* SEND */ case 6:/* EXPECT_EXIT */ case 7:/* INTERACT */ case 10:/* EXPECT_SUSPEND */ case 11:/* REQUIRE_VERSION */ LLtcnt[12]--; break; case 12:/* '>' */ LLtcnt[12]--; LLtcnt[8]++; LL_SCANDONE(62);/* '>' */ LLread(); LLtcnt[8]--; LL_SCANDONE(264);/* NUMBER */ #line 262 "input.g" { LLretval->un.size.min_delay = atoi(yytext); if (LLretval->un.size.min_delay > LLretval->un.size.delay) LLretval->un.size.min_delay = LLretval->un.size.delay; } #line 604 "input.c" LLread(); } } break; case 4:/* EXPECT */ LLscnt[0]--; LLtcnt[9]++; LL_SCANDONE(260);/* EXPECT */ #line 271 "input.g" { if (!start_parsed) fatal("%s:%d: expect directive before start directive\n", file_name, line_number); LLretval->type = EXP_EXPECT; LLretval->line = line_number; } #line 620 "input.c" LLread(); switch (LLcsymb) { case 9:/* STRING */ break; default: LLskip(); break; } LLtcnt[9]--; LLtcnt[9]++; goto LL_5; for (;;) { LL_6: switch (LLcsymb) { default: if (LLskip()) goto LL_6; break; case 0:/* */ case 1:/* ENV */ case 2:/* START */ case 3:/* WINDOW_SIZE */ case 4:/* EXPECT */ case 5:/* SEND */ case 6:/* EXPECT_EXIT */ case 7:/* INTERACT */ case 10:/* EXPECT_SUSPEND */ case 11:/* REQUIRE_VERSION */ break; case 9:/* STRING */ LL_5: LL_SCANDONE(265);/* STRING */ #line 279 "input.g" { *next = safe_calloc(sizeof(StringListNode)); (*next)->string = safe_strdup_remove_quotes(yytext); (*next)->length = parseEscapes((*next)->string); next = &(*next)->next; } #line 657 "input.c" LLread(); continue; } LLtcnt[9]--; break; } break; case 5:/* SEND */ LLscnt[0]--; LLscnt[1]++; LL_SCANDONE(261);/* SEND */ #line 288 "input.g" { if (!start_parsed) fatal("%s:%d: send directive before start directive\n", file_name, line_number); LLretval->type = EXP_SEND; LLretval->line = line_number; } #line 676 "input.c" LLread(); switch (LLcsymb) { case 8:/* NUMBER */ break; default: LLskip(); break; } LLscnt[1]--; LLtcnt[8]++; goto LL_7; for (;;) { LL_8: switch (LLcsymb) { default: if (LLskip()) goto LL_8; break; case 0:/* */ case 1:/* ENV */ case 2:/* START */ case 3:/* WINDOW_SIZE */ case 4:/* EXPECT */ case 5:/* SEND */ case 6:/* EXPECT_EXIT */ case 7:/* INTERACT */ case 10:/* EXPECT_SUSPEND */ case 11:/* REQUIRE_VERSION */ break; case 8:/* NUMBER */ LL_7: LLtcnt[12]++; LLtcnt[9]++; LL_SCANDONE(264);/* NUMBER */ #line 296 "input.g" { *next = safe_calloc(sizeof(StringListNode)); (*next)->delay = atoi(yytext); } #line 713 "input.c" LLread(); LL_9: switch (LLcsymb) { default: if (LLskip()) goto LL_9; LLtcnt[12]--; break; case 9:/* STRING */ LLtcnt[12]--; break; case 12:/* '>' */ LLtcnt[12]--; LLtcnt[8]++; LL_SCANDONE(62);/* '>' */ LLread(); LLtcnt[8]--; LL_SCANDONE(264);/* NUMBER */ #line 303 "input.g" { (*next)->min_delay = atoi(yytext); if ((*next)->delay < (*next)->min_delay) (*next)->min_delay = (*next)->delay; } #line 737 "input.c" LLread(); } LLtcnt[9]--; LL_SCANDONE(265);/* STRING */ #line 310 "input.g" { (*next)->string = safe_strdup_remove_quotes(yytext); (*next)->length = parseEscapes((*next)->string); next = &(*next)->next; } #line 748 "input.c" LLread(); continue; } LLtcnt[8]--; break; } break; case 6:/* EXPECT_EXIT */ LLscnt[0]--; LLtcnt[8]++; LL_SCANDONE(262);/* EXPECT_EXIT */ LLread(); LLtcnt[8]--; LL_SCANDONE(264);/* NUMBER */ #line 319 "input.g" { if (!start_parsed) fatal("%s:%d: expect_exit directive before start directive\n", file_name, line_number); LLretval->type = EXP_EXPECT_EXIT; LLretval->line = line_number; LLretval->un.number = atoi(yytext); } #line 771 "input.c" LLread(); break; default: if (LLskip()) goto LL_0; /*FALLTHROUGH*/ case 10:/* EXPECT_SUSPEND */ LLscnt[0]--; LL_SCANDONE(266);/* EXPECT_SUSPEND */ #line 328 "input.g" { if (!start_parsed) fatal("%s:%d: expect_suspend directive before start directive\n", file_name, line_number); LLretval->type = EXP_EXPECT_SUSPEND; LLretval->line = line_number; } #line 788 "input.c" LLread(); break; case 7:/* INTERACT */ LLscnt[0]--; LL_SCANDONE(263);/* INTERACT */ #line 336 "input.g" { if (!start_parsed) fatal("%s:%d: interact directive before start directive\n", file_name, line_number); LLretval->type = EXP_INTERACT; LLretval->line = line_number; } #line 801 "input.c" LLread(); break; } } return LLretval; } void parse(void) { memset(LLscnt, 0, LL_NSETS * sizeof(int)); memset(LLtcnt, 0, LL_NTERMINALS * sizeof(int)); LLtcnt[0]++; LLsymb = 0; LLreissue = -2 /* LL_NEW_TOKEN */; LLread(); LL0_input(); if (LLcsymb != 0) LLerror(256 /* EOFILE*/); } termdebug-2.2+dfsg/src/input.g000066400000000000000000000206671254722562400163740ustar00rootroot00000000000000/* Copyright (C) 2010-2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 . */ %options "generate-lexer-wrapper generate-symbol-table lowercase-symbols"; %start parse, input; { #include #include #include #include "replay.h" #include "common.h" static td_bool start_parsed; static td_bool first_directive; ExpNode *script; extern int line_number; extern const char *file_name; extern char *yytext; void LLmessage(int class) { switch (class) { case LL_MISSINGEOF: fatal("%s:%d: Unexpected %s at end of file\n", file_name, line_number, LLgetSymbol(LLsymb)); case LL_DELETE: fatal("%s:%d: Unexpected %s\n", file_name, line_number, LLgetSymbol(LLsymb)); default: fatal("%s:%d: Expected %s before %s\n", file_name, line_number, LLgetSymbol(class), LLgetSymbol(LLsymb)); } } void *safe_calloc(size_t size) { void *retval = calloc(1, size); if (retval == NULL) fatal("Out of memory while reading script\n"); return retval; } char *safe_strdup_remove_quotes(const char *string) { size_t size; char *retval = strdup(string + 1); if (retval == NULL) fatal("Out of memory while reading script\n"); if ((size = strlen(retval)) > 0) retval[size - 1] = 0; return retval; } /** Convert a string from the input format to an internally usable string. @param string A @a Token with the string to be converted. @param descr A description of the string to be included in error messages. @return The length of the resulting string. The use of this function processes escape characters. The converted characters are written in the original string. */ static size_t parseEscapes(char *string) { size_t maxReadPosition = strlen(string); size_t readPosition = 0, writePosition = 0; size_t i; while(readPosition < maxReadPosition) { if (string[readPosition] == '\\') { readPosition++; if (readPosition == maxReadPosition) fatal("Interal error\n"); switch(string[readPosition++]) { case 'n': string[writePosition++] = '\n'; break; case 'r': string[writePosition++] = '\r'; break; case '\'': string[writePosition++] = '\''; break; case '\\': string[writePosition++] = '\\'; break; case 't': string[writePosition++] = '\t'; break; case 'b': string[writePosition++] = '\b'; break; case 'f': string[writePosition++] = '\f'; break; case 'a': string[writePosition++] = '\a'; break; case 'v': string[writePosition++] = '\v'; break; case '?': string[writePosition++] = '\?'; break; case '"': string[writePosition++] = '"'; break; case 'x': { /* Hexadecimal escapes */ unsigned int value = 0; /* Read at most two characters, or as many as are valid. */ for (i = 0; i < 2 && (readPosition + i) < maxReadPosition && isxdigit(string[readPosition + i]); i++) { value <<= 4; if (isdigit(string[readPosition + i])) value += (int) (string[readPosition + i] - '0'); else value += (int) (tolower(string[readPosition + i]) - 'a') + 10; if (value > UCHAR_MAX) fatal("%s:%d: Invalid hexadecimal escape sequence\n", file_name, line_number); } readPosition += i; if (i == 0) fatal("%s:%d: Invalid hexadecimal escape sequence\n", file_name, line_number); string[writePosition++] = (char) value; break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { /* Octal escapes */ int value = (int)(string[readPosition - 1] - '0'); size_t maxIdx = string[readPosition - 1] < '4' ? 2 : 1; for (i = 0; i < maxIdx && readPosition + i < maxReadPosition && string[readPosition + i] >= '0' && string[readPosition + i] <= '7'; i++) value = value * 8 + (int)(string[readPosition + i] - '0'); readPosition += i; string[writePosition++] = (char) value; break; } default: string[writePosition++] = string[readPosition - 1]; break; } } else { string[writePosition++] = string[readPosition++]; } } /* Terminate string. */ string[writePosition] = 0; return writePosition; } } %token ENV, START, WINDOW_SIZE, EXPECT, SEND, EXPECT_EXIT, INTERACT, NUMBER, STRING, EXPECT_SUSPEND, REQUIRE_VERSION; input { ExpNode **current = &script; start_parsed = td_false; first_directive = td_true; } : [ command { *current = command; current = &(*current)->next; first_directive = td_false; } ]+ { check_script(file_name, script); } ; command { StringListNode **next; LLretval = safe_calloc(sizeof(ExpNode)); next = &LLretval->un.args; } : ENV STRING { if (start_parsed) fatal("%s:%d: env directive after start directive\n", file_name, line_number); LLretval->type = EXP_ENV; LLretval->line = line_number; *next = safe_calloc(sizeof(StringListNode)); (*next)->string = safe_strdup_remove_quotes(yytext); next = &(*next)->next; } STRING { *next = safe_calloc(sizeof(StringListNode)); (*next)->string = safe_strdup_remove_quotes(yytext); (*next)->length = parseEscapes((*next)->string); } | REQUIRE_VERSION NUMBER { if (!first_directive) fatal("%s:%d: require_version directive should be the first directive in the recording\n", file_name, line_number); LLretval->type = EXP_REQUIRE_VERSION; LLretval->line = line_number; LLretval->un.number = atoi(yytext); if (LLretval->un.number < 1) fatal("%s:%d: lowest possible require_version is 1\n", file_name, line_number); } | START { if (start_parsed) fatal("%s:%d: Multiple start directives specified\n", file_name, line_number); start_parsed = td_true; LLretval->type = EXP_START; LLretval->line = line_number; } [ STRING { *next = safe_calloc(sizeof(StringListNode)); (*next)->string = safe_strdup_remove_quotes(yytext); (*next)->length = parseEscapes((*next)->string); next = &(*next)->next; } ]+ | WINDOW_SIZE NUMBER { LLretval->type = EXP_WINDOW_SIZE; LLretval->line = line_number; LLretval->un.size.columns = atoi(yytext); } NUMBER { LLretval->un.size.rows = atoi(yytext); } [ NUMBER { LLretval->un.size.delay = atoi(yytext); } [ '>' NUMBER { LLretval->un.size.min_delay = atoi(yytext); if (LLretval->un.size.min_delay > LLretval->un.size.delay) LLretval->un.size.min_delay = LLretval->un.size.delay; } ]? ]? | EXPECT { if (!start_parsed) fatal("%s:%d: expect directive before start directive\n", file_name, line_number); LLretval->type = EXP_EXPECT; LLretval->line = line_number; } [ STRING { *next = safe_calloc(sizeof(StringListNode)); (*next)->string = safe_strdup_remove_quotes(yytext); (*next)->length = parseEscapes((*next)->string); next = &(*next)->next; } ]+ | SEND { if (!start_parsed) fatal("%s:%d: send directive before start directive\n", file_name, line_number); LLretval->type = EXP_SEND; LLretval->line = line_number; } [ NUMBER { *next = safe_calloc(sizeof(StringListNode)); (*next)->delay = atoi(yytext); } [ '>' NUMBER { (*next)->min_delay = atoi(yytext); if ((*next)->delay < (*next)->min_delay) (*next)->min_delay = (*next)->delay; } ]? STRING { (*next)->string = safe_strdup_remove_quotes(yytext); (*next)->length = parseEscapes((*next)->string); next = &(*next)->next; } ]+ | EXPECT_EXIT NUMBER { if (!start_parsed) fatal("%s:%d: expect_exit directive before start directive\n", file_name, line_number); LLretval->type = EXP_EXPECT_EXIT; LLretval->line = line_number; LLretval->un.number = atoi(yytext); } | EXPECT_SUSPEND { if (!start_parsed) fatal("%s:%d: expect_suspend directive before start directive\n", file_name, line_number); LLretval->type = EXP_EXPECT_SUSPEND; LLretval->line = line_number; } | INTERACT { if (!start_parsed) fatal("%s:%d: interact directive before start directive\n", file_name, line_number); LLretval->type = EXP_INTERACT; LLretval->line = line_number; } ; termdebug-2.2+dfsg/src/input.h000066400000000000000000000011421254722562400163600ustar00rootroot00000000000000/* THIS FILE HAS BEEN AUTOMATICALLY GENERATED BY LLnextgen. DO NOT EDIT */ #ifndef __LLNEXTGEN_LL_H__ #define __LLNEXTGEN_LL_H__ #ifndef LL_NOTOKENS #define EOFILE 256 #define ENV 257 #define START 258 #define WINDOW_SIZE 259 #define EXPECT 260 #define SEND 261 #define EXPECT_EXIT 262 #define INTERACT 263 #define NUMBER 264 #define STRING 265 #define EXPECT_SUSPEND 266 #define REQUIRE_VERSION 267 #endif #define LL_MAXTOKNO 267 #define LL_MISSINGEOF (-1) #define LL_DELETE (0) #define LL_VERSION 0x000505L #define LL_NEW_TOKEN (-2) void parse(void); const char *LLgetSymbol(int); extern int LLsymb; #endif termdebug-2.2+dfsg/src/input_lex.c000066400000000000000000001365631254722562400172430ustar00rootroot00000000000000#line 2 ".objects/input_lex.c" #line 4 ".objects/input_lex.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include #include #include #include /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have . Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart(yyin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif extern int yyleng; extern FILE *yyin, *yyout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when yytext is formed. */ static char yy_hold_char; static int yy_n_chars; /* number of characters read into yy_ch_buf */ int yyleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = (char *) 0; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow yywrap()'s to do buffer switches * instead of setting up a fresh yyin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void yyrestart (FILE *input_file ); void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ); YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ); void yy_delete_buffer (YY_BUFFER_STATE b ); void yy_flush_buffer (YY_BUFFER_STATE b ); void yypush_buffer_state (YY_BUFFER_STATE new_buffer ); void yypop_buffer_state (void ); static void yyensure_buffer_stack (void ); static void yy_load_buffer_state (void ); static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ); #define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ) YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ); YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ); YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len ); void *yyalloc (yy_size_t ); void *yyrealloc (void *,yy_size_t ); void yyfree (void * ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define yywrap(n) 1 #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; typedef int yy_state_type; extern int yylineno; int yylineno = 1; extern char *yytext; #define yytext_ptr yytext static yy_state_type yy_get_previous_state (void ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); static int yy_get_next_buffer (void ); static void yy_fatal_error (yyconst char msg[] ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ yyleng = (size_t) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 17 #define YY_END_OF_BUFFER 18 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[79] = { 0, 0, 0, 18, 16, 1, 2, 16, 3, 13, 15, 16, 16, 16, 16, 16, 0, 14, 0, 3, 13, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 5, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 6, 0, 0, 0, 0, 10, 0, 12, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 4, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 1, 1, 9, 1, 10, 1, 11, 12, 13, 1, 1, 1, 14, 1, 1, 1, 1, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 1, 26, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[27] = { 0, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int16_t yy_base[81] = { 0, 0, 0, 94, 95, 95, 95, 23, 0, 87, 95, 13, 77, 78, 16, 76, 26, 95, 86, 0, 82, 64, 69, 64, 66, 68, 72, 66, 95, 67, 66, 56, 65, 57, 63, 63, 54, 58, 95, 50, 54, 48, 58, 48, 95, 42, 56, 53, 50, 53, 19, 40, 51, 39, 33, 35, 95, 33, 41, 40, 33, 39, 25, 29, 32, 29, 34, 95, 33, 25, 95, 29, 29, 30, 20, 95, 20, 95, 95, 39, 32 } ; static yyconst flex_int16_t yy_def[81] = { 0, 78, 1, 78, 78, 78, 78, 79, 80, 78, 78, 78, 78, 78, 78, 78, 79, 78, 79, 80, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 0, 78, 78 } ; static yyconst flex_int16_t yy_nxt[122] = { 0, 4, 5, 6, 7, 8, 9, 10, 4, 4, 4, 4, 4, 11, 12, 4, 4, 4, 4, 13, 14, 4, 4, 4, 15, 4, 4, 17, 21, 25, 17, 18, 54, 19, 18, 77, 76, 26, 22, 55, 16, 16, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 20, 78, 27, 24, 23, 20, 78, 3, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78 } ; static yyconst flex_int16_t yy_chk[122] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 7, 11, 14, 16, 7, 50, 80, 16, 76, 74, 14, 11, 50, 79, 79, 73, 72, 71, 69, 68, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 55, 54, 53, 52, 51, 49, 48, 47, 46, 45, 43, 42, 41, 40, 39, 37, 36, 35, 34, 33, 32, 31, 30, 29, 27, 26, 25, 24, 23, 22, 21, 20, 18, 15, 13, 12, 9, 3, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78 } ; static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; extern int yy_flex_debug; int yy_flex_debug = 0; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET char *yytext; #line 1 "input_lex.l" /* Copyright (C) 2010,2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 . */ #line 16 "input_lex.l" #include #include #include #include "replay.h" #include "common.h" #include "input.h" int line_number; const char *file_name; #define YY_NO_INPUT 1 #line 535 ".objects/input_lex.c" #define INITIAL 0 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals (void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy (void ); int yyget_debug (void ); void yyset_debug (int debug_flag ); YY_EXTRA_TYPE yyget_extra (void ); void yyset_extra (YY_EXTRA_TYPE user_defined ); FILE *yyget_in (void ); void yyset_in (FILE * in_str ); FILE *yyget_out (void ); void yyset_out (FILE * out_str ); int yyget_leng (void ); char *yyget_text (void ); int yyget_lineno (void ); void yyset_lineno (int line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap (void ); #else extern int yywrap (void ); #endif #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void ); #else static int input (void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int yylex (void); #define YY_DECL int yylex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; #line 29 "input_lex.l" #line 722 ".objects/input_lex.c" if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_load_buffer_state( ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of yytext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 79 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 95 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: YY_RULE_SETUP #line 30 "input_lex.l" YY_BREAK case 2: /* rule 2 can match eol */ YY_RULE_SETUP #line 31 "input_lex.l" line_number++; YY_BREAK case 3: YY_RULE_SETUP #line 32 "input_lex.l" YY_BREAK case 4: YY_RULE_SETUP #line 33 "input_lex.l" return ENV; YY_BREAK case 5: YY_RULE_SETUP #line 34 "input_lex.l" return START; YY_BREAK case 6: YY_RULE_SETUP #line 35 "input_lex.l" return WINDOW_SIZE; YY_BREAK case 7: YY_RULE_SETUP #line 36 "input_lex.l" return EXPECT; YY_BREAK case 8: YY_RULE_SETUP #line 37 "input_lex.l" return SEND; YY_BREAK case 9: YY_RULE_SETUP #line 38 "input_lex.l" return EXPECT_EXIT; YY_BREAK case 10: YY_RULE_SETUP #line 39 "input_lex.l" return EXPECT_SUSPEND; YY_BREAK case 11: YY_RULE_SETUP #line 40 "input_lex.l" return INTERACT; YY_BREAK case 12: YY_RULE_SETUP #line 41 "input_lex.l" return REQUIRE_VERSION; YY_BREAK case 13: YY_RULE_SETUP #line 42 "input_lex.l" return NUMBER; YY_BREAK case 14: /* rule 14 can match eol */ YY_RULE_SETUP #line 43 "input_lex.l" { int i; for (i = 0; i < yyleng; i++) if (yytext[i] == '\n') line_number++; return STRING; } YY_BREAK case 15: YY_RULE_SETUP #line 44 "input_lex.l" return '>'; YY_BREAK case 16: YY_RULE_SETUP #line 45 "input_lex.l" fatal("%s:%d: Unexpected character '%c'\n", file_name, line_number, yytext[0]); YY_BREAK case 17: YY_RULE_SETUP #line 47 "input_lex.l" YY_FATAL_ERROR( "flex scanner jammed" ); YY_BREAK #line 892 ".objects/input_lex.c" case YY_STATE_EOF(INITIAL): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_c_buf_p); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( yywrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = (yytext_ptr); register int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), (size_t) num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart(yyin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { register yy_state_type yy_current_state; register char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 79 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { register int yy_is_jam; register char *yy_cp = (yy_c_buf_p); register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 79 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 78); return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ int offset = (yy_c_buf_p) - (yytext_ptr); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart(yyin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap( ) ) return EOF; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve yytext */ (yy_hold_char) = *++(yy_c_buf_p); return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void yyrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ); } yy_init_buffer(YY_CURRENT_BUFFER,input_file ); yy_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void yy_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer(b,file ); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * */ void yy_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yyfree((void *) b->yy_ch_buf ); yyfree((void *) b ); } #ifndef __cplusplus extern int isatty (int ); #endif /* __cplusplus */ /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; yy_flush_buffer(b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void yy_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == NULL) return; yyensure_buffer_stack(); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void yypop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { yy_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void yyensure_buffer_stack (void) { int num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer(b ); return b; } /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (yyconst char * yystr ) { return yy_scan_bytes(yystr,strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, int _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) yyalloc(n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer(buf,n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg ) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = (yy_hold_char); \ (yy_c_buf_p) = yytext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ int yyget_lineno (void) { return yylineno; } /** Get the input stream. * */ FILE *yyget_in (void) { return yyin; } /** Get the output stream. * */ FILE *yyget_out (void) { return yyout; } /** Get the length of the current token. * */ int yyget_leng (void) { return yyleng; } /** Get the current token. * */ char *yyget_text (void) { return yytext; } /** Set the current line number. * @param line_number * */ void yyset_lineno (int line_number ) { yylineno = line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * * @see yy_switch_to_buffer */ void yyset_in (FILE * in_str ) { yyin = in_str ; } void yyset_out (FILE * out_str ) { yyout = out_str ; } int yyget_debug (void) { return yy_flex_debug; } void yyset_debug (int bdebug ) { yy_flex_debug = bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ (yy_buffer_stack) = 0; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = (char *) 0; (yy_init) = 0; (yy_start) = 0; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(); } /* Destroy the stack itself. */ yyfree((yy_buffer_stack) ); (yy_buffer_stack) = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals( ); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s ) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *yyalloc (yy_size_t size ) { return (void *) malloc( size ); } void *yyrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void yyfree (void * ptr ) { free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 47 "input_lex.l" void reset_lexer(const char *new_file_name) { if (yyin != NULL) fclose(yyin); if (new_file_name == NULL) return; if ((yyin = fopen(new_file_name, "r")) == NULL) fatal("Can't open input %s: %s\n", new_file_name, strerror(errno)); file_name = new_file_name; line_number = 1; } termdebug-2.2+dfsg/src/input_lex.l000066400000000000000000000035551254722562400172460ustar00rootroot00000000000000/* Copyright (C) 2010,2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 #include #include #include "replay.h" #include "common.h" #include "input.h" int line_number; const char *file_name; %} %option noyywrap nodefault nounput noinput %% [ \t] \n line_number++; #.* env return ENV; start return START; window_size return WINDOW_SIZE; expect return EXPECT; send return SEND; expect_exit return EXPECT_EXIT; expect_suspend return EXPECT_SUSPEND; interact return INTERACT; require_version return REQUIRE_VERSION; [0-9]+ return NUMBER; \"([^\\"]|\\.)*\" { int i; for (i = 0; i < yyleng; i++) if (yytext[i] == '\n') line_number++; return STRING; } > return '>'; . fatal("%s:%d: Unexpected character '%c'\n", file_name, line_number, yytext[0]); %% void reset_lexer(const char *new_file_name) { if (yyin != NULL) fclose(yyin); if (new_file_name == NULL) return; if ((yyin = fopen(new_file_name, "r")) == NULL) fatal("Can't open input %s: %s\n", new_file_name, strerror(errno)); file_name = new_file_name; line_number = 1; } termdebug-2.2+dfsg/src/optionMacros.h000066400000000000000000000251131254722562400177020ustar00rootroot00000000000000/* Copyright (C) 2006-2009,2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 . */ #ifndef OPTIONMACROS_H #define OPTIONMACROS_H #include #include #include #include /* INSTRUCTIONS: - A fatal routine should be provided. - If gettext is required, define the _ macro. Otherwise, the empty definition here will be used. However, if the macro USE_GETTEXT is defined, the automatic definition in this file will not be used to make sure a wrong order of definitions is detected. - Option parsing may change the argument vector. If this should not happen, define the macro OPTION_STRDUP such that it allocates a copy of the string passed to it. - The current option (or the non-option argument) is available in the variable optcurrent. Arguments to options are stored in optArg. - Printing options should be done by using the "%.*s" format and "(int) optlength, optcurrent" arguments or even better, the OPTFMT format macro and OPTPRARG arg. - Checking the current option can be delegated to a child parser. This can be defined by using CHILD_PARSE_FUNCTION (forward declaraction by CHILD_PARSE_FUNCTION_DECL). To attempt checking with the child parser, use the macro CALL_CHILD. If the child parser handles the option, no further option checks will be done. A simple example argument parser is shown below: PARSE_FUNCTION(parse_options) OPTIONS OPTION('f', "long-f", REQUIRED_ARG) END_OPTION DOUBLE_DASH NO_MORE_OPTIONS; END_OPTION printf("Unknown option " OPTFMT "\n", OPTPRARG); NO_OPTION printf("Non-option argument: %s\n", optcurrent); END_OPTIONS END_FUNCTION */ /* Definitions to make the macro's work regardless of configuration. */ #if !defined _ && !defined USE_GETTEXT #define _(_x) (_x) #endif #ifndef OPTION_STRDUP #define OPTION_STRDUP(_x) (_x) #define OPTION_FREE(_x) (void) optptr #else #define OPTION_FREE(_x) free(_x) #endif /** Format string for printing options. */ #define OPTFMT "%.*s" /** Arguments for printf style functions, to be used in combination with @a OPTFMT. */ #define OPTPRARG (int) optlength, optcurrent /** Define an option parsing function. @param name The name of the function to define. */ #define PARSE_FUNCTION(name) void name(int argc, char **argv) {\ char *optArg; \ int optargind; \ int optnomore = 0; /** Declare a child option parsing function. @param name The name of the function to define. */ #define CHILD_PARSE_FUNCTION_DECL(name) int name(int argc, char **argv, char *optcurrent, char *optArg, size_t optlength, ArgType opttype, int _optargind); /** Define a child option parsing function. @param name The name of the function to define. */ #define CHILD_PARSE_FUNCTION(name) int name(int argc, char **argv, char *optcurrent, char *optArg, size_t optlength, ArgType opttype, int _optargind) { \ int optargind = _optargind, optcontrol = 0; /** Signal the end of a child option parsing function. */ #define END_CHILD_FUNCTION return -1; check_next: if (optargind != _optargind) return 4; return optcontrol; } /** Call a child option parsing function. @param name The name of the function to call. */ #define CALL_CHILD(name) do { int retval = name(argc, argv, optcurrent, optArg, optlength, opttype, optargind); \ if (retval == -1) break; \ else if (retval == 4) optargind++; \ else if (retval == 1) optcontrol++; \ goto check_next; } while (0) /** Indicate the start of option processing. This is separate from @a PARSE_FUNCTION so that local variables can be defined. */ #define OPTIONS \ for (optargind = 1; optargind < argc; optargind++) { \ char optcontrol = 0; \ char *optcurrent, *optptr; \ optcurrent = argv[optargind]; \ if (optcurrent[0] == '-' && !optnomore) { \ size_t optlength; \ ArgType opttype; \ \ if (optcurrent[1] == '-') { \ if ((optArg = strchr(optcurrent, '=')) == NULL) { \ optlength = strlen(optcurrent); \ } else { \ optlength = optArg - optcurrent; \ optArg++; \ } \ opttype = LONG; \ } else { \ optlength = 2; \ if (optcurrent[1] != 0 && optcurrent[2] != 0) \ optArg = optcurrent + 2; \ else \ optArg = NULL; \ opttype = SHORT; \ } \ if (optlength > INT_MAX) optlength = INT_MAX; \ next_opt: /* The last line above is to make sure the cast to int in error messages does not overflow. */ /** Signal the start of non-switch option processing. */ #define NO_OPTION } else { /** Signal the end of option processing. */ #define END_OPTIONS check_next: if (optcontrol == 1 || optcontrol == 3) { \ if (optcontrol == 1) { \ optptr = optcurrent = OPTION_STRDUP(optcurrent); \ } \ optcontrol = 2; \ optcurrent++; \ optcurrent[0] = '-'; \ optArg = optcurrent[2] != 0 ? optcurrent + 2 : NULL; \ goto next_opt; \ } else if (optcontrol == 2) { \ OPTION_FREE(optptr); \ } }} goto stop_opt_parse; stop_opt_parse:; /** Signal the end of the option processing function. */ #define END_FUNCTION } /** Internal macro to check whether the requirements regarding option arguments have been met. */ #define CHECK_ARG(argReq) \ switch(argReq) { \ case NO_ARG: \ if (optArg != NULL) { \ if (opttype == SHORT) { \ optcontrol++; \ optArg = NULL; \ } else { \ fatal(_("Option " OPTFMT " does not take an argument\n"), OPTPRARG); \ } \ } \ break; \ case REQUIRED_ARG: \ if (optArg == NULL && (optargind+1 >= argc)) { \ fatal(_("Option " OPTFMT " requires an argument\n"), OPTPRARG); \ } \ if (optArg == NULL) optArg = argv[++optargind]; \ break; \ default: \ break; \ } /** Check for a short style (-o) option. @param shortName The name of the short style option. @param argReq Whether or not an argument is required/allowed. One of NO_ARG, OPTIONAL_ARG or REQUIRED_ARG. */ #define SHORT_OPTION(shortName, argReq) if (opttype == SHORT && optcurrent[1] == shortName) { CHECK_ARG(argReq) { /** Check for a single dash as option. This is usually used to signal standard input/output. */ #define SINGLE_DASH SHORT_OPTION('\0', NO_ARG) /** Check for a double dash as option. This is usually used to signal the end of options. */ #define DOUBLE_DASH LONG_OPTION("", NO_ARG) /** Check for a short style (-o) or long style (--option) option. @param shortName The name of the short style option. @param longName The name of the long style option. @param argReq Whether or not an argument is required/allowed. One of NO_ARG, OPTIONAL_ARG or REQUIRED_ARG. */ #define OPTION(shortName, longName, argReq) if ((opttype == SHORT && optcurrent[1] == shortName) || (opttype == LONG && strlen(longName) == optlength - 2 && strncmp(optcurrent + 2, longName, optlength - 2) == 0)) { CHECK_ARG(argReq) { /** Check for a long style (--option) option. @param longName The name of the long style option. @param argReq Whether or not an argument is required/allowed. One of NO_ARG, OPTIONAL_ARG or REQUIRED_ARG. */ #define LONG_OPTION(longName, argReq) if (opttype == LONG && strlen(longName) == optlength - 2 && strncmp(optcurrent + 2, longName, optlength - 2) == 0) { CHECK_ARG(argReq) { /** Signal the end of processing for the previous (SHORT_|LONG_)OPTION. */ #define END_OPTION } goto check_next; } /** Check for presence of a short style (-o) option and set the variable if so. @param shortName The name of the short style option. @param var The variable to set. */ #define BOOLEAN_SHORT_OPTION(shortName, var) SHORT_OPTION(shortName, NO_ARG) var = 1; END_OPTION /** Check for presence of a long style (--option) option and set the variable if so. @param longName The name of the long style option. @param var The variable to set. */ #define BOOLEAN_LONG_OPTION(longName, var) LONG_OPTION(longName, NO_ARG) var = 1; END_OPTION /** Check for presence of a short style (-o) or long style (--option) option and set the variable if so. @param shortName The name of the short style option. @param longName The name of the long style option. @param var The variable to set. */ #define BOOLEAN_OPTION(shortName, longName, var) OPTION(shortName, longName, NO_ARG) var = 1; END_OPTION /** Tell option processor that all further arguments are non-option arguments. */ #define NO_MORE_OPTIONS do { optnomore = 1; } while(0) /** Tell option processor to jump out of option processing. */ #define STOP_OPTION_PROCESSING do { goto stop_opt_parse; } while(0) /** Check an option argument for an integer value. @param var The variable to store the result in. @param min The minimum allowable value. @param max The maximum allowable value. */ #define PARSE_INT(var, min, max) do {\ char *endptr; \ long value; \ errno = 0; \ \ value = strtol(optArg, &endptr, 10); \ if (*endptr != 0) { \ fatal(_("Garbage after value for " OPTFMT " option\n"), OPTPRARG); \ } \ if (errno != 0 || value < min || value > max) { \ fatal(_("Value for " OPTFMT " option (%ld) is out of range\n"), OPTPRARG, value); \ } \ var = (int) value; } while(0) /** Check an option argument for a double value. @param var The variable to store the result in. @param min The minimum allowable value. @param max The maximum allowable value. */ #define PARSE_DOUBLE(var, min, max) do {\ char *endptr; \ double value; \ errno = 0; \ \ value = strtod(optArg, &endptr); \ if (*endptr != 0) { \ fatal(_("Garbage after value for " OPTFMT " option\n"), OPTPRARG); \ } \ if (errno != 0 || value < min || value > max) { \ fatal(_("Value for " OPTFMT " option (%f) is out of range\n"), OPTPRARG, value); \ } \ var = value; } while(0) /** Check an option argument for a boolean value. @param var The variable to store the result in. */ #define PARSE_BOOLEAN(var) do {\ if (optArg == NULL || strcmp(optArg, "true") == 0 || strcmp(optArg, "t") == 0 || strcmp(optArg, "yes") == 0 || \ strcmp(optArg, "y") == 0 || strcmp(optArg, "1") == 0) \ (var) = 1; \ else if (strcmp(optArg, "false") == 0 || strcmp(optArg, "f") == 0 || strcmp(optArg, "no") == 0 || \ strcmp(optArg, "n") == 0 || strcmp(optArg, "0") == 0) \ (var) = 0; \ else \ fatal(_("Value for " OPTFMT " option (%s) is not a valid boolean value\n"), OPTPRARG, optArg); \ } while (0) typedef enum { SHORT, LONG } ArgType; enum { NO_ARG, OPTIONAL_ARG, REQUIRED_ARG }; #endif termdebug-2.2+dfsg/src/picture_queue.c000066400000000000000000000060561254722562400201040ustar00rootroot00000000000000/* Copyright (C) 2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 #include "common.h" #include "window.h" extern const char *picture_series; typedef struct picture_queue_t picture_queue_t; struct picture_queue_t { window_t *winA, *winB; char *name; picture_queue_t *next; }; static picture_queue_t *picture_queue_head, *picture_queue_tail; static pthread_t picture_thread; static pthread_mutex_t picture_queue_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t picture_queue_cond = PTHREAD_COND_INITIALIZER; static td_bool finished; void enqueue_pictures(window_t *winA, window_t *winB, const char *name) { picture_queue_t *item = malloc(sizeof(picture_queue_t)); if (item == NULL) return; item->winA = win_copy(winA); item->winB = win_copy(winB); item->name = port_strdup(name); item->next = NULL; if (item->winA == NULL || item->winB == NULL || item->name == NULL) { win_del(item->winA); win_del(item->winB); free(item->name); free(item); return; } pthread_mutex_lock(&picture_queue_lock); if (picture_queue_head == NULL) { picture_queue_head = picture_queue_tail = item; } else { picture_queue_tail->next = item; picture_queue_tail = item; } pthread_cond_signal(&picture_queue_cond); pthread_mutex_unlock(&picture_queue_lock); } static void *picture_writer_thead(void *arg) { picture_queue_t *tmp; (void) arg; pthread_mutex_lock(&picture_queue_lock); pthread_cond_signal(&picture_queue_cond); do { if (picture_queue_head == NULL) pthread_cond_wait(&picture_queue_cond, &picture_queue_lock); tmp = picture_queue_head; if (picture_queue_head != NULL) picture_queue_head = picture_queue_head->next; pthread_mutex_unlock(&picture_queue_lock); if (tmp != NULL) { win_write_image(tmp->winA, tmp->winB, tmp->name); win_del(tmp->winA); win_del(tmp->winB); free(tmp); } pthread_mutex_lock(&picture_queue_lock); } while (!finished || picture_queue_head != NULL); pthread_mutex_unlock(&picture_queue_lock); return NULL; } static void join_picture_thread(void) { void *retval; pthread_mutex_lock(&picture_queue_lock); finished = td_true; pthread_cond_signal(&picture_queue_cond); pthread_mutex_unlock(&picture_queue_lock); pthread_join(picture_thread, &retval); } void start_picture_writer_thread(void) { pthread_mutex_lock(&picture_queue_lock); pthread_create(&picture_thread, NULL, picture_writer_thead, NULL); pthread_cond_wait(&picture_queue_cond, &picture_queue_lock); pthread_mutex_unlock(&picture_queue_lock); atexit(join_picture_thread); } termdebug-2.2+dfsg/src/picture_queue.h000066400000000000000000000014201254722562400200770ustar00rootroot00000000000000/* Copyright (C) 2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 . */ #ifndef PICTURE_QUEUE_H #define PICTURE_QUEUE_H void start_picture_writer_thread(void); void enqueue_pictures(window_t *winA, window_t *winB, const char *name); #endif termdebug-2.2+dfsg/src/record.c000066400000000000000000000120751254722562400165010ustar00rootroot00000000000000/* Copyright (C) 2010,2012 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 #include #include #include #include #include #include #include #include "optionMacros.h" #include "common.h" /* TODO: - if we want to allow interact in replay, we may well best integrate replay and record in one program, or split out common code - we could try using TIOCPKT to see whether that could solve our problems with wrong input modes (see tty_ioctl) - should we try to copy tcattrs between consequtive reads/writes from/to pty? */ static char *output, *environment; static const char *directory; static int prog_start_index = -1; static FILE *output_file; static int allow_x11; static void printUsage(void) { printf("Usage: tdrecord [OPTIONS] []\n"); printf(" -d,--directory= Save recording in directory \n"); printf(" -e,--environment= Save environment variables \n"); printf(" -o,--output= Save recording as \n"); printf(" -V, --version Print version and copyright information\n"); printf(" -X, --allow-x11 Don't clear the DISPLAY environment variable\n"); printf(" (allows communication with X11)\n"); exit(EXIT_SUCCESS); } static PARSE_FUNCTION(parse_options) OPTIONS OPTION('d', "directory", REQUIRED_ARG) directory = optArg; END_OPTION OPTION('e', "environment", REQUIRED_ARG) environment = optArg; END_OPTION OPTION('o', "output", REQUIRED_ARG) output = optArg; END_OPTION OPTION('h', "help", NO_ARG) printUsage(); END_OPTION OPTION('V', "version", NO_ARG) fputs("tdrecord " VERSION_STRING "\nCopyright (C) 2010,2012 G.P. Halkes\nLicensed under the GNU General Public License version 3\n", stdout); /* @copyright */ exit(0); END_OPTION OPTION('X', "allow-x11", NO_ARG) allow_x11 = 1; END_OPTION DOUBLE_DASH NO_MORE_OPTIONS; END_OPTION fatal("Unknown option " OPTFMT "\n", OPTPRARG); NO_OPTION NO_MORE_OPTIONS; if (prog_start_index < 0) prog_start_index = optargind; END_OPTIONS END_FUNCTION static void save_env(const char *var) { const char *value = getenv(var); if (value != NULL) { fprintf(output_file, "env \"%s\" ", var); write_escaped_string(output_file, value, strlen(value)); fputc('\n', output_file); } } int tdrecord_main(int argc, char *argv[]) { struct winsize wsz, *wsz_setting; int master, status, i; char *cwd_buffer; pid_t pid; if (!isatty(STDIN_FILENO)) fatal("Can only record from terminal devices\n"); parse_options(argc, argv); if (prog_start_index < 0) fatal("No program specified\n"); output_file = open_output(&output, directory); fprintf(output_file, "# Recorded with working directory %s\n", cwd_buffer = getcwd_wrapper()); free(cwd_buffer); save_env("TERM"); save_env("LINES"); save_env("COLUMS"); save_env("LANG"); save_env("LC_CTYPE"); if (environment != NULL) { char *var; for (var = strtok(environment, ","); var != NULL; var = strtok(NULL, ",")) save_env(var); } init_timestamp(); install_signal_handler(SIGWINCH, sigwinch_handler, "SIGWINCH"); install_signal_handler(SIGCHLD, sigchld_handler, "SIGCHLD"); /* Get terminal size. */ if (ioctl(STDIN_FILENO, TIOCGWINSZ, &wsz) < 0) { fprintf(stderr, "Warning: could not obtain window size: %s\n", strerror(errno)); wsz_setting = NULL; } else { fprintf(output_file, "window_size %d %d\n", wsz.ws_col, wsz.ws_row); wsz_setting = &wsz; } /* Write the program and its arguments to the recording */ fputs("start", output_file); for (i = prog_start_index; i < argc; i++) { fputc(' ', output_file); write_escaped_string(output_file, argv[i], strlen(argv[i])); } fputc('\n', output_file); if ((pid = port_forkpty(&master, wsz_setting)) < 0) fatal("forkpty failed: %s\n", strerror(errno)); if (pid == 0) { /* Slave side: start proces */ if (!allow_x11) /* Don't want program to communicate with X11 server for modifier states. */ unsetenv("DISPLAY"); execvp(argv[prog_start_index], argv + prog_start_index); unlink(output); fatal("Error executing process: %s\n", strerror(errno)); } save_tty(); set_non_block(master, "pty", td_true); set_non_block(STDIN_FILENO, "terminal", td_true); set_non_block(signal_pipe[PIPE_READ], "pipe", td_true); status = interact_loop(master, pid, output_file, -1); fclose(output_file); reset_tty(); fprintf(stderr, "-- recording is saved in %s --\n", output); exit(WEXITSTATUS(status)); } termdebug-2.2+dfsg/src/replay.c000066400000000000000000000651211254722562400165170ustar00rootroot00000000000000/* Copyright (C) 2010,2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 #include #include #include #include #include #include #include #include #include #include #include "optionMacros.h" #include "common.h" #include "replay.h" #include "input.h" #ifdef HAVE_CURSES #include "curses_handling.h" #ifdef HAVE_UNISTRING #include "write_stringlist.h" #if defined(HAVE_CAIRO) && defined(HAVE_PTHREAD) #include "picture_queue.h" #endif #endif #endif /* TODO: - add the posibility to require keypress for next send event (except 0 delay events) - it may be a good idea to have a simultaneous replay mode such that one can verify wether the visual results are still the same. This would require some form of synchronisation between multiple instances of the replay program. - restore the terminal size after completing the replay. This should be done the same for the view program. - the information requests to the terminal may cause more problems: different version of the same terminal may respond differently. That would mean that the output may look slightly off. That is not so much of a problem. What is a problem though is that we should clear the input buffer before switching to interact mode. Furthermore, if we wish to rerecord for the new version of the terminal, we need the proper response and not the recorded one. This may require some new construct to make replay aware of this. - allow user to specify different client to start from the command line - should we allow some way to return to the original script after an interact command? */ #define BUFFER_SIZE 1024 typedef enum { ON_ERROR_ABORT, ON_ERROR_INTERACT, ON_ERROR_CONTINUE } OnError; static FILE *log_file; static char *input; static char *alert; static double key_delay_scale = 1.0; static double key_delay; static td_bool display; static OnError on_error = ON_ERROR_ABORT; static td_bool no_resize; static const char *log_name; #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) static td_bool visual_compare; static td_bool describe; #ifdef HAVE_CAIRO static const char *picture_name; #ifdef HAVE_PTHREAD static const char *picture_series; #endif #endif #endif static td_bool resize_capable; static td_bool exited; static int status; static struct timeval timestamp; static int master; static pid_t pid; static int already_waited; static port_pollfd fdset[2]; #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) static window_t *expectWin, *realWin; #endif static void printUsage(void) { printf("Usage: tdreplay [OPTIONS] \n"); printf(" -a, --alert= Run on error\n"); printf(" -d, --display Show the output of the running program\n"); printf(" -e, --on-error= On error perform (one of\n" " interact, continue, abort)\n"); printf(" -k, --key-delay= Set key delay\n"); printf(" -l, --log= Save a log file to \n"); printf(" -R, --no-resize Do not try to resize the terminal\n"); #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) printf(" -v, --visual-compare Check for visual equality\n"); printf(" -D, --describe Print a description of the first visual difference found\n"); #ifdef HAVE_CAIRO printf(" -p, --picture= Write a picture of the differences to \n" " (only valid with -v)\n"); printf(" -f, --font= Use to show text in picture.\n"); printf(" -W, --cell-width= Use as cell width in picture.\n"); printf(" -H, --cell-height= Use as cell width in picture.\n"); #ifdef HAVE_PTHREAD printf(" -P, --picture-series= Create a series of picutes use as template\n"); #endif #endif #endif printf(" -V, --version Print version and copyright information\n"); exit(EXIT_SUCCESS); } static PARSE_FUNCTION(parse_options) OPTIONS OPTION('a', "alert", REQUIRED_ARG) alert = optArg; END_OPTION OPTION('d', "display", NO_ARG) display = td_true; END_OPTION OPTION('e', "on-error", REQUIRED_ARG) if (strcmp(optArg, "interact") == 0) { on_error = ON_ERROR_INTERACT; } else if (strcmp(optArg, "continue") == 0) { on_error = ON_ERROR_CONTINUE; } else if (strcmp(optArg, "abort") == 0) { on_error = ON_ERROR_ABORT; } else { fatal("Invalid argument for on-error option: %s\n", optArg); } END_OPTION OPTION('k', "key-delay", REQUIRED_ARG) while (*optArg && isspace(*optArg)) optArg++; if (optArg[0] == '/') { optArg++; PARSE_DOUBLE(key_delay_scale, DBL_MIN, DBL_MAX); key_delay = 0; } else if (isdigit(*optArg)) { PARSE_INT(key_delay, 1, INT_MAX); key_delay_scale = 1.0; } else { fatal("Invalid argument for key-delay option: %s\n", optArg); } END_OPTION OPTION('l', "log", REQUIRED_ARG) log_name = optArg; END_OPTION OPTION('R', "no-resize", NO_ARG) no_resize = td_true; END_OPTION OPTION('v', "visual-compare", NO_ARG) #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) visual_compare = td_true; #else fatal("termdebug was built without (n)curses and/or libunistring, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION OPTION('p', "picture", REQUIRED_ARG) #ifdef HAVE_CAIRO if (picture_name != NULL) fatal("Option " OPTFMT " specified twice\n", OPTPRARG); picture_name = optArg; #else fatal("termdebug was built without cairo, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION OPTION('f', "font", REQUIRED_ARG) #ifdef HAVE_CAIRO option_font = optArg; #else fatal("termdebug was built without cairo, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION OPTION('W', "cell-width", REQUIRED_ARG) #ifdef HAVE_CAIRO PARSE_INT(cell_width, 6, 16); #else fatal("termdebug was built without cairo, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION OPTION('H', "cell-heigth", REQUIRED_ARG) #ifdef HAVE_CAIRO PARSE_INT(cell_width, 6, 24); #else fatal("termdebug was built without cairo, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION OPTION('P', "picture-series", REQUIRED_ARG) #ifndef HAVE_CAIRO fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG); #else #ifndef HAVE_PTHREAD fatal("termdebug was built without pthreads, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG); #else if (!check_fmt(optArg)) fatal(OPTFMT " argument must have exactly one d-type printf conversion\n", OPTPRARG); picture_series = optArg; #endif #endif END_OPTION OPTION('D', "describe", NO_ARG) #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) describe = td_true; #else fatal("termdebug was built without (n)curses and/or libunistring, and therefore tdreplay does not provide " OPTFMT "\n", OPTPRARG); #endif END_OPTION OPTION('h', "help", NO_ARG) printUsage(); END_OPTION OPTION('V', "version", NO_ARG) fputs("tdreplay " VERSION_STRING "\nCopyright (C) 2010,2013 G.P. Halkes\nLicensed under the GNU General Public License version 3\n", stdout); /* @copyright */ exit(0); END_OPTION DOUBLE_DASH NO_MORE_OPTIONS; END_OPTION fatal("Unknown option " OPTFMT "\n", OPTPRARG); NO_OPTION if (input != NULL) fatal("More than one recording specified\n"); input = optcurrent; END_OPTIONS if (input == NULL) fatal("No recording specified\n"); #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) && defined(HAVE_CAIRO) && defined(HAVE_PTHREAD) if (picture_series != NULL && !visual_compare) fatal("Picture series can only be generated in visual compare mode\n"); #endif END_FUNCTION static void interact(void); static void end_client(void) { kill(pid, SIGTERM); /* Give client time to respond to SIGTERM */ while (port_poll(fdset + 1, 1, 2000) < 0) {} HANDLE_SIG_BYTES() case SIGNAL_CHILD: if (waitpid(pid, &status, WNOHANG) == pid) return; break; END_HANDLE kill(pid, SIGKILL); waitpid(pid, &status, WNOHANG); } static void unexpected(const char *reason, const char *received, size_t recv_length, int line, ...) { (void) reason; if (alert != NULL) { /* Add reason to the environment to allow the user to be notified of the problem. */ setenv("REASON", reason, 1); ignore_result(system(alert)); /* Only alert user once. */ alert = NULL; } if (log_file != NULL) { va_list args; fprintf(log_file, "!! "); va_start(args, line); vfprintf(log_file, reason, args); va_end(args); if (received) { fprintf(log_file, ": \n"); write_escaped_string(log_file, received, recv_length); } else { fprintf(log_file, "\n"); } } switch (on_error) { case ON_ERROR_ABORT: { va_list args; end_client(); /* Reset tty to show message. */ if (display) { #ifdef HAVE_CURSES sanitize_term(); #endif reset_tty(); putc('\n', stderr); } fprintf(stderr, "Different behaviour from client at line %d: ", line); va_start(args, line); vfprintf(stderr, reason, args); va_end(args); exit(EXIT_FAILURE); } case ON_ERROR_INTERACT: interact(); /* We should not even get here, but just to make sure */ exit(EXIT_SUCCESS); case ON_ERROR_CONTINUE: break; default: fatal("Internal error\n"); } } static void unexpected_death(void) { if (alert != NULL) ignore_result(system(alert)); if (log_file != NULL) fprintf(log_file, "!! Client stopped unexpectedly with status: %d\n", WEXITSTATUS(status)); /* Reset tty to show message. */ if (display) reset_tty(); fprintf(stderr, "Client stopped unexpectedly with status: %d\n", WEXITSTATUS(status)); exit(EXIT_FAILURE); } static void handle_signals(ExpNode *exp, const char *activity) { if (fdset[1].revents & PORT_POLLIN) { HANDLE_SIG_BYTES() case SIGNAL_CHILD: if (waitpid(pid, &status, WNOHANG | WUNTRACED) == pid) { unexpected("Process stopped unexpectedly while waiting %s", NULL, 0, exp->line, activity); if (WIFSTOPPED(status)) { if (display) { printf("Process has stopped. Will send continue signal in 3 seconds\n"); sleep(3); } kill(pid, SIGCONT); } else { unexpected_death(); } } break; END_HANDLE } } static void handle_client_output(ExpNode *exp, const char *activity) { if (fdset[0].revents & PORT_POLLIN) { char buffer[BUFFER_SIZE]; ssize_t result; result = safe_read(master, buffer, sizeof(buffer)); if (result <= 0) return; if (display) safe_write(STDOUT_FILENO, buffer, result); unexpected("Received unexpected output while waiting %s", buffer, result, exp->line, activity); } } static void set_window_size_internal(ExpNode *size) { struct winsize wsz; memset(&wsz, 0, sizeof(wsz)); if (log_file != NULL) fprintf(log_file, "Changing window size to: %d %d\n", size->un.size.columns, size->un.size.rows); if (display && resize_capable && !no_resize) { char buffer[64]; size_t result; result = sprintf(buffer, "\x1b[8;%d;%dt", size->un.size.rows, size->un.size.columns); safe_write(STDOUT_FILENO, buffer, result); } wsz.ws_col = size->un.size.columns; wsz.ws_row = size->un.size.rows; if (ioctl(master, TIOCSWINSZ, &wsz)) fatal("Error setting window size: %s\n", strerror(errno)); } static void set_window_size(ExpNode *size) { ssize_t result; int delay; struct timeval start, now; if (size->un.size.min_delay > 0) delay = size->un.size.min_delay; else if (key_delay) delay = key_delay; else delay = size->un.size.delay / key_delay_scale; if (delay < 0 || delay < already_waited) { set_window_size_internal(size); already_waited = 0; return; } gettimeofday(&start, NULL); while (1) { result = port_poll(fdset, 2, delay - already_waited); if (result == -1) { if (errno != EINTR) fatal("Error during poll: %s\n", strerror(errno)); } handle_signals(size, "to resize window"); if (display) copy_attrs_to_terminal(master); gettimeofday(&now, NULL); already_waited += timevaldiff(start, now); if (result == 0 || delay <= already_waited) { set_window_size_internal(size); already_waited = 0; return; } else { handle_client_output(size, "to resize window"); } } } static int get_next_delay(ExpNode *exp, int *min_delay) { *min_delay = 0; for (; exp != NULL; exp = exp->next) { if (exp->type == EXP_WINDOW_SIZE) { return exp->un.size.delay; } else if (exp->type == EXP_SEND) { if (exp->un.args->min_delay > 0) *min_delay = exp->un.args->min_delay; return exp->un.args->delay; } } return -1; } static void expect(ExpNode *exp) { static td_bool first_expect = td_true; StringListNode *current = exp->un.args; int todo = current->length; char buffer[BUFFER_SIZE]; ssize_t result; struct timeval start, now; int remaining_timeout, timeout, min_delay; if (log_file != NULL) { fprintf(log_file, "Expecting client output: \n"); write_escaped_string(log_file, current->string, current->length); fprintf(log_file, "\n"); } if (key_delay) { timeout = get_next_delay(exp, &min_delay); if (key_delay < timeout || timeout < 0) timeout = key_delay; if (timeout < 10) timeout = 10; } else { timeout = get_next_delay(exp, &min_delay); timeout /= key_delay_scale; if (timeout < 10) timeout = 10; } if (min_delay > timeout) timeout = min_delay; remaining_timeout = timeout; /* The first time we try to read from the socket, we are faced with a problem: the program start up time must be taken into account. Sometimes the program may be slow to start, which would normally cause the timeout to pass before the program is even started. Thus we cheat, and set the initial timeout to a full second, and then reset the start time to the first return from poll. */ if (first_expect) remaining_timeout = 1000; gettimeofday(&start, NULL); while (current != NULL && remaining_timeout > 0) { result = port_poll(fdset, 2, remaining_timeout); if (result == -1) { if (errno != EINTR) fatal("Error during poll: %s\n", strerror(errno)); continue; } /* See comment above. */ if (first_expect) { first_expect = td_false; gettimeofday(&start, NULL); } handle_signals(exp, "for output"); if (display) copy_attrs_to_terminal(master); if (result == 0) { unexpected("No output received within timeout\n", NULL, 0, exp->line); return; } else if (fdset[0].revents & PORT_POLLIN) { /* Read data from the client */ result = safe_read(master, buffer, MIN((int) sizeof(buffer), todo)); if (result <= 0) continue; if (display) safe_write(STDOUT_FILENO, buffer, result); /* Check that the data read from the client matches what we expect */ if (memcmp(buffer, current->string + current->length - todo, result) == 0) { todo -= result; /* Prepare next string to wait for. The while loop takes care of empty strings. */ while (todo == 0 && current != NULL) { current = current->next; if (current == NULL && exp->next != NULL && exp->next->type == EXP_EXPECT) { exp = exp->next; current = exp->un.args; } if (current != NULL) { todo = current->length; if (log_file != NULL) { fprintf(log_file, "Expecting client output:\n"); write_escaped_string(log_file, current->string, current->length); fprintf(log_file, "\n"); } } } } else { unexpected("Different output received then expected", buffer, result, exp->line); } } gettimeofday(&now, NULL); remaining_timeout = timeout - timevaldiff(start, now); } if (current != NULL) { if (log_file != NULL) { fprintf(log_file, "Remaining expected client output:\n"); write_escaped_string(log_file, current->string + current->length - todo, todo); fprintf(log_file, "\n"); } unexpected("Differences after timeout", NULL, 0, exp->line); } already_waited = timevaldiff(start, now); } #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) static void visual_expect(ExpNode *exp) { static td_bool first_expect = td_true; char buffer[BUFFER_SIZE]; ssize_t result; struct timeval start, now; int remaining_timeout, timeout, min_delay; td_bool do_handle_signals = td_true; win_write_stringlist(expectWin, exp->un.args); if (log_file != NULL) { StringListNode *string; fprintf(log_file, "Expecting client output:\n"); string = exp->un.args; while (string != NULL) { for (; string != NULL; string = string->next) { write_escaped_string(log_file, string->string, string->length); fprintf(log_file, "\n"); } if (exp->next != NULL && exp->next->type == EXP_EXPECT) { exp = exp->next; string = exp->un.args; } } } if (log_file != NULL) fprintf(log_file, "Received client output:\n"); if (key_delay) { timeout = get_next_delay(exp, &min_delay); if (timeout == -1) do_handle_signals = td_false; if (key_delay < timeout || timeout < 0) timeout = key_delay; if (timeout < 10) timeout = 10; } else { timeout = get_next_delay(exp, &min_delay); if (timeout == -1) do_handle_signals = td_false; timeout /= key_delay_scale; if (timeout < 10) timeout = 10; } if (min_delay > timeout) timeout = min_delay; remaining_timeout = timeout; /* The first time we try to read from the socket, we are faced with a problem: the program start up time must be taken into account. Sometimes the program may be slow to start, which would normally cause the timeout to pass before the program is even started. Thus we cheat, and set the initial timeout to a full second, and then reset the start time to the first return from poll. */ if (first_expect) remaining_timeout = 1000; gettimeofday(&start, NULL); while (remaining_timeout > 0) { result = port_poll(fdset, 2, remaining_timeout); /* See comment above. */ if (first_expect) { first_expect = td_false; gettimeofday(&start, NULL); } if (result == -1) { if (errno != EINTR) fatal("Error during poll: %s\n", strerror(errno)); continue; } if (display) copy_attrs_to_terminal(master); if (fdset[0].revents & PORT_POLLIN) { /* Read data from the client */ result = safe_read(master, buffer, sizeof(buffer)); if (result <= 0) continue; if (display) safe_write(STDOUT_FILENO, buffer, result); win_write_data(realWin, buffer, result); if (log_file != NULL) { write_escaped_string(log_file, buffer, result); fprintf(log_file, "\n"); } } if (fdset[1].revents & PORT_POLLIN) { if (do_handle_signals) handle_signals(exp, "for output"); else break; } gettimeofday(&now, NULL); remaining_timeout = timeout - timevaldiff(start, now); } #if defined(HAVE_CAIRO) && defined(HAVE_PTHREAD) if (picture_series != NULL) { static int step_count = 1; char output_name_buffer[1024]; snprintf(output_name_buffer, sizeof(output_name_buffer), picture_series, step_count++); enqueue_pictures(expectWin, realWin, output_name_buffer); } #endif if (!win_compare(expectWin, realWin, describe ? stderr : NULL)) { #ifdef HAVE_CAIRO if (picture_name != NULL) #ifdef HAVE_PTHREAD enqueue_pictures(expectWin, realWin, picture_name); #else win_write_image(expectWin, realWin, picture_name); #endif #endif unexpected("Visual differences after timeout", NULL, 0, exp->line); describe = td_false; } already_waited = timevaldiff(start, now); } #endif static void send_keys(ExpNode *keys) { StringListNode *current = keys->un.args; ssize_t result; while (current != NULL) { int delay; /* Calculate the delay that has to be taken into account before sending the key(s) to the application. */ if (current->delay - already_waited < 5) { /* The delay is so small, just send now before the terminal decides to continue. This should solve issues like the one with vi, which sends information requests to the terminal and then doesn't wait for the response. */ if (display) copy_attrs_to_terminal(master); if (log_file != NULL) { fprintf(log_file, "Sending key(s): "); write_escaped_string(log_file, current->string, current->length); fprintf(log_file, "\n"); } safe_write(master, current->string, current->length); current = current->next; already_waited = 0; continue; } else if (key_delay) { delay = key_delay; } else { delay = current->delay / key_delay_scale; } if (delay < current->min_delay - already_waited) delay = current->min_delay - already_waited; already_waited = 0; result = port_poll(fdset, 2, delay); if (result == -1) { if (errno != EINTR) fatal("Error during poll: %s\n", strerror(errno)); } handle_signals(keys, "to send key(s)"); if (display) copy_attrs_to_terminal(master); if (result == 0) { if (log_file != NULL) { fprintf(log_file, "Sending key(s): "); write_escaped_string(log_file, current->string, current->length); fprintf(log_file, "\n"); } safe_write(master, current->string, current->length); current = current->next; } else { handle_client_output(keys, "to send key(s)"); } } } static void handle_exit(ExpNode *exit_data) { if (WEXITSTATUS(status) != exit_data->un.number) { if (alert != NULL) ignore_result(system(alert)); if (log_file != NULL) fprintf(log_file, "!! Program ended with different status: %d iso %d\n", WEXITSTATUS(status), exit_data->un.number); exit(EXIT_FAILURE); } if (log_file != NULL) fprintf(log_file, "Program ended with expected status: %d\n", exit_data->un.number); exit(EXIT_SUCCESS); } static void expect_signal(ExpNode *signal_data) { ssize_t result; if (log_file != NULL) fprintf(log_file, "Waiting for exit\n"); while (1) { result = port_poll(fdset, 2, -1); if (result == -1) { if (errno != EINTR) fatal("Error during poll: %s\n", strerror(errno)); } if (fdset[1].revents & PORT_POLLIN) { HANDLE_SIG_BYTES() case SIGNAL_CHILD: if (waitpid(pid, &status, WNOHANG | WUNTRACED) == pid) { if (WIFSTOPPED(status)) { if (signal_data->type == EXP_EXPECT_EXIT) unexpected("Process stopped unexpectedly while waiting for exit", NULL, 0, signal_data->line); if (display) { printf("Process has stopped. Will send continue signal in 3 seconds\n"); sleep(3); } kill(pid, SIGCONT); if (signal_data->type == EXP_EXPECT_SUSPEND) return; } else { if (signal_data->type == EXP_EXPECT_EXIT) handle_exit(signal_data); else unexpected_death(); } } break; END_HANDLE } if (display) copy_attrs_to_terminal(master); handle_client_output(signal_data, signal_data->type == EXP_EXPECT_EXIT ? "for exit" : "for suspend"); } } static void interact(void) { copy_attrs_to_terminal(master); interact_loop(master, pid, NULL, -1); exit(EXIT_SUCCESS); } int tdreplay_main(int argc, char *argv[]) { #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) struct winsize wsz; #endif int slave; parse_options(argc, argv); if (display && !isatty(STDIN_FILENO)) fatal("Can only replay to a terminal devices\n"); if (log_name != NULL) { if ((log_file = fopen(log_name, "w")) == NULL) fatal("Can't open log: %s\n", strerror(errno)); /* FIXME: do we want this?? setvbuf(log_file, NULL, _IONBF, 0); */ } reset_lexer(input); parse(); gettimeofday(×tamp, NULL); if (display) { resize_capable = detect_resize_capable(); install_signal_handler(SIGWINCH, sigwinch_handler, "SIGWINCH"); /* Get terminal attributes. */ save_tty(); } install_signal_handler(SIGCHLD, sigchld_handler, "SIGCHLD"); unsetenv("TERM"); unsetenv("LINES"); unsetenv("COLUMS"); unsetenv("LANG"); unsetenv("LC_CTYPE"); if (port_openpty(&master, &slave, NULL) < 0) fatal("Error opening pty: %s\n", strerror(errno)); set_non_block(STDIN_FILENO, "terminal", td_true); set_non_block(master, "pty", td_true); set_non_block(signal_pipe[PIPE_READ], "pipe", td_true); fdset[0].fd = master; fdset[0].events = PORT_POLLIN; fdset[1].fd = signal_pipe[PIPE_READ]; fdset[1].events = PORT_POLLIN; #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) if (visual_compare) { const char *term; init_attr_map(); if ((term = get_script_env(script, "TERM")) == NULL) fatal("Recording does not contain a TERM environment variable\n"); setup_ti_strings(term, get_script_env(script, "LANG")); /* Get terminal size. */ if (ioctl(STDIN_FILENO, TIOCGWINSZ, &wsz) < 0 || wsz.ws_col == 0 || wsz.ws_row == 0) { fprintf(stderr, "Warning: could not obtain window size: %s\n", strerror(errno)); wsz.ws_col = 80; wsz.ws_row = 24; } if ((realWin = win_new(wsz.ws_row, wsz.ws_col)) == NULL) fatal("Out of memory\n"); if ((expectWin = win_new(wsz.ws_row, wsz.ws_col)) == NULL) fatal("Out of memory\n"); #if defined(HAVE_CAIRO) && defined(HAVE_PTHREAD) if (picture_series != NULL || picture_name != NULL) start_picture_writer_thread(); #endif } #endif while (script != NULL) { if (exited) { if (script->type != EXP_EXPECT_EXIT) unexpected_death(); else handle_exit(script); } switch (script->type) { case EXP_START: pid = start_client(script, slave, log_file); break; case EXP_EXPECT: #if defined(HAVE_CURSES) && defined(HAVE_UNISTRING) if (visual_compare) visual_expect(script); else #endif expect(script); while (script->next != NULL && script->next->type == EXP_EXPECT) script = script->next; break; case EXP_SEND: send_keys(script); break; case EXP_EXPECT_EXIT: case EXP_EXPECT_SUSPEND: expect_signal(script); break; case EXP_INTERACT: if (display) interact(); break; case EXP_WINDOW_SIZE: set_window_size(script); break; case EXP_ENV: if (log_file != NULL) fprintf(log_file, "Setting environment variable %s to %s\n", script->un.args->string, script->un.args->next->string); setenv(script->un.args->string, script->un.args->next->string, 0); break; case EXP_REQUIRE_VERSION: break; default: fatal("Internal error\n"); } script = script->next; } end_client(); return EXIT_SUCCESS; } termdebug-2.2+dfsg/src/replay.h000066400000000000000000000023771254722562400165300ustar00rootroot00000000000000/* Copyright (C) 2010,2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 . */ #ifndef REPLAY_H #define REPLAY_H typedef enum { EXP_START, EXP_ENV, EXP_WINDOW_SIZE, EXP_EXPECT, EXP_SEND, EXP_EXPECT_EXIT, EXP_INTERACT, EXP_EXPECT_SUSPEND, EXP_REQUIRE_VERSION } ExpType; typedef struct StringListNode StringListNode; struct StringListNode { int length; char *string; StringListNode *next; int delay, min_delay; }; typedef struct ExpNode ExpNode; struct ExpNode { ExpType type; ExpNode *next; int line; union { StringListNode *args; struct { int columns; int rows; int delay; int min_delay; } size; int number; } un; }; extern ExpNode *script; void reset_lexer(const char *new_file_name); #endif termdebug-2.2+dfsg/src/rerecord.c000066400000000000000000000167201254722562400170310ustar00rootroot00000000000000/* Copyright (C) 2010,2012-2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 #include #include #include #include #include #include #include "optionMacros.h" #include "replay.h" #include "common.h" #include "input.h" /* TODO: allow user to specify different client to start from the command line */ static int master; static pid_t pid; static td_bool resize_capable; static const char *directory; static char *output; static FILE *output_file; static char *input; static td_bool strip_location_reports = td_true; static void printUsage(void) { printf("Usage: tdrerecord [OPTIONS] \n"); printf(" -d,--directory= Save recording in directory \n"); printf(" -o,--output= Save recording as \n"); printf(" -V, --version Print version and copyright information\n"); printf(" -l, --no-strip-location-reports Don't strip the location reports from the\n" " 'send' strings\n"); exit(EXIT_SUCCESS); } static PARSE_FUNCTION(parse_options) OPTIONS OPTION('o', "output", REQUIRED_ARG) output = optArg; END_OPTION OPTION('d', "directory", REQUIRED_ARG) directory = optArg; END_OPTION OPTION('h', "help", NO_ARG) printUsage(); END_OPTION OPTION('V', "version", NO_ARG) fputs("tdrerecord " VERSION_STRING "\nCopyright (C) 2010,2013 G.P. Halkes\nLicensed under the GNU General Public License version 3\n", stdout); /* @copyright */ exit(0); END_OPTION OPTION('l', "no-strip-location-reports", NO_ARG) strip_location_reports = td_false; END_OPTION DOUBLE_DASH NO_MORE_OPTIONS; END_OPTION fatal("Unknown option " OPTFMT "\n", OPTPRARG); NO_OPTION if (input != NULL) fatal("More than one replay specified\n"); input = optcurrent; END_OPTIONS if (input == NULL) fatal("No replay specified\n"); if (output != NULL && directory != NULL) fatal("Can only specify one of --output and --directory\n"); END_FUNCTION static void set_window_size(ExpNode *size) { struct winsize wsz; memset(&wsz, 0, sizeof(wsz)); interact_loop(master, pid, output_file, size->un.size.delay); fprintf(output_file, "window_size %d %d", size->un.size.columns, size->un.size.rows); if (size->un.size.delay > 0) { fprintf(output_file, " %d", size->un.size.delay); if (size->un.size.min_delay) fprintf(output_file, " >%d", size->un.size.min_delay); } fputc('\n', output_file); /* Resync timestamp */ init_timestamp(); if (resize_capable) { char buffer[64]; size_t result; /* FIXME: this should use tparm or similar to ensure proper padding etc. */ result = sprintf(buffer, "\x1b[8;%d;%dt", size->un.size.rows, size->un.size.columns); safe_write(STDOUT_FILENO, buffer, result); /* FIXME: wait for terminal to respond because otherwise the next updates may fail. */ } wsz.ws_col = size->un.size.columns; wsz.ws_row = size->un.size.rows; if (ioctl(master, TIOCSWINSZ, &wsz)) fatal("Error setting window size: %s\n", strerror(errno)); } static void send_keys(ExpNode *keys) { StringListNode *current = keys->un.args; for (; current != NULL; current = current->next) { /* If the delay is very small, just send now before the terminal decides to continue. This should solve issues like the one with vi, which sends information requests to the terminal and then doesn't wait for the response. */ if (current->delay >= 5) { int status = interact_loop(master, pid, output_file, current->delay); if (status != -1) { fclose(output_file); reset_tty(); fprintf(stderr, "-- recording is saved in %s --\n", output); exit(WEXITSTATUS(status)); } } if (strip_location_reports) { int i, j; for (i = 0; i < current->length; i++) { if (current->string[i] == 27 && i + 1 < current->length && current->string[i + 1] == '[') { for (j = i + 2; j < current->length && ((current->string[j] >= '0' && current->string[j] <= '9') || current->string[j] == ';'); j++) {} if (j < current->length && current->string[j] == 'R') { memmove(current->string + i, current->string + j + 1, current->length - j - 1); current->length -= j + 1 - i; i--; } } } } if (current->length == 0) continue; write_record(output_file, TYPE_INPUT, current->delay, current->min_delay, (unsigned char *) current->string, current->length); /* Resync timestamp */ init_timestamp(); copy_attrs_to_terminal(master); safe_write(master, current->string, current->length); } } int tdrerecord_main(int argc, char *argv[]) { int slave; int status; char *cwd_buffer; parse_options(argc, argv); if (!isatty(STDIN_FILENO)) fatal("Can only rerecord from a terminal devices\n"); reset_lexer(input); parse(); output_file = open_output(&output, directory); fprintf(output_file, "# Recorded with working directory %s\n", cwd_buffer = getcwd_wrapper()); free(cwd_buffer); resize_capable = detect_resize_capable(); init_timestamp(); install_signal_handler(SIGWINCH, sigwinch_handler, "SIGWINCH"); /* Get terminal attributes. */ save_tty(); install_signal_handler(SIGCHLD, sigchld_handler, "SIGCHLD"); /* Unset the variables saved in the recording. */ unsetenv("TERM"); unsetenv("LINES"); unsetenv("COLUMS"); unsetenv("LANG"); unsetenv("LC_CTYPE"); if (port_openpty(&master, &slave, NULL) < 0) fatal("Error opening pty: %s\n", strerror(errno)); set_non_block(STDIN_FILENO, "terminal", td_true); set_non_block(master, "pty", td_true); set_non_block(signal_pipe[PIPE_READ], "pipe", td_true); while (script != NULL) { switch (script->type) { case EXP_START: { StringListNode *ptr; fprintf(output_file, "start"); ptr = script->un.args; while (ptr != NULL) { fputc(' ', output_file); write_escaped_string(output_file, ptr->string, strlen(ptr->string)); ptr = ptr->next; } fprintf(output_file, "\n"); pid = start_client(script, slave, NULL); break; } case EXP_EXPECT: case EXP_EXPECT_SUSPEND: /* IGNORE */ break; case EXP_SEND: send_keys(script); break; case EXP_EXPECT_EXIT: case EXP_INTERACT: copy_attrs_to_terminal(master); status = interact_loop(master, pid, output_file, -1); fclose(output_file); reset_tty(); fprintf(stderr, "-- recording is saved in %s --\n", output); exit(WEXITSTATUS(status)); break; case EXP_WINDOW_SIZE: set_window_size(script); break; case EXP_ENV: fprintf(output_file, "env \"%s\" ", script->un.args->string); write_escaped_string(output_file, script->un.args->next->string, strlen(script->un.args->next->string)); fputc('\n', output_file); setenv(script->un.args->string, script->un.args->next->string, 0); break; case EXP_REQUIRE_VERSION: fprintf(output_file, "require_version %d\n", script->un.number); break; default: fatal("Internal error\n"); } script = script->next; } return EXIT_SUCCESS; } termdebug-2.2+dfsg/src/view.c000066400000000000000000000110011254722562400161610ustar00rootroot00000000000000/* Copyright (C) 2010,2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 #include #include #include #include #include #include #include "common.h" #include "optionMacros.h" #include "replay.h" #include "input.h" /* TODO: - perhaps we should empty the input buffer as well and even set no-echo and non-canonical mode - wait for signal before continuing after set_window_size (if we do the actual resize that is). However, we first must check whether we actually get a signal! */ static int key_delay; static double key_delay_scale = 1.0; static const char *input; static td_bool resize_capable; static void printUsage(void) { printf("Usage: tdview [OPTIONS] \n"); printf(" -k, --key-delay= Set key delay\n"); printf(" -V, --version Print version and copyright information\n"); exit(EXIT_SUCCESS); } static PARSE_FUNCTION(parse_options) OPTIONS OPTION('k', "key-delay", REQUIRED_ARG) while (*optArg && isspace(*optArg)) optArg++; if (optArg[0] == '/') { optArg++; PARSE_DOUBLE(key_delay_scale, DBL_MIN, DBL_MAX); key_delay = 0; } else if (isdigit(*optArg)) { PARSE_INT(key_delay, 1, INT_MAX); key_delay_scale = 1.0; } else { fatal("Invalid argument for key-delay option: %s\n", optArg); } END_OPTION OPTION('h', "help", NO_ARG) printUsage(); END_OPTION OPTION('V', "version", NO_ARG) fputs("tdview " VERSION_STRING "\nCopyright (C) 2010,2013 G.P. Halkes\nLicensed under the GNU General Public License version 3\n", stdout); /* @copyright */ exit(0); END_OPTION DOUBLE_DASH NO_MORE_OPTIONS; END_OPTION fatal("Unknown option " OPTFMT "\n", OPTPRARG); NO_OPTION if (input != NULL) fatal("More than one recording specified\n"); input = optcurrent; END_OPTIONS if (input == NULL) fatal("No recording specified\n"); END_FUNCTION static void print_string_list(StringListNode *string) { for (; string != NULL; string = string->next) safe_write(STDOUT_FILENO, string->string, string->length); } static void do_delay(int delay) { struct timespec delay_spec; if (delay == 0) return; else if (key_delay) delay = key_delay; else delay = delay / key_delay_scale; delay_spec.tv_nsec = (long) (delay % 1000) * 1000000; delay_spec.tv_sec = delay / 1000; while (nanosleep(&delay_spec, &delay_spec) < 0) { if (errno == EINTR) continue; fatal("Error sleeping: %s\n", strerror(errno)); } } static void set_window_size(ExpNode *size) { if (resize_capable) { char buffer[64]; size_t result; /* FIXME: this should use tparm or similar to ensure proper padding etc. */ result = sprintf(buffer, "\x1b[8;%d;%dt", size->un.size.rows, size->un.size.columns); safe_write(STDOUT_FILENO, buffer, result); /* FIXME: wait for terminal to respond because otherwise the next updates may fail. */ } } int tdview_main(int argc, char *argv[]) { parse_options(argc, argv); if (!isatty(STDIN_FILENO)) fatal("Can only replay to a terminal devices\n"); resize_capable = detect_resize_capable(); reset_lexer(input); parse(); save_tty(); copy_attrs_to_terminal(STDIN_FILENO); while (script != NULL) { switch (script->type) { case EXP_START: case EXP_INTERACT: case EXP_ENV: /* Ignore stuff that isn't relavant to simply viewing the replay. */ break; case EXP_EXPECT: print_string_list(script->un.args); break; case EXP_SEND: { StringListNode *key; for (key = script->un.args; key != NULL; key = key->next) do_delay(key->delay); break; } case EXP_EXPECT_EXIT: exit(EXIT_SUCCESS); break; case EXP_WINDOW_SIZE: do_delay(script->un.size.delay); set_window_size(script); break; case EXP_EXPECT_SUSPEND: printf("Process has stopped. Will continue in 3 seconds\n"); sleep(3); break; case EXP_REQUIRE_VERSION: break; default: fatal("Internal error\n"); } script = script->next; } return EXIT_SUCCESS; } termdebug-2.2+dfsg/src/window.c000066400000000000000000001104631254722562400165320ustar00rootroot00000000000000/* Copyright (C) 2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 . */ /** @file */ #include #include #include #include #include "window.h" /* TODO - eliminate the start member from the line_t struct */ /** @internal @brief The maximum size of a UTF-8 character in bytes. Used in ::win_addnstr. */ #define UTF8_MAX_BYTES 4 /* Attribute to index mapping. For now this uses a simple linear search. Should this turn out to be too expensive, it can be easily replaced by a hash-table based solution, an LRU cache with linear search or a sorted list with binary search. Whatever the data structure used, by ensuring use of the internal API, we can easily replace the implementation later. */ /* Attribute to index mapping. To make the mapping quick, a simple hash table with hash chaining is used. */ typedef struct attr_map_t attr_map_t; struct attr_map_t { attr_t attr; int next; }; /** @internal @brief The initial allocation for ::attr_map. */ #define ATTR_MAP_START_SIZE 32 /** @internal @brief The size of the hash map used for ::t3_attr_t mapping. */ #define ATTR_HASH_MAP_SIZE 337 static attr_map_t *attr_map; /**< @internal @brief The map of indices to attribute sets. */ static int attr_map_fill, /**< @internal @brief The number of elements used in ::attr_map. */ attr_map_allocated; /**< @internal @brief The number of elements allocated in ::attr_map. */ static int attr_hash_map[ATTR_HASH_MAP_SIZE]; /**< @internal @brief Hash map for quickly mapping ::t3_attr_t's to indices. */ td_bool win_bce; static void adjust_lines(window_t *win); /** Create a new window_t. @param parent window_t used for clipping and relative positioning. @param height The desired height in terminal lines. @param width The desired width in terminal columns. @param y The vertical location of the window in terminal lines. @param x The horizontal location of the window in terminal columns. @param depth The depth of the window in the stack of windows. @return A pointer to a new window_t struct or @c NULL if not enough memory could be allocated. The @p depth parameter determines the z-order of the windows. Windows with lower depth will hide windows with higher depths. However, this only holds relative to the @p parent window. The position will be relative to the top-left corner of the @p parent window, or to the top-left corner of the terminal if @p parent is @c NULL. */ window_t *win_new(int height, int width) { window_t *retval; int i; if (height <= 0 || width <= 0) return NULL; if ((retval = calloc(1, sizeof(window_t))) == NULL) return NULL; retval->width = width; retval->height = height; retval->cursor_state = CURSOR_NORM; if ((retval->lines = calloc(1, sizeof(line_data_t) * height)) == NULL) { win_del(retval); return NULL; } for (i = 0; i < height; i++) { retval->lines[i].allocated = width > INITIAL_ALLOC ? INITIAL_ALLOC : width; if ((retval->lines[i].data = malloc(retval->lines[i].allocated)) == NULL) { win_del(retval); return NULL; } } adjust_lines(retval); if ((retval->output_buffer.data = malloc(INITIAL_ALLOC)) == NULL) { win_del(retval); return NULL; } retval->output_buffer.allocated = INITIAL_ALLOC; return retval; } /** Discard a window_t. @param win The window_t to discard. Note that child windows are @em not automatically discarded as well. All child windows have their parent attribute set to @c NULL. */ void win_del(window_t *win) { int i; if (win == NULL) return; if (win->lines != NULL) { for (i = 0; i < win->height; i++) free(win->lines[i].data); free(win->lines); } free(win->output_buffer.data); free(win); } /** Make a deep copy of a window_t. */ window_t *win_copy(window_t *win) { window_t *retval; int i; if (win == NULL) return NULL; if ((retval = calloc(1, sizeof(window_t))) == NULL) return NULL; retval->width = win->width; retval->height = win->height; retval->cursor_state = win->cursor_state; retval->paint_x = win->paint_x; retval->paint_y = win->paint_y; if ((retval->lines = calloc(1, sizeof(line_data_t) * retval->height)) == NULL) { win_del(retval); return NULL; } for (i = 0; i < retval->height; i++) { retval->lines[i].length = win->lines[i].length; retval->lines[i].allocated = win->lines[i].length; if ((retval->lines[i].data = malloc(retval->lines[i].allocated)) == NULL) { win_del(retval); return NULL; } memcpy(retval->lines[i].data, win->lines[i].data, win->lines[i].length); } if ((retval->output_buffer.data = malloc(INITIAL_ALLOC)) == NULL) { win_del(retval); return NULL; } retval->output_buffer.allocated = INITIAL_ALLOC; return retval; } /** Change a window_t's size. @param win The window_t to change the size of. @param height The desired new height of the window_t in terminal lines. @param width The desired new width of the window_t in terminal columns. @return A boolean indicating succes, depending on the validity of the parameters and whether reallocation of the internal data structures succeeds. */ td_bool win_resize(window_t *win, int height, int width) { int i; if (height <= 0 || width <= 0) return td_false; if (win->lines == NULL) { win->height = height; win->width = width; return td_true; } if (height > win->height) { void *result; if ((result = realloc(win->lines, height * sizeof(line_data_t))) == NULL) return td_false; win->lines = result; memset(win->lines + win->height, 0, sizeof(line_data_t) * (height - win->height)); for (i = win->height; i < height; i++) { if ((win->lines[i].data = malloc(INITIAL_ALLOC)) == NULL) { for (i = win->height; i < height && win->lines[i].data != NULL; i++) free(win->lines[i].data); return td_false; } win->lines[i].allocated = INITIAL_ALLOC; } } else if (height < win->height) { for (i = height; i < win->height; i++) free(win->lines[i].data); memset(win->lines + height, 0, sizeof(line_data_t) * (win->height - height)); } adjust_lines(win); win->height = height; win->width = width; return td_true; } /** Change the position where characters are written to the window_t. */ void win_set_paint(window_t *win, int y, int x) { win->paint_x = x < 0 ? 0 : (x < win->width ? x : win->width - 1); win->paint_y = y < 0 ? 0 : (y < win->height ? y : win->height - 1); } td_bool win_compare(window_t *winA, window_t *winB, FILE *descr_out) { int i; if (winA->height != winB->height || winA->width != winB->width) { if (descr_out != NULL) fprintf(descr_out, "Terminals have different size: %dx%d vs. %dx%d\n", winA->width, winA->height, winB->width, winB->height); return td_false; } if (winA->cursor_state != winB->cursor_state || (winA->cursor_state != CURSOR_INVIS && (winA->paint_x != winB->paint_x || winA->paint_y != winB->paint_y))) { static const char *cursor_state_strings[3] = { "visible", "invisible", "highly visible" }; if (descr_out != NULL) fprintf(descr_out, "Cursor state is different: %s at %d,%d vs. %s at %d,%d\n", cursor_state_strings[winA->cursor_state], winA->paint_x + 1, winA->paint_y + 1, cursor_state_strings[winB->cursor_state], winB->paint_x + 1, winB->paint_y + 1); return td_false; } for (i = 0; i < winA->height; i++) { if (winA->lines[i].width != winB->lines[i].width) fatal("Internal error in tracking window contents.\n"); if (winA->lines[i].length != winB->lines[i].length || memcmp(winA->lines[i].data, winB->lines[i].data, winA->lines[i].length) != 0) { if (descr_out != NULL) { size_t block_size_bytesA, block_size_bytesB; uint32_t block_sizeA, block_sizeB; int column; int offset; /* Find first block that is different. */ for (offset = 0, column = 0; offset < winA->lines[i].length && offset < winB->lines[i].length; offset += (block_sizeA >> 1), column += _BLOCK_SIZE_TO_WIDTH(block_sizeA)) { block_sizeA = get_value(winA->lines[i].data + offset, &block_size_bytesA); block_sizeB = get_value(winB->lines[i].data + offset, &block_size_bytesB); if (block_sizeA != block_sizeB) break; offset += block_size_bytesA; if (memcmp(winA->lines[i].data + offset, winB->lines[i].data + offset, block_sizeA >> 1) != 0) break; } fprintf(descr_out, "First difference encountered at position %d,%d\n", column + 1, i + 1); } return td_false; } } return td_true; } int win_get_paint_x(window_t *win) { return win->paint_x; } int win_get_paint_y(window_t *win) { return win->paint_y; } int win_get_height(window_t *win) { return win->height; } int win_get_width(window_t *win) { return win->width; } void win_scroll(window_t *win) { line_data_t first_line = win->lines[0]; int i; for (i = 1; i < win->height; i++) win->lines[i - 1] = win->lines[i]; first_line.length = 0; first_line.width = 0; win->lines[win->height - 1] = first_line; adjust_lines(win); } void win_scroll_back(window_t *win) { line_data_t last_line = win->lines[win->height - 1]; int i; for (i = win->height - 1; i > 0; i--) win->lines[i] = win->lines[i - 1]; last_line.length = 0; last_line.width = 0; win->lines[0] = last_line; adjust_lines(win); } /** Ensure that a line_data_t struct has at least a specified number of bytes of unused space. @param line The line_data_t struct to check. @param n The required unused space in bytes. @return A boolean indicating whether, after possibly reallocating, the requested number of bytes is available. */ td_bool ensure_space(line_data_t *line, size_t n) { int newsize; char *resized; if (n > INT_MAX || INT_MAX - (int) n < line->length) return td_false; if (line->allocated > line->length + (int) n) return td_true; newsize = line->allocated; do { /* Sanity check for overflow of allocated variable. Prevents infinite loops. */ if (newsize > INT_MAX / 2) newsize = INT_MAX; else newsize *= 2; } while (newsize - line->length < (int) n); if ((resized = realloc(line->data, sizeof(attr_t) * newsize)) == NULL) return td_false; line->data = resized; line->allocated = newsize; return td_true; } /** @internal @brief Map a set of attributes to an integer. @param attr The attribute set to map. */ int map_attr(attr_t attr) { int ptr; for (ptr = attr_hash_map[attr % ATTR_HASH_MAP_SIZE]; ptr != -1 && attr_map[ptr].attr != attr; ptr = attr_map[ptr].next) {} if (ptr != -1) return ptr; if (attr_map_fill >= attr_map_allocated) { int new_allocation = attr_map_allocated == 0 ? ATTR_MAP_START_SIZE : attr_map_allocated * 2; attr_map_t *new_map; if ((new_map = realloc(attr_map, new_allocation * sizeof(attr_map_t))) == NULL) fatal("Out of memory\n"); attr_map = new_map; attr_map_allocated = new_allocation; } attr_map[attr_map_fill].attr = attr; attr_map[attr_map_fill].next = attr_hash_map[attr % ATTR_HASH_MAP_SIZE]; attr_hash_map[attr % ATTR_HASH_MAP_SIZE] = attr_map_fill; return attr_map_fill++; } /** @internal @brief Get the set of attributes associated with a mapped integer. @param idx The mapped attribute index as returned by ::_t3_map_attr. */ attr_t get_attr(int idx) { if (idx < 0 || idx > attr_map_fill) return 0; return attr_map[idx].attr; } /** @internal @brief Initialize data structures used for attribute set mappings. */ void init_attr_map(void) { int i; for (i = 0; i < ATTR_HASH_MAP_SIZE; i++) attr_hash_map[i] = -1; } /** @internal @brief Clean up the memory used for attribute set mappings. */ void free_attr_map(void) { free(attr_map); attr_map = NULL; attr_map_allocated = 0; attr_map_fill = 0; init_attr_map(); } void win_set_default_attrs(window_t *win, attr_t attrs) { win->default_attrs = map_attr(attrs); } attr_t win_get_default_attrs(window_t *win) { return get_attr(win->default_attrs); } /** Get the first UTF-8 value encoded in a string. @param src The UTF-8 string to parse. @param size The location to store the size of the character. @return The value at the start of @p src. @note This function assumes that the input is a valid UTF-8 encoded value. */ uint32_t get_value(const char *src, size_t *size) { int bytes_left; uint32_t retval; switch ((uint8_t) src[0]) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 59: case 60: case 61: case 62: case 63: case 64: case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: case 108: case 109: case 110: case 111: case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: case 124: case 125: case 126: case 127: *size = 1; return src[0]; case 194: case 195: case 196: case 197: case 198: case 199: case 200: case 201: case 202: case 203: case 204: case 205: case 206: case 207: case 208: case 209: case 210: case 211: case 212: case 213: case 214: case 215: case 216: case 217: case 218: case 219: case 220: case 221: case 222: case 223: bytes_left = 1; retval = src[0] & 0x1F; break; case 224: case 225: case 226: case 227: case 228: case 229: case 230: case 231: case 232: case 233: case 234: case 235: case 236: case 237: case 238: case 239: bytes_left = 2; retval = src[0] & 0x0F; break; case 240: case 241: case 242: case 243: case 244: case 245: case 246: case 247: bytes_left = 3; retval = src[0] & 0x07; break; case 248: case 249: case 250: case 251: bytes_left = 4; retval = src[0] & 0x03; break; case 252: case 253: bytes_left = 5; retval = src[1] & 1; break; /* Add default case to shut up the compiler. */ default: return 0; } *size = bytes_left + 1; src++; for (; bytes_left > 0; bytes_left--) retval = (retval << 6) | (src++[0] & 0x3f); return retval; } /** Get the first codepoint represented by a UTF-8 string. @param src The UTF-8 string to parse. @param size The location to store the number of bytes in the first codepoint, which should contain the number of bytes in src on entry (may be @c NULL). @return The codepoint at the start of @p src or @c FFFD if an invalid codepoint is encountered. */ uint32_t utf8_get(const char *src, size_t *size) { size_t max_size, _size; int bytes_left; uint32_t retval, least; /* Just assume the buffer is large enough if size is not passed. */ max_size = size == NULL ? 4 : *size; _size = 1; switch ((uint8_t) src[0]) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 59: case 60: case 61: case 62: case 63: case 64: case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: case 108: case 109: case 110: case 111: case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: case 124: case 125: case 126: case 127: if (size != NULL) *size = _size; return src[0]; case 128: case 129: case 130: case 131: case 132: case 133: case 134: case 135: case 136: case 137: case 138: case 139: case 140: case 141: case 142: case 143: case 144: case 145: case 146: case 147: case 148: case 149: case 150: case 151: case 152: case 153: case 154: case 155: case 156: case 157: case 158: case 159: case 160: case 161: case 162: case 163: case 164: case 165: case 166: case 167: case 168: case 169: case 170: case 171: case 172: case 173: case 174: case 175: case 176: case 177: case 178: case 179: case 180: case 181: case 182: case 183: case 184: case 185: case 186: case 187: case 188: case 189: case 190: case 191: case 192: case 193: if (size != NULL) *size = _size; return 0xFFFD; case 194: case 195: case 196: case 197: case 198: case 199: case 200: case 201: case 202: case 203: case 204: case 205: case 206: case 207: case 208: case 209: case 210: case 211: case 212: case 213: case 214: case 215: case 216: case 217: case 218: case 219: case 220: case 221: case 222: case 223: least = 0x80; bytes_left = 1; retval = src[0] & 0x1F; break; case 224: case 225: case 226: case 227: case 228: case 229: case 230: case 231: case 232: case 233: case 234: case 235: case 236: case 237: case 238: case 239: least = 0x800; bytes_left = 2; retval = src[0] & 0x0F; break; case 240: case 241: case 242: case 243: case 244: least = 0x10000L; bytes_left = 3; retval = src[0] & 0x07; break; case 245: case 246: case 247: case 248: case 249: case 250: case 251: case 252: case 253: case 254: case 255: if (size != NULL) *size = _size; return 0xFFFD; default: if (size != NULL) *size = _size; return 0xFFFD; } src++; for (; bytes_left > 0 && _size < max_size; bytes_left--, _size++) { if ((src[0] & 0xC0) != 0x80) { if (size != NULL) *size = _size; return 0xFFFD; } retval = (retval << 6) | (src[0] & 0x3F); src++; } if (size != NULL) *size = _size; if (retval < least) return 0xFFFD; if (retval > 0x10FFFFL) return 0xFFFD; if (bytes_left > 0) return 0xFFFD; return retval; } /** Write a UTF-8 encoded value. @param c The codepoint to convert. @param dst The location to store the result. @return The number of bytes stored in @p dst. The value must be lower than 0x80000000 (i.e. at most 31 bits may be used). No check is made for this however, so the calling code must ensure that this is the case. */ size_t _put_value(uint32_t c, char *dst) { if (c < 0x80) { dst[0] = c; return 1; } else if (c < 0x800) { dst[0] = 0xc0 | (c >> 6); dst[1] = 0x80 | (c & 0x3f); return 2; } else if (c < 0x10000) { dst[0] = 0xe0 | (c >> 12); dst[1] = 0x80 | ((c >> 6) & 0x3f); dst[2] = 0x80 | (c & 0x3f); return 3; } else if (c < 0x200000) { dst[0] = 0xf0 | (c >> 18); dst[1] = 0x80 | ((c >> 12) & 0x3f); dst[2] = 0x80 | ((c >> 6) & 0x3f); dst[3] = 0x80 | (c & 0x3f); return 4; } else if (c < 0x4000000) { dst[0] = 0xf8 | (c >> 24); dst[1] = 0x80 | ((c >> 18) & 0x3f); dst[1] = 0x80 | ((c >> 12) & 0x3f); dst[2] = 0x80 | ((c >> 6) & 0x3f); dst[3] = 0x80 | (c & 0x3f); return 5; } else { dst[0] = 0xfc | (c >> 30); dst[1] = 0x80 | ((c >> 24) & 0x3f); dst[1] = 0x80 | ((c >> 18) & 0x3f); dst[1] = 0x80 | ((c >> 12) & 0x3f); dst[2] = 0x80 | ((c >> 6) & 0x3f); dst[3] = 0x80 | (c & 0x3f); return 6; } } /** Get the width of a Unicode codepoint. This function is a wrapper around uc_width, which takes into account that for some characters uc_width returns a value that is different from what terminals actually use. */ int utf8_wcwidth(uint32_t c) { static const char nul; if (c >= 0x1160 && c < 0x11fa) return 0; if (c == 0x00ad) return 1; return uc_width(c, &nul); } /** Create memory block representing a space character with specific attributes. @param attr The attribute index to use. @param out An array of size at least 8 to write to. @return The number of bytes written to @p out. */ static size_t create_space_block(int attr, char *out) { size_t result_size; result_size = _put_value(attr, out + 1); result_size++; out[result_size] = ' '; out[0] = result_size << 1; result_size++; return result_size; } /** Get the attribute index from a block. */ static uint32_t get_block_attr(const char *block) { size_t discard; for (block++; ((*block) & 0xc0) == 0x80; block++) {} return get_value(block, &discard); } /** Insert a zero-width character into an existing block. @param win The window to write to. @param str The string containing the UTF-8 encoded zero-width character. @param n The number of bytes in @p str. @return A boolean indicating success. */ static td_bool _win_add_zerowidth(window_t *win, const char *str, size_t n) { uint32_t block_size, new_block_size; size_t block_size_bytes, new_block_size_bytes; char new_block_size_str[6]; int pos_width, i; if (win->lines == NULL) return td_false; if (win->paint_y >= win->height) return td_true; /* Combining characters may be added _at_ width. */ if (win->paint_x > win->width) return td_true; if (win->cached_pos_line != win->paint_y || win->cached_pos_width >= win->paint_x) { win->cached_pos_line = win->paint_y; win->cached_pos = 0; win->cached_pos_width = 0; } /* Simply drop characters that don't belong to any other character. */ if (win->lines[win->paint_y].length == 0 || win->paint_x == 0 || win->paint_x > win->lines[win->paint_y].width) return td_true; /* Ensure we have space for n characters, and possibly extend the block size header by 1. */ if (!ensure_space(win->lines + win->paint_y, n + 1)) return td_false; pos_width = win->cached_pos_width; /* Locate the first character that at least partially overlaps the position where this string is supposed to go. Note that this loop will iterate at least once, because if win->cached_pos == win->lines[win->paint_y].length, then win->cached_pos_width will equal win->paint_x, and thereby get invalidated above. */ block_size = 0; /* Shut up the compiler. */ for (i = win->cached_pos; i < win->lines[win->paint_y].length; i += (block_size >> 1) + block_size_bytes) { block_size = get_value(win->lines[win->paint_y].data + i, &block_size_bytes); pos_width += _BLOCK_SIZE_TO_WIDTH(block_size); /* Do the check for whether we found the insertion point here, so we don't update i. */ if (pos_width >= win->paint_x) break; } /* Check whether we are being asked to add a zero-width character in the middle of a double-width character. If so, ignore. */ if (pos_width > win->paint_x) return td_true; new_block_size = block_size + (n << 1); new_block_size_bytes = _put_value(new_block_size, new_block_size_str); /* WARNING: from this point on, the block_size and new_block_size variables have a new meaning: the actual size of the block, rather than including the bit indicating the width of the character as well. */ block_size >>= 1; new_block_size >>= 1; /* Move the data after the insertion point up by the size of the character string to insert and the difference in block size header size. */ memmove(win->lines[win->paint_y].data + i + new_block_size + new_block_size_bytes, win->lines[win->paint_y].data + i + block_size + block_size_bytes, win->lines[win->paint_y].length - i - block_size - block_size_bytes); /* Copy the bytes of the new character into the string. */ memcpy(win->lines[win->paint_y].data + i + block_size + block_size_bytes, str, n); /* If applicable, move the data for this block by the difference in block size header size. */ if (new_block_size_bytes != block_size_bytes) { memmove(win->lines[win->paint_y].data + i + new_block_size_bytes, win->lines[win->paint_y].data + i + block_size_bytes, new_block_size); } /* Copy in the new block size header. */ memcpy(win->lines[win->paint_y].data + i, new_block_size_str, new_block_size_bytes); win->lines[win->paint_y].length += n + (new_block_size_bytes - block_size_bytes); return td_true; } /** Write one or more blocks to a window. @param win The window to write to. @param blocks The string containing the blocks. @param n The number of bytes in @p blocks. @return A boolean indicating success. */ static td_bool _win_write_blocks(window_t *win, const char *blocks, size_t n) { uint32_t block_size; size_t block_size_bytes; size_t k; int i; int width = 0; int extra_spaces = 0; uint32_t extra_spaces_attr; td_bool result = td_true; if (win->lines == NULL) return td_false; if (win->paint_y >= win->height || win->paint_x >= win->width || n == 0) return td_true; for (k = 0; k < n; k += (block_size >> 1) + block_size_bytes) { block_size = get_value(blocks + k, &block_size_bytes); if (win->paint_x + width + _BLOCK_SIZE_TO_WIDTH(block_size) > win->width) break; width += _BLOCK_SIZE_TO_WIDTH(block_size); } if (k < n) { extra_spaces = win->width - win->paint_x - width; extra_spaces_attr = get_block_attr(blocks + k); } n = k; if (win->cached_pos_line != win->paint_y || win->cached_pos_width > win->paint_x) { win->cached_pos_line = win->paint_y; win->cached_pos = 0; win->cached_pos_width = 0; } if (win->lines[win->paint_y].width <= win->paint_x) { /* Add characters after existing characters. */ char default_attr_str[8]; size_t default_attr_size; int diff = win->paint_x - win->lines[win->paint_y].width; default_attr_size = create_space_block(map_attr(win->default_attrs), default_attr_str); if (!ensure_space(win->lines + win->paint_y, n + diff * (default_attr_size))) return td_false; for (i = diff; i > 0; i--) { memcpy(win->lines[win->paint_y].data + win->lines[win->paint_y].length, default_attr_str, default_attr_size); win->lines[win->paint_y].length += default_attr_size; } memcpy(win->lines[win->paint_y].data + win->lines[win->paint_y].length, blocks, n); win->lines[win->paint_y].length += n; win->lines[win->paint_y].width += width + diff; } else { /* Character (partly) overwrite existing chars. */ int pos_width = win->cached_pos_width; size_t start_replace = 0, start_space_attr, start_spaces, end_replace, end_space_attr, end_spaces; int sdiff; char start_space_str[8], end_space_str[8]; size_t start_space_bytes, end_space_bytes; /* Locate the first character that at least partially overlaps the position where this string is supposed to go. Note that this loop will always be entered once, because win->cached_pos will always be < line length. To see why this is the case, consider that when win->cached_pos equals the line length. Then win->paint_x equals the width of the line and that case will be handled above. */ block_size = 0; /* Shut up the compiler. */ for (i = win->cached_pos; i < win->lines[win->paint_y].length; i += (block_size >> 1) + block_size_bytes) { block_size = get_value(win->lines[win->paint_y].data + i, &block_size_bytes); if (_BLOCK_SIZE_TO_WIDTH(block_size) + pos_width > win->paint_x) break; pos_width += _BLOCK_SIZE_TO_WIDTH(block_size); } win->cached_pos = i; win->cached_pos_width = pos_width; start_replace = i; /* If the character only partially overlaps, we replace the first part with spaces with the attributes of the old character. */ start_space_attr = get_block_attr(win->lines[win->paint_y].data + start_replace); start_spaces = win->paint_x - pos_width; /* Now we need to find which other character(s) overlap. However, the current string may overlap with a double width character but only for a single position. In that case we will replace the trailing portion of the character with spaces with the old character's attributes. */ pos_width += _BLOCK_SIZE_TO_WIDTH(block_size); i += (block_size >> 1) + block_size_bytes; /* If the character where we start overwriting already fully overlaps with the new string, then we need to only replace this and any spaces that result from replacing the trailing portion need to use the start space attribute */ if (pos_width >= win->paint_x + width) { end_space_attr = start_space_attr; end_replace = i; } else { for (; i < win->lines[win->paint_y].length; i += (block_size >> 1) + block_size_bytes) { block_size = get_value(win->lines[win->paint_y].data + i, &block_size_bytes); pos_width += _BLOCK_SIZE_TO_WIDTH(block_size); if (pos_width >= win->paint_x + width) break; } end_space_attr = get_block_attr(win->lines[win->paint_y].data + i); end_replace = i < win->lines[win->paint_y].length ? (int) (i + (block_size >> 1) + block_size_bytes) : i; } end_spaces = pos_width > win->paint_x + width ? pos_width - win->paint_x - width : 0; start_space_bytes = create_space_block(start_space_attr, start_space_str); end_space_bytes = create_space_block(end_space_attr, end_space_str); /* Move the existing characters out of the way. */ sdiff = n + end_spaces * end_space_bytes + start_spaces * start_space_bytes - (end_replace - start_replace); if (sdiff > 0 && !ensure_space(win->lines + win->paint_y, sdiff)) return td_false; memmove(win->lines[win->paint_y].data + end_replace + sdiff, win->lines[win->paint_y].data + end_replace, win->lines[win->paint_y].length - end_replace); for (i = start_replace; start_spaces > 0; start_spaces--) { memcpy(win->lines[win->paint_y].data + i, start_space_str, start_space_bytes); i += start_space_bytes; } memcpy(win->lines[win->paint_y].data + i, blocks, n); i += n; for (; end_spaces > 0; end_spaces--) { memcpy(win->lines[win->paint_y].data + i, end_space_str, end_space_bytes); i += end_space_bytes; } win->lines[win->paint_y].length += sdiff; if (win->lines[win->paint_y].width < width + win->paint_x) win->lines[win->paint_y].width = width + win->paint_x; } win->paint_x += width; if (extra_spaces > 0) { char extra_space_str[8]; size_t extra_space_bytes; extra_space_bytes = create_space_block(extra_spaces_attr, extra_space_str); for (i = 0; i < extra_spaces; i++) result &= _win_write_blocks(win, extra_space_str, extra_space_bytes); } return result; } /** Add a string with explicitly specified size to a window_t with specified attributes. @param win The window_t to add the string to. @param str The string to add. @param n The size of @p str. @param attr The attributes to use. @retval ::ERR_SUCCESS on succes @retval ::ERR_NONPRINT if a control character was encountered. @retval ::ERR_ERRNO otherwise. The default attributes are combined with the specified attributes, with @p attr used as the priority attributes. All other win_add* functions are (indirectly) implemented using this function. */ int win_addnstr(window_t *win, const char *str, size_t n) { size_t bytes_read; char block[1 + 6 + UTF8_MAX_BYTES]; uint32_t c; int retval = ERR_SUCCESS; int width; size_t block_bytes; for (; n > 0; n -= bytes_read, str += bytes_read) { bytes_read = n; c = utf8_get(str, &bytes_read); width = utf8_wcwidth(c); /* UC_CATEGORY_MASK_Cn is for unassigned/reserved code points. These are not necessarily unprintable. */ if (width < 0 || uc_is_general_category_withtable(c, UTF8_CONTROL_MASK)) { retval = ERR_NONPRINT; continue; } else if (width == 0) { _win_add_zerowidth(win, str, bytes_read); continue; } block_bytes = _put_value(win->default_attrs, block + 1); memcpy(block + 1 + block_bytes, str, bytes_read); block_bytes += bytes_read; _put_value((block_bytes << 1) + (width == 2 ? 1 : 0), block); block_bytes++; if (!_win_write_blocks(win, block, block_bytes)) return ERR_ERRNO; if (win->paint_x >= win->width) { win->paint_y++; win->paint_x = 0; if (win->paint_y >= win->height) { if (win->cup_active) { win->paint_y = win->height - 1; } else { win_scroll(win); win->paint_y = win->height - 1; } } } } return retval; } /** Clear current window_t painting line to end. */ void win_clrtoeol(window_t *win) { char space_str[8]; size_t space_str_bytes; int saved_paint_x, saved_paint_y; int spaces; if (win->paint_y >= win->height || win->paint_x >= win->width) return; space_str_bytes = create_space_block(map_attr(win_bce ? win->default_attrs : 0), space_str); saved_paint_x = win->paint_x; saved_paint_y = win->paint_y; for (spaces = win->width - win->paint_x; spaces > 0; spaces--) _win_write_blocks(win, space_str, space_str_bytes); win->paint_x = saved_paint_x; win->paint_y = saved_paint_y; } /** Clear current window_t painting line to begin. */ void win_clrtobol(window_t *win) { char space_str[8]; size_t space_str_bytes; int saved_paint_x, saved_paint_y; int spaces; if (win->paint_y >= win->height || win->paint_x >= win->width) return; space_str_bytes = create_space_block(map_attr(win_bce ? win->default_attrs : 0), space_str); saved_paint_x = win->paint_x; saved_paint_y = win->paint_y; win->paint_x = 0; for (spaces = saved_paint_x; spaces > 0; spaces--) _win_write_blocks(win, space_str, space_str_bytes); win->paint_x = saved_paint_x; win->paint_y = saved_paint_y; } void win_clrtobot(window_t *win) { int saved_paint_x, saved_paint_y; saved_paint_x = win->paint_x; saved_paint_y = win->paint_y; win_clrtoeol(win); for (; win->paint_y + 1 != win->height; win->paint_y++) win_clrtoeol(win); win_clrtoeol(win); win->paint_x = saved_paint_x; win->paint_y = saved_paint_y; } void win_clrtotop(window_t *win) { int saved_paint_x, saved_paint_y, i; saved_paint_x = win->paint_x; saved_paint_y = win->paint_y; win->paint_x = 0; win->paint_y = 0; for (i = 0; i < saved_paint_y; i++) win_clrtoeol(win); win->paint_x = saved_paint_x; win->paint_y = saved_paint_y; win_clrtobol(win); } static void adjust_lines(window_t *win) { char space_str[8]; size_t space_str_bytes; int saved_paint_x = win->paint_x; int saved_paint_y = win->paint_y; int line; space_str_bytes = create_space_block(map_attr(win->default_attrs), space_str); for (line = 0; line < win->height; line++) { if (win->lines[line].width < win->width) { win->paint_y = line; win->paint_x = win->width - 1; _win_write_blocks(win, space_str, space_str_bytes); } else if (win->width < win->lines[line].width) { int sumwidth = 0, i; uint32_t block_size; size_t block_size_bytes; block_size = get_value(win->lines[line].data, & block_size_bytes); for (i = 0; i < win->lines[line].length && sumwidth + _BLOCK_SIZE_TO_WIDTH(block_size) <= win->width; i += (block_size >> 1) + block_size_bytes) { sumwidth += _BLOCK_SIZE_TO_WIDTH(block_size); block_size = get_value(win->lines[line].data + i, & block_size_bytes); } if (sumwidth < win->width) { int spaces = win->width - sumwidth; char space_str[8]; size_t space_str_bytes; space_str_bytes = create_space_block(map_attr(0), space_str); if ((int) (spaces * space_str_bytes) < win->lines[line].length - i || ensure_space(win->lines + line, spaces * space_str_bytes - win->lines[line].length + i)) { win->paint_x = sumwidth; for (; spaces > 0; spaces--) _win_write_blocks(win, space_str, space_str_bytes); } } win->lines[line].length = i; win->lines[line].width = win->width; } } win->paint_x = saved_paint_x; win->paint_y = saved_paint_y; } void win_set_cursor(window_t *win, cursor_t cursor_state) { win->cursor_state = cursor_state; } void win_save_cursor(window_t *win) { win->saved_cursor_x = win->paint_x; win->saved_cursor_y = win->paint_y; } void win_restore_cursor(window_t *win) { win->paint_x = win->saved_cursor_x; win->paint_y = win->saved_cursor_y; } void win_set_cup(window_t *win, td_bool cup_active) { win->cup_active = cup_active; } td_bool win_get_cup(window_t *win) { return win->cup_active; } /** @} */ termdebug-2.2+dfsg/src/window.h000066400000000000000000000152651254722562400165430ustar00rootroot00000000000000/* Copyright (C) 2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 . */ #ifndef WINDOW_H #define WINDOW_H /** @defgroup t3window_win Window manipulation functions. */ #include #include #include #include "common.h" /** @typedef attr_t @brief Type to hold attributes used for terminal display. The value of a ::attr_t should be a bitwise or of ATTR_* attribute values. When the terminal only supports setting colors by color pair, the ::ATTR_FG macro can be used to specify the color pair to activate. */ #if INT_MAX < 2147483647L typedef long attr_t; #else typedef int attr_t; #endif /** @name Attributes */ /*@{*/ /** Draw characters with invisibility. */ #define ATTR_INVISIBLE ((attr_t) (1L << 0)) /** Draw characters with underlining. */ #define ATTR_UNDERLINE ((attr_t) (1L << 1)) /** Draw characters with bold face/bright appearance. */ #define ATTR_BOLD ((attr_t) (1L << 2)) /** Draw characters with reverse video. */ #define ATTR_REVERSE ((attr_t) (1L << 3)) /** Draw characters blinking. */ #define ATTR_BLINK ((attr_t) (1L << 4)) /** Draw characters with dim appearance. */ #define ATTR_DIM ((attr_t) (1L << 5)) /** Draw characters with alternate character set (for line drawing etc). */ #define ATTR_ACS ((attr_t) (1L << 6)) /** Draw characters with stand-out. */ #define ATTR_STAND_OUT ((attr_t) (1L << 7)) /** Bit number of the least significant color attribute bit. */ #define ATTR_COLOR_SHIFT 8 /** Convert a color number to a foreground color attribute. */ #define ATTR_FG(x) (((((attr_t) (x)) & 0xff) + 1) << ATTR_COLOR_SHIFT) /** Convert a color number to a background color attribute. */ #define ATTR_BG(x) (((((attr_t) (x)) & 0xff) + 1) << (ATTR_COLOR_SHIFT + 9)) /** Bitmask to leave only the foreground color in a ::attr_t value. */ #define ATTR_FG_MASK (0x1ff << ATTR_COLOR_SHIFT) /** Bitmask to leave only the background color in a ::attr_t value. */ #define ATTR_BG_MASK (0x1ff << (ATTR_COLOR_SHIFT + 9)) /** Foreground color unspecified. */ #define ATTR_FG_DEFAULT ((attr_t) 0L) /** Foreground color black. */ #define ATTR_FG_BLACK ATTR_FG(0) /** Foreground color red. */ #define ATTR_FG_RED ATTR_FG(1) /** Foreground color green. */ #define ATTR_FG_GREEN ATTR_FG(2) /** Foreground color yellow. */ #define ATTR_FG_YELLOW ATTR_FG(3) /** Foreground color blue. */ #define ATTR_FG_BLUE ATTR_FG(4) /** Foreground color magenta. */ #define ATTR_FG_MAGENTA ATTR_FG(5) /** Foreground color cyan. */ #define ATTR_FG_CYAN ATTR_FG(6) /** Foreground color white. */ #define ATTR_FG_WHITE ATTR_FG(7) /** Background color unspecified. */ #define ATTR_BG_DEFAULT ((attr_t) 0L) /** Background color black. */ #define ATTR_BG_BLACK ATTR_BG(0) /** Background color red. */ #define ATTR_BG_RED ATTR_BG(1) /** Background color green. */ #define ATTR_BG_GREEN ATTR_BG(2) /** Background color yellow. */ #define ATTR_BG_YELLOW ATTR_BG(3) /** Background color blue. */ #define ATTR_BG_BLUE ATTR_BG(4) /** Background color magenta. */ #define ATTR_BG_MAGENTA ATTR_BG(5) /** Background color cyan. */ #define ATTR_BG_CYAN ATTR_BG(6) /** Background color white. */ #define ATTR_BG_WHITE ATTR_BG(7) /*@}*/ #define ERR_SUCCESS 0 #define ERR_OUT_OF_MEMORY -1 #define ERR_NONPRINT -2 #define ERR_ERRNO -3 /** Category mask for libunistring's @c uc_is_general_category_withtable for finding control characters. */ #define UTF8_CONTROL_MASK (UC_CATEGORY_MASK_Cs | UC_CATEGORY_MASK_Cf | UC_CATEGORY_MASK_Co | \ UC_CATEGORY_MASK_Cc | UC_CATEGORY_MASK_Zl | UC_CATEGORY_MASK_Zp) #define WIDTH_TO_META(_w) (((_w) & 3) << CHAR_BIT) #define WIDTH_MASK (3 << CHAR_BIT) #define META_MASK (~((1 << CHAR_BIT) - 1)) #define BASIC_ATTRS (T3_ATTR_UNDERLINE | T3_ATTR_BOLD | T3_ATTR_REVERSE | T3_ATTR_BLINK | T3_ATTR_DIM | T3_ATTR_ACS) #define INITIAL_ALLOC 80 #define _BLOCK_SIZE_TO_WIDTH(x) ((int)((x & 1) + 1)) typedef struct { char *data; /* Data bytes. */ int width; /* Width in cells of the the data. */ int length; /* Length in bytes. */ int allocated; /* Allocated number of bytes. */ } line_data_t; typedef enum { CURSOR_NORM, CURSOR_INVIS, CURSOR_VVIS } cursor_t; typedef struct { int paint_x, paint_y; /* Drawing cursor */ int width, height; /* Height and width of the t3_window_t */ attr_t default_attrs; /* Default attributes to be combined with drawing attributes. Mostly useful for background specification. */ line_data_t *lines; /* The contents of the t3_window_t. */ int saved_cursor_x, saved_cursor_y; int cached_pos_line; int cached_pos; int cached_pos_width; cursor_t cursor_state; td_bool cup_active; /* Abuse the line_data_t data structure to create an output buffer. It would be nicer to have it as a separate type, but this prevents us from having to duplicate code. */ line_data_t output_buffer; } window_t; extern td_bool win_bce; td_bool ensure_space(line_data_t *line, size_t n); void init_attr_map(void); void free_attr_map(void); window_t *win_new(int height, int width); window_t *win_copy(window_t *win); void win_del(window_t *win); attr_t get_attr(int idx); uint32_t get_value(const char *str, size_t *bytes); td_bool win_resize(window_t *win, int height, int width); void win_set_paint(window_t *win, int y, int x); int win_get_paint_x(window_t *win); int win_get_paint_y(window_t *win); int win_get_height(window_t *win); int win_get_width(window_t *win); td_bool win_compare(window_t *winA, window_t *winB, FILE *descr_out); void win_scroll(window_t *win); void win_scroll_back(window_t *win); void win_set_default_attrs(window_t *win, attr_t attrs); attr_t win_get_default_attrs(window_t *win); int win_addnstr(window_t *win, const char *str, size_t n); void win_clrtoeol(window_t *win); void win_clrtobol(window_t *win); void win_clrtobot(window_t *win); void win_clrtotop(window_t *win); void win_set_cursor(window_t *win, cursor_t cursor_state); void win_save_cursor(window_t *win); void win_restore_cursor(window_t *win); void win_set_cup(window_t *win, td_bool cup_active); td_bool win_get_cup(window_t *win); /*============= in write_image.c =============*/ #ifdef HAVE_CAIRO void win_write_image(window_t *winA, window_t *winB, const char *name); extern int cell_width, cell_height; extern const char *option_font; #endif #endif termdebug-2.2+dfsg/src/write_image.c000066400000000000000000000236541254722562400175240ustar00rootroot00000000000000/* Copyright (C) 2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 #include #include #include #include "window.h" /* TODO: these should be setable from the command line */ int cell_width = 8, cell_height = 16; const char *option_font = "DejaVu Sans Mono"; typedef struct { const char idx; const char *utf8, *alt; } acs_map_t; static acs_map_t acs_map[] = { { '}', "\xc2\xa3", "f" }, /* U+00A3 POUND SIGN [1.1] */ { '.', "\xe2\x96\xbc", "v" }, /* U+25BC BLACK DOWN-POINTING TRIANGLE [1.1] */ { ',', "\xe2\x97\x80", "<" }, /* U+25C0 BLACK LEFT-POINTING TRIANGLE [1.1] */ { '+', "\xe2\x96\xb6", ">" }, /* U+25B6 BLACK RIGHT-POINTING TRIANGLE [1.1] */ { '-', "\xe2\x96\xb2", "^" }, /* U+25B2 BLACK UP-POINTING TRIANGLE [1.1] */ { 'h', "\xe2\x96\x92", "#" }, /* U+2592 MEDIUM SHADE [1.1] */ { '~', "\xc2\xb7", "o" }, /* U+00B7 MIDDLE DOT [1.1] */ { 'a', "\xe2\x96\x92", ":" }, /* U+2592 MEDIUM SHADE [1.1] */ { 'f', "\xc2\xb0", "\\" }, /* U+00B0 DEGREE SIGN [1.1] */ { '`', "\xe2\x97\x86", "+" }, /* U+25C6 BLACK DIAMOND [1.1] */ { 'z', "\xe2\x89\xa5", ">" }, /* U+2265 GREATER-THAN OR EQUAL TO [1.1] */ { '{', "\xcf\x80", "*" }, /* U+03C0 GREEK SMALL LETTER PI [1.1] */ { 'q', "\xe2\x94\x80", "-" }, /* U+2500 BOX DRAWINGS LIGHT HORIZONTAL [1.1] */ /* Should probably be something like a crossed box, for now keep #. - ncurses maps to SNOWMAN! - xterm shows 240B, which is not desirable either */ { 'i', "#", "#" }, { 'n', "\xe2\x94\xbc", "+" }, /* U+253C BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL [1.1] */ { 'y', "\xe2\x89\xa4", "<" }, /* U+2264 LESS-THAN OR EQUAL TO [1.1] */ { 'm', "\xe2\x94\x94", "+" }, /* U+2514 BOX DRAWINGS LIGHT UP AND RIGHT [1.1] */ { 'j', "\xe2\x94\x98", "+" }, /* U+2518 BOX DRAWINGS LIGHT UP AND LEFT [1.1] */ { '|', "\xe2\x89\xa0", "!" }, /* U+2260 NOT EQUAL TO [1.1] */ { 'g', "\xc2\xb1", "#" }, /* U+00B1 PLUS-MINUS SIGN [1.1] */ { 'o', "\xe2\x8e\xba", "~" }, /* U+23BA HORIZONTAL SCAN LINE-1 [3.2] */ { 'p', "\xe2\x8e\xbb", "-" }, /* U+23BB HORIZONTAL SCAN LINE-3 [3.2] */ { 'r', "\xe2\x8e\xbc", "-" }, /* U+23BC HORIZONTAL SCAN LINE-7 [3.2] */ { 's', "\xe2\x8e\xbd", "_" }, /* U+23BD HORIZONTAL SCAN LINE-9 [3.2] */ { '0', "\xe2\x96\xae", "#" }, /* U+25AE BLACK VERTICAL RECTANGLE [1.1] */ { 'w', "\xe2\x94\xac", "+" }, /* U+252C BOX DRAWINGS LIGHT DOWN AND HORIZONTAL [1.1] */ { 'u', "\xe2\x94\xa4", "+" }, /* U+2524 BOX DRAWINGS LIGHT VERTICAL AND LEFT [1.1] */ { 't', "\xe2\x94\x9c", "+" }, /* U+251C BOX DRAWINGS LIGHT VERTICAL AND RIGHT [1.1] */ { 'v', "\xe2\x94\xb4", "+" }, /* U+2534 BOX DRAWINGS LIGHT UP AND HORIZONTAL [1.1] */ { 'l', "\xe2\x94\x8c", "+" }, /* U+250C BOX DRAWINGS LIGHT DOWN AND RIGHT [1.1] */ { 'k', "\xe2\x94\x90", "+" }, /* U+2510 BOX DRAWINGS LIGHT DOWN AND LEFT [1.1] */ { 'x', "\xe2\x94\x82", "|" } /* U+2502 BOX DRAWINGS LIGHT VERTICAL [1.1] */ }; static void color2rgb(int color, int *red, int *green, int *blue) { if (color < 16) { int color_map[16][3] = { { 0, 0, 0 }, { 205, 0, 0 }, { 0, 205, 0 }, { 205, 205, 0 }, { 0, 0, 238 }, { 205, 0, 205 }, { 0, 205, 205 }, { 229, 229, 229 }, { 127, 127, 127 }, { 255, 0, 0 }, { 0, 255, 0 }, { 255, 255, 0 }, { 92, 92, 255 }, { 255, 0, 255 }, { 0, 255, 255 }, { 255, 255, 255} }; *red = color_map[color][0]; *green = color_map[color][1]; *blue = color_map[color][2]; } else if (color < 232) { color -= 16; *red = color / 36; color -= 36 * *red; *red = *red == 0 ? 0 : 55 + 40 * *red; *green = color / 6; color -= 6 * *green; *green = *green == 0 ? 0 : 55 + 40 * *green; *blue = color; *blue = *blue == 0 ? 0 : 55 + 40 * *blue; } else if (color < 256) { color -= 232; *red = *green = *blue = color * 10 + 8; } else if (color == 256) { *red = *green = *blue = 0; } else if (color == 257) { *red = *green = *blue = 255; } } static void set_context_from_attr_idx(cairo_t *cr, PangoLayout *layout, PangoFontDescription *normal, PangoFontDescription *bold, attr_t attr) { int fg_color, bg_color; int r, g, b; if (attr & ATTR_BOLD) { pango_layout_set_font_description(layout, bold); } else { pango_layout_set_font_description(layout, normal); } fg_color = ((attr & ATTR_FG_MASK) >> ATTR_COLOR_SHIFT) - 1; bg_color = ((attr & ATTR_BG_MASK) >> (ATTR_COLOR_SHIFT + 9)) - 1; if (fg_color < 0) fg_color = 256; if (bg_color < 0) bg_color = 257; if (attr & ATTR_REVERSE) { int tmp; tmp = fg_color; fg_color = bg_color; bg_color = tmp; } color2rgb(bg_color, &r, &g, &b); cairo_set_source_rgb(cr, r, g, b); cairo_fill(cr); color2rgb(fg_color, &r, &g, &b); cairo_set_source_rgb(cr, r, g, b); } static void write_chars(cairo_t *cr, PangoLayout *layout, const char *str, size_t len) { size_t idx = 0, bytes; while (idx < len) { get_value(str + idx, &bytes); pango_layout_set_text(layout, str + idx, bytes); pango_cairo_show_layout(cr, layout); idx += bytes; } } #if 0 /* FIXME: finish drawing of the following attributes. */ /** Draw characters blinking. */ #define ATTR_BLINK ((attr_t) (1L << 4)) /** Draw characters with dim appearance. */ #define ATTR_DIM ((attr_t) (1L << 5)) /** Draw characters with stand-out. */ #define ATTR_STAND_OUT ((attr_t) (1L << 7)) #endif static void write_single_image(window_t *win, int offset, cairo_t *cr, PangoLayout *layout, PangoFontDescription *font_description, PangoFontDescription *bold_font_description) { int i, j; for (i = 0; i < win->height; i++) { int idx; for (j = 0, idx = 0; j < win->width && idx < win->lines[i].length; j++) { uint32_t block_size; attr_t attr; size_t bytes; td_bool fullwidth = td_false; block_size = get_value(win->lines[i].data + idx, &bytes); if (_BLOCK_SIZE_TO_WIDTH(block_size) == 2) fullwidth = td_true; cairo_rectangle(cr, j * cell_width + offset, i * cell_height, fullwidth ? cell_width * 2 : cell_width, cell_height); cairo_clip(cr); /* Set up path for fill. */ cairo_rectangle(cr, j * cell_width + offset, i * cell_height, fullwidth ? cell_width * 2 : cell_width, cell_height); block_size >>= 1; idx += bytes; attr = get_attr(get_value(win->lines[i].data + idx, &bytes)); idx += bytes; block_size -= bytes; set_context_from_attr_idx(cr, layout, font_description, bold_font_description, attr); if (!(attr & ATTR_INVISIBLE)) { cairo_move_to(cr, j * cell_width + offset, i * cell_height); if (attr & ATTR_ACS) { size_t k; for (k = 0; k < ARRAY_SIZE(acs_map); k++) { if (acs_map[k].idx == win->lines[i].data[idx]) { pango_layout_set_text(layout, acs_map[k].utf8, strlen(acs_map[k].utf8)); if (pango_layout_get_unknown_glyphs_count(layout) > 0) pango_layout_set_text(layout, acs_map[k].alt, strlen(acs_map[k].alt)); pango_cairo_show_layout(cr, layout); break; } } } else { write_chars(cr, layout, win->lines[i].data + idx, block_size); } } if (attr & ATTR_UNDERLINE) { cairo_move_to(cr, j * cell_width + 0.5 + offset, (i + 1) * cell_height - 0.5); cairo_line_to(cr, (j + 1) * cell_width - 0.5 + offset, (i + 1) * cell_height - 0.5); cairo_close_path(cr); cairo_set_line_width(cr, 1); cairo_stroke(cr); } idx += block_size; if (fullwidth) j++; cairo_reset_clip(cr); } } if (win->cursor_state != CURSOR_INVIS) { if (win->cursor_state == CURSOR_NORM) { cairo_rectangle(cr, win->paint_x * cell_width + 0.5 + offset, win->paint_y * cell_height + 0.5, cell_width - 1, cell_height - 1); cairo_set_line_width(cr, 1); } else { cairo_rectangle(cr, win->paint_x * cell_width + 1 + offset, win->paint_y * cell_height + 1, cell_width - 2, cell_height - 2); cairo_set_line_width(cr, 2); } cairo_set_operator(cr, CAIRO_OPERATOR_DIFFERENCE); cairo_set_source_rgb(cr, 255, 255, 255); cairo_stroke(cr); cairo_set_operator(cr, CAIRO_OPERATOR_OVER); } } void win_write_image(window_t *winA, window_t *winB, const char *name) { cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, winA->width * cell_width + winB->width * cell_width + 4, MAX(winA->height, winB->height) * cell_height); cairo_t *cr = cairo_create(surface); cairo_surface_t *mask_surface = cairo_image_surface_create(CAIRO_FORMAT_A1, cell_width, cell_height); cairo_t *mask_cr = cairo_create(mask_surface); PangoLayout *layout; PangoFontDescription *font_description, *bold_font_description; cairo_set_source_rgba(mask_cr, 0, 0, 0, 1); cairo_paint(mask_cr); font_description = pango_font_description_new(); pango_font_description_set_family(font_description, option_font); bold_font_description = pango_font_description_new(); pango_font_description_set_absolute_size(font_description, cell_height * PANGO_SCALE * 0.75); pango_font_description_set_family(bold_font_description, option_font); pango_font_description_set_weight(bold_font_description, PANGO_WEIGHT_BOLD); pango_font_description_set_absolute_size(bold_font_description, cell_height * PANGO_SCALE * 0.75); layout = pango_cairo_create_layout(cr); pango_layout_set_font_description(layout, font_description); write_single_image(winA, 0, cr, layout, font_description, bold_font_description); write_single_image(winB, winA->width * cell_width + 4, cr, layout, font_description, bold_font_description); g_object_unref(layout); pango_font_description_free(font_description); cairo_destroy(cr); cairo_surface_write_to_png(surface, name); cairo_surface_destroy(surface); cairo_destroy(mask_cr); cairo_surface_destroy(mask_surface); return; } termdebug-2.2+dfsg/src/write_stringlist.c000066400000000000000000000402631254722562400206370ustar00rootroot00000000000000/* Copyright (C) 2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 #include #include #include "write_stringlist.h" #include "curses_handling.h" /* FIXME: - allow specification of the Unicode full-width support level */ typedef enum { ACTION_NONE, ACTION_ATTR_OFF, ACTION_ATTR_ON, ACTION_CLEAR, ACTION_CR, ACTION_CUP_OFF, ACTION_CUP_ON, ACTION_CURSOR_INVIS, ACTION_CURSOR_NORMAL, ACTION_CURSOR_VVIS, ACTION_HOME, ACTION_RESTORE_CURSOR, ACTION_SAVE_CURSOR, ACTION_SCROLL_BCK, ACTION_SCROLL_FWD, ACTION_TAB } action_t; typedef struct { const char *name; char *str; action_t action; attr_t attr; } terminfo_mapping_t; static iconv_t iconv_handle; static terminfo_mapping_t terminfo_mappings[] = { /* WARNING: do not change the order of the attributes below, or insert any new items except for at the end. Otherwise, the REV_IDX, RMSO_IDX and SMSO_IDX values below have to be adjusted accordingly. */ { "blink", NULL, ACTION_ATTR_ON, ATTR_BLINK }, { "bold", NULL, ACTION_ATTR_ON, ATTR_BOLD }, { "civis", NULL, ACTION_CURSOR_INVIS, 0 }, { "clear", NULL, ACTION_CLEAR, 0 }, { "cnorm", NULL, ACTION_CURSOR_NORMAL, 0 }, { "cr", NULL, ACTION_CR, 0 }, { "cvvis", NULL, ACTION_CURSOR_VVIS, 0 }, { "home", NULL, ACTION_HOME, 0 }, { "ht", NULL, ACTION_TAB, 0 }, { "hts", NULL, ACTION_NONE, 0 }, { "ind", NULL, ACTION_SCROLL_FWD, 0 }, { "invis", NULL, ACTION_ATTR_ON, ATTR_INVISIBLE }, { "op", NULL, ACTION_ATTR_OFF, ATTR_FG_MASK | ATTR_BG_MASK }, { "rc", NULL, ACTION_RESTORE_CURSOR, 0 }, { "rev", NULL, ACTION_ATTR_ON, ATTR_REVERSE }, { "ri", NULL, ACTION_SCROLL_BCK, 0 }, { "rmacs", NULL, ACTION_ATTR_OFF, ATTR_ACS }, { "rmam", NULL, ACTION_NONE, 0 }, { "rmcup", NULL, ACTION_CUP_OFF, 0 }, { "rmir", NULL, ACTION_NONE, 0 }, { "rmkx", NULL, ACTION_NONE, 0 }, { "rmso", NULL, ACTION_ATTR_OFF, ATTR_STAND_OUT }, { "rmul", NULL, ACTION_ATTR_OFF, ATTR_UNDERLINE }, { "sc", NULL, ACTION_SAVE_CURSOR, 0 }, { "smacs", NULL, ACTION_ATTR_ON, ATTR_ACS }, { "smam", NULL, ACTION_NONE, 0 }, { "smcup", NULL, ACTION_CUP_ON, 0 }, { "smir", NULL, ACTION_NONE, 0 }, { "smkx", NULL, ACTION_NONE, 0 }, { "smso", NULL, ACTION_ATTR_ON, ATTR_STAND_OUT }, { "smul", NULL, ACTION_ATTR_ON, ATTR_UNDERLINE } }; #define REV_IDX 14 #define RMSO_IDX 21 #define SMSO_IDX 29 static const char *get_param(const char *str, int *param, td_bool *more) { char *endptr; long result = strtol(str, &endptr, 10); if (*endptr == ';') { endptr++; *more = td_true; } else if (*endptr >= 64 && *endptr <= 126) { endptr++; *more = td_false; } else { return NULL; } if (result > INT_MAX || result < 0) return NULL; *param = (int) result; return endptr; } static void do_action(window_t *win, action_t action, attr_t attr) { switch (action) { case ACTION_ATTR_OFF: win_set_default_attrs(win, win_get_default_attrs(win) & ~attr); break; case ACTION_ATTR_ON: win_set_default_attrs(win, win_get_default_attrs(win) | attr); break; case ACTION_CLEAR: win_set_paint(win, 0, 0); win_clrtobot(win); break; case ACTION_CR: win_set_paint(win, win_get_paint_y(win), 0); break; case ACTION_CUP_OFF: win_set_cup(win, td_false); break; case ACTION_CUP_ON: win_set_cup(win, td_true); break; case ACTION_CURSOR_INVIS: win_set_cursor(win, CURSOR_INVIS); break; case ACTION_CURSOR_NORMAL: win_set_cursor(win, CURSOR_NORM); break; case ACTION_CURSOR_VVIS: win_set_cursor(win, CURSOR_VVIS); break; case ACTION_HOME: win_set_paint(win, 0, 0); break; case ACTION_NONE: break; case ACTION_RESTORE_CURSOR: win_restore_cursor(win); break; case ACTION_SAVE_CURSOR: win_save_cursor(win); break; case ACTION_SCROLL_BCK: win_scroll_back(win); break; case ACTION_SCROLL_FWD: win_scroll(win); break; case ACTION_TAB: { int paint_x = win_get_paint_x(win); paint_x = (paint_x & ~0x7) + 8 - (paint_x & 0x7); if (paint_x >= win_get_width(win)) { int paint_y = win_get_paint_y(win); if (paint_y + 1 < win_get_height(win)) win_set_paint(win, paint_y + 1, 0); } else { win_set_paint(win, win_get_paint_y(win), paint_x); } break; } } } static int handle_escape(char *str, int len, window_t *win) { int i; if (len == 0) return 0; for (i = 0; i < (int) ARRAY_SIZE(terminfo_mappings); i++) { size_t ti_len; if (terminfo_mappings[i].str != NULL && terminfo_mappings[i].str[0] == 27 && (ti_len = strlen(terminfo_mappings[i].str + 1)) <= (size_t) len && memcmp(terminfo_mappings[i].str + 1, str, ti_len) == 0) { do_action(win, terminfo_mappings[i].action, terminfo_mappings[i].attr); return ti_len; } } if (str[0] == '[') { int param = 1; td_bool more; for (i = 1; i < len && (str[i] < 64 || str[i] > 126) && str[i] != 27; i++) {} if (i == len) return 0; switch (str[i]) { case 'A': /* Cursor up (n or 1) */ if (get_param(str + 1, ¶m, &more) == NULL || more) break; win_set_paint(win, win_get_paint_y(win) - param, win_get_paint_x(win)); break; case 'B': /* Cursor down (n or 1) */ if (get_param(str + 1, ¶m, &more) == NULL || more) break; win_set_paint(win, win_get_paint_y(win) + param, win_get_paint_x(win)); break; case 'C': /* Cursor forward (n or 1) */ if (get_param(str + 1, ¶m, &more) == NULL || more) break; win_set_paint(win, win_get_paint_y(win), win_get_paint_x(win) + param); break; case 'D': /* Cursor back (n or 1) */ if (get_param(str + 1, ¶m, &more) == NULL || more) break; win_set_paint(win, win_get_paint_y(win), win_get_paint_x(win) - param); break; case 'E': /* Cursor next line (n or 1) (like 'B' but set x to 0) */ if (get_param(str + 1, ¶m, &more) == NULL || more) break; win_set_paint(win, win_get_paint_y(win) + param, 0); break; case 'F': /* Cursor previous line (n or 1) (like 'B' but set x to 0) */ if (get_param(str + 1, ¶m, &more) == NULL || more) break; win_set_paint(win, win_get_paint_y(win) - param, 0); break; case 'G': /* Cursor horizontal absolute */ if (i == 2 || get_param(str + 1, ¶m, &more) == NULL || more) break; win_set_paint(win, win_get_paint_y(win), param - 1); break; case 'f': /* Same as cup */ case 'H': { /* Cursor position */ const char *new_str; int param2; if (!win_get_cup(win)) break; if ((new_str = get_param(str + 1, ¶m, &more)) == NULL || !more || get_param(new_str, ¶m2, &more) == NULL || more) break; win_set_paint(win, param - 1, param2 - 1); break; } case 'J': /* Erase data (0 or missing = to end, 1 = to beginning, 2 = entire screen) */ if (param == 0) { win_clrtobot(win); } else if (param == 1) { win_clrtotop(win); } else if (param == 2) { win_clrtobot(win); win_clrtotop(win); } break; case 'K': /* Erase line (0 or missing = to end, 1 = to beginning, 2 = entire line) */ param = 0; if (get_param(str + 1, ¶m, &more) == NULL || more) break; if (param == 0) { win_clrtoeol(win); } else if (param == 1) { win_clrtobol(win); } else if (param == 2) { win_clrtoeol(win); win_clrtobol(win); } break; case 'S': /* Scroll up (n or 1) */ if (get_param(str + 1, ¶m, &more) == NULL || more) break; for (; param > 0; param--) win_scroll(win); break; case 'T': /* Scroll down (n or 1) */ if (get_param(str + 1, ¶m, &more) == NULL || more) break; for (; param > 0; param--) win_scroll_back(win); break; case 'd': /* Vertical position absolute */ if (i == 2 || get_param(str + 1, ¶m, &more) == NULL || more) break; win_set_paint(win, param - 1, win_get_paint_x(win)); break; case 'm': /* Set graphics rendition (SGR) */ param = 0; str++; while ((str = (char *) get_param(str, ¶m, &more)) != NULL) { if (param == 0) { /* Turn all attributes off, except ACS. At least xterm does not consider it an "attribute" in the normal sense. */ win_set_default_attrs(win, win_get_default_attrs(win) & ATTR_ACS); } else if (param == 1) { win_set_default_attrs(win, win_get_default_attrs(win) | ATTR_BOLD); } else if (param == 2) { win_set_default_attrs(win, win_get_default_attrs(win) | ATTR_DIM); } else if (param == 4) { win_set_default_attrs(win, win_get_default_attrs(win) | ATTR_UNDERLINE); } else if (param == 5) { win_set_default_attrs(win, win_get_default_attrs(win) | ATTR_BLINK); } else if (param == 7) { win_set_default_attrs(win, win_get_default_attrs(win) | ATTR_REVERSE); } else if (param == 8) { win_set_default_attrs(win, win_get_default_attrs(win) | ATTR_INVISIBLE); } else if (param == 21) { win_set_default_attrs(win, win_get_default_attrs(win) & ~ATTR_BOLD); } else if (param == 22) { win_set_default_attrs(win, win_get_default_attrs(win) & ~(ATTR_BOLD | ATTR_DIM)); } else if (param == 24) { win_set_default_attrs(win, win_get_default_attrs(win) & ~ATTR_UNDERLINE); } else if (param == 25) { win_set_default_attrs(win, win_get_default_attrs(win) & ~ATTR_BLINK); } else if (param == 27) { win_set_default_attrs(win, win_get_default_attrs(win) & ~ATTR_REVERSE); } else if (param == 28) { win_set_default_attrs(win, win_get_default_attrs(win) & ~ATTR_INVISIBLE); } else if (param >= 30 && param < 38) { win_set_default_attrs(win, (win_get_default_attrs(win) & ~ATTR_FG_MASK) | ATTR_FG(param - 30)); } else if (param == 38) { if ((str = (char *) get_param(str, ¶m, &more)) == NULL) break; if (param == 5) { if (!more || (str = (char *) get_param(str, ¶m, &more)) == NULL) break; if (param < 256) win_set_default_attrs(win, (win_get_default_attrs(win) & ~ATTR_FG_MASK) | ATTR_FG(param)); } } else if (param == 39) { win_set_default_attrs(win, win_get_default_attrs(win) & ~ATTR_FG_MASK); } else if (param >= 40 && param < 48) { win_set_default_attrs(win, (win_get_default_attrs(win) & ~ATTR_BG_MASK) | ATTR_BG(param - 40)); } else if (param == 48) { if ((str = (char *) get_param(str, ¶m, &more)) == NULL) break; if (param == 5) { if (!more || (str = (char *) get_param(str, ¶m, &more)) == NULL) break; if (param < 256) win_set_default_attrs(win, (win_get_default_attrs(win) & ~ATTR_BG_MASK) | ATTR_BG(param)); } } else if (param == 49) { win_set_default_attrs(win, win_get_default_attrs(win) & ~ATTR_BG_MASK); } param = 0; /* Retrieving more parameters may have exhausted the string. */ if (!more) break; } break; case 'n': /* With parameter 6: device status report */ break; default: break; } return i + 1; } else if (str[0] == ']') { /* OSC (operating system control). These may be used to set the title of the terminal etc. */ for (i = 1; i < len; i++) { if (str[i] == 7) return i + 1; if (str[i] == 27 && i + 1 < len && str[i] == '\\') return i + 2; } return 0; } return 0; } static int write_text(window_t *win, int start, int end, td_bool force) { char output[1024], *output_ptr; char *input_ptr = win->output_buffer.data + start; size_t inbytes_left = end - start, outbytes_left; size_t result; int saved_errno; if (iconv_handle == (iconv_t) -1) { win_addnstr(win, win->output_buffer.data + start, inbytes_left); return 0; } while (td_true) { output_ptr = output; outbytes_left = sizeof(output); result = iconv(iconv_handle, &input_ptr, &inbytes_left, &output_ptr, &outbytes_left); saved_errno = errno; if (outbytes_left != sizeof(output)) win_addnstr(win, output, sizeof(output) - outbytes_left); if (result == (size_t) -1) { if (saved_errno == EILSEQ) { input_ptr++; inbytes_left--; win_addnstr(win, "\357\277\275", 3); } else if (saved_errno == EINVAL) { if (force) { inbytes_left = 0; outbytes_left = 0; iconv(iconv_handle, NULL, &inbytes_left, NULL, &outbytes_left); win_addnstr(win, "\357\277\275", 3); return 0; } else { return (int) inbytes_left; } } else if (saved_errno != E2BIG) { fatal("Error in character-set conversion\n"); } } else { return 0; } } } static void parse_output_buffer(window_t *win) { int i, j; int start_normal; int handled; start_normal = 0; for (i = 0; i < win->output_buffer.length; i++) { if (win->output_buffer.data[i] < 32 && win->output_buffer.data[i] >= 0) { if (i != start_normal) write_text(win, start_normal, i, td_true); if (win->output_buffer.data[i] == 27) { if ((handled = handle_escape(win->output_buffer.data + i + 1, win->output_buffer.length - i, win)) == 0) { win->output_buffer.length -= i; memmove(win->output_buffer.data, win->output_buffer.data + i, win->output_buffer.length); return; } i += handled; } else { /* Check single character, non-escape terminfo mappings */ for (j = 0; j < (int) ARRAY_SIZE(terminfo_mappings); j++) { if (terminfo_mappings[j].str != NULL && terminfo_mappings[j].str[1] == 0 && terminfo_mappings[j].str[0] == win->output_buffer.data[i]) { do_action(win, terminfo_mappings[j].action, terminfo_mappings[j].attr); break; } } /* If the terminfo mappings didn't yield a result, check for other standard control characters. */ if (j >= (int) ARRAY_SIZE(terminfo_mappings)) { switch (win->output_buffer.data[i]) { case 8: /* Backspace */ win_set_paint(win, win_get_paint_y(win), win_get_paint_x(win) - 1); break; case 9: /* Tab */ do_action(win, ACTION_TAB, 0); break; case 10: /* NL */ if (win_get_paint_y(win) == win_get_height(win) - 1) win_scroll(win); else win_set_paint(win, win_get_paint_y(win) + 1, win_get_paint_x(win)); break; case 13: /* CR */ do_action(win, ACTION_CR, 0); break; default: break; } } } start_normal = i + 1; } } if (start_normal != i) { int to_save = write_text(win, start_normal, win->output_buffer.length, td_false); memmove(win->output_buffer.data, win->output_buffer.data + win->output_buffer.length - to_save, to_save); win->output_buffer.length = to_save; } else { win->output_buffer.length = 0; } } void win_write_data(window_t *win, char *data, size_t length) { if (!ensure_space(&win->output_buffer, length)) fatal("Out of memory\n"); memcpy(win->output_buffer.data + win->output_buffer.length, data, length); win->output_buffer.length += length; parse_output_buffer(win); } void win_write_stringlist(window_t *win, StringListNode *string) { for (; string != NULL; string = string->next) win_write_data(win, string->string, string->length); } void setup_ti_strings(const char *term, const char *lang) { size_t i; const char *codeset; call_setupterm(term); for (i = 0; i < ARRAY_SIZE(terminfo_mappings); i++) terminfo_mappings[i].str = get_ti_string(terminfo_mappings[i].name); if (strcmp(terminfo_mappings[REV_IDX].str, terminfo_mappings[SMSO_IDX].str) == 0) { free(terminfo_mappings[SMSO_IDX].str); free(terminfo_mappings[RMSO_IDX].str); terminfo_mappings[SMSO_IDX].str = NULL; terminfo_mappings[RMSO_IDX].str = NULL; } win_bce = get_ti_bool("bce") != 0; /* Initialize the character-set convertion, based on the current LANG setting. */ if (lang == NULL) iconv_handle = (iconv_t) -1; else if ((codeset = strchr(lang, '.')) != NULL) iconv_handle = iconv_open("UTF-8", codeset + 1); else if (strcmp(lang, "C") == 0 || strcmp(lang, "POSIX") == 0) iconv_handle = iconv_open("UTF-8", "ANSI_X3.4-1968"); else iconv_handle = (iconv_t) -1; } termdebug-2.2+dfsg/src/write_stringlist.h000066400000000000000000000016121254722562400206370ustar00rootroot00000000000000/* Copyright (C) 2013 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 . */ #ifndef WRITE_STRINGLIST_H #define WRITE_STRINGLIST_H #include "replay.h" #include "window.h" void win_write_data(window_t *win, char *data, size_t length); void win_write_stringlist(window_t *win, StringListNode *string); void setup_ti_strings(const char *term, const char *lang); #endif