commit f255ae1922e1c1d07ef03a920f7ce5d4476ea6aa Author: Jim Date: Mon Sep 30 19:37:13 2013 -0700 first commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..fb5e4e664 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +* text=auto + +*.sln text eol=crlf +*.vcproj text eol=crlf +*.vcxproj text eol=crlf +*.vcxproj text eol=crlf +*.vcxproj.filters text eol=crlf diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..173be7bc7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,36 @@ +*.exe +*.dll + +/other/ +Release_MD/ +Release/ +Debug/ +x64/ +ipch/ + +tags +*.swp +*.dat +*.clbin +*.log +*.tlog +*.sdf +*.opensdf +*.xml +*.ipch +*.css +*.xslt +*.aps +*.suo +*.ncb +*.user +*.o +*.obj +*.pdb +*.res +*.manifest +*.dep +*.zip +*.lnk +*.chm +*~ diff --git a/COPYING b/COPYING new file mode 100644 index 000000000..94a9ed024 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README b/README new file mode 100644 index 000000000..5acc89f36 --- /dev/null +++ b/README @@ -0,0 +1,166 @@ + +What is OBS? + + This project is a rewrite of what was formerly known as "Open Broadcaster + Software", software originally designed for recording and streaming live + video content, efficiently. + + +What's the goal of rewriting OBS? + + - Make it multiplatform. Use multiplatform libraries/functions/classes where + possible to allow this. Multi-platform support was one of the primary + reasons for the rewrite. This also means using a UI toolkit will be + necessary for user interface. It also means allowing the use of OpenGL as + well as Direct3D. + + - Separate the application from the core, allowing custom user interfaces and + custom appliction of the core if desired, and easier extending of the user + interface. + + - Simplify complex systems to not only make it easier to use, but easier to + maintain. + + - Write a better core API, and design the entire system to be modular. + + - Now that we have much more experience, improve the overall design of all + the subsystems/API, and minimize/eliminate design flaws. Make it so we can + do all the things we've had trouble with before, such as custom outputs, + multiple outputs at once, better handling of inputs, custom services. + + - Make a better/cleaner code base, use better coding standards, use standard + libraries where possible (not just STL and C standard library, but also + things like ffmpeg as well), and improve maintainability of the project as a + whole. + + - Implement a new API-independent shader/effect system allowing better and + easier shaders usage and customization without having to duplicate shader + code. + + - Better device support. Again, I didn't know what I was getting into when + I originally started writing code for devices. It evolved into a totally + convoluted mess. I would have improved the existing device plugin code, but + it was just all so fundamentally bad and flawed that it would have been + detrimental to progression to continue working on it rather than rewrite it. + + +What was wrong with the original OBS? + + The original OBS was rewritten not because it was bad, at least in terms of + optimization. Optimization and graphics are things I love. However, there + were some serious problems with the code and design that were deep and + fundamental, which prevented myself and other developers from being able to + improve/extend the application or add new features very easily. + + First, the design flaws: + + - The original OBS was completely and hopelessly hard-coded for windows, + and only windows. It was just totally impossible to use it on other + systems. + + - All the sub-systems were written before I really knew what I was getting + into. When I started the project, I didn't really fully comprehend the + scope of what I would need or how to properly design the project. My + design and plans for the application were just to write something that + would "stream games and a webcam, with things like overlays and such." + This turned out fine for most casual gamers and streamers (and very + successful), but left anyone wanting to do anything more advanced left + massively wanting. + + - Subsystems and core functionalities intermingled in such a way that it + was a nightmare to get proper custom functionality out of it. Things + like QSV had to be meshed in with the main encoding loop, and it just + made things a nightmare to deal with. Custom outputs were nigh + impossible. + + - The API was poorly designed because most of it came after I originally + wrote the application, it was more of an afterthought, and plugin API + would routinely break for plugin developers due to changing C++ + interfaces (one of the reasons the core is now C). + + - API was intermeshed with the main executable. The OBSApi DLL was + nothing more than basically this mutant growth upon OBS.exe that allowed + plugin developers to barely write plugins, but all the important API + code was actually stored in the executable. Navigation was a total mess. + + - The graphics subsystem, while not bad, was incomplete, and though far + easier to use than bare D3D, wasn't ideal, and was hard-coded for D3D + specifically. + + - The devices and audio code was poor, I had no idea what I was getting into + when I started writing them in. I did not realize beforehand all the + device-specific quirks that each device/system could have. Some devices + had bad timing and quirks that I never aniticipated while writing them. + I struggled with devices, and my original design for the audio subsystem + for example morphed over and over into an abomination that, though works, + is basically this giant duct-taped zombie monster. + + - Shaders were difficult to customize because they had to be duplicated if + you wanted slightly different functionality that required more than just + changing shader constants. + + - Oriantation of sources was fixed, and required special code for each + source to do any custom modification of rotation/position/scale/etc. + This is one of those fundamental flaws that I look back on and regret, as + it was a stupid idea from the beginning. I originally thought I could + get more accurate source position/sizes, but it just turned out to be + totally bad. Should have been matrices from the beginning just like with + a regular 3D engine. + + Second, the coding flaws: + + - The coding style was inconsistent. + + - C++98, C-Style C++, there was no exception usage, no STL. C++ used + poorly. + + - Not Invented Here Syndrome everywhere. Custom string functions/classes, + custom templates, custom everything everywhere. To be fair, it was all + hand-me-down code from the early 2000s that I had become used to, but + that was no excuse -- C-standard libraries and the STL should have been + used from the beginning over anything else. That doesn't mean to say + that using custom stuff is always bad, but doing it to the extent I did + definitely was. Made it horrible to maintain as well, required extra + knowledge for plugin developers and anyone messing with the code. + + - Giant monolithic classes everywhere, the main OBS class was paricularly + bad in this regard. This meant navigation was a nightmare, and no one + really knew where to go or where to add/change things. + + - Giant monolithic functions everywhere. This was particularly bad + because it meant that functions became harder to debug and harder to + keep track of what was going on in any particular function at any given + time. These large functions, though not inefficient, were delicate and + easily breakable. (See OBS::MainCaptureLoop for a nightmarish example, + or the listbox subclass window procedure in WindowStuff.cpp) + + - Very large file sizes with everything clumped up into single files (for + another particularly nightmarish example, see WindowStuff.cpp) + + - Bad formatting. Code could go beyond 200 columns in some cases, making + it very unpleasant to read with many editors. Spaces instead of tabs, + K&R mixed with allman (which was admittedly my fault). + + +New (actual) coding guidelines + + - For the C code (especially in the core), guidelines are pretty strict K&R, + kernel style. See the linux kernel "CodingStyle" document for more + information. That particular coding style guideline is for more than just + style, it actually helps produce a better overall code base. + + - For C++ code, I still use CamelCase instead of all_lowercase just because + I prefer it that way, it feels right with C++ for some reason. It also + helps make it distinguishable from C code. + + - I've started using 8-column tabs for almost everything -- I really + personally like it over 4-column tabs. I feel that 8-column tabs are very + helpful in preventing large amounts of indentation. A self-imposed + limitation, if you will. I also use actual tabs now, instead of spaces. + Also, I feel that the K&R style looks much better/cleaner when viewed with + 8-column tabs. + + - Preferred maximum columns: 80. I've also been doing this because in + combination with 8-column tabs, it further prevents large/bad functions + with high indentation. Another self-imposed limitation. Also, it makes + for much cleaner viewing in certain editors that wrap (like vim). diff --git a/build/.gitignore b/build/.gitignore new file mode 100644 index 000000000..e69de29bb diff --git a/config.mak b/config.mak new file mode 100644 index 000000000..2eb2a7fdc --- /dev/null +++ b/config.mak @@ -0,0 +1,12 @@ +SRCPATH=. +CC=gcc +CCDEP=gcc +CFLAGS=-std=gnu99 -I$(SRCPATH) +CXXFLAGS=-std=c++11 -I$(SRCPATH) +#CPPFLAGS=-Wall -msse2 -O3 -ffast-math -fomit-frame-pointer +CPPFLAGS=-Wall -msse2 -g +LD=gcc -o +LDFLAGS=-shared +OBJ=o +SOEXT=dll +EXT=.exe diff --git a/libobs-d3d11/GS_D3D11Exports.h b/libobs-d3d11/GS_D3D11Exports.h new file mode 100644 index 000000000..03777b957 --- /dev/null +++ b/libobs-d3d11/GS_D3D11Exports.h @@ -0,0 +1,200 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef GS_D3D11EXPORTS_H +#define GS_D3D11EXPORTS_H + +#include "util/c99defs.h" + +extern "C" { + +EXPORT device_t device_create(struct gs_init_data *data); +EXPORT void device_destroy(device_t device); +EXPORT swapchain_t device_create_swapchain(device_t device, + struct gs_init_data *data); +EXPORT void device_resize(device_t device, uint32_t x, uint32_t y); +EXPORT void device_getsize(device_t device, uint32_t *x, uint32_t *y); +EXPORT uint32_t device_getwidth(device_t device); +EXPORT uint32_t device_getheight(device_t device); +EXPORT texture_t device_create_texture(device_t device, uint32_t width, + uint32_t height, enum gs_color_format color_format, void *data, + uint32_t flags); +EXPORT texture_t device_create_cubetexture(device_t device, uint32_t size, + enum gs_color_format color_format, void *data[6], + uint32_t flags); +EXPORT texture_t device_create_volumetexture(device_t device, uint32_t width, + uint32_t height, uint32_t depth, + enum gs_color_format color_format, void *data, uint32_t flags); +EXPORT zstencil_t device_create_zstencil(device_t device, uint32_t width, + uint32_t height, enum gs_zstencil_format format); +EXPORT stagesurf_t device_create_stagesurface(device_t device, uint32_t width, + uint32_t height, enum gs_color_format color_format); +EXPORT samplerstate_t device_create_samplerstate(device_t device, + struct gs_sampler_info *info); +EXPORT shader_t device_create_vertexshader(device_t device, + const char *shader, const char *file, + char **error_string); +EXPORT shader_t device_create_pixelshader(device_t device, + const char *shader, const char *file, + char **error_string); +EXPORT vertbuffer_t device_create_vertexbuffer(device_t device, + struct vb_data *data, uint32_t flags); +EXPORT indexbuffer_t device_create_indexbuffer(device_t device, + enum gs_index_type type, void *indices, size_t num, + uint32_t flags); +EXPORT enum gs_texture_type device_gettexturetype(device_t device, + texture_t texture); +EXPORT void device_load_vertexbuffer(device_t device, vertbuffer_t vertbuffer); +EXPORT void device_load_indexbuffer(device_t device, indexbuffer_t indexbuffer); +EXPORT void device_load_texture(device_t device, texture_t tex, int unit); +EXPORT void device_load_cubetexture(device_t device, texture_t cubetex, + int unit); +EXPORT void device_load_volumetexture(device_t device, texture_t voltex, + int unit); +EXPORT void device_load_samplerstate(device_t device, + samplerstate_t samplerstate, int unit); +EXPORT void device_load_vertexshader(device_t device, shader_t vertshader); +EXPORT void device_load_pixelshader(device_t device, shader_t pixelshader); +EXPORT void device_load_defaultsamplerstate(device_t device, bool b_3d, + int unit); +EXPORT shader_t device_getvertexshader(device_t device); +EXPORT shader_t device_getpixelshader(device_t device); +EXPORT texture_t device_getrendertarget(device_t device); +EXPORT zstencil_t device_getzstenciltarget(device_t device); +EXPORT void device_setrendertarget(device_t device, texture_t tex, + zstencil_t zstencil); +EXPORT void device_setcuberendertarget(device_t device, texture_t cubetex, + int side, zstencil_t zstencil); +EXPORT void device_copy_texture(device_t device, texture_t dst, texture_t src); +EXPORT void device_stage_texture(device_t device, stagesurf_t dst, + texture_t src); +EXPORT void device_beginscene(device_t device); +EXPORT void device_draw(device_t device, enum gs_draw_mode draw_mode, + uint32_t start_vert, uint32_t num_verts); +EXPORT void device_endscene(device_t device); +EXPORT void device_load_swapchain(device_t device, swapchain_t swapchain); +EXPORT void device_clear(device_t device, uint32_t clear_flags, + struct vec4 *color, float depth, uint8_t stencil); +EXPORT void device_present(device_t device); +EXPORT void device_setcullmode(device_t device, enum gs_cull_mode mode); +EXPORT enum gs_cull_mode device_getcullmode(device_t device); +EXPORT void device_enable_blending(device_t device, bool enable); +EXPORT void device_enable_depthtest(device_t device, bool enable); +EXPORT void device_enable_stenciltest(device_t device, bool enable); +EXPORT void device_enable_stencilwrite(device_t device, bool enable); +EXPORT void device_enable_color(device_t device, bool red, bool blue, + bool green, bool alpha); +EXPORT void device_blendfunction(device_t device, enum gs_blend_type src, + enum gs_blend_type dest); +EXPORT void device_depthfunction(device_t device, enum gs_depth_test test); +EXPORT void device_stencilfunction(device_t device, enum gs_stencil_side side, + enum gs_depth_test test); +EXPORT void device_stencilop(device_t device, enum gs_stencil_side side, + enum gs_stencil_op fail, enum gs_stencil_op zfail, + enum gs_stencil_op zpass); +EXPORT void device_enable_fullscreen(device_t device, bool enable); +EXPORT int device_fullscreen_enabled(device_t device); +EXPORT void device_setdisplaymode(device_t device, + const struct gs_display_mode *mode); +EXPORT void device_getdisplaymode(device_t device, + struct gs_display_mode *mode); +EXPORT void device_setcolorramp(device_t device, float gamma, float brightness, + float contrast); +EXPORT void device_setviewport(device_t device, int x, int y, int width, + int height); +EXPORT void device_getviewport(device_t device, struct gs_rect *rect); +EXPORT void device_setscissorrect(device_t device, struct gs_rect *rect); +EXPORT void device_ortho(device_t device, float left, float right, + float top, float bottom, float znear, float zfar); +EXPORT void device_frustum(device_t device, float left, float right, + float top, float bottom, float znear, float zfar); +EXPORT void device_perspective(device_t device, float fovy, float aspect, + float znear, float zfar); +EXPORT void device_set_view_matrix(device_t device, struct matrix3 *mat); +EXPORT void device_projection_push(device_t device); +EXPORT void device_projection_pop(device_t device); + +EXPORT void swapchain_destroy(swapchain_t swapchain); + +EXPORT void texture_destroy(texture_t tex); +EXPORT uint32_t texture_getwidth(texture_t tex); +EXPORT uint32_t texture_getheight(texture_t tex); +EXPORT enum gs_color_format texture_getcolorformat(texture_t tex); +EXPORT bool texture_map(texture_t tex, void **ptr, uint32_t *byte_width); +EXPORT void texture_unmap(texture_t tex); + +EXPORT void cubetexture_destroy(texture_t cubetex); +EXPORT uint32_t cubetexture_getsize(texture_t cubetex); +EXPORT enum gs_color_format cubetexture_getcolorformat(texture_t cubetex); + +EXPORT void volumetexture_destroy(texture_t voltex); +EXPORT uint32_t volumetexture_getwidth(texture_t voltex); +EXPORT uint32_t volumetexture_getheight(texture_t voltex); +EXPORT uint32_t volumetexture_getdepth(texture_t voltex); +EXPORT enum gs_color_format volumetexture_getcolorformat(texture_t voltex); + +EXPORT void stagesurface_destroy(stagesurf_t stagesurf); +EXPORT uint32_t stagesurface_getwidth(stagesurf_t stagesurf); +EXPORT uint32_t stagesurface_getheight(stagesurf_t stagesurf); +EXPORT enum gs_color_format stagesurface_getcolorformat(stagesurf_t stagesurf); +EXPORT bool stagesurface_map(stagesurf_t stagesurf, const void **data, + uint32_t *byte_width); +EXPORT void stagesurface_unmap(stagesurf_t stagesurf); + +EXPORT void zstencil_destroy(zstencil_t zstencil); + +EXPORT void samplerstate_destroy(samplerstate_t samplerstate); + +EXPORT void vertexbuffer_destroy(vertbuffer_t vertbuffer); +EXPORT void vertexbuffer_flush(vertbuffer_t vertbuffer, bool rebuild); +EXPORT struct vb_data *vertexbuffer_getdata(vertbuffer_t vertbuffer); + +EXPORT void indexbuffer_destroy(indexbuffer_t indexbuffer); +EXPORT void indexbuffer_flush(indexbuffer_t indexbuffer); +EXPORT void *indexbuffer_getdata(indexbuffer_t indexbuffer); +EXPORT size_t indexbuffer_numindices(indexbuffer_t indexbuffer); +EXPORT enum gs_index_type indexbuffer_gettype(indexbuffer_t indexbuffer); + +EXPORT void shader_destroy(shader_t shader); +EXPORT int shader_numparams(shader_t shader); +EXPORT sparam_t shader_getparambyidx(shader_t shader, int param); +EXPORT sparam_t shader_getparambyname(shader_t shader, const char *name); +EXPORT void shader_getparaminfo(shader_t shader, sparam_t param, + struct shader_param_info *info); +EXPORT sparam_t shader_getviewprojmatrix(shader_t shader); +EXPORT sparam_t shader_getworldmatrix(shader_t shader); +EXPORT void shader_setbool(shader_t shader, sparam_t param, bool val); +EXPORT void shader_setfloat(shader_t shader, sparam_t param, float val); +EXPORT void shader_setint(shader_t shader, sparam_t param, int val); +EXPORT void shader_setmatrix3(shader_t shader, sparam_t param, + const struct matrix3 *val); +EXPORT void shader_setmatrix4(shader_t shader, sparam_t param, + const struct matrix4 *val); +EXPORT void shader_setvec2(shader_t shader, sparam_t param, + const struct vec2 *val); +EXPORT void shader_setvec3(shader_t shader, sparam_t param, + const struct vec3 *val); +EXPORT void shader_setvec4(shader_t shader, sparam_t param, + const struct vec4 *val); +EXPORT void shader_settexture(shader_t shader, sparam_t param, texture_t val); +EXPORT void shader_setval(shader_t shader, sparam_t param, const void *val, + size_t size); +EXPORT void shader_setdefault(shader_t shader, sparam_t param); + +} + +#endif diff --git a/libobs-d3d11/GS_D3D11IndexBuffer.cpp b/libobs-d3d11/GS_D3D11IndexBuffer.cpp new file mode 100644 index 000000000..7e15adcc4 --- /dev/null +++ b/libobs-d3d11/GS_D3D11IndexBuffer.cpp @@ -0,0 +1,54 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "GS_D3D11SubSystem.hpp" + +void gs_index_buffer::InitBuffer() +{ + D3D11_BUFFER_DESC bd; + D3D11_SUBRESOURCE_DATA srd; + HRESULT hr; + + memset(&bd, 0, sizeof(bd)); + memset(&srd, 0, sizeof(srd)); + + bd.Usage = dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT; + bd.CPUAccessFlags = dynamic ? D3D11_CPU_ACCESS_WRITE : 0; + bd.BindFlags = D3D11_BIND_INDEX_BUFFER; + bd.ByteWidth = UINT(indexSize * num); + srd.pSysMem = indices.data; + + hr = device->device->CreateBuffer(&bd, &srd, indexBuffer.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create buffer", hr); +} + +gs_index_buffer::gs_index_buffer(device_t device, enum gs_index_type type, + void *indices, size_t num, uint32_t flags) + : device (device), + type (type), + indices (indices), + num (num), + dynamic ((flags & GS_DYNAMIC) != 0) +{ + switch (type) { + case GS_UNSIGNED_SHORT: indexSize = 2; break; + case GS_UNSIGNED_LONG: indexSize = 4; break; + } + + InitBuffer(); +} diff --git a/libobs-d3d11/GS_D3D11SamplerState.cpp b/libobs-d3d11/GS_D3D11SamplerState.cpp new file mode 100644 index 000000000..bf6d6f994 --- /dev/null +++ b/libobs-d3d11/GS_D3D11SamplerState.cpp @@ -0,0 +1,66 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "GS_D3D11SubSystem.hpp" +#include "graphics/vec4.h" + +const D3D11_TEXTURE_ADDRESS_MODE convertAddressMode[] = +{ + D3D11_TEXTURE_ADDRESS_CLAMP, + D3D11_TEXTURE_ADDRESS_WRAP, + D3D11_TEXTURE_ADDRESS_MIRROR, + D3D11_TEXTURE_ADDRESS_BORDER, + D3D11_TEXTURE_ADDRESS_MIRROR_ONCE +}; + +const D3D11_FILTER convertFilter[] = +{ + D3D11_FILTER_MIN_MAG_MIP_LINEAR, + D3D11_FILTER_MIN_MAG_MIP_POINT, + D3D11_FILTER_ANISOTROPIC, + D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR, + D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT, + D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR, + D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT, + D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR, + D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT +}; + +gs_sampler_state::gs_sampler_state(device_t device, gs_sampler_info *info) + : device (device), + info (*info) +{ + D3D11_SAMPLER_DESC sd; + HRESULT hr; + vec4 v4; + + memset(&sd, 0, sizeof(sd)); + sd.AddressU = convertAddressMode[(uint32_t)info->address_u]; + sd.AddressV = convertAddressMode[(uint32_t)info->address_v]; + sd.AddressW = convertAddressMode[(uint32_t)info->address_w]; + sd.ComparisonFunc = D3D11_COMPARISON_ALWAYS; + sd.Filter = convertFilter[(uint32_t)info->filter]; + sd.MaxAnisotropy = info->max_anisotropy; + sd.MaxLOD = FLT_MAX; + + vec4_from_rgba(&v4, info->border_color); + memcpy(sd.BorderColor, v4.ptr, sizeof(v4)); + + hr = device->device->CreateSamplerState(&sd, state.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create sampler state", hr); +} diff --git a/libobs-d3d11/GS_D3D11Shader.cpp b/libobs-d3d11/GS_D3D11Shader.cpp new file mode 100644 index 000000000..1e1c4c139 --- /dev/null +++ b/libobs-d3d11/GS_D3D11Shader.cpp @@ -0,0 +1,338 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "GS_D3D11SubSystem.hpp" +#include "GS_D3D11ShaderProcessor.hpp" +#include "graphics/vec2.h" +#include "graphics/vec3.h" +#include "graphics/matrix3.h" +#include "graphics/matrix4.h" + +void gs_vertex_shader::GetBuffersExpected( + const vector &inputs) +{ + for (size_t i = 0; i < inputs.size(); i++) { + const D3D11_INPUT_ELEMENT_DESC &input = inputs[i]; + if (strcmp(input.SemanticName, "NORMAL") == 0) + hasNormals = true; + else if (strcmp(input.SemanticName, "TANGENT") == 0) + hasTangents = true; + else if (strcmp(input.SemanticName, "COLOR") == 0) + hasColors = true; + else if (strcmp(input.SemanticName, "TEXCOORD") == 0) + nTexUnits++; + } +} + +gs_vertex_shader::gs_vertex_shader(device_t device, const char *file, + const char *shaderString) + : gs_shader (device, SHADER_VERTEX), + hasNormals (false), + hasColors (false), + hasTangents (false), + nTexUnits (0) +{ + vector inputs; + ShaderProcessor processor(device); + ComPtr shaderBlob; + string outputString; + HRESULT hr; + + processor.Process(shaderString, file); + processor.BuildString(outputString); + processor.BuildParams(params); + processor.BuildInputLayout(inputs); + GetBuffersExpected(inputs); + BuildConstantBuffer(); + + Compile(outputString.c_str(), file, "vs_4_0", shaderBlob.Assign()); + + hr = device->device->CreateVertexShader(shaderBlob->GetBufferPointer(), + shaderBlob->GetBufferSize(), NULL, shader.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create vertex shader", hr); + + hr = device->device->CreateInputLayout(inputs.data(), + (UINT)inputs.size(), shaderBlob->GetBufferPointer(), + shaderBlob->GetBufferSize(), layout.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create input layout", hr); + + viewProj = shader_getparambyname(this, "ViewProj"); + world = shader_getparambyname(this, "World"); +} + +gs_pixel_shader::gs_pixel_shader(device_t device, const char *file, + const char *shaderString) + : gs_shader(device, SHADER_PIXEL) +{ + ShaderProcessor processor(device); + ComPtr shaderBlob; + string outputString; + HRESULT hr; + + processor.Process(shaderString, file); + processor.BuildString(outputString); + processor.BuildParams(params); + processor.BuildSamplers(samplers); + BuildConstantBuffer(); + + Compile(outputString.c_str(), file, "ps_4_0", shaderBlob.Assign()); + + hr = device->device->CreatePixelShader(shaderBlob->GetBufferPointer(), + shaderBlob->GetBufferSize(), NULL, shader.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create vertex shader", hr); +} + +void gs_shader::BuildConstantBuffer() +{ + for (size_t i = 0; i < params.size(); i++) { + shader_param ¶m = params[i]; + switch (param.type) { + case SHADER_PARAM_BOOL: + case SHADER_PARAM_INT: + case SHADER_PARAM_FLOAT: constantSize += sizeof(float); break; + case SHADER_PARAM_VEC2: constantSize += sizeof(vec2); break; + case SHADER_PARAM_VEC3: constantSize += sizeof(float)*3; break; + case SHADER_PARAM_VEC4: constantSize += sizeof(vec4); break; + case SHADER_PARAM_MATRIX3X3: + constantSize += sizeof(float)*3*3; + break; + case SHADER_PARAM_MATRIX4X4: + constantSize += sizeof(float)*4*4; + } + } + + if (constantSize) { + D3D11_BUFFER_DESC bd; + HRESULT hr; + + memset(&bd, 0, sizeof(bd)); + bd.ByteWidth = (constantSize+15)&0xFFFFFFF0; /* align */ + bd.Usage = D3D11_USAGE_DYNAMIC; + bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + + hr = device->device->CreateBuffer(&bd, NULL, + constants.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create constant buffer", hr); + } + + for (size_t i = 0; i < params.size(); i++) + shader_setdefault(this, ¶ms[i]); +} + +void gs_shader::Compile(const char *shaderString, const char *file, + const char *target, ID3D10Blob **shader) +{ + ComPtr errorsBlob; + HRESULT hr; + + if (!shaderString) + throw "No shader string specified"; + + hr = D3DCompile(shaderString, strlen(shaderString), file, NULL, NULL, + "main", target, + D3D10_SHADER_OPTIMIZATION_LEVEL1, 0, + shader, errorsBlob.Assign()); + if (FAILED(hr)) { + if (errorsBlob != NULL && errorsBlob->GetBufferSize()) + throw ShaderError(errorsBlob, hr); + else + throw HRError("Failed to compile shader", hr); + } +} + +inline void gs_shader::UpdateParam(vector &constData, + shader_param ¶m, bool &upload) +{ + if (param.type != SHADER_PARAM_TEXTURE) { + if (!param.curValue.size()) + throw "Not all shader parameters were set"; + + constData.insert(constData.end(), + param.curValue.begin(), + param.curValue.end()); + + if (param.changed) { + upload = true; + param.changed = false; + } + } else if (param.curValue.size() == sizeof(texture_t)) { + texture_t tex; + memcpy(&tex, param.curValue.data(), sizeof(texture_t)); + device_load_texture(device, tex, param.textureID); + } +} + +void gs_shader::UploadParams() +{ + vector constData; + bool upload = false; + + constData.reserve(constantSize); + + for (size_t i = 0; i < params.size(); i++) + UpdateParam(constData, params[i], upload); + + if (constData.size() != constantSize) + throw "Invalid constant data size given to shader"; + + if (upload) { + D3D11_MAPPED_SUBRESOURCE map; + HRESULT hr; + + hr = device->context->Map(constants, 0, D3D11_MAP_WRITE_DISCARD, + 0, &map); + if (FAILED(hr)) + throw HRError("Could not lock constant buffer", hr); + + memcpy(map.pData, constData.data(), constData.size()); + device->context->Unmap(constants, 0); + } +} + +void shader_destroy(shader_t shader) +{ + delete shader; +} + +int shader_numparams(shader_t shader) +{ + return (int)shader->params.size(); +} + +sparam_t shader_getparambyidx(shader_t shader, int param) +{ + return &shader->params[param]; +} + +sparam_t shader_getparambyname(shader_t shader, const char *name) +{ + for (size_t i = 0; i < shader->params.size(); i++) { + shader_param ¶m = shader->params[i]; + if (strcmp(param.name.c_str(), name) == 0) + return ¶m; + } + + return NULL; +} + +void shader_getparaminfo(shader_t shader, sparam_t param, + struct shader_param_info *info) +{ + if (!param || !shader) + return; + + info->name = param->name.c_str(); + info->type = param->type; +} + +sparam_t shader_getviewprojmatrix(shader_t shader) +{ + if (shader->type != SHADER_VERTEX) + return NULL; + + return static_cast(shader)->viewProj; +} + +sparam_t shader_getworldmatrix(shader_t shader) +{ + if (shader->type != SHADER_VERTEX) + return NULL; + + return static_cast(shader)->world; +} + +static inline void shader_setval_inline(gs_shader *shader, shader_param *param, + const void *data, size_t size) +{ + assert(param); + if (!param) + return; + + bool size_changed = param->curValue.size() != size; + if (size_changed) + param->curValue.resize(size); + + if (size_changed || memcmp(param->curValue.data(), data, size) != 0) { + memcpy(param->curValue.data(), data, size); + param->changed = true; + } +} + +void shader_setbool(shader_t shader, sparam_t param, bool val) +{ + shader_setval_inline(shader, param, &val, sizeof(bool)); +} + +void shader_setfloat(shader_t shader, sparam_t param, float val) +{ + shader_setval_inline(shader, param, &val, sizeof(float)); +} + +void shader_setint(shader_t shader, sparam_t param, int val) +{ + shader_setval_inline(shader, param, &val, sizeof(int)); +} + +void shader_setmatrix3(shader_t shader, sparam_t param, + const struct matrix3 *val) +{ + shader_setval_inline(shader, param, val, sizeof(matrix3)); +} + +void shader_setmatrix4(shader_t shader, sparam_t param, + const struct matrix4 *val) +{ + shader_setval_inline(shader, param, val, sizeof(matrix4)); +} + +void shader_setvec2(shader_t shader, sparam_t param, const struct vec2 *val) +{ + shader_setval_inline(shader, param, val, sizeof(vec2)); +} + +void shader_setvec3(shader_t shader, sparam_t param, const struct vec3 *val) +{ + shader_setval_inline(shader, param, val, sizeof(float) * 3); +} + +void shader_setvec4(shader_t shader, sparam_t param, const struct vec4 *val) +{ + shader_setval_inline(shader, param, val, sizeof(vec4)); +} + +void shader_settexture(shader_t shader, sparam_t param, texture_t val) +{ + shader_setval_inline(shader, param, &val, sizeof(texture_t)); +} + +void shader_setval(shader_t shader, sparam_t param, const void *val, + size_t size) +{ + shader_setval_inline(shader, param, val, size); +} + +void shader_setdefault(shader_t shader, sparam_t param) +{ + if (param->defaultValue.size()) + shader_setval_inline(shader, param, param->defaultValue.data(), + param->defaultValue.size()); +} diff --git a/libobs-d3d11/GS_D3D11ShaderProcessor.cpp b/libobs-d3d11/GS_D3D11ShaderProcessor.cpp new file mode 100644 index 000000000..a836e3ed7 --- /dev/null +++ b/libobs-d3d11/GS_D3D11ShaderProcessor.cpp @@ -0,0 +1,236 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "GS_D3D11SubSystem.hpp" +#include "GS_D3D11ShaderProcessor.hpp" + +#include +using namespace std; + +static const char *semanticInputNames[] = + {"POSITION", "NORMAL", "COLOR", "TANGENT", "TEXCOORD"}; +static const char *semanticOutputNames[] = + {"SV_Position", "NORMAL", "COLOR", "TANGENT", "TEXCOORD"}; + +static const char *ConvertSemanticName(const char *name) +{ + const size_t num = sizeof(semanticInputNames) / sizeof(const char*); + for (size_t i = 0; i < num; i++) { + if (strcmp(name, semanticInputNames[i]) == 0) + return semanticOutputNames[i]; + } + + throw "Unknown Semantic Name"; + return NULL; +} + +static void GetSemanticInfo(shader_var *var, const char *&name, + uint32_t &index) +{ + const char *mapping = var->mapping; + const char *indexStr = mapping; + + while (*indexStr && !isdigit(*indexStr)) + indexStr++; + index = (*indexStr) ? strtol(indexStr, NULL, 10) : 0; + + string nameStr; + nameStr.assign(mapping, indexStr-mapping); + name = ConvertSemanticName(nameStr.c_str()); +} + +static void AddInputLayoutVar(shader_var *var, + vector &layout) +{ + D3D11_INPUT_ELEMENT_DESC ied; + const char *semanticName; + uint32_t semanticIndex; + + GetSemanticInfo(var, semanticName, semanticIndex); + + memset(&ied, 0, sizeof(ied)); + ied.SemanticName = semanticName; + ied.SemanticIndex = semanticIndex; + ied.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; + + if (strcmp(var->mapping, "COLOR") == 0) { + ied.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + + } else if (strcmp(var->mapping, "POSITION") == 0 || + strcmp(var->mapping, "NORMAL") == 0 || + strcmp(var->mapping, "TANGENT") == 0) { + ied.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + + } else if (astrcmp_n(var->mapping, "TEXCOORD", 8) == 0) { + /* type is always a 'float' type */ + switch (var->type[5]) { + case 0: ied.Format = DXGI_FORMAT_R32_FLOAT; break; + case '2': ied.Format = DXGI_FORMAT_R32G32_FLOAT; break; + case '3': + case '4': ied.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; break; + } + } + + layout.push_back(ied); +} + +static inline bool SetSlot(vector &layout, + const char *name, uint32_t index, uint32_t &slotIdx) +{ + for (size_t i = 0; i < layout.size(); i++) { + D3D11_INPUT_ELEMENT_DESC &input = layout[i]; + if (input.SemanticIndex == index && + strcmpi(input.SemanticName, name) == 0) { + layout[i].InputSlot = slotIdx++; + return true; + } + } + + return false; +} + +static void BuildInputLayoutFromVars(shader_parser *parser, darray *vars, + vector &layout) +{ + shader_var *array = (shader_var*)vars->array; + + for (size_t i = 0; i < vars->num; i++) { + shader_var *var = array+i; + + if (var->mapping) { + AddInputLayoutVar(var, layout); + } else { + shader_struct *st = shader_parser_getstruct(parser, + var->type); + if (st) + BuildInputLayoutFromVars(parser, &st->vars.da, + layout); + } + } + + /* + * Sets the input slot value for each semantic, however we do it in + * a specific order so that it will always match the vertex buffer's + * sub-buffer order (points-> normals-> colors-> tangents-> uvcoords) + */ + uint32_t slot = 0; + SetSlot(layout, "SV_Position", 0, slot); + SetSlot(layout, "NORMAL", 0, slot); + SetSlot(layout, "COLOR", 0, slot); + SetSlot(layout, "TANGENT", 0, slot); + + uint32_t index = 0; + while (SetSlot(layout, "TEXCOORD", index++, slot)); +} + +void ShaderProcessor::BuildInputLayout( + vector &layout) +{ + shader_func *func = shader_parser_getfunc(&parser, "main"); + if (!func) + throw "Failed to find 'main' shader function"; + + BuildInputLayoutFromVars(&parser, &func->params.da, layout); +} + +shader_param::shader_param(shader_var &var, uint32_t &texCounter) + : type (get_shader_param_type(var.type)), + name (var.name), + textureID (texCounter), + arrayCount (var.array_count), + changed (false) +{ + defaultValue.resize(var.default_val.num); + memcpy(defaultValue.data(), var.default_val.array, var.default_val.num); + + if (type == SHADER_PARAM_TEXTURE) + texCounter++; + else + textureID = 0; +} + +static inline void AddParam(shader_var &var, vector ¶ms, + uint32_t &texCounter) +{ + if (var.var_type != SHADER_VAR_UNIFORM || + strcmp(var.type, "sampler") == 0) + return; + + params.push_back(shader_param(var, texCounter)); +} + +void ShaderProcessor::BuildParams(vector ¶ms) +{ + uint32_t texCounter = 0; + + for (size_t i = 0; i < parser.params.num; i++) + AddParam(parser.params.array[i], params, texCounter); +} + +static inline void AddSampler(device_t device, shader_sampler &sampler, + vector &samplers) +{ + gs_sampler_info si; + shader_sampler_convert(&sampler, &si); + samplers.push_back(ShaderSampler(sampler.name, device, &si)); +} + +void ShaderProcessor::BuildSamplers(vector &samplers) +{ + for (size_t i = 0; i < parser.samplers.num; i++) + AddSampler(device, parser.samplers.array[i], samplers); +} + +void ShaderProcessor::BuildString(string &outputString) +{ + stringstream output; + cf_token *token = cf_preprocessor_gettokens(&parser.cfp.pp); + while (token->type != CFTOKEN_NONE) { + /* cheaply just replace specific tokens */ + if (strref_cmp(&token->str, "POSITION") == 0) + output << "SV_Position"; + else if (strref_cmp(&token->str, "TARGET") == 0) + output << "SV_Target"; + else if (strref_cmp(&token->str, "texture2d") == 0) + output << "Texture2D"; + else if (strref_cmp(&token->str, "texture3d") == 0) + output << "Texture3D"; + else if (strref_cmp(&token->str, "texture_cube") == 0) + output << "TextureCube"; + else if (strref_cmp(&token->str, "sampler_state") == 0) + output << "SamplerState"; + else + output.write(token->str.array, token->str.len); + + token++; + } + + outputString = move(output.str()); +} + +void ShaderProcessor::Process(const char *shader_string, const char *file) +{ + if (!shader_parse(&parser, shader_string, file)) { + char *str = error_data_buildstring(&parser.cfp.error_list); + if (str) { + blog(LOG_WARNING, "Shader parser errors/warnings:\n" + "%s\n", str); + bfree(str); + } + throw "Failed to parse shader"; + } +} diff --git a/libobs-d3d11/GS_D3D11ShaderProcessor.hpp b/libobs-d3d11/GS_D3D11ShaderProcessor.hpp new file mode 100644 index 000000000..61d4118c3 --- /dev/null +++ b/libobs-d3d11/GS_D3D11ShaderProcessor.hpp @@ -0,0 +1,40 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#pragma once + +#include "graphics/shader-parser.h" + +struct ShaderParser : shader_parser { + inline ShaderParser() {shader_parser_init(this);} + inline ~ShaderParser() {shader_parser_free(this);} +}; + +struct ShaderProcessor { + device_t device; + ShaderParser parser; + + void BuildInputLayout(vector &inputs); + void BuildParams(vector ¶ms); + void BuildSamplers(vector &samplers); + void BuildString(string &outputString); + void Process(const char *shader_string, const char *file); + + inline ShaderProcessor(device_t device) : device(device) + { + } +}; diff --git a/libobs-d3d11/GS_D3D11StageSurf.cpp b/libobs-d3d11/GS_D3D11StageSurf.cpp new file mode 100644 index 000000000..b281b3faa --- /dev/null +++ b/libobs-d3d11/GS_D3D11StageSurf.cpp @@ -0,0 +1,44 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "GS_D3D11SubSystem.hpp" + +gs_stage_surface::gs_stage_surface(device_t device, uint32_t width, + uint32_t height, gs_color_format colorFormat) + : device (device), + width (width), + height (height), + format (colorFormat), + dxgiFormat (ConvertGSTextureFormat(colorFormat)) +{ + D3D11_TEXTURE2D_DESC td; + HRESULT hr; + + memset(&td, 0, sizeof(td)); + td.Width = width; + td.Height = height; + td.MipLevels = 1; + td.ArraySize = 1; + td.Format = dxgiFormat; + td.SampleDesc.Count = 1; + td.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + td.Usage = D3D11_USAGE_STAGING; + + hr = device->device->CreateTexture2D(&td, NULL, texture.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create 2D texture", hr); +} diff --git a/libobs-d3d11/GS_D3D11SubSystem.cpp b/libobs-d3d11/GS_D3D11SubSystem.cpp new file mode 100644 index 000000000..123ce543e --- /dev/null +++ b/libobs-d3d11/GS_D3D11SubSystem.cpp @@ -0,0 +1,1574 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "util/base.h" +#include "util/platform.h" +#include "graphics/matrix3.h" +#include "GS_D3D11SubSystem.hpp" + +static const IID dxgiFactory2 = +{0x50c83a1c, 0xe072, 0x4c48, {0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0}}; + +static inline void make_swap_desc(DXGI_SWAP_CHAIN_DESC &desc, + gs_init_data *data) +{ + memset(&desc, 0, sizeof(desc)); + desc.BufferCount = data->num_backbuffers; + desc.BufferDesc.Format = ConvertGSTextureFormat(data->format); + desc.BufferDesc.Width = data->cx; + desc.BufferDesc.Height = data->cy; + desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + desc.OutputWindow = (HWND)data->hwnd; + desc.SampleDesc.Count = 1; + desc.Windowed = true; +} + +void gs_swap_chain::InitTarget(uint32_t cx, uint32_t cy) +{ + HRESULT hr; + + target.width = cx; + target.height = cy; + + hr = swap->GetBuffer(0, __uuidof(ID3D11Texture2D), + (void**)target.texture.Assign()); + if (FAILED(hr)) + throw HRError("Failed to get swap buffer texture", hr); + + hr = device->device->CreateRenderTargetView(target.texture, NULL, + target.renderTarget[0].Assign()); + if (FAILED(hr)) + throw HRError("Failed to create swap render target view", hr); +} + +void gs_swap_chain::InitZStencilBuffer(uint32_t cx, uint32_t cy) +{ + zs.width = cx; + zs.height = cy; + + if (zs.format != GS_ZS_NONE && cx != 0 && cy != 0) { + zs.InitBuffer(); + } else { + zs.texture.Clear(); + zs.view.Clear(); + } +} + +void gs_swap_chain::Resize(uint32_t cx, uint32_t cy) +{ + RECT clientRect; + HRESULT hr; + + target.texture.Clear(); + target.renderTarget[0].Clear(); + zs.texture.Clear(); + zs.view.Clear(); + + if (cx == 0 || cy == 0) { + GetClientRect(hwnd, &clientRect); + if (cx == 0) cx = clientRect.right; + if (cy == 0) cy = clientRect.bottom; + } + + hr = swap->ResizeBuffers(numBuffers, cx, cy, target.dxgiFormat, 0); + if (FAILED(hr)) + throw HRError("Failed to resize swap buffers", hr); + + InitTarget(cx, cy); + InitZStencilBuffer(cx, cy); +} + +void gs_swap_chain::Init(gs_init_data *data) +{ + target.device = device; + target.isRenderTarget = true; + target.format = data->format; + target.dxgiFormat = ConvertGSTextureFormat(data->format); + InitTarget(data->cx, data->cy); + + zs.device = device; + zs.format = data->zsformat; + zs.dxgiFormat = ConvertGSZStencilFormat(data->zsformat); + InitZStencilBuffer(data->cx, data->cy); +} + +gs_swap_chain::gs_swap_chain(gs_device *device, gs_init_data *data) + : device (device), + numBuffers (data->num_backbuffers), + hwnd ((HWND)data->hwnd) +{ + HRESULT hr; + DXGI_SWAP_CHAIN_DESC swapDesc; + + make_swap_desc(swapDesc, data); + hr = device->factory->CreateSwapChain(device->device, &swapDesc, + swap.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create swap chain", hr); + + Init(data); +} + +void gs_device::InitFactory(uint32_t adapterIdx, IDXGIAdapter1 **padapter) +{ + HRESULT hr; + IID factoryIID = (GetWinVer() >= 0x602) ? dxgiFactory2 : + __uuidof(IDXGIFactory1); + + hr = CreateDXGIFactory1(factoryIID, (void**)factory.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create DXGIFactory", hr); + + hr = factory->EnumAdapters1(adapterIdx, padapter); + if (FAILED(hr)) + throw HRError("Failed to enumerate DXGIAdapter", hr); +} + +const static D3D_FEATURE_LEVEL featureLevels[] = +{ + D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0, + D3D_FEATURE_LEVEL_9_3, +}; + +void gs_device::InitDevice(gs_init_data *data, IDXGIAdapter *adapter) +{ + wstring adapterName; + DXGI_SWAP_CHAIN_DESC swapDesc; + DXGI_ADAPTER_DESC desc; + D3D_FEATURE_LEVEL levelUsed; + HRESULT hr; + + make_swap_desc(swapDesc, data); + + uint32_t createFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; +#ifdef _DEBUG + createFlags |= D3D11_CREATE_DEVICE_DEBUG; +#endif + + adapterName = (adapter->GetDesc(&desc) == S_OK) ? desc.Description : + L""; + + char *adapterNameUTF8; + os_wcs_to_utf8(adapterName.c_str(), 0, &adapterNameUTF8); + blog(LOG_INFO, "Loading up D3D11 on adapter %s", adapterNameUTF8); + bfree(adapterNameUTF8); + + hr = D3D11CreateDeviceAndSwapChain(adapter, D3D_DRIVER_TYPE_UNKNOWN, + NULL, createFlags, featureLevels, + sizeof(featureLevels) / sizeof(D3D_FEATURE_LEVEL), + D3D11_SDK_VERSION, &swapDesc, + defaultSwap.swap.Assign(), device.Assign(), + &levelUsed, context.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create device and swap chain", hr); + + blog(LOG_INFO, "D3D11 loaded sucessfully, feature level used: %u", + (uint32_t)levelUsed); + + defaultSwap.device = this; + defaultSwap.hwnd = (HWND)data->hwnd; + defaultSwap.numBuffers = data->num_backbuffers; + defaultSwap.Init(data); +} + +static inline void ConvertStencilSide(D3D11_DEPTH_STENCILOP_DESC &desc, + const StencilSide &side) +{ + desc.StencilFunc = ConvertGSDepthTest(side.test); + desc.StencilFailOp = ConvertGSStencilOp(side.fail); + desc.StencilDepthFailOp = ConvertGSStencilOp(side.zfail); + desc.StencilPassOp = ConvertGSStencilOp(side.zpass); +} + +ID3D11DepthStencilState *gs_device::AddZStencilState() +{ + HRESULT hr; + D3D11_DEPTH_STENCIL_DESC dsd; + SavedZStencilState savedState(zstencilState); + ID3D11DepthStencilState *state; + + dsd.DepthEnable = zstencilState.depthEnabled; + dsd.DepthFunc = ConvertGSDepthTest(zstencilState.depthFunc); + dsd.DepthWriteMask = zstencilState.depthWriteEnabled ? + D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; + dsd.StencilEnable = zstencilState.stencilEnabled; + dsd.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; + dsd.StencilWriteMask = zstencilState.stencilWriteEnabled ? + D3D11_DEFAULT_STENCIL_WRITE_MASK : 0; + ConvertStencilSide(dsd.FrontFace, zstencilState.stencilFront); + ConvertStencilSide(dsd.BackFace, zstencilState.stencilBack); + + hr = device->CreateDepthStencilState(&dsd, savedState.state.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create depth stencil state", hr); + + state = savedState.state; + zstencilStates.push_back(savedState); + + return state; +} + +ID3D11RasterizerState *gs_device::AddRasterState() +{ + HRESULT hr; + D3D11_RASTERIZER_DESC rd; + SavedRasterState savedState(rasterState); + ID3D11RasterizerState *state; + + memset(&rd, 0, sizeof(rd)); + rd.FillMode = D3D11_FILL_SOLID; + rd.CullMode = ConvertGSCullMode(rasterState.cullMode); + rd.DepthClipEnable = true; + rd.ScissorEnable = rasterState.scissorEnabled; + + hr = device->CreateRasterizerState(&rd, savedState.state.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create rasterizer state", hr); + + state = savedState.state; + rasterStates.push_back(savedState); + + return state; +} + +ID3D11BlendState *gs_device::AddBlendState() +{ + HRESULT hr; + D3D11_BLEND_DESC bd; + SavedBlendState savedState(blendState); + ID3D11BlendState *state; + + memset(&bd, 0, sizeof(bd)); + for (int i = 0; i < 8; i++) { + bd.RenderTarget[i].BlendEnable = blendState.blendEnabled; + bd.RenderTarget[i].BlendOp = D3D11_BLEND_OP_ADD; + bd.RenderTarget[i].BlendOpAlpha = D3D11_BLEND_OP_ADD; + bd.RenderTarget[i].SrcBlendAlpha = D3D11_BLEND_ONE; + bd.RenderTarget[i].DestBlendAlpha = D3D11_BLEND_ZERO; + bd.RenderTarget[i].SrcBlend = + ConvertGSBlendType(blendState.srcFactor); + bd.RenderTarget[i].DestBlend = + ConvertGSBlendType(blendState.destFactor); + bd.RenderTarget[i].RenderTargetWriteMask = + D3D11_COLOR_WRITE_ENABLE_ALL; + } + + hr = device->CreateBlendState(&bd, savedState.state.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create disabled blend state", hr); + + state = savedState.state; + blendStates.push_back(savedState); + + return state; +} + +void gs_device::UpdateZStencilState() +{ + ID3D11DepthStencilState *state = NULL; + + if (!zstencilStateChanged) + return; + + for (size_t i = 0; i < zstencilStates.size(); i++) { + SavedZStencilState &s = zstencilStates[i]; + if (memcmp(&s, &zstencilState, sizeof(zstencilState)) == 0) { + state = s.state; + break; + } + } + + if (!state) + state = AddZStencilState(); + + if (state != curDepthStencilState) { + context->OMSetDepthStencilState(state, 0); + curDepthStencilState = state; + } + + zstencilStateChanged = false; +} + +void gs_device::UpdateRasterState() +{ + ID3D11RasterizerState *state = NULL; + + if (!rasterStateChanged) + return; + + for (size_t i = 0; i < rasterStates.size(); i++) { + SavedRasterState &s = rasterStates[i]; + if (memcmp(&s, &rasterState, sizeof(rasterState)) == 0) { + state = s.state; + break; + } + } + + if (!state) + state = AddRasterState(); + + if (state != curRasterState) { + context->RSSetState(state); + curRasterState = state; + } + + rasterStateChanged = false; +} + +void gs_device::UpdateBlendState() +{ + ID3D11BlendState *state = NULL; + + if (!blendStateChanged) + return; + + for (size_t i = 0; i < blendStates.size(); i++) { + SavedBlendState &s = blendStates[i]; + if (memcmp(&s, &blendState, sizeof(blendState)) == 0) { + state = s.state; + break; + } + } + + if (!state) + state = AddBlendState(); + + if (state != curBlendState) { + float f[4] = {1.0f, 1.0f, 1.0f, 1.0f}; + context->OMSetBlendState(state, f, 0xFFFFFFFF); + curBlendState = state; + } + + blendStateChanged = false; +} + +void gs_device::UpdateViewProjMatrix() +{ + matrix3 cur_matrix; + gs_matrix_get(&cur_matrix); + + matrix4_from_matrix3(&curViewMatrix, &cur_matrix); + matrix4_mul(&curViewProjMatrix, &curViewMatrix, &curProjMatrix); + matrix4_transpose(&curViewProjMatrix, &curViewProjMatrix); + + if (curVertexShader->viewProj) + shader_setmatrix4(curVertexShader, curVertexShader->viewProj, + &curViewProjMatrix); +} + +gs_device::gs_device(gs_init_data *data) + : curRenderTarget (NULL), + curZStencilBuffer (NULL), + curRenderSide (0), + curIndexBuffer (NULL), + curVertexBuffer (NULL), + curVertexShader (NULL), + curPixelShader (NULL), + curSwapChain (&defaultSwap), + zstencilStateChanged (true), + rasterStateChanged (true), + blendStateChanged (true), + curDepthStencilState (NULL), + curRasterState (NULL), + curBlendState (NULL), + curToplogy (D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED) +{ + ComPtr adapter; + + matrix4_identity(&curProjMatrix); + matrix4_identity(&curViewMatrix); + matrix4_identity(&curViewProjMatrix); + + memset(&viewport, 0, sizeof(viewport)); + + for (size_t i = 0; i < MAX_TEXTURES; i++) { + curTextures[i] = NULL; + curSamplers[i] = NULL; + } + + InitFactory(data->adapter, adapter.Assign()); + InitDevice(data, adapter); + device_setrendertarget(this, NULL, NULL); +} + +gs_device *device_create(gs_init_data *data) +{ + gs_device *device = NULL; + + try { + device = new gs_device(data); + } catch (HRError error) { + blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str, + error.hr); + } + + return device; +} + +void device_destroy(device_t device) +{ + delete device; +} + +swapchain_t device_create_swapchain(device_t device, struct gs_init_data *data) +{ + gs_swap_chain *swap = NULL; + + try { + swap = new gs_swap_chain(device, data); + } catch (HRError error) { + blog(LOG_ERROR, "device_create_swapchain (D3D11): %s (%08lX)", + error.str, error.hr); + } + + return swap; +} + +void device_resize(device_t device, uint32_t cx, uint32_t cy) +{ + try { + ID3D11RenderTargetView *renderView = NULL; + ID3D11DepthStencilView *depthView = NULL; + int i = device->curRenderSide; + + device->context->OMSetRenderTargets(1, &renderView, depthView); + device->curSwapChain->Resize(cx, cy); + + if (device->curRenderTarget) + renderView = device->curRenderTarget->renderTarget[i]; + if (device->curZStencilBuffer) + depthView = device->curZStencilBuffer->view; + device->context->OMSetRenderTargets(1, &renderView, depthView); + + } catch (HRError error) { + blog(LOG_ERROR, "device_resize (D3D11): %s (%08lX)", + error.str, error.hr); + } +} + +void device_getsize(device_t device, uint32_t *cx, uint32_t *cy) +{ + *cx = device->curSwapChain->target.width; + *cy = device->curSwapChain->target.height; +} + +uint32_t device_getwidth(device_t device) +{ + return device->curSwapChain->target.width; +} + +uint32_t device_getheight(device_t device) +{ + return device->curSwapChain->target.height; +} + +texture_t device_create_texture(device_t device, uint32_t width, + uint32_t height, enum gs_color_format color_format, void *data, + uint32_t flags) +{ + gs_texture *texture = NULL; + try { + texture = new gs_texture_2d(device, width, height, color_format, + data, flags, false, false, false); + } catch (HRError error) { + blog(LOG_ERROR, "device_create_texture (D3D11): %s (%08lX)", + error.str, error.hr); + } catch (const char *error) { + blog(LOG_ERROR, "device_create_texture (D3D11): %s", error); + } + + return texture; +} + +texture_t device_create_cubetexture(device_t device, uint32_t size, + enum gs_color_format color_format, void *data[6], + uint32_t flags) +{ + gs_texture *texture = NULL; + try { + texture = new gs_texture_2d(device, size, size, color_format, + data, flags, true, false, false); + } catch (HRError error) { + blog(LOG_ERROR, "device_create_cubetexture (D3D11): %s " + "(%08lX)", + error.str, error.hr); + } catch (const char *error) { + blog(LOG_ERROR, "device_create_cubetexture (D3D11): %s", + error); + } + + return texture; +} + +texture_t device_create_volumetexture(device_t device, uint32_t width, + uint32_t height, uint32_t depth, + enum gs_color_format color_format, void *data, uint32_t flags) +{ + /* TODO */ + return NULL; +} + +zstencil_t device_create_zstencil(device_t device, uint32_t width, + uint32_t height, enum gs_zstencil_format format) +{ + gs_zstencil_buffer *zstencil = NULL; + try { + zstencil = new gs_zstencil_buffer(device, width, height, + format); + } catch (HRError error) { + blog(LOG_ERROR, "device_create_zstencil (D3D11): %s (%08lX)", + error.str, error.hr); + } + + return zstencil; +} + +stagesurf_t device_create_stagesurface(device_t device, uint32_t width, + uint32_t height, enum gs_color_format color_format) +{ + gs_stage_surface *surf = NULL; + try { + surf = new gs_stage_surface(device, width, height, + color_format); + } catch (HRError error) { + blog(LOG_ERROR, "device_create_stagesurface (D3D11): %s " + "(%08lX)", + error.str, error.hr); + } + + return surf; +} + +samplerstate_t device_create_samplerstate(device_t device, + struct gs_sampler_info *info) +{ + gs_sampler_state *ss = NULL; + try { + ss = new gs_sampler_state(device, info); + } catch (HRError error) { + blog(LOG_ERROR, "device_create_samplerstate (D3D11): %s " + "(%08lX)", + error.str, error.hr); + } + + return ss; +} + +shader_t device_create_vertexshader(device_t device, + const char *shader_string, const char *file, + char **error_string) +{ + gs_vertex_shader *shader = NULL; + try { + shader = new gs_vertex_shader(device, file, shader_string); + + } catch (HRError error) { + blog(LOG_ERROR, "device_create_vertexshader (D3D11): %s " + "(%08lX)", + error.str, error.hr); + + } catch (ShaderError error) { + const char *buf = (const char*)error.errors->GetBufferPointer(); + if (error_string) + *error_string = bstrdup(buf); + blog(LOG_ERROR, "device_create_vertexshader (D3D11): " + "Compile errors for %s:\n%s", + file, buf); + + } catch (const char *error) { + blog(LOG_ERROR, "device_create_vertexshader (D3D11): %s", + error); + } + + return shader; +} + +shader_t device_create_pixelshader(device_t device, + const char *shader_string, const char *file, + char **error_string) +{ + gs_pixel_shader *shader = NULL; + try { + shader = new gs_pixel_shader(device, file, shader_string); + + } catch (HRError error) { + blog(LOG_ERROR, "device_create_pixelshader (D3D11): %s " + "(%08lX)", + error.str, error.hr); + + } catch (ShaderError error) { + const char *buf = (const char*)error.errors->GetBufferPointer(); + if (error_string) + *error_string = bstrdup(buf); + blog(LOG_ERROR, "device_create_pixelshader (D3D11): " + "Compiler errors for %s:\n%s", + file, buf); + + } catch (const char *error) { + blog(LOG_ERROR, "device_create_pixelshader (D3D11): %s", + error); + } + + return shader; +} + +vertbuffer_t device_create_vertexbuffer(device_t device, + struct vb_data *data, uint32_t flags) +{ + gs_vertex_buffer *buffer = NULL; + try { + buffer = new gs_vertex_buffer(device, data, flags); + } catch (HRError error) { + blog(LOG_ERROR, "device_create_vertexbuffer (D3D11): %s " + "(%08lX)", + error.str, error.hr); + } catch (const char *error) { + blog(LOG_ERROR, "device_create_vertexbuffer (D3D11): %s", + error); + } + + return buffer; +} + +indexbuffer_t device_create_indexbuffer(device_t device, + enum gs_index_type type, void *indices, size_t num, + uint32_t flags) +{ + gs_index_buffer *buffer = NULL; + try { + buffer = new gs_index_buffer(device, type, indices, num, flags); + } catch (HRError error) { + blog(LOG_ERROR, "device_create_indexbuffer (D3D11): %s (%08lX)", + error.str, error.hr); + } + + return buffer; +} + +enum gs_texture_type device_gettexturetype(device_t device, texture_t texture) +{ + return texture->type; +} + +void device_load_vertexbuffer(device_t device, vertbuffer_t vertbuffer) +{ + if (device->curVertexBuffer == vertbuffer) + return; + + device->curVertexBuffer = vertbuffer; + + if (!device->curVertexShader) + return; + + vector buffers; + vector strides; + vector offsets; + + if (vertbuffer) { + vertbuffer->MakeBufferList(device->curVertexShader, + buffers, strides); + } else { + size_t buffersToClear = + device->curVertexShader->NumBuffersExpected(); + buffers.resize(buffersToClear); + strides.resize(buffersToClear); + } + + offsets.resize(buffers.size()); + device->context->IASetVertexBuffers(0, (UINT)buffers.size(), + buffers.data(), strides.data(), offsets.data()); +} + +void device_load_indexbuffer(device_t device, indexbuffer_t indexbuffer) +{ + DXGI_FORMAT format; + ID3D11Buffer *buffer; + + if (device->curIndexBuffer == indexbuffer) + return; + + if (indexbuffer) { + switch (indexbuffer->indexSize) { + case 2: format = DXGI_FORMAT_R16_UINT; break; + case 4: format = DXGI_FORMAT_R32_UINT; break; + } + + buffer = indexbuffer->indexBuffer; + } else { + buffer = NULL; + format = DXGI_FORMAT_R32_UINT; + } + + device->curIndexBuffer = indexbuffer; + device->context->IASetIndexBuffer(buffer, format, 0); +} + +void device_load_texture(device_t device, texture_t tex, int unit) +{ + ID3D11ShaderResourceView *view = NULL; + + if (device->curTextures[unit] == tex) + return; + + if (tex) + view = tex->shaderRes; + + device->curTextures[unit] = tex; + device->context->PSSetShaderResources(unit, 1, &view); +} + +void device_load_samplerstate(device_t device, + samplerstate_t samplerstate, int unit) +{ + ID3D11SamplerState *state = NULL; + + if (device->curSamplers[unit] == samplerstate) + return; + + if (samplerstate) + state = samplerstate->state; + + device->curSamplers[unit] = samplerstate; + device->context->PSSetSamplers(unit, 1, &state); +} + +void device_load_vertexshader(device_t device, shader_t vertshader) +{ + ID3D11VertexShader *shader = NULL; + ID3D11InputLayout *layout = NULL; + ID3D11Buffer *constants = NULL; + + if (device->curVertexShader == vertshader) + return; + + gs_vertex_shader *vs = static_cast(vertshader); + gs_vertex_buffer *curVB = device->curVertexBuffer; + + if (vertshader) { + if (vertshader->type != SHADER_VERTEX) { + blog(LOG_ERROR, "device_load_vertexshader (D3D11): " + "Shader is not a vertex shader"); + return; + } + + if (curVB) + device_load_vertexbuffer(device, NULL); + + shader = vs->shader; + layout = vs->layout; + constants = vs->constants; + } + + device->curVertexShader = vs; + device->context->VSSetShader(shader, NULL, 0); + device->context->IASetInputLayout(layout); + device->context->VSSetConstantBuffers(0, 1, &constants); + + if (vertshader && curVB) + device_load_vertexbuffer(device, curVB); +} + +static inline void clear_textures(device_t device) +{ + ID3D11ShaderResourceView *views[MAX_TEXTURES]; + memset(views, 0, sizeof(views)); + memset(device->curTextures, 0, sizeof(device->curTextures)); + device->context->PSSetShaderResources(0, MAX_TEXTURES, views); +} + +void device_load_pixelshader(device_t device, shader_t pixelshader) +{ + ID3D11PixelShader *shader = NULL; + ID3D11Buffer *constants = NULL; + ID3D11SamplerState *states[MAX_TEXTURES]; + + if (device->curPixelShader == pixelshader) + return; + + gs_pixel_shader *ps = static_cast(pixelshader); + + if (pixelshader) { + if (pixelshader->type != SHADER_PIXEL) { + blog(LOG_ERROR, "device_load_pixelshader (D3D11): " + "Shader is not a pixel shader"); + return; + } + + shader = ps->shader; + constants = ps->constants; + ps->GetSamplerStates(states); + } else { + memset(states, 0, sizeof(states)); + } + + clear_textures(device); + + device->curPixelShader = ps; + device->context->PSSetShader(shader, NULL, 0); + device->context->PSSetConstantBuffers(0, 1, &constants); + device->context->PSSetSamplers(0, MAX_TEXTURES, states); +} + +void device_load_defaultsamplerstate(device_t device, bool b_3d, + int unit) +{ + /* TODO */ +} + +shader_t device_getvertexshader(device_t device) +{ + return device->curVertexShader; +} + +shader_t device_getpixelshader(device_t device) +{ + return device->curPixelShader; +} + +texture_t device_getrendertarget(device_t device) +{ + if (device->curRenderTarget == &device->curSwapChain->target) + return NULL; + + return device->curRenderTarget; +} + +zstencil_t device_getzstenciltarget(device_t device) +{ + if (device->curZStencilBuffer == &device->curSwapChain->zs) + return NULL; + + return device->curZStencilBuffer; +} + +void device_setrendertarget(device_t device, texture_t tex, zstencil_t zstencil) +{ + if (!tex) + tex = &device->curSwapChain->target; + if (!zstencil) + zstencil = &device->curSwapChain->zs; + + if (device->curRenderTarget == tex && + device->curZStencilBuffer == zstencil) + return; + + if (tex->type != GS_TEXTURE_2D) { + blog(LOG_ERROR, "device_setrendertarget (D3D11): " + "texture is not a 2D texture"); + return; + } + + gs_texture_2d *tex2d = static_cast(tex); + if (!tex2d->renderTarget[0]) { + blog(LOG_ERROR, "device_setrendertarget (D3D11): " + "texture is not a render target"); + return; + } + + ID3D11RenderTargetView *rt = tex2d->renderTarget[0]; + + device->curRenderTarget = tex2d; + device->curRenderSide = 0; + device->curZStencilBuffer = zstencil; + device->context->OMSetRenderTargets(1, &rt, zstencil->view); +} + +void device_setcuberendertarget(device_t device, texture_t tex, int side, + zstencil_t zstencil) +{ + if (!tex) { + tex = &device->curSwapChain->target; + side = 0; + } + + if (!zstencil) + zstencil = &device->curSwapChain->zs; + + if (device->curRenderTarget == tex && + device->curRenderSide == side && + device->curZStencilBuffer == zstencil) + return; + + if (tex->type != GS_TEXTURE_CUBE) { + blog(LOG_ERROR, "device_setcuberendertarget (D3D11): " + "texture is not a cube texture"); + return; + } + + gs_texture_2d *tex2d = static_cast(tex); + if (!tex2d->renderTarget[side]) { + blog(LOG_ERROR, "device_setcuberendertarget (D3D11): " + "texture is not a render target"); + return; + } + + ID3D11RenderTargetView *rt = tex2d->renderTarget[0]; + + device->curRenderTarget = tex2d; + device->curRenderSide = side; + device->curZStencilBuffer = zstencil; + device->context->OMSetRenderTargets(1, &rt, zstencil->view); +} + +inline void gs_device::CopyTex(ID3D11Texture2D *dst, texture_t src) +{ + if (!src) + src = curRenderTarget; + if (src->type != GS_TEXTURE_2D) + throw "Source texture must be a 2D texture"; + + gs_texture_2d *tex2d = static_cast(src); + context->CopyResource(dst, tex2d->texture); +} + +void device_copy_texture(device_t device, texture_t dst, texture_t src) +{ + try { + if (!dst) + throw "Failed because destination texture is NULL"; + if (dst->type != GS_TEXTURE_2D) + throw "Destination texture must be a 2D texture"; + + gs_texture_2d *tex2d = static_cast(dst); + device->CopyTex(tex2d->texture, src); + + } catch (const char *error) { + blog(LOG_ERROR, "device_copy_texture (D3D11): %s", error); + } +} + +void device_stage_texture(device_t device, stagesurf_t dst, texture_t src) +{ + try { + if (!dst) + throw "Failed because destination texture is NULL"; + + device->CopyTex(dst->texture, src); + + } catch (const char *error) { + blog(LOG_ERROR, "device_copy_texture (D3D11): %s", error); + } +} + +void device_beginscene(device_t device) +{ + clear_textures(device); +} + +void device_draw(device_t device, enum gs_draw_mode draw_mode, + uint32_t start_vert, uint32_t num_verts) +{ + try { + if (!device->curVertexShader) + throw "No vertex shader specified"; + + if (!device->curPixelShader) + throw "No pixel shader specified"; + + if (!device->curVertexBuffer) + throw "No vertex buffer specified"; + + effect_t effect = gs_geteffect(); + if (effect) + effect_updateparams(effect); + + device->UpdateBlendState(); + device->UpdateRasterState(); + device->UpdateZStencilState(); + device->UpdateViewProjMatrix(); + device->curVertexShader->UploadParams(); + device->curPixelShader->UploadParams(); + + } catch (const char *error) { + blog(LOG_ERROR, "device_draw (D3D11): %s", error); + return; + + } catch (HRError error) { + blog(LOG_ERROR, "device_draw (D3D11): %s (%08lX)", error.str, + error.hr); + return; + } + + D3D10_PRIMITIVE_TOPOLOGY newTopology = ConvertGSTopology(draw_mode); + if (device->curToplogy != newTopology) { + device->context->IASetPrimitiveTopology(newTopology); + device->curToplogy = newTopology; + } + + if (num_verts == 0) + num_verts = (uint32_t)device->curVertexBuffer->numVerts; + + if (device->curIndexBuffer) + device->context->DrawIndexed(num_verts, start_vert, 0); + else + device->context->Draw(num_verts, start_vert); +} + +void device_endscene(device_t device) +{ + /* does nothing in D3D11 */ +} + +void device_load_swapchain(device_t device, swapchain_t swapchain) +{ + texture_t target = device->curRenderTarget; + zstencil_t zs = device->curZStencilBuffer; + bool is_cube = device->curRenderTarget->type == GS_TEXTURE_CUBE; + + if (target == &device->curSwapChain->target) + target = NULL; + if (zs == &device->curSwapChain->zs) + zs = NULL; + + if (swapchain == NULL) + swapchain = &device->defaultSwap; + + device->curSwapChain = swapchain; + + if (is_cube) + device_setcuberendertarget(device, target, + device->curRenderSide, zs); + else + device_setrendertarget(device, target, zs); +} + +void device_clear(device_t device, uint32_t clear_flags, struct vec4 *color, + float depth, uint8_t stencil) +{ + int side = device->curRenderSide; + if ((clear_flags & GS_CLEAR_COLOR) != 0 && device->curRenderTarget) + device->context->ClearRenderTargetView( + device->curRenderTarget->renderTarget[side], + color->ptr); + + if (device->curZStencilBuffer) { + uint32_t flags = 0; + if ((clear_flags & GS_CLEAR_DEPTH) != 0) + flags |= D3D11_CLEAR_DEPTH; + if ((clear_flags & GS_CLEAR_STENCIL) != 0) + flags |= D3D11_CLEAR_STENCIL; + + if (flags && device->curZStencilBuffer->view) + device->context->ClearDepthStencilView( + device->curZStencilBuffer->view, + flags, depth, stencil); + } +} + +void device_present(device_t device) +{ + device->curSwapChain->swap->Present(0, 0); +} + +void device_setcullmode(device_t device, enum gs_cull_mode mode) +{ + if (mode == device->rasterState.cullMode) + return; + + device->rasterState.cullMode = mode; + device->rasterStateChanged = true; +} + +enum gs_cull_mode device_getcullmode(device_t device) +{ + return device->rasterState.cullMode; +} + +void device_enable_blending(device_t device, bool enable) +{ + if (enable == device->blendState.blendEnabled) + return; + + device->blendState.blendEnabled = enable; + device->blendStateChanged = true; +} + +void device_enable_depthtest(device_t device, bool enable) +{ + if (enable == device->zstencilState.depthEnabled) + return; + + device->zstencilState.depthEnabled = enable; + device->zstencilStateChanged = true; +} + +void device_enable_stenciltest(device_t device, bool enable) +{ + if (enable == device->zstencilState.stencilEnabled) + return; + + device->zstencilState.stencilEnabled = enable; + device->zstencilStateChanged = true; +} + +void device_enable_stencilwrite(device_t device, bool enable) +{ + if (enable == device->zstencilState.stencilWriteEnabled) + return; + + device->zstencilState.stencilWriteEnabled = enable; + device->zstencilStateChanged = true; +} + +void device_enable_color(device_t device, bool red, bool blue, + bool green, bool alpha) +{ + if (device->blendState.redEnabled == red && + device->blendState.greenEnabled == green && + device->blendState.blueEnabled == blue && + device->blendState.alphaEnabled == alpha) + return; + + device->blendState.redEnabled = red; + device->blendState.greenEnabled = green; + device->blendState.blueEnabled = blue; + device->blendState.alphaEnabled = alpha; + device->blendStateChanged = true; +} + +void device_blendfunction(device_t device, enum gs_blend_type src, + enum gs_blend_type dest) +{ + if (device->blendState.srcFactor == src && + device->blendState.destFactor == dest) + return; + + device->blendState.srcFactor = src; + device->blendState.destFactor = dest; + device->blendStateChanged = true; +} + +void device_depthfunction(device_t device, enum gs_depth_test test) +{ + if (device->zstencilState.depthFunc == test) + return; + + device->zstencilState.depthFunc = test; + device->zstencilStateChanged = true; +} + +static inline void update_stencilside_test(device_t device, StencilSide &side, + gs_depth_test test) +{ + if (side.test == test) + return; + + side.test = test; + device->zstencilStateChanged = true; +} + +void device_stencilfunction(device_t device, enum gs_stencil_side side, + enum gs_depth_test test) +{ + int sideVal = (int)side; + + if (sideVal & GS_STENCIL_FRONT) + update_stencilside_test(device, + device->zstencilState.stencilFront, test); + if (sideVal & GS_STENCIL_BACK) + update_stencilside_test(device, + device->zstencilState.stencilBack, test); +} + +static inline void update_stencilside_op(device_t device, StencilSide &side, + enum gs_stencil_op fail, enum gs_stencil_op zfail, + enum gs_stencil_op zpass) +{ + if (side.fail == fail && side.zfail == zfail && side.zpass == zpass) + return; + + side.fail = fail; + side.zfail = zfail; + side.zpass = zpass; + device->zstencilStateChanged = true; +} + +void device_stencilop(device_t device, enum gs_stencil_side side, + enum gs_stencil_op fail, enum gs_stencil_op zfail, + enum gs_stencil_op zpass) +{ + int sideVal = (int)side; + + if (sideVal & GS_STENCIL_FRONT) + update_stencilside_op(device, + device->zstencilState.stencilFront, + fail, zfail, zpass); + if (sideVal & GS_STENCIL_BACK) + update_stencilside_op(device, + device->zstencilState.stencilBack, + fail, zfail, zpass); +} + +void device_enable_fullscreen(device_t device, bool enable) +{ + /* TODO */ +} + +int device_fullscreen_enabled(device_t device) +{ + /* TODO */ + return 0; +} + +void device_setdisplaymode(device_t device, + const struct gs_display_mode *mode) +{ + /* TODO */ +} + +void device_getdisplaymode(device_t device, + struct gs_display_mode *mode) +{ + /* TODO */ +} + +void device_setcolorramp(device_t device, float gamma, float brightness, + float contrast) +{ + /* TODO */ +} + +void device_setviewport(device_t device, int x, int y, int width, + int height) +{ + D3D11_VIEWPORT vp; + memset(&vp, 0, sizeof(vp)); + vp.MaxDepth = 1.0f; + vp.TopLeftX = (float)x; + vp.TopLeftY = (float)y; + vp.Width = (float)width; + vp.Height = (float)height; + device->context->RSSetViewports(1, &vp); + + device->viewport.x = x; + device->viewport.y = y; + device->viewport.cx = width; + device->viewport.cy = height; +} + +void device_getviewport(device_t device, struct gs_rect *rect) +{ + memcpy(rect, &device->viewport, sizeof(gs_rect)); +} + +void device_setscissorrect(device_t device, struct gs_rect *rect) +{ + D3D11_RECT d3drect; + d3drect.left = rect->x; + d3drect.top = rect->y; + d3drect.right = rect->x + rect->cx; + d3drect.bottom = rect->y + rect->cy; + device->context->RSSetScissorRects(1, &d3drect); +} + +void device_ortho(device_t device, float left, float right, float top, + float bottom, float znear, float zfar) +{ + matrix4_ortho(&device->curProjMatrix, left, right, top, bottom, znear, + zfar); +} + +void device_frustum(device_t device, float left, float right, float top, + float bottom, float znear, float zfar) +{ + matrix4_frustum(&device->curProjMatrix, left, right, top, bottom, + znear, zfar); +} + +void device_perspective(device_t device, float fovy, float aspect, + float znear, float zfar) +{ + matrix4_perspective(&device->curProjMatrix, fovy, aspect, znear, zfar); +} + +void device_projection_push(device_t device) +{ + mat4float mat; + memcpy(&mat, &device->curProjMatrix, sizeof(matrix4)); + device->projStack.push_back(mat); +} + +void device_projection_pop(device_t device) +{ + if (!device->projStack.size()) + return; + + mat4float *mat = device->projStack.data(); + size_t end = device->projStack.size()-1; + + /* XXX - does anyone know a better way of doing this? */ + memcpy(&device->curProjMatrix, mat+end, sizeof(matrix4)); + device->projStack.pop_back(); +} + +void swapchain_destroy(swapchain_t swapchain) +{ + if (!swapchain) + return; + + gs_device *device = swapchain->device; + if (device->curSwapChain == swapchain) + device->curSwapChain = &device->defaultSwap; + + delete swapchain; +} + +void texture_destroy(texture_t tex) +{ + delete tex; +} + +uint32_t texture_getwidth(texture_t tex) +{ + if (tex->type != GS_TEXTURE_2D) + return 0; + + return static_cast(tex)->width; +} + +uint32_t texture_getheight(texture_t tex) +{ + if (tex->type != GS_TEXTURE_2D) + return 0; + + return static_cast(tex)->height; +} + +enum gs_color_format texture_getcolorformat(texture_t tex) +{ + if (tex->type != GS_TEXTURE_2D) + return GS_UNKNOWN; + + return static_cast(tex)->format; +} + +bool texture_map(texture_t tex, void **ptr, uint32_t *byte_width) +{ + HRESULT hr; + + if (tex->type != GS_TEXTURE_2D) + return false; + + gs_texture_2d *tex2d = static_cast(tex); + + D3D11_MAPPED_SUBRESOURCE map; + hr = tex2d->device->context->Map(tex2d->texture, 0, + D3D11_MAP_WRITE_DISCARD, 0, &map); + if (FAILED(hr)) + return false; + + *ptr = map.pData; + *byte_width = map.RowPitch; + return true; +} + +void texture_unmap(texture_t tex) +{ + if (tex->type != GS_TEXTURE_2D) + return; + + gs_texture_2d *tex2d = static_cast(tex); + tex2d->device->context->Unmap(tex2d->texture, 0); +} + + +void cubetexture_destroy(texture_t cubetex) +{ + delete cubetex; +} + +uint32_t cubetexture_getsize(texture_t cubetex) +{ + if (cubetex->type != GS_TEXTURE_CUBE) + return 0; + + gs_texture_2d *tex = static_cast(cubetex); + return tex->width; +} + +enum gs_color_format cubetexture_getcolorformat(texture_t cubetex) +{ + if (cubetex->type != GS_TEXTURE_CUBE) + return GS_UNKNOWN; + + gs_texture_2d *tex = static_cast(cubetex); + return tex->format; +} + + +void volumetexture_destroy(texture_t voltex) +{ + delete voltex; +} + +uint32_t volumetexture_getwidth(texture_t voltex) +{ + /* TODO */ + return 0; +} + +uint32_t volumetexture_getheight(texture_t voltex) +{ + /* TODO */ + return 0; +} + +uint32_t volumetexture_getdepth(texture_t voltex) +{ + /* TODO */ + return 0; +} + +enum gs_color_format volumetexture_getcolorformat(texture_t voltex) +{ + /* TODO */ + return GS_UNKNOWN; +} + + +void stagesurface_destroy(stagesurf_t stagesurf) +{ + delete stagesurf; +} + +uint32_t stagesurface_getwidth(stagesurf_t stagesurf) +{ + return stagesurf->width; +} + +uint32_t stagesurface_getheight(stagesurf_t stagesurf) +{ + return stagesurf->height; +} + +enum gs_color_format stagesurface_getcolorformat(stagesurf_t stagesurf) +{ + return stagesurf->format; +} + +bool stagesurface_map(stagesurf_t stagesurf, const void **data, + uint32_t *byte_width) +{ + D3D11_MAPPED_SUBRESOURCE map; + if (FAILED(stagesurf->device->context->Map(stagesurf->texture, 0, + D3D11_MAP_READ, 0, &map))) + return false; + + *data = map.pData; + *byte_width = map.RowPitch; + return true; +} + +void stagesurface_unmap(stagesurf_t stagesurf) +{ + stagesurf->device->context->Unmap(stagesurf->texture, 0); +} + + +void zstencil_destroy(zstencil_t zstencil) +{ + delete zstencil; +} + + +void samplerstate_destroy(samplerstate_t samplerstate) +{ + delete samplerstate; +} + + +void vertexbuffer_destroy(vertbuffer_t vertbuffer) +{ + delete vertbuffer; +} + +void vertexbuffer_flush(vertbuffer_t vertbuffer, bool rebuild) +{ + if (!vertbuffer->dynamic) { + blog(LOG_WARNING, "vertexbuffer_flush: vertex buffer is " + "not dynamic"); + return; + } + + vertbuffer->FlushBuffer(vertbuffer->vertexBuffer, + vertbuffer->vbd.data->points, sizeof(vec3)); + + if (vertbuffer->normalBuffer) + vertbuffer->FlushBuffer(vertbuffer->normalBuffer, + vertbuffer->vbd.data->normals, sizeof(vec3)); + + if (vertbuffer->tangentBuffer) + vertbuffer->FlushBuffer(vertbuffer->tangentBuffer, + vertbuffer->vbd.data->tangents, sizeof(vec3)); + + if (vertbuffer->colorBuffer) + vertbuffer->FlushBuffer(vertbuffer->colorBuffer, + vertbuffer->vbd.data->colors, sizeof(uint32_t)); + + for (size_t i = 0; i < vertbuffer->uvBuffers.size(); i++) { + tvertarray &tv = vertbuffer->vbd.data->tvarray[i]; + vertbuffer->FlushBuffer(vertbuffer->uvBuffers[i], + tv.array, tv.width*sizeof(float)); + } +} + +struct vb_data *vertexbuffer_getdata(vertbuffer_t vertbuffer) +{ + return vertbuffer->vbd.data; +} + + +void indexbuffer_destroy(indexbuffer_t indexbuffer) +{ + delete indexbuffer; +} + +void indexbuffer_flush(indexbuffer_t indexbuffer) +{ + HRESULT hr; + + if (!indexbuffer->dynamic) + return; + + D3D11_MAPPED_SUBRESOURCE map; + hr = indexbuffer->device->context->Map(indexbuffer->indexBuffer, 0, + D3D11_MAP_WRITE_DISCARD, 0, &map); + if (FAILED(hr)) + return; + + memcpy(map.pData, indexbuffer->indices.data, + indexbuffer->num * indexbuffer->indexSize); + + indexbuffer->device->context->Unmap(indexbuffer->indexBuffer, 0); +} + +void *indexbuffer_getdata(indexbuffer_t indexbuffer) +{ + return indexbuffer->indices.data; +} + +size_t indexbuffer_numindices(indexbuffer_t indexbuffer) +{ + return indexbuffer->num; +} + +enum gs_index_type indexbuffer_gettype(indexbuffer_t indexbuffer) +{ + return indexbuffer->type; +} diff --git a/libobs-d3d11/GS_D3D11SubSystem.hpp b/libobs-d3d11/GS_D3D11SubSystem.hpp new file mode 100644 index 000000000..70a7b7e59 --- /dev/null +++ b/libobs-d3d11/GS_D3D11SubSystem.hpp @@ -0,0 +1,642 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#pragma once + +#include +#include + +#include +#include +#include +#include + +#include "util/base.h" +#include "graphics/matrix4.h" +#include "graphics/graphics.h" +#include "util/windows/ComPtr.hpp" +#include "util/windows/HRError.hpp" + +struct shader_var; +struct shader_sampler; +struct gs_vertex_shader; + +#include "GS_D3D11Exports.h" + +using namespace std; + +/* + * Just to clarify, all structs, and all public. These are exporting only + * via encapsulated C bindings, not C++ bindings, so the whole concept of + * "public" and "private" does not matter at all for this subproject. + */ + +#define MAX_TEXTURES 8 + +static inline uint32_t GetWinVer() +{ + OSVERSIONINFO ovi; + ovi.dwOSVersionInfoSize = sizeof(ovi); + GetVersionEx(&ovi); + + return (ovi.dwMajorVersion << 8) | (ovi.dwMinorVersion); +} + +static inline uint32_t GetFormatBPP(gs_color_format format) +{ + switch (format) + { + case GS_A8: return 1; + case GS_R8: return 1; + case GS_RGBA: return 4; + case GS_BGRX: return 4; + case GS_BGRA: return 4; + case GS_R10G10B10A2: return 4; + case GS_RGBA16: return 8; + case GS_R16: return 2; + case GS_RGBA16F: return 8; + case GS_RGBA32F: return 16; + case GS_RG16F: return 4; + case GS_RG32F: return 8; + case GS_R16F: return 2; + case GS_R32F: return 4; + case GS_DXT1: return 0; + case GS_DXT3: return 0; + case GS_DXT5: return 0; + default: return 0; + } +} + +static inline DXGI_FORMAT ConvertGSTextureFormat(gs_color_format format) +{ + switch (format) + { + case GS_A8: return DXGI_FORMAT_A8_UNORM; + case GS_R8: return DXGI_FORMAT_R8_UNORM; + case GS_RGBA: return DXGI_FORMAT_R8G8B8A8_UNORM; + case GS_BGRX: return DXGI_FORMAT_B8G8R8X8_UNORM; + case GS_BGRA: return DXGI_FORMAT_B8G8R8A8_UNORM; + case GS_R10G10B10A2: return DXGI_FORMAT_R10G10B10A2_UNORM; + case GS_RGBA16: return DXGI_FORMAT_R16G16B16A16_UNORM; + case GS_R16: return DXGI_FORMAT_R16_UNORM; + case GS_RGBA16F: return DXGI_FORMAT_R16G16B16A16_FLOAT; + case GS_RGBA32F: return DXGI_FORMAT_R32G32B32A32_FLOAT; + case GS_RG16F: return DXGI_FORMAT_R16G16_FLOAT; + case GS_RG32F: return DXGI_FORMAT_R32G32_FLOAT; + case GS_R16F: return DXGI_FORMAT_R16_FLOAT; + case GS_R32F: return DXGI_FORMAT_R32_FLOAT; + case GS_DXT1: return DXGI_FORMAT_BC1_UNORM; + case GS_DXT3: return DXGI_FORMAT_BC2_UNORM; + case GS_DXT5: return DXGI_FORMAT_BC3_UNORM; + default: return DXGI_FORMAT_UNKNOWN; + } +} + +static inline DXGI_FORMAT ConvertGSZStencilFormat(gs_zstencil_format format) +{ + switch (format) { + case GS_Z16: return DXGI_FORMAT_D16_UNORM; + case GS_Z24_S8: return DXGI_FORMAT_D24_UNORM_S8_UINT; + case GS_Z32F: return DXGI_FORMAT_D32_FLOAT; + case GS_Z32F_S8X24: return DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + default: return DXGI_FORMAT_UNKNOWN; + } +} + +static inline D3D11_COMPARISON_FUNC ConvertGSDepthTest(gs_depth_test test) +{ + switch (test) { + default: + case GS_NEVER: return D3D11_COMPARISON_NEVER; + case GS_LESS: return D3D11_COMPARISON_LESS; + case GS_LEQUAL: return D3D11_COMPARISON_LESS_EQUAL; + case GS_EQUAL: return D3D11_COMPARISON_EQUAL; + case GS_GEQUAL: return D3D11_COMPARISON_GREATER_EQUAL; + case GS_GREATER: return D3D11_COMPARISON_GREATER; + case GS_NOTEQUAL: return D3D11_COMPARISON_NOT_EQUAL; + case GS_ALWAYS: return D3D11_COMPARISON_ALWAYS; + } +} + +static inline D3D11_STENCIL_OP ConvertGSStencilOp(gs_stencil_op op) +{ + switch (op) { + default: + case GS_KEEP: return D3D11_STENCIL_OP_KEEP; + case GS_ZERO: return D3D11_STENCIL_OP_ZERO; + case GS_REPLACE: return D3D11_STENCIL_OP_REPLACE; + case GS_INCR: return D3D11_STENCIL_OP_INCR; + case GS_DECR: return D3D11_STENCIL_OP_DECR; + case GS_INVERT: return D3D11_STENCIL_OP_INVERT; + } +} + +static inline D3D11_BLEND ConvertGSBlendType(gs_blend_type type) +{ + switch (type) { + default: + case GS_BLEND_ZERO: return D3D11_BLEND_ZERO; + case GS_BLEND_ONE: return D3D11_BLEND_ONE; + case GS_BLEND_SRCCOLOR: return D3D11_BLEND_SRC_COLOR; + case GS_BLEND_INVSRCCOLOR: return D3D11_BLEND_INV_SRC_COLOR; + case GS_BLEND_SRCALPHA: return D3D11_BLEND_SRC_ALPHA; + case GS_BLEND_INVSRCALPHA: return D3D11_BLEND_INV_SRC_ALPHA; + case GS_BLEND_DSTCOLOR: return D3D11_BLEND_DEST_COLOR; + case GS_BLEND_INVDSTCOLOR: return D3D11_BLEND_INV_DEST_COLOR; + case GS_BLEND_DSTALPHA: return D3D11_BLEND_DEST_ALPHA; + case GS_BLEND_INVDSTALPHA: return D3D11_BLEND_INV_DEST_ALPHA; + case GS_BLEND_SRCALPHASAT: return D3D11_BLEND_SRC_ALPHA_SAT; + } +} + +static inline D3D11_CULL_MODE ConvertGSCullMode(gs_cull_mode mode) +{ + switch (mode) { + default: + case GS_BACK: return D3D11_CULL_BACK; + case GS_FRONT: return D3D11_CULL_FRONT; + case GS_NEITHER: return D3D11_CULL_NONE; + } +} + +static inline D3D11_PRIMITIVE_TOPOLOGY ConvertGSTopology(gs_draw_mode mode) +{ + switch (mode) { + default: + case GS_POINTS: return D3D11_PRIMITIVE_TOPOLOGY_POINTLIST; + case GS_LINES: return D3D11_PRIMITIVE_TOPOLOGY_LINELIST; + case GS_LINESTRIP: return D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP; + case GS_TRIS: return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; + case GS_TRISTRIP: return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; + } +} + +/* exception-safe RAII wrapper for vertex buffer data (NOTE: not copy-safe) */ +struct VBDataPtr { + vb_data *data; + + inline VBDataPtr(vb_data *data) : data(data) {} + inline ~VBDataPtr() {vbdata_destroy(data);} +}; + +struct gs_vertex_buffer { + ComPtr vertexBuffer; + ComPtr normalBuffer; + ComPtr colorBuffer; + ComPtr tangentBuffer; + vector> uvBuffers; + + device_t device; + bool dynamic; + VBDataPtr vbd; + size_t numVerts; + vector uvSizes; + + void FlushBuffer(ID3D11Buffer *buffer, void *array, + size_t elementSize); + + void MakeBufferList(gs_vertex_shader *shader, + vector &buffers, + vector &strides); + + inline void InitBuffer(const size_t elementSize, + const size_t numVerts, void *array, + ID3D11Buffer **buffer); + + gs_vertex_buffer(device_t device, struct vb_data *data, uint32_t flags); +}; + +/* exception-safe RAII wrapper for index buffer data (NOTE: not copy-safe) */ +struct DataPtr { + void *data; + + inline DataPtr(void *data) : data(data) {} + inline ~DataPtr() {bfree(data);} +}; + +struct gs_index_buffer { + ComPtr indexBuffer; + device_t device; + bool dynamic; + gs_index_type type; + size_t indexSize; + size_t num; + DataPtr indices; + + void InitBuffer(); + + gs_index_buffer(device_t device, enum gs_index_type type, + void *indices, size_t num, uint32_t flags); +}; + +struct gs_texture { + gs_texture_type type; + ComPtr shaderRes; + gs_device *device; + + inline gs_texture(gs_device *device, gs_texture_type type) + : device (device), + type (type) + { + } + + virtual ~gs_texture() {} +}; + +struct gs_texture_2d : gs_texture { + ComPtr texture; + ComPtr renderTarget[6]; + ComPtr gdiSurface; + + uint32_t width, height; + gs_color_format format; + DXGI_FORMAT dxgiFormat; + bool isRenderTarget; + bool isGDICompatible; + bool isDynamic; + bool isShared; + bool genMipmaps; + HANDLE sharedHandle; + + void InitSRD(D3D11_SUBRESOURCE_DATA *srd, void *data); + void InitTexture(void *data); + void InitResourceView(); + void InitRenderTargets(); + + inline gs_texture_2d() + : gs_texture (NULL, GS_TEXTURE_2D), + width (0), + height (0), + format (GS_UNKNOWN), + dxgiFormat (DXGI_FORMAT_UNKNOWN), + isRenderTarget (false), + isGDICompatible (false), + isDynamic (false), + isShared (false), + genMipmaps (false), + sharedHandle (NULL) + { + } + + gs_texture_2d(device_t device, uint32_t width, uint32_t height, + gs_color_format colorFormat, void *data, + uint32_t flags, bool isCubeMap, bool gdiCompatible, + bool shared); +}; + +struct gs_zstencil_buffer { + ComPtr texture; + ComPtr view; + + gs_device *device; + uint32_t width, height; + gs_zstencil_format format; + DXGI_FORMAT dxgiFormat; + + void InitBuffer(); + + inline gs_zstencil_buffer() + : device (NULL), + width (0), + height (0), + dxgiFormat (DXGI_FORMAT_UNKNOWN) + { + } + + gs_zstencil_buffer(device_t device, uint32_t width, uint32_t height, + gs_zstencil_format format); +}; + +struct gs_stage_surface { + ComPtr texture; + + gs_device *device; + uint32_t width, height; + gs_color_format format; + DXGI_FORMAT dxgiFormat; + + gs_stage_surface(device_t device, uint32_t width, uint32_t height, + gs_color_format colorFormat); +}; + +struct gs_sampler_state { + ComPtr state; + device_t device; + gs_sampler_info info; + + gs_sampler_state(device_t device, gs_sampler_info *info); +}; + +struct shader_param { + string name; + shader_param_type type; + + uint32_t textureID; + + int arrayCount; + + vector curValue; + vector defaultValue; + bool changed; + + shader_param(shader_var &var, uint32_t &texCounter); +}; + +struct ShaderError { + ComPtr errors; + HRESULT hr; + + inline ShaderError(const ComPtr &errors, HRESULT hr) + : errors (errors), + hr (hr) + { + } +}; + +struct gs_shader { + device_t device; + shader_type type; + vector params; + ComPtr constants; + size_t constantSize; + + inline void UpdateParam(vector &constData, shader_param ¶m, + bool &upload); + void UploadParams(); + + void BuildConstantBuffer(); + void Compile(const char *shaderStr, const char *file, + const char *target, ID3D10Blob **shader); + + inline gs_shader(device_t device, shader_type type) + : device (device), + type (type), + constantSize (0) + { + } + + virtual ~gs_shader() {} +}; + +struct ShaderSampler { + string name; + gs_sampler_state sampler; + + inline ShaderSampler(const char *name, device_t device, + gs_sampler_info *info) + : name (name), + sampler (device, info) + { + } +}; + +struct gs_vertex_shader : gs_shader { + ComPtr shader; + ComPtr layout; + + shader_param *world, *viewProj; + + bool hasNormals; + bool hasColors; + bool hasTangents; + uint32_t nTexUnits; + + inline uint32_t NumBuffersExpected() const + { + uint32_t count = nTexUnits+1; + if (hasNormals) count++; + if (hasColors) count++; + if (hasTangents) count++; + + return count; + } + + void GetBuffersExpected(const vector &inputs); + + gs_vertex_shader(device_t device, const char *file, + const char *shaderString); +}; + +struct gs_pixel_shader : gs_shader { + ComPtr shader; + vector samplers; + + inline void GetSamplerStates(ID3D11SamplerState **states) + { + size_t i; + for (i = 0; i < samplers.size(); i++) + states[i] = samplers[i].sampler.state; + for (; i < MAX_TEXTURES; i++) + states[i] = NULL; + } + + gs_pixel_shader(device_t device, const char *file, + const char *shaderString); +}; + +struct gs_swap_chain { + gs_device *device; + uint32_t numBuffers; + HWND hwnd; + + gs_texture_2d target; + gs_zstencil_buffer zs; + ComPtr swap; + + void InitTarget(uint32_t cx, uint32_t cy); + void InitZStencilBuffer(uint32_t cx, uint32_t cy); + void Resize(uint32_t cx, uint32_t cy); + void Init(gs_init_data *data); + + inline gs_swap_chain() + : device (NULL), + numBuffers (0), + hwnd (NULL) + { + } + + gs_swap_chain(gs_device *device, gs_init_data *data); +}; + +struct BlendState { + bool blendEnabled; + gs_blend_type srcFactor; + gs_blend_type destFactor; + + bool redEnabled; + bool greenEnabled; + bool blueEnabled; + bool alphaEnabled; + + inline BlendState() + : blendEnabled (true), + srcFactor (GS_BLEND_SRCALPHA), + destFactor (GS_BLEND_INVSRCALPHA), + redEnabled (true), + greenEnabled (true), + blueEnabled (true), + alphaEnabled (true) + { + } + + inline BlendState(const BlendState &state) + { + memcpy(this, &state, sizeof(BlendState)); + } +}; + +struct SavedBlendState : BlendState { + ComPtr state; + + inline SavedBlendState(const BlendState &val) : BlendState(val) + { + } +}; + +struct StencilSide { + gs_depth_test test; + gs_stencil_op fail; + gs_stencil_op zfail; + gs_stencil_op zpass; + + inline StencilSide() + : test (GS_ALWAYS), + fail (GS_KEEP), + zfail (GS_KEEP), + zpass (GS_KEEP) + { + } +}; + +struct ZStencilState { + bool depthEnabled; + bool depthWriteEnabled; + gs_depth_test depthFunc; + + bool stencilEnabled; + bool stencilWriteEnabled; + StencilSide stencilFront; + StencilSide stencilBack; + + inline ZStencilState() + : depthEnabled (true), + depthWriteEnabled (true), + depthFunc (GS_LESS), + stencilEnabled (false), + stencilWriteEnabled (true) + { + } + + inline ZStencilState(const ZStencilState &state) + { + memcpy(this, &state, sizeof(ZStencilState)); + } +}; + +struct SavedZStencilState : ZStencilState { + ComPtr state; + + inline SavedZStencilState(const ZStencilState &val) + : ZStencilState (val) + { + } +}; + +struct RasterState { + gs_cull_mode cullMode; + bool scissorEnabled; + + inline RasterState() + : cullMode (GS_BACK), + scissorEnabled (false) + { + } + + inline RasterState(const RasterState &state) + { + memcpy(this, &state, sizeof(RasterState)); + } +}; + +struct SavedRasterState : RasterState { + ComPtr state; + + inline SavedRasterState(const RasterState &val) + : RasterState (val) + { + } +}; + +struct mat4float { + float mat[16]; +}; + +struct gs_device { + ComPtr factory; + ComPtr device; + ComPtr context; + gs_swap_chain defaultSwap; + + gs_texture_2d *curRenderTarget; + gs_zstencil_buffer *curZStencilBuffer; + int curRenderSide; + gs_texture *curTextures[MAX_TEXTURES]; + gs_sampler_state *curSamplers[MAX_TEXTURES]; + gs_vertex_buffer *curVertexBuffer; + gs_vertex_shader *curVertexShader; + gs_index_buffer *curIndexBuffer; + gs_pixel_shader *curPixelShader; + gs_swap_chain *curSwapChain; + + bool zstencilStateChanged; + bool rasterStateChanged; + bool blendStateChanged; + ZStencilState zstencilState; + RasterState rasterState; + BlendState blendState; + vector zstencilStates; + vector rasterStates; + vector blendStates; + ID3D11DepthStencilState *curDepthStencilState; + ID3D11RasterizerState *curRasterState; + ID3D11BlendState *curBlendState; + D3D11_PRIMITIVE_TOPOLOGY curToplogy; + + gs_rect viewport; + + vector projStack; + + matrix4 curProjMatrix; + matrix4 curViewMatrix; + matrix4 curViewProjMatrix; + + void InitFactory(uint32_t adapterIdx, IDXGIAdapter1 **adapter); + void InitDevice(gs_init_data *data, IDXGIAdapter *adapter); + + ID3D11DepthStencilState *AddZStencilState(); + ID3D11RasterizerState *AddRasterState(); + ID3D11BlendState *AddBlendState(); + void UpdateZStencilState(); + void UpdateRasterState(); + void UpdateBlendState(); + + inline void CopyTex(ID3D11Texture2D *dst, texture_t src); + + void UpdateViewProjMatrix(); + + gs_device(gs_init_data *data); +}; diff --git a/libobs-d3d11/GS_D3D11Texture2D.cpp b/libobs-d3d11/GS_D3D11Texture2D.cpp new file mode 100644 index 000000000..374c5c259 --- /dev/null +++ b/libobs-d3d11/GS_D3D11Texture2D.cpp @@ -0,0 +1,154 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "util/base.h" +#include "GS_D3D11SubSystem.hpp" + +static inline bool IsPow2(uint32_t num) +{ + return num >= 2 && (num & (num-1)) == 0; +} + +void gs_texture_2d::InitSRD(D3D11_SUBRESOURCE_DATA *srd, void *data) +{ + uint32_t rowSizeBytes = width * GetFormatBPP(format); + uint32_t texSizeBytes = rowSizeBytes * height; + + if (type == GS_TEXTURE_2D) { + srd->pSysMem = (uint8_t*)data; + srd->SysMemPitch = rowSizeBytes; + srd->SysMemSlicePitch = texSizeBytes; + + } else { /* GS_TEXTURE_CUBE */ + void **buffers = (void**)data; + for (size_t i = 0; i < 6; i++) { + srd[i].pSysMem = buffers[i]; + srd[i].SysMemPitch = rowSizeBytes; + srd[i].SysMemSlicePitch = texSizeBytes; + } + } +} + +void gs_texture_2d::InitTexture(void *data) +{ + D3D11_TEXTURE2D_DESC td; + D3D11_SUBRESOURCE_DATA srd[6]; + HRESULT hr; + + memset(&td, 0, sizeof(td)); + td.Width = width; + td.Height = height; + td.MipLevels = genMipmaps ? 0 : 1; + td.ArraySize = type == GS_TEXTURE_CUBE ? 6 : 1; + td.Format = dxgiFormat; + td.BindFlags = D3D10_BIND_SHADER_RESOURCE; + td.SampleDesc.Count = 1; + td.CPUAccessFlags = isDynamic ? D3D11_CPU_ACCESS_WRITE : 0; + td.Usage = isDynamic ? D3D11_USAGE_DYNAMIC : + D3D11_USAGE_DEFAULT; + + if (type == GS_TEXTURE_CUBE) + td.MiscFlags |= D3D11_RESOURCE_MISC_TEXTURECUBE; + + if (isRenderTarget || isGDICompatible) + td.BindFlags |= D3D10_BIND_RENDER_TARGET; + + if (data) + InitSRD(srd, data); + + hr = device->device->CreateTexture2D(&td, data ? srd : NULL, + texture.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create 2D texture", hr); +} + +void gs_texture_2d::InitResourceView() +{ + D3D11_SHADER_RESOURCE_VIEW_DESC resourceDesc; + HRESULT hr; + + memset(&resourceDesc, 0, sizeof(resourceDesc)); + resourceDesc.Format = dxgiFormat; + + if (type == GS_TEXTURE_CUBE) { + resourceDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURECUBE; + resourceDesc.TextureCube.MipLevels = genMipmaps ? -1 : 1; + } else { + resourceDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; + resourceDesc.Texture2D.MipLevels = genMipmaps ? -1 : 1; + } + + hr = device->device->CreateShaderResourceView(texture, &resourceDesc, + shaderRes.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create resource view", hr); +} + +void gs_texture_2d::InitRenderTargets() +{ + HRESULT hr; + if (type == GS_TEXTURE_2D) { + hr = device->device->CreateRenderTargetView(texture, NULL, + renderTarget[0].Assign()); + if (FAILED(hr)) + throw HRError("Failed to create render target view", + hr); + } else { + D3D11_RENDER_TARGET_VIEW_DESC rtv; + rtv.Format = dxgiFormat; + rtv.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY; + rtv.Texture2DArray.MipSlice = 0; + rtv.Texture2DArray.ArraySize = 1; + + for (UINT i = 0; i < 6; i++) { + rtv.Texture2DArray.FirstArraySlice = i; + hr = device->device->CreateRenderTargetView(texture, + &rtv, renderTarget[i].Assign()); + if (FAILED(hr)) + throw HRError("Failed to create cube render " + "target view", hr); + } + } +} + +gs_texture_2d::gs_texture_2d(device_t device, uint32_t width, uint32_t height, + gs_color_format colorFormat, void *data, uint32_t flags, + bool isCubeMap, bool gdiCompatible, bool shared) + : gs_texture (device, isCubeMap ? GS_TEXTURE_CUBE : GS_TEXTURE_2D), + width (width), + height (height), + format (colorFormat), + dxgiFormat (ConvertGSTextureFormat(format)), + isGDICompatible (gdiCompatible), + isShared (shared), + isDynamic ((flags & GS_DYNAMIC) != 0), + isRenderTarget ((flags & GS_RENDERTARGET) != 0), + genMipmaps ((flags & GS_BUILDMIPMAPS) != 0) +{ + if (genMipmaps && (!IsPow2(width) || !IsPow2(height))) { + blog(LOG_WARNING, "Cannot generate mipmaps for a " + "non-power-of-two texture. Disabling " + "mipmaps for this texture."); + genMipmaps = false; + } + + InitTexture(data); + InitResourceView(); + + if (isRenderTarget) + InitRenderTargets(); +} diff --git a/libobs-d3d11/GS_D3D11VertexBuffer.cpp b/libobs-d3d11/GS_D3D11VertexBuffer.cpp new file mode 100644 index 000000000..88e1f8b09 --- /dev/null +++ b/libobs-d3d11/GS_D3D11VertexBuffer.cpp @@ -0,0 +1,143 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "util/base.h" +#include "graphics/vec3.h" +#include "GS_D3D11SubSystem.hpp" + +static inline void PushBuffer(vector &buffers, + vector &strides, ID3D11Buffer *buffer, + size_t elementSize, const char *name) +{ + if (buffer) { + buffers.push_back(buffer); + strides.push_back((uint32_t)elementSize); + } else { + blog(LOG_ERROR, "This vertex shader requires a %s buffer", + name); + } +} + +void gs_vertex_buffer::FlushBuffer(ID3D11Buffer *buffer, void *array, + size_t elementSize) +{ + D3D11_MAPPED_SUBRESOURCE msr; + HRESULT hr; + + if (FAILED(hr = device->context->Map(buffer, 0, + D3D11_MAP_WRITE_DISCARD, 0, &msr))) + throw HRError("Failed to map buffer", hr); + + memcpy(msr.pData, array, elementSize * vbd.data->num); + device->context->Unmap(buffer, 0); +} + +void gs_vertex_buffer::MakeBufferList(gs_vertex_shader *shader, + vector &buffers, vector &strides) +{ + PushBuffer(buffers, strides, vertexBuffer, sizeof(vec3), "point"); + + if (shader->hasNormals) + PushBuffer(buffers, strides, vertexBuffer, sizeof(vec3), + "normal"); + if (shader->hasColors) + PushBuffer(buffers, strides, vertexBuffer, sizeof(vec3), + "color"); + if (shader->hasTangents) + PushBuffer(buffers, strides, vertexBuffer, sizeof(vec3), + "tangent"); + if (shader->nTexUnits <= uvBuffers.size()) { + for (size_t i = 0; i < shader->nTexUnits; i++) { + buffers.push_back(uvBuffers[i]); + strides.push_back((uint32_t)uvSizes[i]); + } + } else { + blog(LOG_ERROR, "This vertex shader requires at least %u " + "texture buffers.", + (uint32_t)shader->nTexUnits); + } +} + +inline void gs_vertex_buffer::InitBuffer(const size_t elementSize, + const size_t numVerts, void *array, ID3D11Buffer **buffer) +{ + D3D11_BUFFER_DESC bd; + D3D11_SUBRESOURCE_DATA srd; + HRESULT hr; + + memset(&bd, 0, sizeof(bd)); + memset(&srd, 0, sizeof(srd)); + + bd.Usage = dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT; + bd.CPUAccessFlags = dynamic ? D3D11_CPU_ACCESS_WRITE : 0; + bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; + bd.ByteWidth = UINT(elementSize * numVerts); + srd.pSysMem = array; + + hr = device->device->CreateBuffer(&bd, &srd, buffer); + if (FAILED(hr)) + throw HRError("Failed to create buffer", hr); +} + +gs_vertex_buffer::gs_vertex_buffer(device_t device, struct vb_data *data, + uint32_t flags) + : device (device), + vbd (data), + numVerts (data->num), + dynamic ((flags & GS_DYNAMIC) != 0) +{ + if (!data->num) + throw "Cannot initialize vertex buffer with 0 vertices"; + if (!data->points) + throw "No points specified for vertex buffer"; + + InitBuffer(sizeof(vec3), data->num, data->points, + vertexBuffer.Assign()); + + if (data->normals) + InitBuffer(sizeof(vec3), data->num, data->normals, + normalBuffer.Assign()); + + if (data->tangents) + InitBuffer(sizeof(vec3), data->num, data->tangents, + tangentBuffer.Assign()); + + if (data->colors) + InitBuffer(sizeof(uint32_t), data->num, data->colors, + colorBuffer.Assign()); + + for (size_t i = 0; i < data->num_tex; i++) { + struct tvertarray *tverts = data->tvarray+i; + + if (tverts->width != 2 && tverts->width != 4) + throw "Invalid texture vertex size specified"; + if (!tverts->array) + throw "No texture vertices specified"; + + ComPtr buffer; + InitBuffer(tverts->width * sizeof(float), data->num, + tverts->array, buffer.Assign()); + + uvBuffers.push_back(buffer); + uvSizes.push_back(tverts->width * sizeof(float)); + } + + if (!dynamic) { + bfree(data); + data = NULL; + } +} diff --git a/libobs-d3d11/GS_D3D11ZStencilBuffer.cpp b/libobs-d3d11/GS_D3D11ZStencilBuffer.cpp new file mode 100644 index 000000000..496cb5448 --- /dev/null +++ b/libobs-d3d11/GS_D3D11ZStencilBuffer.cpp @@ -0,0 +1,60 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "GS_D3D11SubSystem.hpp" + +void gs_zstencil_buffer::InitBuffer() +{ + D3D11_TEXTURE2D_DESC td; + D3D11_DEPTH_STENCIL_VIEW_DESC dsvd; + HRESULT hr; + + memset(&td, 0, sizeof(td)); + td.Width = width; + td.Height = height; + td.MipLevels = 1; + td.ArraySize = 1; + td.Format = dxgiFormat; + td.BindFlags = D3D11_BIND_DEPTH_STENCIL; + td.SampleDesc.Count = 1; + td.Usage = D3D11_USAGE_DEFAULT; + + hr = device->device->CreateTexture2D(&td, NULL, texture.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create depth stencil texture", hr); + + memset(&dsvd, 0, sizeof(dsvd)); + dsvd.Format = dxgiFormat; + dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; + + hr = device->device->CreateDepthStencilView(texture, &dsvd, + view.Assign()); + if (FAILED(hr)) + throw HRError("Failed to create depth stencil view", hr); +} + +gs_zstencil_buffer::gs_zstencil_buffer(device_t device, + uint32_t width, uint32_t height, + gs_zstencil_format format) + : device (device), + width (width), + height (height), + format (format), + dxgiFormat (ConvertGSZStencilFormat(format)) +{ + InitBuffer(); +} diff --git a/libobs-d3d11/makefile b/libobs-d3d11/makefile new file mode 100644 index 000000000..a11fd1af7 --- /dev/null +++ b/libobs-d3d11/makefile @@ -0,0 +1,51 @@ +include ../config.mak + +all: default + +SRCFILES=GS_D3D11SubSystem.cpp \ + GS_D3D11IndexBuffer.cpp \ + GS_D3D11Shader.cpp \ + GS_D3D11ShaderProcessor.cpp \ + GS_D3D11StageSurf.cpp \ + GS_D3D11Texture2D.cpp \ + GS_D3D11VertexBuffer.cpp \ + GS_D3D11ZStencilBuffer.cpp + +SONAME=../build/libobs-d3d11.$(SOEXT) + +LD=g++ -o + +CPPFLAGS += -iquote $(BASEINC) +CPPFLAGS += -iquote ../libobs-graphics/ +CPPFLAGS += -isystem ./mingw/ + +LDFLAGS += -L../build/ + +ifdef monolithic +LDFLAGS += -lobs +else +LDFLAGS += -lobs-util -lobs-graphics +endif + +.PHONY: all monolithic default clean + +OBJS += $(SRCFILES:%.cpp=%.$(OBJ)) + +default: $(SONAME) + +$(SONAME): .depend $(OBJS) + $(LD)$@ $(LDFLAGS) $(OBJS) + +.depend: + @rm -f .depend + @$(foreach SRC, $(addprefix $(SRCPATH)/, $(SRCFILES)), $(CCDEP) \ + -std=c++11 $(CPPFLAGS) $(SRC) -I$(BASEINC) \ + -MT $(SRC:$(SRCPATH)/%.cpp=%.$(OBJ)) -MM 1>> .depend;) + +depend: .depend +ifneq ($(wildcard .depend),) +include .depend +endif + +clean: + rm -f $(OBJS) $(SONAME) *.a *.lib *.exp *.pdb .depend diff --git a/libobs-d3d11/mingw/dxgi.h b/libobs-d3d11/mingw/dxgi.h new file mode 100644 index 000000000..b2fd70656 --- /dev/null +++ b/libobs-d3d11/mingw/dxgi.h @@ -0,0 +1,2713 @@ +/*** Autogenerated by WIDL 1.5.25 from direct-x/include/dxgi.idl - Do not edit ***/ + +#ifndef __REQUIRED_RPCNDR_H_VERSION__ +#define __REQUIRED_RPCNDR_H_VERSION__ 475 +#endif + +#include +#include + +#ifndef COM_NO_WINDOWS_H +#include +#include +#endif + +#ifndef __dxgi_h__ +#define __dxgi_h__ + +/* Forward declarations */ + +#ifndef __IDXGIObject_FWD_DEFINED__ +#define __IDXGIObject_FWD_DEFINED__ +typedef interface IDXGIObject IDXGIObject; +#endif + +#ifndef __IDXGIDeviceSubObject_FWD_DEFINED__ +#define __IDXGIDeviceSubObject_FWD_DEFINED__ +typedef interface IDXGIDeviceSubObject IDXGIDeviceSubObject; +#endif + +#ifndef __IDXGIResource_FWD_DEFINED__ +#define __IDXGIResource_FWD_DEFINED__ +typedef interface IDXGIResource IDXGIResource; +#endif + +#ifndef __IDXGIKeyedMutex_FWD_DEFINED__ +#define __IDXGIKeyedMutex_FWD_DEFINED__ +typedef interface IDXGIKeyedMutex IDXGIKeyedMutex; +#endif + +#ifndef __IDXGISurface_FWD_DEFINED__ +#define __IDXGISurface_FWD_DEFINED__ +typedef interface IDXGISurface IDXGISurface; +#endif + +#ifndef __IDXGISurface1_FWD_DEFINED__ +#define __IDXGISurface1_FWD_DEFINED__ +typedef interface IDXGISurface1 IDXGISurface1; +#endif + +#ifndef __IDXGIOutput_FWD_DEFINED__ +#define __IDXGIOutput_FWD_DEFINED__ +typedef interface IDXGIOutput IDXGIOutput; +#endif + +#ifndef __IDXGIAdapter_FWD_DEFINED__ +#define __IDXGIAdapter_FWD_DEFINED__ +typedef interface IDXGIAdapter IDXGIAdapter; +#endif + +#ifndef __IDXGISwapChain_FWD_DEFINED__ +#define __IDXGISwapChain_FWD_DEFINED__ +typedef interface IDXGISwapChain IDXGISwapChain; +#endif + +#ifndef __IDXGIFactory_FWD_DEFINED__ +#define __IDXGIFactory_FWD_DEFINED__ +typedef interface IDXGIFactory IDXGIFactory; +#endif + +#ifndef __IDXGIDevice_FWD_DEFINED__ +#define __IDXGIDevice_FWD_DEFINED__ +typedef interface IDXGIDevice IDXGIDevice; +#endif + +#ifndef __IDXGIAdapter1_FWD_DEFINED__ +#define __IDXGIAdapter1_FWD_DEFINED__ +typedef interface IDXGIAdapter1 IDXGIAdapter1; +#endif + +#ifndef __IDXGIFactory1_FWD_DEFINED__ +#define __IDXGIFactory1_FWD_DEFINED__ +typedef interface IDXGIFactory1 IDXGIFactory1; +#endif + +/* Headers for imported files */ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define _FACDXGI (0x87a) + +#define MAKE_DXGI_STATUS(x) MAKE_HRESULT(0, _FACDXGI, x) +#define DXGI_STATUS_OCCLUDED MAKE_DXGI_STATUS(1) +#define DXGI_STATUS_CLIPPED MAKE_DXGI_STATUS(2) +#define DXGI_STATUS_NO_REDIRECTION MAKE_DXGI_STATUS(4) +#define DXGI_STATUS_NO_DESKTOP_ACCESS MAKE_DXGI_STATUS(5) +#define DXGI_STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE MAKE_DXGI_STATUS(6) +#define DXGI_STATUS_MODE_CHANGED MAKE_DXGI_STATUS(7) +#define DXGI_STATUS_MODE_CHANGE_IN_PROGRESS MAKE_DXGI_STATUS(8) +#define MAKE_DXGI_HRESULT(x) MAKE_HRESULT(1, _FACDXGI, x) +#define DXGI_ERROR_INVALID_CALL MAKE_DXGI_HRESULT(1) +#define DXGI_ERROR_NOT_FOUND MAKE_DXGI_HRESULT(2) +#define DXGI_ERROR_MORE_DATA MAKE_DXGI_HRESULT(3) +#define DXGI_ERROR_UNSUPPORTED MAKE_DXGI_HRESULT(4) +#define DXGI_ERROR_DEVICE_REMOVED MAKE_DXGI_HRESULT(5) +#define DXGI_ERROR_DEVICE_HUNG MAKE_DXGI_HRESULT(6) +#define DXGI_ERROR_DEVICE_RESET MAKE_DXGI_HRESULT(7) +#define DXGI_ERROR_WAS_STILL_DRAWING MAKE_DXGI_HRESULT(10) +#define DXGI_ERROR_FRAME_STATISTICS_DISJOINT MAKE_DXGI_HRESULT(11) +#define DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE MAKE_DXGI_HRESULT(12) +#define DXGI_ERROR_DRIVER_INTERNAL_ERROR MAKE_DXGI_HRESULT(32) +#define DXGI_ERROR_NONEXCLUSIVE MAKE_DXGI_HRESULT(33) +#define DXGI_ERROR_NOT_CURRENTLY_AVAILABLE MAKE_DXGI_HRESULT(34) +#if 0 +typedef HANDLE HMONITOR; +typedef struct _LUID { + DWORD LowPart; + LONG HighPart; +} LUID; +typedef struct _LUID *PLUID; +#endif +typedef UINT DXGI_USAGE; +#define DXGI_USAGE_SHADER_INPUT (0x10) + +#define DXGI_USAGE_RENDER_TARGET_OUTPUT (0x20) + +#define DXGI_USAGE_BACK_BUFFER (0x40) + +#define DXGI_USAGE_SHARED (0x80) + +#define DXGI_USAGE_READ_ONLY (0x100) + +#define DXGI_ENUM_MODES_INTERLACED (1) + +#define DXGI_ENUM_MODES_SCALING (2) + +typedef enum DXGI_SWAP_EFFECT { + DXGI_SWAP_EFFECT_DISCARD = 0, + DXGI_SWAP_EFFECT_SEQUENTIAL = 1 +} DXGI_SWAP_EFFECT; +typedef enum DXGI_RESIDENCY { + DXGI_RESIDENCY_FULLY_RESIDENT = 1, + DXGI_RESIDENCY_RESIDENT_IN_SHARED_MEMORY = 2, + DXGI_RESIDENCY_EVICTED_TO_DISK = 3 +} DXGI_RESIDENCY; +typedef struct DXGI_SURFACE_DESC { + UINT Width; + UINT Height; + DXGI_FORMAT Format; + DXGI_SAMPLE_DESC SampleDesc; +} DXGI_SURFACE_DESC; +typedef struct DXGI_MAPPED_RECT { + INT Pitch; + BYTE *pBits; +} DXGI_MAPPED_RECT; +typedef struct DXGI_OUTPUT_DESC { + WCHAR DeviceName[32]; + RECT DesktopCoordinates; + WINBOOL AttachedToDesktop; + DXGI_MODE_ROTATION Rotation; + HMONITOR Monitor; +} DXGI_OUTPUT_DESC; +typedef struct DXGI_FRAME_STATISTICS { + UINT PresentCount; + UINT PresentRefreshCount; + UINT SyncRefreshCount; + LARGE_INTEGER SyncQPCTime; + LARGE_INTEGER SyncGPUTime; +} DXGI_FRAME_STATISTICS; +typedef struct DXGI_ADAPTER_DESC { + WCHAR Description[128]; + UINT VendorId; + UINT DeviceId; + UINT SubSysId; + UINT Revision; + SIZE_T DedicatedVideoMemory; + SIZE_T DedicatedSystemMemory; + SIZE_T SharedSystemMemory; + LUID AdapterLuid; +} DXGI_ADAPTER_DESC; +typedef enum DXGI_SWAP_CHAIN_FLAG { + DXGI_SWAP_CHAIN_FLAG_NONPREROTATED = 1, + DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH = 2, + DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE = 4 +} DXGI_SWAP_CHAIN_FLAG; +typedef struct DXGI_SWAP_CHAIN_DESC { + DXGI_MODE_DESC BufferDesc; + DXGI_SAMPLE_DESC SampleDesc; + DXGI_USAGE BufferUsage; + UINT BufferCount; + HWND OutputWindow; + WINBOOL Windowed; + DXGI_SWAP_EFFECT SwapEffect; + UINT Flags; +} DXGI_SWAP_CHAIN_DESC; +typedef struct DXGI_SHARED_RESOURCE { + HANDLE Handle; +} DXGI_SHARED_RESOURCE; +/***************************************************************************** + * IDXGIObject interface + */ +#ifndef __IDXGIObject_INTERFACE_DEFINED__ +#define __IDXGIObject_INTERFACE_DEFINED__ + +DEFINE_GUID(IID_IDXGIObject, 0xaec22fb8, 0x76f3, 0x4639, 0x9b,0xe0, 0x28,0xeb,0x43,0xa6,0x7a,0x2e); +#if defined(__cplusplus) && !defined(CINTERFACE) +MIDL_INTERFACE("aec22fb8-76f3-4639-9be0-28eb43a67a2e") +IDXGIObject : public IUnknown +{ + virtual HRESULT STDMETHODCALLTYPE SetPrivateData( + REFGUID guid, + UINT data_size, + const void *data) = 0; + + virtual HRESULT STDMETHODCALLTYPE SetPrivateDataInterface( + REFGUID guid, + const IUnknown *object) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetPrivateData( + REFGUID guid, + UINT *data_size, + void *data) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetParent( + REFIID riid, + void **parent) = 0; + +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IDXGIObject, 0xaec22fb8, 0x76f3, 0x4639, 0x9b,0xe0, 0x28,0xeb,0x43,0xa6,0x7a,0x2e) +#endif +#else +typedef struct IDXGIObjectVtbl { + BEGIN_INTERFACE + + /*** IUnknown methods ***/ + HRESULT (STDMETHODCALLTYPE *QueryInterface)( + IDXGIObject* This, + REFIID riid, + void **ppvObject); + + ULONG (STDMETHODCALLTYPE *AddRef)( + IDXGIObject* This); + + ULONG (STDMETHODCALLTYPE *Release)( + IDXGIObject* This); + + /*** IDXGIObject methods ***/ + HRESULT (STDMETHODCALLTYPE *SetPrivateData)( + IDXGIObject* This, + REFGUID guid, + UINT data_size, + const void *data); + + HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)( + IDXGIObject* This, + REFGUID guid, + const IUnknown *object); + + HRESULT (STDMETHODCALLTYPE *GetPrivateData)( + IDXGIObject* This, + REFGUID guid, + UINT *data_size, + void *data); + + HRESULT (STDMETHODCALLTYPE *GetParent)( + IDXGIObject* This, + REFIID riid, + void **parent); + + END_INTERFACE +} IDXGIObjectVtbl; +interface IDXGIObject { + CONST_VTBL IDXGIObjectVtbl* lpVtbl; +}; + +#ifdef COBJMACROS +#ifndef WIDL_C_INLINE_WRAPPERS +/*** IUnknown methods ***/ +#define IDXGIObject_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) +#define IDXGIObject_AddRef(This) (This)->lpVtbl->AddRef(This) +#define IDXGIObject_Release(This) (This)->lpVtbl->Release(This) +/*** IDXGIObject methods ***/ +#define IDXGIObject_SetPrivateData(This,guid,data_size,data) (This)->lpVtbl->SetPrivateData(This,guid,data_size,data) +#define IDXGIObject_SetPrivateDataInterface(This,guid,object) (This)->lpVtbl->SetPrivateDataInterface(This,guid,object) +#define IDXGIObject_GetPrivateData(This,guid,data_size,data) (This)->lpVtbl->GetPrivateData(This,guid,data_size,data) +#define IDXGIObject_GetParent(This,riid,parent) (This)->lpVtbl->GetParent(This,riid,parent) +#else +/*** IUnknown methods ***/ +static FORCEINLINE HRESULT IDXGIObject_QueryInterface(IDXGIObject* This,REFIID riid,void **ppvObject) { + return This->lpVtbl->QueryInterface(This,riid,ppvObject); +} +static FORCEINLINE ULONG IDXGIObject_AddRef(IDXGIObject* This) { + return This->lpVtbl->AddRef(This); +} +static FORCEINLINE ULONG IDXGIObject_Release(IDXGIObject* This) { + return This->lpVtbl->Release(This); +} +/*** IDXGIObject methods ***/ +static FORCEINLINE HRESULT IDXGIObject_SetPrivateData(IDXGIObject* This,REFGUID guid,UINT data_size,const void *data) { + return This->lpVtbl->SetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIObject_SetPrivateDataInterface(IDXGIObject* This,REFGUID guid,const IUnknown *object) { + return This->lpVtbl->SetPrivateDataInterface(This,guid,object); +} +static FORCEINLINE HRESULT IDXGIObject_GetPrivateData(IDXGIObject* This,REFGUID guid,UINT *data_size,void *data) { + return This->lpVtbl->GetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIObject_GetParent(IDXGIObject* This,REFIID riid,void **parent) { + return This->lpVtbl->GetParent(This,riid,parent); +} +#endif +#endif + +#endif + +HRESULT STDMETHODCALLTYPE IDXGIObject_SetPrivateData_Proxy( + IDXGIObject* This, + REFGUID guid, + UINT data_size, + const void *data); +void __RPC_STUB IDXGIObject_SetPrivateData_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIObject_SetPrivateDataInterface_Proxy( + IDXGIObject* This, + REFGUID guid, + const IUnknown *object); +void __RPC_STUB IDXGIObject_SetPrivateDataInterface_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIObject_GetPrivateData_Proxy( + IDXGIObject* This, + REFGUID guid, + UINT *data_size, + void *data); +void __RPC_STUB IDXGIObject_GetPrivateData_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIObject_GetParent_Proxy( + IDXGIObject* This, + REFIID riid, + void **parent); +void __RPC_STUB IDXGIObject_GetParent_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); + +#endif /* __IDXGIObject_INTERFACE_DEFINED__ */ + +/***************************************************************************** + * IDXGIDeviceSubObject interface + */ +#ifndef __IDXGIDeviceSubObject_INTERFACE_DEFINED__ +#define __IDXGIDeviceSubObject_INTERFACE_DEFINED__ + +DEFINE_GUID(IID_IDXGIDeviceSubObject, 0x3d3e0379, 0xf9de, 0x4d58, 0xbb,0x6c, 0x18,0xd6,0x29,0x92,0xf1,0xa6); +#if defined(__cplusplus) && !defined(CINTERFACE) +MIDL_INTERFACE("3d3e0379-f9de-4d58-bb6c-18d62992f1a6") +IDXGIDeviceSubObject : public IDXGIObject +{ + virtual HRESULT STDMETHODCALLTYPE GetDevice( + REFIID riid, + void **device) = 0; + +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IDXGIDeviceSubObject, 0x3d3e0379, 0xf9de, 0x4d58, 0xbb,0x6c, 0x18,0xd6,0x29,0x92,0xf1,0xa6) +#endif +#else +typedef struct IDXGIDeviceSubObjectVtbl { + BEGIN_INTERFACE + + /*** IUnknown methods ***/ + HRESULT (STDMETHODCALLTYPE *QueryInterface)( + IDXGIDeviceSubObject* This, + REFIID riid, + void **ppvObject); + + ULONG (STDMETHODCALLTYPE *AddRef)( + IDXGIDeviceSubObject* This); + + ULONG (STDMETHODCALLTYPE *Release)( + IDXGIDeviceSubObject* This); + + /*** IDXGIObject methods ***/ + HRESULT (STDMETHODCALLTYPE *SetPrivateData)( + IDXGIDeviceSubObject* This, + REFGUID guid, + UINT data_size, + const void *data); + + HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)( + IDXGIDeviceSubObject* This, + REFGUID guid, + const IUnknown *object); + + HRESULT (STDMETHODCALLTYPE *GetPrivateData)( + IDXGIDeviceSubObject* This, + REFGUID guid, + UINT *data_size, + void *data); + + HRESULT (STDMETHODCALLTYPE *GetParent)( + IDXGIDeviceSubObject* This, + REFIID riid, + void **parent); + + /*** IDXGIDeviceSubObject methods ***/ + HRESULT (STDMETHODCALLTYPE *GetDevice)( + IDXGIDeviceSubObject* This, + REFIID riid, + void **device); + + END_INTERFACE +} IDXGIDeviceSubObjectVtbl; +interface IDXGIDeviceSubObject { + CONST_VTBL IDXGIDeviceSubObjectVtbl* lpVtbl; +}; + +#ifdef COBJMACROS +#ifndef WIDL_C_INLINE_WRAPPERS +/*** IUnknown methods ***/ +#define IDXGIDeviceSubObject_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) +#define IDXGIDeviceSubObject_AddRef(This) (This)->lpVtbl->AddRef(This) +#define IDXGIDeviceSubObject_Release(This) (This)->lpVtbl->Release(This) +/*** IDXGIObject methods ***/ +#define IDXGIDeviceSubObject_SetPrivateData(This,guid,data_size,data) (This)->lpVtbl->SetPrivateData(This,guid,data_size,data) +#define IDXGIDeviceSubObject_SetPrivateDataInterface(This,guid,object) (This)->lpVtbl->SetPrivateDataInterface(This,guid,object) +#define IDXGIDeviceSubObject_GetPrivateData(This,guid,data_size,data) (This)->lpVtbl->GetPrivateData(This,guid,data_size,data) +#define IDXGIDeviceSubObject_GetParent(This,riid,parent) (This)->lpVtbl->GetParent(This,riid,parent) +/*** IDXGIDeviceSubObject methods ***/ +#define IDXGIDeviceSubObject_GetDevice(This,riid,device) (This)->lpVtbl->GetDevice(This,riid,device) +#else +/*** IUnknown methods ***/ +static FORCEINLINE HRESULT IDXGIDeviceSubObject_QueryInterface(IDXGIDeviceSubObject* This,REFIID riid,void **ppvObject) { + return This->lpVtbl->QueryInterface(This,riid,ppvObject); +} +static FORCEINLINE ULONG IDXGIDeviceSubObject_AddRef(IDXGIDeviceSubObject* This) { + return This->lpVtbl->AddRef(This); +} +static FORCEINLINE ULONG IDXGIDeviceSubObject_Release(IDXGIDeviceSubObject* This) { + return This->lpVtbl->Release(This); +} +/*** IDXGIObject methods ***/ +static FORCEINLINE HRESULT IDXGIDeviceSubObject_SetPrivateData(IDXGIDeviceSubObject* This,REFGUID guid,UINT data_size,const void *data) { + return This->lpVtbl->SetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIDeviceSubObject_SetPrivateDataInterface(IDXGIDeviceSubObject* This,REFGUID guid,const IUnknown *object) { + return This->lpVtbl->SetPrivateDataInterface(This,guid,object); +} +static FORCEINLINE HRESULT IDXGIDeviceSubObject_GetPrivateData(IDXGIDeviceSubObject* This,REFGUID guid,UINT *data_size,void *data) { + return This->lpVtbl->GetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIDeviceSubObject_GetParent(IDXGIDeviceSubObject* This,REFIID riid,void **parent) { + return This->lpVtbl->GetParent(This,riid,parent); +} +/*** IDXGIDeviceSubObject methods ***/ +static FORCEINLINE HRESULT IDXGIDeviceSubObject_GetDevice(IDXGIDeviceSubObject* This,REFIID riid,void **device) { + return This->lpVtbl->GetDevice(This,riid,device); +} +#endif +#endif + +#endif + +HRESULT STDMETHODCALLTYPE IDXGIDeviceSubObject_GetDevice_Proxy( + IDXGIDeviceSubObject* This, + REFIID riid, + void **device); +void __RPC_STUB IDXGIDeviceSubObject_GetDevice_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); + +#endif /* __IDXGIDeviceSubObject_INTERFACE_DEFINED__ */ + +/***************************************************************************** + * IDXGIResource interface + */ +#ifndef __IDXGIResource_INTERFACE_DEFINED__ +#define __IDXGIResource_INTERFACE_DEFINED__ + +DEFINE_GUID(IID_IDXGIResource, 0x035f3ab4, 0x482e, 0x4e50, 0xb4,0x1f, 0x8a,0x7f,0x8b,0xd8,0x96,0x0b); +#if defined(__cplusplus) && !defined(CINTERFACE) +MIDL_INTERFACE("035f3ab4-482e-4e50-b41f-8a7f8bd8960b") +IDXGIResource : public IDXGIDeviceSubObject +{ + virtual HRESULT STDMETHODCALLTYPE GetSharedHandle( + HANDLE *pSharedHandle) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetUsage( + DXGI_USAGE *pUsage) = 0; + + virtual HRESULT STDMETHODCALLTYPE SetEvictionPriority( + UINT EvictionPriority) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetEvictionPriority( + UINT *pEvictionPriority) = 0; + +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IDXGIResource, 0x035f3ab4, 0x482e, 0x4e50, 0xb4,0x1f, 0x8a,0x7f,0x8b,0xd8,0x96,0x0b) +#endif +#else +typedef struct IDXGIResourceVtbl { + BEGIN_INTERFACE + + /*** IUnknown methods ***/ + HRESULT (STDMETHODCALLTYPE *QueryInterface)( + IDXGIResource* This, + REFIID riid, + void **ppvObject); + + ULONG (STDMETHODCALLTYPE *AddRef)( + IDXGIResource* This); + + ULONG (STDMETHODCALLTYPE *Release)( + IDXGIResource* This); + + /*** IDXGIObject methods ***/ + HRESULT (STDMETHODCALLTYPE *SetPrivateData)( + IDXGIResource* This, + REFGUID guid, + UINT data_size, + const void *data); + + HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)( + IDXGIResource* This, + REFGUID guid, + const IUnknown *object); + + HRESULT (STDMETHODCALLTYPE *GetPrivateData)( + IDXGIResource* This, + REFGUID guid, + UINT *data_size, + void *data); + + HRESULT (STDMETHODCALLTYPE *GetParent)( + IDXGIResource* This, + REFIID riid, + void **parent); + + /*** IDXGIDeviceSubObject methods ***/ + HRESULT (STDMETHODCALLTYPE *GetDevice)( + IDXGIResource* This, + REFIID riid, + void **device); + + /*** IDXGIResource methods ***/ + HRESULT (STDMETHODCALLTYPE *GetSharedHandle)( + IDXGIResource* This, + HANDLE *pSharedHandle); + + HRESULT (STDMETHODCALLTYPE *GetUsage)( + IDXGIResource* This, + DXGI_USAGE *pUsage); + + HRESULT (STDMETHODCALLTYPE *SetEvictionPriority)( + IDXGIResource* This, + UINT EvictionPriority); + + HRESULT (STDMETHODCALLTYPE *GetEvictionPriority)( + IDXGIResource* This, + UINT *pEvictionPriority); + + END_INTERFACE +} IDXGIResourceVtbl; +interface IDXGIResource { + CONST_VTBL IDXGIResourceVtbl* lpVtbl; +}; + +#ifdef COBJMACROS +#ifndef WIDL_C_INLINE_WRAPPERS +/*** IUnknown methods ***/ +#define IDXGIResource_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) +#define IDXGIResource_AddRef(This) (This)->lpVtbl->AddRef(This) +#define IDXGIResource_Release(This) (This)->lpVtbl->Release(This) +/*** IDXGIObject methods ***/ +#define IDXGIResource_SetPrivateData(This,guid,data_size,data) (This)->lpVtbl->SetPrivateData(This,guid,data_size,data) +#define IDXGIResource_SetPrivateDataInterface(This,guid,object) (This)->lpVtbl->SetPrivateDataInterface(This,guid,object) +#define IDXGIResource_GetPrivateData(This,guid,data_size,data) (This)->lpVtbl->GetPrivateData(This,guid,data_size,data) +#define IDXGIResource_GetParent(This,riid,parent) (This)->lpVtbl->GetParent(This,riid,parent) +/*** IDXGIDeviceSubObject methods ***/ +#define IDXGIResource_GetDevice(This,riid,device) (This)->lpVtbl->GetDevice(This,riid,device) +/*** IDXGIResource methods ***/ +#define IDXGIResource_GetSharedHandle(This,pSharedHandle) (This)->lpVtbl->GetSharedHandle(This,pSharedHandle) +#define IDXGIResource_GetUsage(This,pUsage) (This)->lpVtbl->GetUsage(This,pUsage) +#define IDXGIResource_SetEvictionPriority(This,EvictionPriority) (This)->lpVtbl->SetEvictionPriority(This,EvictionPriority) +#define IDXGIResource_GetEvictionPriority(This,pEvictionPriority) (This)->lpVtbl->GetEvictionPriority(This,pEvictionPriority) +#else +/*** IUnknown methods ***/ +static FORCEINLINE HRESULT IDXGIResource_QueryInterface(IDXGIResource* This,REFIID riid,void **ppvObject) { + return This->lpVtbl->QueryInterface(This,riid,ppvObject); +} +static FORCEINLINE ULONG IDXGIResource_AddRef(IDXGIResource* This) { + return This->lpVtbl->AddRef(This); +} +static FORCEINLINE ULONG IDXGIResource_Release(IDXGIResource* This) { + return This->lpVtbl->Release(This); +} +/*** IDXGIObject methods ***/ +static FORCEINLINE HRESULT IDXGIResource_SetPrivateData(IDXGIResource* This,REFGUID guid,UINT data_size,const void *data) { + return This->lpVtbl->SetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIResource_SetPrivateDataInterface(IDXGIResource* This,REFGUID guid,const IUnknown *object) { + return This->lpVtbl->SetPrivateDataInterface(This,guid,object); +} +static FORCEINLINE HRESULT IDXGIResource_GetPrivateData(IDXGIResource* This,REFGUID guid,UINT *data_size,void *data) { + return This->lpVtbl->GetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIResource_GetParent(IDXGIResource* This,REFIID riid,void **parent) { + return This->lpVtbl->GetParent(This,riid,parent); +} +/*** IDXGIDeviceSubObject methods ***/ +static FORCEINLINE HRESULT IDXGIResource_GetDevice(IDXGIResource* This,REFIID riid,void **device) { + return This->lpVtbl->GetDevice(This,riid,device); +} +/*** IDXGIResource methods ***/ +static FORCEINLINE HRESULT IDXGIResource_GetSharedHandle(IDXGIResource* This,HANDLE *pSharedHandle) { + return This->lpVtbl->GetSharedHandle(This,pSharedHandle); +} +static FORCEINLINE HRESULT IDXGIResource_GetUsage(IDXGIResource* This,DXGI_USAGE *pUsage) { + return This->lpVtbl->GetUsage(This,pUsage); +} +static FORCEINLINE HRESULT IDXGIResource_SetEvictionPriority(IDXGIResource* This,UINT EvictionPriority) { + return This->lpVtbl->SetEvictionPriority(This,EvictionPriority); +} +static FORCEINLINE HRESULT IDXGIResource_GetEvictionPriority(IDXGIResource* This,UINT *pEvictionPriority) { + return This->lpVtbl->GetEvictionPriority(This,pEvictionPriority); +} +#endif +#endif + +#endif + +HRESULT STDMETHODCALLTYPE IDXGIResource_GetSharedHandle_Proxy( + IDXGIResource* This, + HANDLE *pSharedHandle); +void __RPC_STUB IDXGIResource_GetSharedHandle_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIResource_GetUsage_Proxy( + IDXGIResource* This, + DXGI_USAGE *pUsage); +void __RPC_STUB IDXGIResource_GetUsage_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIResource_SetEvictionPriority_Proxy( + IDXGIResource* This, + UINT EvictionPriority); +void __RPC_STUB IDXGIResource_SetEvictionPriority_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIResource_GetEvictionPriority_Proxy( + IDXGIResource* This, + UINT *pEvictionPriority); +void __RPC_STUB IDXGIResource_GetEvictionPriority_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); + +#endif /* __IDXGIResource_INTERFACE_DEFINED__ */ + +/***************************************************************************** + * IDXGIKeyedMutex interface + */ +#ifndef __IDXGIKeyedMutex_INTERFACE_DEFINED__ +#define __IDXGIKeyedMutex_INTERFACE_DEFINED__ + +DEFINE_GUID(IID_IDXGIKeyedMutex, 0x9d8e1289, 0xd7b3, 0x465f, 0x81,0x26, 0x25,0x0e,0x34,0x9a,0xf8,0x5d); +#if defined(__cplusplus) && !defined(CINTERFACE) +MIDL_INTERFACE("9d8e1289-d7b3-465f-8126-250e349af85d") +IDXGIKeyedMutex : public IDXGIDeviceSubObject +{ + virtual HRESULT STDMETHODCALLTYPE AcquireSync( + UINT64 Key, + DWORD dwMilliseconds) = 0; + + virtual HRESULT STDMETHODCALLTYPE ReleaseSync( + UINT64 Key) = 0; + +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IDXGIKeyedMutex, 0x9d8e1289, 0xd7b3, 0x465f, 0x81,0x26, 0x25,0x0e,0x34,0x9a,0xf8,0x5d) +#endif +#else +typedef struct IDXGIKeyedMutexVtbl { + BEGIN_INTERFACE + + /*** IUnknown methods ***/ + HRESULT (STDMETHODCALLTYPE *QueryInterface)( + IDXGIKeyedMutex* This, + REFIID riid, + void **ppvObject); + + ULONG (STDMETHODCALLTYPE *AddRef)( + IDXGIKeyedMutex* This); + + ULONG (STDMETHODCALLTYPE *Release)( + IDXGIKeyedMutex* This); + + /*** IDXGIObject methods ***/ + HRESULT (STDMETHODCALLTYPE *SetPrivateData)( + IDXGIKeyedMutex* This, + REFGUID guid, + UINT data_size, + const void *data); + + HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)( + IDXGIKeyedMutex* This, + REFGUID guid, + const IUnknown *object); + + HRESULT (STDMETHODCALLTYPE *GetPrivateData)( + IDXGIKeyedMutex* This, + REFGUID guid, + UINT *data_size, + void *data); + + HRESULT (STDMETHODCALLTYPE *GetParent)( + IDXGIKeyedMutex* This, + REFIID riid, + void **parent); + + /*** IDXGIDeviceSubObject methods ***/ + HRESULT (STDMETHODCALLTYPE *GetDevice)( + IDXGIKeyedMutex* This, + REFIID riid, + void **device); + + /*** IDXGIKeyedMutex methods ***/ + HRESULT (STDMETHODCALLTYPE *AcquireSync)( + IDXGIKeyedMutex* This, + UINT64 Key, + DWORD dwMilliseconds); + + HRESULT (STDMETHODCALLTYPE *ReleaseSync)( + IDXGIKeyedMutex* This, + UINT64 Key); + + END_INTERFACE +} IDXGIKeyedMutexVtbl; +interface IDXGIKeyedMutex { + CONST_VTBL IDXGIKeyedMutexVtbl* lpVtbl; +}; + +#ifdef COBJMACROS +#ifndef WIDL_C_INLINE_WRAPPERS +/*** IUnknown methods ***/ +#define IDXGIKeyedMutex_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) +#define IDXGIKeyedMutex_AddRef(This) (This)->lpVtbl->AddRef(This) +#define IDXGIKeyedMutex_Release(This) (This)->lpVtbl->Release(This) +/*** IDXGIObject methods ***/ +#define IDXGIKeyedMutex_SetPrivateData(This,guid,data_size,data) (This)->lpVtbl->SetPrivateData(This,guid,data_size,data) +#define IDXGIKeyedMutex_SetPrivateDataInterface(This,guid,object) (This)->lpVtbl->SetPrivateDataInterface(This,guid,object) +#define IDXGIKeyedMutex_GetPrivateData(This,guid,data_size,data) (This)->lpVtbl->GetPrivateData(This,guid,data_size,data) +#define IDXGIKeyedMutex_GetParent(This,riid,parent) (This)->lpVtbl->GetParent(This,riid,parent) +/*** IDXGIDeviceSubObject methods ***/ +#define IDXGIKeyedMutex_GetDevice(This,riid,device) (This)->lpVtbl->GetDevice(This,riid,device) +/*** IDXGIKeyedMutex methods ***/ +#define IDXGIKeyedMutex_AcquireSync(This,Key,dwMilliseconds) (This)->lpVtbl->AcquireSync(This,Key,dwMilliseconds) +#define IDXGIKeyedMutex_ReleaseSync(This,Key) (This)->lpVtbl->ReleaseSync(This,Key) +#else +/*** IUnknown methods ***/ +static FORCEINLINE HRESULT IDXGIKeyedMutex_QueryInterface(IDXGIKeyedMutex* This,REFIID riid,void **ppvObject) { + return This->lpVtbl->QueryInterface(This,riid,ppvObject); +} +static FORCEINLINE ULONG IDXGIKeyedMutex_AddRef(IDXGIKeyedMutex* This) { + return This->lpVtbl->AddRef(This); +} +static FORCEINLINE ULONG IDXGIKeyedMutex_Release(IDXGIKeyedMutex* This) { + return This->lpVtbl->Release(This); +} +/*** IDXGIObject methods ***/ +static FORCEINLINE HRESULT IDXGIKeyedMutex_SetPrivateData(IDXGIKeyedMutex* This,REFGUID guid,UINT data_size,const void *data) { + return This->lpVtbl->SetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIKeyedMutex_SetPrivateDataInterface(IDXGIKeyedMutex* This,REFGUID guid,const IUnknown *object) { + return This->lpVtbl->SetPrivateDataInterface(This,guid,object); +} +static FORCEINLINE HRESULT IDXGIKeyedMutex_GetPrivateData(IDXGIKeyedMutex* This,REFGUID guid,UINT *data_size,void *data) { + return This->lpVtbl->GetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIKeyedMutex_GetParent(IDXGIKeyedMutex* This,REFIID riid,void **parent) { + return This->lpVtbl->GetParent(This,riid,parent); +} +/*** IDXGIDeviceSubObject methods ***/ +static FORCEINLINE HRESULT IDXGIKeyedMutex_GetDevice(IDXGIKeyedMutex* This,REFIID riid,void **device) { + return This->lpVtbl->GetDevice(This,riid,device); +} +/*** IDXGIKeyedMutex methods ***/ +static FORCEINLINE HRESULT IDXGIKeyedMutex_AcquireSync(IDXGIKeyedMutex* This,UINT64 Key,DWORD dwMilliseconds) { + return This->lpVtbl->AcquireSync(This,Key,dwMilliseconds); +} +static FORCEINLINE HRESULT IDXGIKeyedMutex_ReleaseSync(IDXGIKeyedMutex* This,UINT64 Key) { + return This->lpVtbl->ReleaseSync(This,Key); +} +#endif +#endif + +#endif + +HRESULT STDMETHODCALLTYPE IDXGIKeyedMutex_AcquireSync_Proxy( + IDXGIKeyedMutex* This, + UINT64 Key, + DWORD dwMilliseconds); +void __RPC_STUB IDXGIKeyedMutex_AcquireSync_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIKeyedMutex_ReleaseSync_Proxy( + IDXGIKeyedMutex* This, + UINT64 Key); +void __RPC_STUB IDXGIKeyedMutex_ReleaseSync_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); + +#endif /* __IDXGIKeyedMutex_INTERFACE_DEFINED__ */ + +/***************************************************************************** + * IDXGISurface interface + */ +#ifndef __IDXGISurface_INTERFACE_DEFINED__ +#define __IDXGISurface_INTERFACE_DEFINED__ + +DEFINE_GUID(IID_IDXGISurface, 0xcafcb56c, 0x6ac3, 0x4889, 0xbf,0x47, 0x9e,0x23,0xbb,0xd2,0x60,0xec); +#if defined(__cplusplus) && !defined(CINTERFACE) +MIDL_INTERFACE("cafcb56c-6ac3-4889-bf47-9e23bbd260ec") +IDXGISurface : public IDXGIDeviceSubObject +{ + virtual HRESULT STDMETHODCALLTYPE GetDesc( + DXGI_SURFACE_DESC *desc) = 0; + + virtual HRESULT STDMETHODCALLTYPE Map( + DXGI_MAPPED_RECT *mapped_rect, + UINT flags) = 0; + + virtual HRESULT STDMETHODCALLTYPE Unmap( + ) = 0; + +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IDXGISurface, 0xcafcb56c, 0x6ac3, 0x4889, 0xbf,0x47, 0x9e,0x23,0xbb,0xd2,0x60,0xec) +#endif +#else +typedef struct IDXGISurfaceVtbl { + BEGIN_INTERFACE + + /*** IUnknown methods ***/ + HRESULT (STDMETHODCALLTYPE *QueryInterface)( + IDXGISurface* This, + REFIID riid, + void **ppvObject); + + ULONG (STDMETHODCALLTYPE *AddRef)( + IDXGISurface* This); + + ULONG (STDMETHODCALLTYPE *Release)( + IDXGISurface* This); + + /*** IDXGIObject methods ***/ + HRESULT (STDMETHODCALLTYPE *SetPrivateData)( + IDXGISurface* This, + REFGUID guid, + UINT data_size, + const void *data); + + HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)( + IDXGISurface* This, + REFGUID guid, + const IUnknown *object); + + HRESULT (STDMETHODCALLTYPE *GetPrivateData)( + IDXGISurface* This, + REFGUID guid, + UINT *data_size, + void *data); + + HRESULT (STDMETHODCALLTYPE *GetParent)( + IDXGISurface* This, + REFIID riid, + void **parent); + + /*** IDXGIDeviceSubObject methods ***/ + HRESULT (STDMETHODCALLTYPE *GetDevice)( + IDXGISurface* This, + REFIID riid, + void **device); + + /*** IDXGISurface methods ***/ + HRESULT (STDMETHODCALLTYPE *GetDesc)( + IDXGISurface* This, + DXGI_SURFACE_DESC *desc); + + HRESULT (STDMETHODCALLTYPE *Map)( + IDXGISurface* This, + DXGI_MAPPED_RECT *mapped_rect, + UINT flags); + + HRESULT (STDMETHODCALLTYPE *Unmap)( + IDXGISurface* This); + + END_INTERFACE +} IDXGISurfaceVtbl; +interface IDXGISurface { + CONST_VTBL IDXGISurfaceVtbl* lpVtbl; +}; + +#ifdef COBJMACROS +#ifndef WIDL_C_INLINE_WRAPPERS +/*** IUnknown methods ***/ +#define IDXGISurface_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) +#define IDXGISurface_AddRef(This) (This)->lpVtbl->AddRef(This) +#define IDXGISurface_Release(This) (This)->lpVtbl->Release(This) +/*** IDXGIObject methods ***/ +#define IDXGISurface_SetPrivateData(This,guid,data_size,data) (This)->lpVtbl->SetPrivateData(This,guid,data_size,data) +#define IDXGISurface_SetPrivateDataInterface(This,guid,object) (This)->lpVtbl->SetPrivateDataInterface(This,guid,object) +#define IDXGISurface_GetPrivateData(This,guid,data_size,data) (This)->lpVtbl->GetPrivateData(This,guid,data_size,data) +#define IDXGISurface_GetParent(This,riid,parent) (This)->lpVtbl->GetParent(This,riid,parent) +/*** IDXGIDeviceSubObject methods ***/ +#define IDXGISurface_GetDevice(This,riid,device) (This)->lpVtbl->GetDevice(This,riid,device) +/*** IDXGISurface methods ***/ +#define IDXGISurface_GetDesc(This,desc) (This)->lpVtbl->GetDesc(This,desc) +#define IDXGISurface_Map(This,mapped_rect,flags) (This)->lpVtbl->Map(This,mapped_rect,flags) +#define IDXGISurface_Unmap(This) (This)->lpVtbl->Unmap(This) +#else +/*** IUnknown methods ***/ +static FORCEINLINE HRESULT IDXGISurface_QueryInterface(IDXGISurface* This,REFIID riid,void **ppvObject) { + return This->lpVtbl->QueryInterface(This,riid,ppvObject); +} +static FORCEINLINE ULONG IDXGISurface_AddRef(IDXGISurface* This) { + return This->lpVtbl->AddRef(This); +} +static FORCEINLINE ULONG IDXGISurface_Release(IDXGISurface* This) { + return This->lpVtbl->Release(This); +} +/*** IDXGIObject methods ***/ +static FORCEINLINE HRESULT IDXGISurface_SetPrivateData(IDXGISurface* This,REFGUID guid,UINT data_size,const void *data) { + return This->lpVtbl->SetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGISurface_SetPrivateDataInterface(IDXGISurface* This,REFGUID guid,const IUnknown *object) { + return This->lpVtbl->SetPrivateDataInterface(This,guid,object); +} +static FORCEINLINE HRESULT IDXGISurface_GetPrivateData(IDXGISurface* This,REFGUID guid,UINT *data_size,void *data) { + return This->lpVtbl->GetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGISurface_GetParent(IDXGISurface* This,REFIID riid,void **parent) { + return This->lpVtbl->GetParent(This,riid,parent); +} +/*** IDXGIDeviceSubObject methods ***/ +static FORCEINLINE HRESULT IDXGISurface_GetDevice(IDXGISurface* This,REFIID riid,void **device) { + return This->lpVtbl->GetDevice(This,riid,device); +} +/*** IDXGISurface methods ***/ +static FORCEINLINE HRESULT IDXGISurface_GetDesc(IDXGISurface* This,DXGI_SURFACE_DESC *desc) { + return This->lpVtbl->GetDesc(This,desc); +} +static FORCEINLINE HRESULT IDXGISurface_Map(IDXGISurface* This,DXGI_MAPPED_RECT *mapped_rect,UINT flags) { + return This->lpVtbl->Map(This,mapped_rect,flags); +} +static FORCEINLINE HRESULT IDXGISurface_Unmap(IDXGISurface* This) { + return This->lpVtbl->Unmap(This); +} +#endif +#endif + +#endif + +HRESULT STDMETHODCALLTYPE IDXGISurface_GetDesc_Proxy( + IDXGISurface* This, + DXGI_SURFACE_DESC *desc); +void __RPC_STUB IDXGISurface_GetDesc_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGISurface_Map_Proxy( + IDXGISurface* This, + DXGI_MAPPED_RECT *mapped_rect, + UINT flags); +void __RPC_STUB IDXGISurface_Map_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGISurface_Unmap_Proxy( + IDXGISurface* This); +void __RPC_STUB IDXGISurface_Unmap_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); + +#endif /* __IDXGISurface_INTERFACE_DEFINED__ */ + +/***************************************************************************** + * IDXGISurface1 interface + */ +#ifndef __IDXGISurface_INTERFACE_DEFINED__ +#define __IDXGISurface_INTERFACE_DEFINED__ + +DEFINE_GUID(IID_IDXGISurface, 0x4AE63092, 0x6327, 0x4c1b, 0x80,0xae, 0xbf,0xe1,0x2e,0xa3,0x2b,0xa6); +#if defined(__cplusplus) && !defined(CINTERFACE) +MIDL_INTERFACE("4AE63092-6327-4c1b-80AE-BFE12EA32B86") +IDXGISurface : public IDXGISurface +{ + virtual HRESULT STDMETHODCALLTYPE GetDC( + BOOL discard, + HDC *phdc) = 0; + + virtual HRESULT STDMETHODCALLTYPE ReleaseDC( + RECT *pdirty_rect) = 0; + +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IDXGISurface1, 0x4AE63092, 0x6327, 0x4c1b, 0x80,0xae, 0xbf,0xe1,0x2e,0xa3,0x2b,0xa6) +#endif +#endif /* c++ */ + +#endif /* __IDXGISurface_INTERFACE_DEFINED__ */ + +/***************************************************************************** + * IDXGIOutput interface + */ +#ifndef __IDXGIOutput_INTERFACE_DEFINED__ +#define __IDXGIOutput_INTERFACE_DEFINED__ + +DEFINE_GUID(IID_IDXGIOutput, 0xae02eedb, 0xc735, 0x4690, 0x8d,0x52, 0x5a,0x8d,0xc2,0x02,0x13,0xaa); +#if defined(__cplusplus) && !defined(CINTERFACE) +MIDL_INTERFACE("ae02eedb-c735-4690-8d52-5a8dc20213aa") +IDXGIOutput : public IDXGIObject +{ + virtual HRESULT STDMETHODCALLTYPE GetDesc( + DXGI_OUTPUT_DESC *desc) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetDisplayModeList( + DXGI_FORMAT format, + UINT flags, + UINT *mode_count, + DXGI_MODE_DESC *desc) = 0; + + virtual HRESULT STDMETHODCALLTYPE FindClosestMatchingMode( + const DXGI_MODE_DESC *mode, + DXGI_MODE_DESC *closest_match, + IUnknown *device) = 0; + + virtual HRESULT STDMETHODCALLTYPE WaitForVBlank( + ) = 0; + + virtual HRESULT STDMETHODCALLTYPE TakeOwnership( + IUnknown *device, + WINBOOL exclusive) = 0; + + virtual void STDMETHODCALLTYPE ReleaseOwnership( + ) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetGammaControlCapabilities( + DXGI_GAMMA_CONTROL_CAPABILITIES *gamma_caps) = 0; + + virtual HRESULT STDMETHODCALLTYPE SetGammaControl( + const DXGI_GAMMA_CONTROL *gamma_control) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetGammaControl( + DXGI_GAMMA_CONTROL *gamma_control) = 0; + + virtual HRESULT STDMETHODCALLTYPE SetDisplaySurface( + IDXGISurface *surface) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetDisplaySurfaceData( + IDXGISurface *surface) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetFrameStatistics( + DXGI_FRAME_STATISTICS *stats) = 0; + +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IDXGIOutput, 0xae02eedb, 0xc735, 0x4690, 0x8d,0x52, 0x5a,0x8d,0xc2,0x02,0x13,0xaa) +#endif +#else +typedef struct IDXGIOutputVtbl { + BEGIN_INTERFACE + + /*** IUnknown methods ***/ + HRESULT (STDMETHODCALLTYPE *QueryInterface)( + IDXGIOutput* This, + REFIID riid, + void **ppvObject); + + ULONG (STDMETHODCALLTYPE *AddRef)( + IDXGIOutput* This); + + ULONG (STDMETHODCALLTYPE *Release)( + IDXGIOutput* This); + + /*** IDXGIObject methods ***/ + HRESULT (STDMETHODCALLTYPE *SetPrivateData)( + IDXGIOutput* This, + REFGUID guid, + UINT data_size, + const void *data); + + HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)( + IDXGIOutput* This, + REFGUID guid, + const IUnknown *object); + + HRESULT (STDMETHODCALLTYPE *GetPrivateData)( + IDXGIOutput* This, + REFGUID guid, + UINT *data_size, + void *data); + + HRESULT (STDMETHODCALLTYPE *GetParent)( + IDXGIOutput* This, + REFIID riid, + void **parent); + + /*** IDXGIOutput methods ***/ + HRESULT (STDMETHODCALLTYPE *GetDesc)( + IDXGIOutput* This, + DXGI_OUTPUT_DESC *desc); + + HRESULT (STDMETHODCALLTYPE *GetDisplayModeList)( + IDXGIOutput* This, + DXGI_FORMAT format, + UINT flags, + UINT *mode_count, + DXGI_MODE_DESC *desc); + + HRESULT (STDMETHODCALLTYPE *FindClosestMatchingMode)( + IDXGIOutput* This, + const DXGI_MODE_DESC *mode, + DXGI_MODE_DESC *closest_match, + IUnknown *device); + + HRESULT (STDMETHODCALLTYPE *WaitForVBlank)( + IDXGIOutput* This); + + HRESULT (STDMETHODCALLTYPE *TakeOwnership)( + IDXGIOutput* This, + IUnknown *device, + WINBOOL exclusive); + + void (STDMETHODCALLTYPE *ReleaseOwnership)( + IDXGIOutput* This); + + HRESULT (STDMETHODCALLTYPE *GetGammaControlCapabilities)( + IDXGIOutput* This, + DXGI_GAMMA_CONTROL_CAPABILITIES *gamma_caps); + + HRESULT (STDMETHODCALLTYPE *SetGammaControl)( + IDXGIOutput* This, + const DXGI_GAMMA_CONTROL *gamma_control); + + HRESULT (STDMETHODCALLTYPE *GetGammaControl)( + IDXGIOutput* This, + DXGI_GAMMA_CONTROL *gamma_control); + + HRESULT (STDMETHODCALLTYPE *SetDisplaySurface)( + IDXGIOutput* This, + IDXGISurface *surface); + + HRESULT (STDMETHODCALLTYPE *GetDisplaySurfaceData)( + IDXGIOutput* This, + IDXGISurface *surface); + + HRESULT (STDMETHODCALLTYPE *GetFrameStatistics)( + IDXGIOutput* This, + DXGI_FRAME_STATISTICS *stats); + + END_INTERFACE +} IDXGIOutputVtbl; +interface IDXGIOutput { + CONST_VTBL IDXGIOutputVtbl* lpVtbl; +}; + +#ifdef COBJMACROS +#ifndef WIDL_C_INLINE_WRAPPERS +/*** IUnknown methods ***/ +#define IDXGIOutput_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) +#define IDXGIOutput_AddRef(This) (This)->lpVtbl->AddRef(This) +#define IDXGIOutput_Release(This) (This)->lpVtbl->Release(This) +/*** IDXGIObject methods ***/ +#define IDXGIOutput_SetPrivateData(This,guid,data_size,data) (This)->lpVtbl->SetPrivateData(This,guid,data_size,data) +#define IDXGIOutput_SetPrivateDataInterface(This,guid,object) (This)->lpVtbl->SetPrivateDataInterface(This,guid,object) +#define IDXGIOutput_GetPrivateData(This,guid,data_size,data) (This)->lpVtbl->GetPrivateData(This,guid,data_size,data) +#define IDXGIOutput_GetParent(This,riid,parent) (This)->lpVtbl->GetParent(This,riid,parent) +/*** IDXGIOutput methods ***/ +#define IDXGIOutput_GetDesc(This,desc) (This)->lpVtbl->GetDesc(This,desc) +#define IDXGIOutput_GetDisplayModeList(This,format,flags,mode_count,desc) (This)->lpVtbl->GetDisplayModeList(This,format,flags,mode_count,desc) +#define IDXGIOutput_FindClosestMatchingMode(This,mode,closest_match,device) (This)->lpVtbl->FindClosestMatchingMode(This,mode,closest_match,device) +#define IDXGIOutput_WaitForVBlank(This) (This)->lpVtbl->WaitForVBlank(This) +#define IDXGIOutput_TakeOwnership(This,device,exclusive) (This)->lpVtbl->TakeOwnership(This,device,exclusive) +#define IDXGIOutput_ReleaseOwnership(This) (This)->lpVtbl->ReleaseOwnership(This) +#define IDXGIOutput_GetGammaControlCapabilities(This,gamma_caps) (This)->lpVtbl->GetGammaControlCapabilities(This,gamma_caps) +#define IDXGIOutput_SetGammaControl(This,gamma_control) (This)->lpVtbl->SetGammaControl(This,gamma_control) +#define IDXGIOutput_GetGammaControl(This,gamma_control) (This)->lpVtbl->GetGammaControl(This,gamma_control) +#define IDXGIOutput_SetDisplaySurface(This,surface) (This)->lpVtbl->SetDisplaySurface(This,surface) +#define IDXGIOutput_GetDisplaySurfaceData(This,surface) (This)->lpVtbl->GetDisplaySurfaceData(This,surface) +#define IDXGIOutput_GetFrameStatistics(This,stats) (This)->lpVtbl->GetFrameStatistics(This,stats) +#else +/*** IUnknown methods ***/ +static FORCEINLINE HRESULT IDXGIOutput_QueryInterface(IDXGIOutput* This,REFIID riid,void **ppvObject) { + return This->lpVtbl->QueryInterface(This,riid,ppvObject); +} +static FORCEINLINE ULONG IDXGIOutput_AddRef(IDXGIOutput* This) { + return This->lpVtbl->AddRef(This); +} +static FORCEINLINE ULONG IDXGIOutput_Release(IDXGIOutput* This) { + return This->lpVtbl->Release(This); +} +/*** IDXGIObject methods ***/ +static FORCEINLINE HRESULT IDXGIOutput_SetPrivateData(IDXGIOutput* This,REFGUID guid,UINT data_size,const void *data) { + return This->lpVtbl->SetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIOutput_SetPrivateDataInterface(IDXGIOutput* This,REFGUID guid,const IUnknown *object) { + return This->lpVtbl->SetPrivateDataInterface(This,guid,object); +} +static FORCEINLINE HRESULT IDXGIOutput_GetPrivateData(IDXGIOutput* This,REFGUID guid,UINT *data_size,void *data) { + return This->lpVtbl->GetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIOutput_GetParent(IDXGIOutput* This,REFIID riid,void **parent) { + return This->lpVtbl->GetParent(This,riid,parent); +} +/*** IDXGIOutput methods ***/ +static FORCEINLINE HRESULT IDXGIOutput_GetDesc(IDXGIOutput* This,DXGI_OUTPUT_DESC *desc) { + return This->lpVtbl->GetDesc(This,desc); +} +static FORCEINLINE HRESULT IDXGIOutput_GetDisplayModeList(IDXGIOutput* This,DXGI_FORMAT format,UINT flags,UINT *mode_count,DXGI_MODE_DESC *desc) { + return This->lpVtbl->GetDisplayModeList(This,format,flags,mode_count,desc); +} +static FORCEINLINE HRESULT IDXGIOutput_FindClosestMatchingMode(IDXGIOutput* This,const DXGI_MODE_DESC *mode,DXGI_MODE_DESC *closest_match,IUnknown *device) { + return This->lpVtbl->FindClosestMatchingMode(This,mode,closest_match,device); +} +static FORCEINLINE HRESULT IDXGIOutput_WaitForVBlank(IDXGIOutput* This) { + return This->lpVtbl->WaitForVBlank(This); +} +static FORCEINLINE HRESULT IDXGIOutput_TakeOwnership(IDXGIOutput* This,IUnknown *device,WINBOOL exclusive) { + return This->lpVtbl->TakeOwnership(This,device,exclusive); +} +static FORCEINLINE void IDXGIOutput_ReleaseOwnership(IDXGIOutput* This) { + This->lpVtbl->ReleaseOwnership(This); +} +static FORCEINLINE HRESULT IDXGIOutput_GetGammaControlCapabilities(IDXGIOutput* This,DXGI_GAMMA_CONTROL_CAPABILITIES *gamma_caps) { + return This->lpVtbl->GetGammaControlCapabilities(This,gamma_caps); +} +static FORCEINLINE HRESULT IDXGIOutput_SetGammaControl(IDXGIOutput* This,const DXGI_GAMMA_CONTROL *gamma_control) { + return This->lpVtbl->SetGammaControl(This,gamma_control); +} +static FORCEINLINE HRESULT IDXGIOutput_GetGammaControl(IDXGIOutput* This,DXGI_GAMMA_CONTROL *gamma_control) { + return This->lpVtbl->GetGammaControl(This,gamma_control); +} +static FORCEINLINE HRESULT IDXGIOutput_SetDisplaySurface(IDXGIOutput* This,IDXGISurface *surface) { + return This->lpVtbl->SetDisplaySurface(This,surface); +} +static FORCEINLINE HRESULT IDXGIOutput_GetDisplaySurfaceData(IDXGIOutput* This,IDXGISurface *surface) { + return This->lpVtbl->GetDisplaySurfaceData(This,surface); +} +static FORCEINLINE HRESULT IDXGIOutput_GetFrameStatistics(IDXGIOutput* This,DXGI_FRAME_STATISTICS *stats) { + return This->lpVtbl->GetFrameStatistics(This,stats); +} +#endif +#endif + +#endif + +HRESULT STDMETHODCALLTYPE IDXGIOutput_GetDesc_Proxy( + IDXGIOutput* This, + DXGI_OUTPUT_DESC *desc); +void __RPC_STUB IDXGIOutput_GetDesc_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIOutput_GetDisplayModeList_Proxy( + IDXGIOutput* This, + DXGI_FORMAT format, + UINT flags, + UINT *mode_count, + DXGI_MODE_DESC *desc); +void __RPC_STUB IDXGIOutput_GetDisplayModeList_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIOutput_FindClosestMatchingMode_Proxy( + IDXGIOutput* This, + const DXGI_MODE_DESC *mode, + DXGI_MODE_DESC *closest_match, + IUnknown *device); +void __RPC_STUB IDXGIOutput_FindClosestMatchingMode_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIOutput_WaitForVBlank_Proxy( + IDXGIOutput* This); +void __RPC_STUB IDXGIOutput_WaitForVBlank_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIOutput_TakeOwnership_Proxy( + IDXGIOutput* This, + IUnknown *device, + WINBOOL exclusive); +void __RPC_STUB IDXGIOutput_TakeOwnership_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +void STDMETHODCALLTYPE IDXGIOutput_ReleaseOwnership_Proxy( + IDXGIOutput* This); +void __RPC_STUB IDXGIOutput_ReleaseOwnership_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIOutput_GetGammaControlCapabilities_Proxy( + IDXGIOutput* This, + DXGI_GAMMA_CONTROL_CAPABILITIES *gamma_caps); +void __RPC_STUB IDXGIOutput_GetGammaControlCapabilities_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIOutput_SetGammaControl_Proxy( + IDXGIOutput* This, + const DXGI_GAMMA_CONTROL *gamma_control); +void __RPC_STUB IDXGIOutput_SetGammaControl_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIOutput_GetGammaControl_Proxy( + IDXGIOutput* This, + DXGI_GAMMA_CONTROL *gamma_control); +void __RPC_STUB IDXGIOutput_GetGammaControl_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIOutput_SetDisplaySurface_Proxy( + IDXGIOutput* This, + IDXGISurface *surface); +void __RPC_STUB IDXGIOutput_SetDisplaySurface_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIOutput_GetDisplaySurfaceData_Proxy( + IDXGIOutput* This, + IDXGISurface *surface); +void __RPC_STUB IDXGIOutput_GetDisplaySurfaceData_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIOutput_GetFrameStatistics_Proxy( + IDXGIOutput* This, + DXGI_FRAME_STATISTICS *stats); +void __RPC_STUB IDXGIOutput_GetFrameStatistics_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); + +#endif /* __IDXGIOutput_INTERFACE_DEFINED__ */ + +/***************************************************************************** + * IDXGIAdapter interface + */ +#ifndef __IDXGIAdapter_INTERFACE_DEFINED__ +#define __IDXGIAdapter_INTERFACE_DEFINED__ + +DEFINE_GUID(IID_IDXGIAdapter, 0x2411e7e1, 0x12ac, 0x4ccf, 0xbd,0x14, 0x97,0x98,0xe8,0x53,0x4d,0xc0); +#if defined(__cplusplus) && !defined(CINTERFACE) +MIDL_INTERFACE("2411e7e1-12ac-4ccf-bd14-9798e8534dc0") +IDXGIAdapter : public IDXGIObject +{ + virtual HRESULT STDMETHODCALLTYPE EnumOutputs( + UINT output_idx, + IDXGIOutput **output) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetDesc( + DXGI_ADAPTER_DESC *desc) = 0; + + virtual HRESULT STDMETHODCALLTYPE CheckInterfaceSupport( + REFGUID guid, + LARGE_INTEGER *umd_version) = 0; + +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IDXGIAdapter, 0x2411e7e1, 0x12ac, 0x4ccf, 0xbd,0x14, 0x97,0x98,0xe8,0x53,0x4d,0xc0) +#endif +#else +typedef struct IDXGIAdapterVtbl { + BEGIN_INTERFACE + + /*** IUnknown methods ***/ + HRESULT (STDMETHODCALLTYPE *QueryInterface)( + IDXGIAdapter* This, + REFIID riid, + void **ppvObject); + + ULONG (STDMETHODCALLTYPE *AddRef)( + IDXGIAdapter* This); + + ULONG (STDMETHODCALLTYPE *Release)( + IDXGIAdapter* This); + + /*** IDXGIObject methods ***/ + HRESULT (STDMETHODCALLTYPE *SetPrivateData)( + IDXGIAdapter* This, + REFGUID guid, + UINT data_size, + const void *data); + + HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)( + IDXGIAdapter* This, + REFGUID guid, + const IUnknown *object); + + HRESULT (STDMETHODCALLTYPE *GetPrivateData)( + IDXGIAdapter* This, + REFGUID guid, + UINT *data_size, + void *data); + + HRESULT (STDMETHODCALLTYPE *GetParent)( + IDXGIAdapter* This, + REFIID riid, + void **parent); + + /*** IDXGIAdapter methods ***/ + HRESULT (STDMETHODCALLTYPE *EnumOutputs)( + IDXGIAdapter* This, + UINT output_idx, + IDXGIOutput **output); + + HRESULT (STDMETHODCALLTYPE *GetDesc)( + IDXGIAdapter* This, + DXGI_ADAPTER_DESC *desc); + + HRESULT (STDMETHODCALLTYPE *CheckInterfaceSupport)( + IDXGIAdapter* This, + REFGUID guid, + LARGE_INTEGER *umd_version); + + END_INTERFACE +} IDXGIAdapterVtbl; +interface IDXGIAdapter { + CONST_VTBL IDXGIAdapterVtbl* lpVtbl; +}; + +#ifdef COBJMACROS +#ifndef WIDL_C_INLINE_WRAPPERS +/*** IUnknown methods ***/ +#define IDXGIAdapter_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) +#define IDXGIAdapter_AddRef(This) (This)->lpVtbl->AddRef(This) +#define IDXGIAdapter_Release(This) (This)->lpVtbl->Release(This) +/*** IDXGIObject methods ***/ +#define IDXGIAdapter_SetPrivateData(This,guid,data_size,data) (This)->lpVtbl->SetPrivateData(This,guid,data_size,data) +#define IDXGIAdapter_SetPrivateDataInterface(This,guid,object) (This)->lpVtbl->SetPrivateDataInterface(This,guid,object) +#define IDXGIAdapter_GetPrivateData(This,guid,data_size,data) (This)->lpVtbl->GetPrivateData(This,guid,data_size,data) +#define IDXGIAdapter_GetParent(This,riid,parent) (This)->lpVtbl->GetParent(This,riid,parent) +/*** IDXGIAdapter methods ***/ +#define IDXGIAdapter_EnumOutputs(This,output_idx,output) (This)->lpVtbl->EnumOutputs(This,output_idx,output) +#define IDXGIAdapter_GetDesc(This,desc) (This)->lpVtbl->GetDesc(This,desc) +#define IDXGIAdapter_CheckInterfaceSupport(This,guid,umd_version) (This)->lpVtbl->CheckInterfaceSupport(This,guid,umd_version) +#else +/*** IUnknown methods ***/ +static FORCEINLINE HRESULT IDXGIAdapter_QueryInterface(IDXGIAdapter* This,REFIID riid,void **ppvObject) { + return This->lpVtbl->QueryInterface(This,riid,ppvObject); +} +static FORCEINLINE ULONG IDXGIAdapter_AddRef(IDXGIAdapter* This) { + return This->lpVtbl->AddRef(This); +} +static FORCEINLINE ULONG IDXGIAdapter_Release(IDXGIAdapter* This) { + return This->lpVtbl->Release(This); +} +/*** IDXGIObject methods ***/ +static FORCEINLINE HRESULT IDXGIAdapter_SetPrivateData(IDXGIAdapter* This,REFGUID guid,UINT data_size,const void *data) { + return This->lpVtbl->SetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIAdapter_SetPrivateDataInterface(IDXGIAdapter* This,REFGUID guid,const IUnknown *object) { + return This->lpVtbl->SetPrivateDataInterface(This,guid,object); +} +static FORCEINLINE HRESULT IDXGIAdapter_GetPrivateData(IDXGIAdapter* This,REFGUID guid,UINT *data_size,void *data) { + return This->lpVtbl->GetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIAdapter_GetParent(IDXGIAdapter* This,REFIID riid,void **parent) { + return This->lpVtbl->GetParent(This,riid,parent); +} +/*** IDXGIAdapter methods ***/ +static FORCEINLINE HRESULT IDXGIAdapter_EnumOutputs(IDXGIAdapter* This,UINT output_idx,IDXGIOutput **output) { + return This->lpVtbl->EnumOutputs(This,output_idx,output); +} +static FORCEINLINE HRESULT IDXGIAdapter_GetDesc(IDXGIAdapter* This,DXGI_ADAPTER_DESC *desc) { + return This->lpVtbl->GetDesc(This,desc); +} +static FORCEINLINE HRESULT IDXGIAdapter_CheckInterfaceSupport(IDXGIAdapter* This,REFGUID guid,LARGE_INTEGER *umd_version) { + return This->lpVtbl->CheckInterfaceSupport(This,guid,umd_version); +} +#endif +#endif + +#endif + +HRESULT STDMETHODCALLTYPE IDXGIAdapter_EnumOutputs_Proxy( + IDXGIAdapter* This, + UINT output_idx, + IDXGIOutput **output); +void __RPC_STUB IDXGIAdapter_EnumOutputs_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIAdapter_GetDesc_Proxy( + IDXGIAdapter* This, + DXGI_ADAPTER_DESC *desc); +void __RPC_STUB IDXGIAdapter_GetDesc_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIAdapter_CheckInterfaceSupport_Proxy( + IDXGIAdapter* This, + REFGUID guid, + LARGE_INTEGER *umd_version); +void __RPC_STUB IDXGIAdapter_CheckInterfaceSupport_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); + +#endif /* __IDXGIAdapter_INTERFACE_DEFINED__ */ + +/***************************************************************************** + * IDXGISwapChain interface + */ +#ifndef __IDXGISwapChain_INTERFACE_DEFINED__ +#define __IDXGISwapChain_INTERFACE_DEFINED__ + +DEFINE_GUID(IID_IDXGISwapChain, 0x310d36a0, 0xd2e7, 0x4c0a, 0xaa,0x04, 0x6a,0x9d,0x23,0xb8,0x88,0x6a); +#if defined(__cplusplus) && !defined(CINTERFACE) +MIDL_INTERFACE("310d36a0-d2e7-4c0a-aa04-6a9d23b8886a") +IDXGISwapChain : public IDXGIDeviceSubObject +{ + virtual HRESULT STDMETHODCALLTYPE Present( + UINT sync_interval, + UINT flags) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetBuffer( + UINT buffer_idx, + REFIID riid, + void **surface) = 0; + + virtual HRESULT STDMETHODCALLTYPE SetFullscreenState( + WINBOOL fullscreen, + IDXGIOutput *target) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetFullscreenState( + WINBOOL *fullscreen, + IDXGIOutput **target) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetDesc( + DXGI_SWAP_CHAIN_DESC *desc) = 0; + + virtual HRESULT STDMETHODCALLTYPE ResizeBuffers( + UINT buffer_count, + UINT width, + UINT height, + DXGI_FORMAT format, + UINT flags) = 0; + + virtual HRESULT STDMETHODCALLTYPE ResizeTarget( + const DXGI_MODE_DESC *target_mode_desc) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetContainingOutput( + IDXGIOutput **output) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetFrameStatistics( + DXGI_FRAME_STATISTICS *stats) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetLastPresentCount( + UINT *last_present_count) = 0; + +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IDXGISwapChain, 0x310d36a0, 0xd2e7, 0x4c0a, 0xaa,0x04, 0x6a,0x9d,0x23,0xb8,0x88,0x6a) +#endif +#else +typedef struct IDXGISwapChainVtbl { + BEGIN_INTERFACE + + /*** IUnknown methods ***/ + HRESULT (STDMETHODCALLTYPE *QueryInterface)( + IDXGISwapChain* This, + REFIID riid, + void **ppvObject); + + ULONG (STDMETHODCALLTYPE *AddRef)( + IDXGISwapChain* This); + + ULONG (STDMETHODCALLTYPE *Release)( + IDXGISwapChain* This); + + /*** IDXGIObject methods ***/ + HRESULT (STDMETHODCALLTYPE *SetPrivateData)( + IDXGISwapChain* This, + REFGUID guid, + UINT data_size, + const void *data); + + HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)( + IDXGISwapChain* This, + REFGUID guid, + const IUnknown *object); + + HRESULT (STDMETHODCALLTYPE *GetPrivateData)( + IDXGISwapChain* This, + REFGUID guid, + UINT *data_size, + void *data); + + HRESULT (STDMETHODCALLTYPE *GetParent)( + IDXGISwapChain* This, + REFIID riid, + void **parent); + + /*** IDXGIDeviceSubObject methods ***/ + HRESULT (STDMETHODCALLTYPE *GetDevice)( + IDXGISwapChain* This, + REFIID riid, + void **device); + + /*** IDXGISwapChain methods ***/ + HRESULT (STDMETHODCALLTYPE *Present)( + IDXGISwapChain* This, + UINT sync_interval, + UINT flags); + + HRESULT (STDMETHODCALLTYPE *GetBuffer)( + IDXGISwapChain* This, + UINT buffer_idx, + REFIID riid, + void **surface); + + HRESULT (STDMETHODCALLTYPE *SetFullscreenState)( + IDXGISwapChain* This, + WINBOOL fullscreen, + IDXGIOutput *target); + + HRESULT (STDMETHODCALLTYPE *GetFullscreenState)( + IDXGISwapChain* This, + WINBOOL *fullscreen, + IDXGIOutput **target); + + HRESULT (STDMETHODCALLTYPE *GetDesc)( + IDXGISwapChain* This, + DXGI_SWAP_CHAIN_DESC *desc); + + HRESULT (STDMETHODCALLTYPE *ResizeBuffers)( + IDXGISwapChain* This, + UINT buffer_count, + UINT width, + UINT height, + DXGI_FORMAT format, + UINT flags); + + HRESULT (STDMETHODCALLTYPE *ResizeTarget)( + IDXGISwapChain* This, + const DXGI_MODE_DESC *target_mode_desc); + + HRESULT (STDMETHODCALLTYPE *GetContainingOutput)( + IDXGISwapChain* This, + IDXGIOutput **output); + + HRESULT (STDMETHODCALLTYPE *GetFrameStatistics)( + IDXGISwapChain* This, + DXGI_FRAME_STATISTICS *stats); + + HRESULT (STDMETHODCALLTYPE *GetLastPresentCount)( + IDXGISwapChain* This, + UINT *last_present_count); + + END_INTERFACE +} IDXGISwapChainVtbl; +interface IDXGISwapChain { + CONST_VTBL IDXGISwapChainVtbl* lpVtbl; +}; + +#ifdef COBJMACROS +#ifndef WIDL_C_INLINE_WRAPPERS +/*** IUnknown methods ***/ +#define IDXGISwapChain_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) +#define IDXGISwapChain_AddRef(This) (This)->lpVtbl->AddRef(This) +#define IDXGISwapChain_Release(This) (This)->lpVtbl->Release(This) +/*** IDXGIObject methods ***/ +#define IDXGISwapChain_SetPrivateData(This,guid,data_size,data) (This)->lpVtbl->SetPrivateData(This,guid,data_size,data) +#define IDXGISwapChain_SetPrivateDataInterface(This,guid,object) (This)->lpVtbl->SetPrivateDataInterface(This,guid,object) +#define IDXGISwapChain_GetPrivateData(This,guid,data_size,data) (This)->lpVtbl->GetPrivateData(This,guid,data_size,data) +#define IDXGISwapChain_GetParent(This,riid,parent) (This)->lpVtbl->GetParent(This,riid,parent) +/*** IDXGIDeviceSubObject methods ***/ +#define IDXGISwapChain_GetDevice(This,riid,device) (This)->lpVtbl->GetDevice(This,riid,device) +/*** IDXGISwapChain methods ***/ +#define IDXGISwapChain_Present(This,sync_interval,flags) (This)->lpVtbl->Present(This,sync_interval,flags) +#define IDXGISwapChain_GetBuffer(This,buffer_idx,riid,surface) (This)->lpVtbl->GetBuffer(This,buffer_idx,riid,surface) +#define IDXGISwapChain_SetFullscreenState(This,fullscreen,target) (This)->lpVtbl->SetFullscreenState(This,fullscreen,target) +#define IDXGISwapChain_GetFullscreenState(This,fullscreen,target) (This)->lpVtbl->GetFullscreenState(This,fullscreen,target) +#define IDXGISwapChain_GetDesc(This,desc) (This)->lpVtbl->GetDesc(This,desc) +#define IDXGISwapChain_ResizeBuffers(This,buffer_count,width,height,format,flags) (This)->lpVtbl->ResizeBuffers(This,buffer_count,width,height,format,flags) +#define IDXGISwapChain_ResizeTarget(This,target_mode_desc) (This)->lpVtbl->ResizeTarget(This,target_mode_desc) +#define IDXGISwapChain_GetContainingOutput(This,output) (This)->lpVtbl->GetContainingOutput(This,output) +#define IDXGISwapChain_GetFrameStatistics(This,stats) (This)->lpVtbl->GetFrameStatistics(This,stats) +#define IDXGISwapChain_GetLastPresentCount(This,last_present_count) (This)->lpVtbl->GetLastPresentCount(This,last_present_count) +#else +/*** IUnknown methods ***/ +static FORCEINLINE HRESULT IDXGISwapChain_QueryInterface(IDXGISwapChain* This,REFIID riid,void **ppvObject) { + return This->lpVtbl->QueryInterface(This,riid,ppvObject); +} +static FORCEINLINE ULONG IDXGISwapChain_AddRef(IDXGISwapChain* This) { + return This->lpVtbl->AddRef(This); +} +static FORCEINLINE ULONG IDXGISwapChain_Release(IDXGISwapChain* This) { + return This->lpVtbl->Release(This); +} +/*** IDXGIObject methods ***/ +static FORCEINLINE HRESULT IDXGISwapChain_SetPrivateData(IDXGISwapChain* This,REFGUID guid,UINT data_size,const void *data) { + return This->lpVtbl->SetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGISwapChain_SetPrivateDataInterface(IDXGISwapChain* This,REFGUID guid,const IUnknown *object) { + return This->lpVtbl->SetPrivateDataInterface(This,guid,object); +} +static FORCEINLINE HRESULT IDXGISwapChain_GetPrivateData(IDXGISwapChain* This,REFGUID guid,UINT *data_size,void *data) { + return This->lpVtbl->GetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGISwapChain_GetParent(IDXGISwapChain* This,REFIID riid,void **parent) { + return This->lpVtbl->GetParent(This,riid,parent); +} +/*** IDXGIDeviceSubObject methods ***/ +static FORCEINLINE HRESULT IDXGISwapChain_GetDevice(IDXGISwapChain* This,REFIID riid,void **device) { + return This->lpVtbl->GetDevice(This,riid,device); +} +/*** IDXGISwapChain methods ***/ +static FORCEINLINE HRESULT IDXGISwapChain_Present(IDXGISwapChain* This,UINT sync_interval,UINT flags) { + return This->lpVtbl->Present(This,sync_interval,flags); +} +static FORCEINLINE HRESULT IDXGISwapChain_GetBuffer(IDXGISwapChain* This,UINT buffer_idx,REFIID riid,void **surface) { + return This->lpVtbl->GetBuffer(This,buffer_idx,riid,surface); +} +static FORCEINLINE HRESULT IDXGISwapChain_SetFullscreenState(IDXGISwapChain* This,WINBOOL fullscreen,IDXGIOutput *target) { + return This->lpVtbl->SetFullscreenState(This,fullscreen,target); +} +static FORCEINLINE HRESULT IDXGISwapChain_GetFullscreenState(IDXGISwapChain* This,WINBOOL *fullscreen,IDXGIOutput **target) { + return This->lpVtbl->GetFullscreenState(This,fullscreen,target); +} +static FORCEINLINE HRESULT IDXGISwapChain_GetDesc(IDXGISwapChain* This,DXGI_SWAP_CHAIN_DESC *desc) { + return This->lpVtbl->GetDesc(This,desc); +} +static FORCEINLINE HRESULT IDXGISwapChain_ResizeBuffers(IDXGISwapChain* This,UINT buffer_count,UINT width,UINT height,DXGI_FORMAT format,UINT flags) { + return This->lpVtbl->ResizeBuffers(This,buffer_count,width,height,format,flags); +} +static FORCEINLINE HRESULT IDXGISwapChain_ResizeTarget(IDXGISwapChain* This,const DXGI_MODE_DESC *target_mode_desc) { + return This->lpVtbl->ResizeTarget(This,target_mode_desc); +} +static FORCEINLINE HRESULT IDXGISwapChain_GetContainingOutput(IDXGISwapChain* This,IDXGIOutput **output) { + return This->lpVtbl->GetContainingOutput(This,output); +} +static FORCEINLINE HRESULT IDXGISwapChain_GetFrameStatistics(IDXGISwapChain* This,DXGI_FRAME_STATISTICS *stats) { + return This->lpVtbl->GetFrameStatistics(This,stats); +} +static FORCEINLINE HRESULT IDXGISwapChain_GetLastPresentCount(IDXGISwapChain* This,UINT *last_present_count) { + return This->lpVtbl->GetLastPresentCount(This,last_present_count); +} +#endif +#endif + +#endif + +HRESULT STDMETHODCALLTYPE IDXGISwapChain_Present_Proxy( + IDXGISwapChain* This, + UINT sync_interval, + UINT flags); +void __RPC_STUB IDXGISwapChain_Present_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGISwapChain_GetBuffer_Proxy( + IDXGISwapChain* This, + UINT buffer_idx, + REFIID riid, + void **surface); +void __RPC_STUB IDXGISwapChain_GetBuffer_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGISwapChain_SetFullscreenState_Proxy( + IDXGISwapChain* This, + WINBOOL fullscreen, + IDXGIOutput *target); +void __RPC_STUB IDXGISwapChain_SetFullscreenState_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGISwapChain_GetFullscreenState_Proxy( + IDXGISwapChain* This, + WINBOOL *fullscreen, + IDXGIOutput **target); +void __RPC_STUB IDXGISwapChain_GetFullscreenState_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGISwapChain_GetDesc_Proxy( + IDXGISwapChain* This, + DXGI_SWAP_CHAIN_DESC *desc); +void __RPC_STUB IDXGISwapChain_GetDesc_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGISwapChain_ResizeBuffers_Proxy( + IDXGISwapChain* This, + UINT buffer_count, + UINT width, + UINT height, + DXGI_FORMAT format, + UINT flags); +void __RPC_STUB IDXGISwapChain_ResizeBuffers_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGISwapChain_ResizeTarget_Proxy( + IDXGISwapChain* This, + const DXGI_MODE_DESC *target_mode_desc); +void __RPC_STUB IDXGISwapChain_ResizeTarget_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGISwapChain_GetContainingOutput_Proxy( + IDXGISwapChain* This, + IDXGIOutput **output); +void __RPC_STUB IDXGISwapChain_GetContainingOutput_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGISwapChain_GetFrameStatistics_Proxy( + IDXGISwapChain* This, + DXGI_FRAME_STATISTICS *stats); +void __RPC_STUB IDXGISwapChain_GetFrameStatistics_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGISwapChain_GetLastPresentCount_Proxy( + IDXGISwapChain* This, + UINT *last_present_count); +void __RPC_STUB IDXGISwapChain_GetLastPresentCount_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); + +#endif /* __IDXGISwapChain_INTERFACE_DEFINED__ */ + +#define DXGI_MWA_NO_WINDOW_CHANGES 0x1 +#define DXGI_MWA_NO_ALT_ENTER 0x2 +#define DXGI_MWA_NO_PRINT_SCREEN 0x4 +#define DXGI_MWA_VALID 0x7 +/***************************************************************************** + * IDXGIFactory interface + */ +#ifndef __IDXGIFactory_INTERFACE_DEFINED__ +#define __IDXGIFactory_INTERFACE_DEFINED__ + +DEFINE_GUID(IID_IDXGIFactory, 0x7b7166ec, 0x21c7, 0x44ae, 0xb2,0x1a, 0xc9,0xae,0x32,0x1a,0xe3,0x69); +#if defined(__cplusplus) && !defined(CINTERFACE) +MIDL_INTERFACE("7b7166ec-21c7-44ae-b21a-c9ae321ae369") +IDXGIFactory : public IDXGIObject +{ + virtual HRESULT STDMETHODCALLTYPE EnumAdapters( + UINT adapter_idx, + IDXGIAdapter **adapter) = 0; + + virtual HRESULT STDMETHODCALLTYPE MakeWindowAssociation( + HWND window, + UINT flags) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetWindowAssociation( + HWND *window) = 0; + + virtual HRESULT STDMETHODCALLTYPE CreateSwapChain( + IUnknown *device, + DXGI_SWAP_CHAIN_DESC *desc, + IDXGISwapChain **swapchain) = 0; + + virtual HRESULT STDMETHODCALLTYPE CreateSoftwareAdapter( + HMODULE swrast, + IDXGIAdapter **adapter) = 0; + +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IDXGIFactory, 0x7b7166ec, 0x21c7, 0x44ae, 0xb2,0x1a, 0xc9,0xae,0x32,0x1a,0xe3,0x69) +#endif +#else +typedef struct IDXGIFactoryVtbl { + BEGIN_INTERFACE + + /*** IUnknown methods ***/ + HRESULT (STDMETHODCALLTYPE *QueryInterface)( + IDXGIFactory* This, + REFIID riid, + void **ppvObject); + + ULONG (STDMETHODCALLTYPE *AddRef)( + IDXGIFactory* This); + + ULONG (STDMETHODCALLTYPE *Release)( + IDXGIFactory* This); + + /*** IDXGIObject methods ***/ + HRESULT (STDMETHODCALLTYPE *SetPrivateData)( + IDXGIFactory* This, + REFGUID guid, + UINT data_size, + const void *data); + + HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)( + IDXGIFactory* This, + REFGUID guid, + const IUnknown *object); + + HRESULT (STDMETHODCALLTYPE *GetPrivateData)( + IDXGIFactory* This, + REFGUID guid, + UINT *data_size, + void *data); + + HRESULT (STDMETHODCALLTYPE *GetParent)( + IDXGIFactory* This, + REFIID riid, + void **parent); + + /*** IDXGIFactory methods ***/ + HRESULT (STDMETHODCALLTYPE *EnumAdapters)( + IDXGIFactory* This, + UINT adapter_idx, + IDXGIAdapter **adapter); + + HRESULT (STDMETHODCALLTYPE *MakeWindowAssociation)( + IDXGIFactory* This, + HWND window, + UINT flags); + + HRESULT (STDMETHODCALLTYPE *GetWindowAssociation)( + IDXGIFactory* This, + HWND *window); + + HRESULT (STDMETHODCALLTYPE *CreateSwapChain)( + IDXGIFactory* This, + IUnknown *device, + DXGI_SWAP_CHAIN_DESC *desc, + IDXGISwapChain **swapchain); + + HRESULT (STDMETHODCALLTYPE *CreateSoftwareAdapter)( + IDXGIFactory* This, + HMODULE swrast, + IDXGIAdapter **adapter); + + END_INTERFACE +} IDXGIFactoryVtbl; +interface IDXGIFactory { + CONST_VTBL IDXGIFactoryVtbl* lpVtbl; +}; + +#ifdef COBJMACROS +#ifndef WIDL_C_INLINE_WRAPPERS +/*** IUnknown methods ***/ +#define IDXGIFactory_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) +#define IDXGIFactory_AddRef(This) (This)->lpVtbl->AddRef(This) +#define IDXGIFactory_Release(This) (This)->lpVtbl->Release(This) +/*** IDXGIObject methods ***/ +#define IDXGIFactory_SetPrivateData(This,guid,data_size,data) (This)->lpVtbl->SetPrivateData(This,guid,data_size,data) +#define IDXGIFactory_SetPrivateDataInterface(This,guid,object) (This)->lpVtbl->SetPrivateDataInterface(This,guid,object) +#define IDXGIFactory_GetPrivateData(This,guid,data_size,data) (This)->lpVtbl->GetPrivateData(This,guid,data_size,data) +#define IDXGIFactory_GetParent(This,riid,parent) (This)->lpVtbl->GetParent(This,riid,parent) +/*** IDXGIFactory methods ***/ +#define IDXGIFactory_EnumAdapters(This,adapter_idx,adapter) (This)->lpVtbl->EnumAdapters(This,adapter_idx,adapter) +#define IDXGIFactory_MakeWindowAssociation(This,window,flags) (This)->lpVtbl->MakeWindowAssociation(This,window,flags) +#define IDXGIFactory_GetWindowAssociation(This,window) (This)->lpVtbl->GetWindowAssociation(This,window) +#define IDXGIFactory_CreateSwapChain(This,device,desc,swapchain) (This)->lpVtbl->CreateSwapChain(This,device,desc,swapchain) +#define IDXGIFactory_CreateSoftwareAdapter(This,swrast,adapter) (This)->lpVtbl->CreateSoftwareAdapter(This,swrast,adapter) +#else +/*** IUnknown methods ***/ +static FORCEINLINE HRESULT IDXGIFactory_QueryInterface(IDXGIFactory* This,REFIID riid,void **ppvObject) { + return This->lpVtbl->QueryInterface(This,riid,ppvObject); +} +static FORCEINLINE ULONG IDXGIFactory_AddRef(IDXGIFactory* This) { + return This->lpVtbl->AddRef(This); +} +static FORCEINLINE ULONG IDXGIFactory_Release(IDXGIFactory* This) { + return This->lpVtbl->Release(This); +} +/*** IDXGIObject methods ***/ +static FORCEINLINE HRESULT IDXGIFactory_SetPrivateData(IDXGIFactory* This,REFGUID guid,UINT data_size,const void *data) { + return This->lpVtbl->SetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIFactory_SetPrivateDataInterface(IDXGIFactory* This,REFGUID guid,const IUnknown *object) { + return This->lpVtbl->SetPrivateDataInterface(This,guid,object); +} +static FORCEINLINE HRESULT IDXGIFactory_GetPrivateData(IDXGIFactory* This,REFGUID guid,UINT *data_size,void *data) { + return This->lpVtbl->GetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIFactory_GetParent(IDXGIFactory* This,REFIID riid,void **parent) { + return This->lpVtbl->GetParent(This,riid,parent); +} +/*** IDXGIFactory methods ***/ +static FORCEINLINE HRESULT IDXGIFactory_EnumAdapters(IDXGIFactory* This,UINT adapter_idx,IDXGIAdapter **adapter) { + return This->lpVtbl->EnumAdapters(This,adapter_idx,adapter); +} +static FORCEINLINE HRESULT IDXGIFactory_MakeWindowAssociation(IDXGIFactory* This,HWND window,UINT flags) { + return This->lpVtbl->MakeWindowAssociation(This,window,flags); +} +static FORCEINLINE HRESULT IDXGIFactory_GetWindowAssociation(IDXGIFactory* This,HWND *window) { + return This->lpVtbl->GetWindowAssociation(This,window); +} +static FORCEINLINE HRESULT IDXGIFactory_CreateSwapChain(IDXGIFactory* This,IUnknown *device,DXGI_SWAP_CHAIN_DESC *desc,IDXGISwapChain **swapchain) { + return This->lpVtbl->CreateSwapChain(This,device,desc,swapchain); +} +static FORCEINLINE HRESULT IDXGIFactory_CreateSoftwareAdapter(IDXGIFactory* This,HMODULE swrast,IDXGIAdapter **adapter) { + return This->lpVtbl->CreateSoftwareAdapter(This,swrast,adapter); +} +#endif +#endif + +#endif + +HRESULT STDMETHODCALLTYPE IDXGIFactory_EnumAdapters_Proxy( + IDXGIFactory* This, + UINT adapter_idx, + IDXGIAdapter **adapter); +void __RPC_STUB IDXGIFactory_EnumAdapters_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIFactory_MakeWindowAssociation_Proxy( + IDXGIFactory* This, + HWND window, + UINT flags); +void __RPC_STUB IDXGIFactory_MakeWindowAssociation_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIFactory_GetWindowAssociation_Proxy( + IDXGIFactory* This, + HWND *window); +void __RPC_STUB IDXGIFactory_GetWindowAssociation_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIFactory_CreateSwapChain_Proxy( + IDXGIFactory* This, + IUnknown *device, + DXGI_SWAP_CHAIN_DESC *desc, + IDXGISwapChain **swapchain); +void __RPC_STUB IDXGIFactory_CreateSwapChain_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIFactory_CreateSoftwareAdapter_Proxy( + IDXGIFactory* This, + HMODULE swrast, + IDXGIAdapter **adapter); +void __RPC_STUB IDXGIFactory_CreateSoftwareAdapter_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); + +#endif /* __IDXGIFactory_INTERFACE_DEFINED__ */ + +HRESULT __stdcall CreateDXGIFactory(REFIID riid,void **factory); +HRESULT __stdcall CreateDXGIFactory1(REFIID riid,void **factory); + +/***************************************************************************** + * IDXGIDevice interface + */ +#ifndef __IDXGIDevice_INTERFACE_DEFINED__ +#define __IDXGIDevice_INTERFACE_DEFINED__ + +DEFINE_GUID(IID_IDXGIDevice, 0x54ec77fa, 0x1377, 0x44e6, 0x8c,0x32, 0x88,0xfd,0x5f,0x44,0xc8,0x4c); +#if defined(__cplusplus) && !defined(CINTERFACE) +MIDL_INTERFACE("54ec77fa-1377-44e6-8c32-88fd5f44c84c") +IDXGIDevice : public IDXGIObject +{ + virtual HRESULT STDMETHODCALLTYPE GetAdapter( + IDXGIAdapter **adapter) = 0; + + virtual HRESULT STDMETHODCALLTYPE CreateSurface( + const DXGI_SURFACE_DESC *desc, + UINT surface_count, + DXGI_USAGE usage, + const DXGI_SHARED_RESOURCE *shared_resource, + IDXGISurface **surface) = 0; + + virtual HRESULT STDMETHODCALLTYPE QueryResourceResidency( + IUnknown *const *resources, + DXGI_RESIDENCY *residency, + UINT resource_count) = 0; + + virtual HRESULT STDMETHODCALLTYPE SetGPUThreadPriority( + INT priority) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetGPUThreadPriority( + INT *priority) = 0; + +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IDXGIDevice, 0x54ec77fa, 0x1377, 0x44e6, 0x8c,0x32, 0x88,0xfd,0x5f,0x44,0xc8,0x4c) +#endif +#else +typedef struct IDXGIDeviceVtbl { + BEGIN_INTERFACE + + /*** IUnknown methods ***/ + HRESULT (STDMETHODCALLTYPE *QueryInterface)( + IDXGIDevice* This, + REFIID riid, + void **ppvObject); + + ULONG (STDMETHODCALLTYPE *AddRef)( + IDXGIDevice* This); + + ULONG (STDMETHODCALLTYPE *Release)( + IDXGIDevice* This); + + /*** IDXGIObject methods ***/ + HRESULT (STDMETHODCALLTYPE *SetPrivateData)( + IDXGIDevice* This, + REFGUID guid, + UINT data_size, + const void *data); + + HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)( + IDXGIDevice* This, + REFGUID guid, + const IUnknown *object); + + HRESULT (STDMETHODCALLTYPE *GetPrivateData)( + IDXGIDevice* This, + REFGUID guid, + UINT *data_size, + void *data); + + HRESULT (STDMETHODCALLTYPE *GetParent)( + IDXGIDevice* This, + REFIID riid, + void **parent); + + /*** IDXGIDevice methods ***/ + HRESULT (STDMETHODCALLTYPE *GetAdapter)( + IDXGIDevice* This, + IDXGIAdapter **adapter); + + HRESULT (STDMETHODCALLTYPE *CreateSurface)( + IDXGIDevice* This, + const DXGI_SURFACE_DESC *desc, + UINT surface_count, + DXGI_USAGE usage, + const DXGI_SHARED_RESOURCE *shared_resource, + IDXGISurface **surface); + + HRESULT (STDMETHODCALLTYPE *QueryResourceResidency)( + IDXGIDevice* This, + IUnknown *const *resources, + DXGI_RESIDENCY *residency, + UINT resource_count); + + HRESULT (STDMETHODCALLTYPE *SetGPUThreadPriority)( + IDXGIDevice* This, + INT priority); + + HRESULT (STDMETHODCALLTYPE *GetGPUThreadPriority)( + IDXGIDevice* This, + INT *priority); + + END_INTERFACE +} IDXGIDeviceVtbl; +interface IDXGIDevice { + CONST_VTBL IDXGIDeviceVtbl* lpVtbl; +}; + +#ifdef COBJMACROS +#ifndef WIDL_C_INLINE_WRAPPERS +/*** IUnknown methods ***/ +#define IDXGIDevice_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) +#define IDXGIDevice_AddRef(This) (This)->lpVtbl->AddRef(This) +#define IDXGIDevice_Release(This) (This)->lpVtbl->Release(This) +/*** IDXGIObject methods ***/ +#define IDXGIDevice_SetPrivateData(This,guid,data_size,data) (This)->lpVtbl->SetPrivateData(This,guid,data_size,data) +#define IDXGIDevice_SetPrivateDataInterface(This,guid,object) (This)->lpVtbl->SetPrivateDataInterface(This,guid,object) +#define IDXGIDevice_GetPrivateData(This,guid,data_size,data) (This)->lpVtbl->GetPrivateData(This,guid,data_size,data) +#define IDXGIDevice_GetParent(This,riid,parent) (This)->lpVtbl->GetParent(This,riid,parent) +/*** IDXGIDevice methods ***/ +#define IDXGIDevice_GetAdapter(This,adapter) (This)->lpVtbl->GetAdapter(This,adapter) +#define IDXGIDevice_CreateSurface(This,desc,surface_count,usage,shared_resource,surface) (This)->lpVtbl->CreateSurface(This,desc,surface_count,usage,shared_resource,surface) +#define IDXGIDevice_QueryResourceResidency(This,resources,residency,resource_count) (This)->lpVtbl->QueryResourceResidency(This,resources,residency,resource_count) +#define IDXGIDevice_SetGPUThreadPriority(This,priority) (This)->lpVtbl->SetGPUThreadPriority(This,priority) +#define IDXGIDevice_GetGPUThreadPriority(This,priority) (This)->lpVtbl->GetGPUThreadPriority(This,priority) +#else +/*** IUnknown methods ***/ +static FORCEINLINE HRESULT IDXGIDevice_QueryInterface(IDXGIDevice* This,REFIID riid,void **ppvObject) { + return This->lpVtbl->QueryInterface(This,riid,ppvObject); +} +static FORCEINLINE ULONG IDXGIDevice_AddRef(IDXGIDevice* This) { + return This->lpVtbl->AddRef(This); +} +static FORCEINLINE ULONG IDXGIDevice_Release(IDXGIDevice* This) { + return This->lpVtbl->Release(This); +} +/*** IDXGIObject methods ***/ +static FORCEINLINE HRESULT IDXGIDevice_SetPrivateData(IDXGIDevice* This,REFGUID guid,UINT data_size,const void *data) { + return This->lpVtbl->SetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIDevice_SetPrivateDataInterface(IDXGIDevice* This,REFGUID guid,const IUnknown *object) { + return This->lpVtbl->SetPrivateDataInterface(This,guid,object); +} +static FORCEINLINE HRESULT IDXGIDevice_GetPrivateData(IDXGIDevice* This,REFGUID guid,UINT *data_size,void *data) { + return This->lpVtbl->GetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIDevice_GetParent(IDXGIDevice* This,REFIID riid,void **parent) { + return This->lpVtbl->GetParent(This,riid,parent); +} +/*** IDXGIDevice methods ***/ +static FORCEINLINE HRESULT IDXGIDevice_GetAdapter(IDXGIDevice* This,IDXGIAdapter **adapter) { + return This->lpVtbl->GetAdapter(This,adapter); +} +static FORCEINLINE HRESULT IDXGIDevice_CreateSurface(IDXGIDevice* This,const DXGI_SURFACE_DESC *desc,UINT surface_count,DXGI_USAGE usage,const DXGI_SHARED_RESOURCE *shared_resource,IDXGISurface **surface) { + return This->lpVtbl->CreateSurface(This,desc,surface_count,usage,shared_resource,surface); +} +static FORCEINLINE HRESULT IDXGIDevice_QueryResourceResidency(IDXGIDevice* This,IUnknown *const *resources,DXGI_RESIDENCY *residency,UINT resource_count) { + return This->lpVtbl->QueryResourceResidency(This,resources,residency,resource_count); +} +static FORCEINLINE HRESULT IDXGIDevice_SetGPUThreadPriority(IDXGIDevice* This,INT priority) { + return This->lpVtbl->SetGPUThreadPriority(This,priority); +} +static FORCEINLINE HRESULT IDXGIDevice_GetGPUThreadPriority(IDXGIDevice* This,INT *priority) { + return This->lpVtbl->GetGPUThreadPriority(This,priority); +} +#endif +#endif + +#endif + +HRESULT STDMETHODCALLTYPE IDXGIDevice_GetAdapter_Proxy( + IDXGIDevice* This, + IDXGIAdapter **adapter); +void __RPC_STUB IDXGIDevice_GetAdapter_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIDevice_CreateSurface_Proxy( + IDXGIDevice* This, + const DXGI_SURFACE_DESC *desc, + UINT surface_count, + DXGI_USAGE usage, + const DXGI_SHARED_RESOURCE *shared_resource, + IDXGISurface **surface); +void __RPC_STUB IDXGIDevice_CreateSurface_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIDevice_QueryResourceResidency_Proxy( + IDXGIDevice* This, + IUnknown *const *resources, + DXGI_RESIDENCY *residency, + UINT resource_count); +void __RPC_STUB IDXGIDevice_QueryResourceResidency_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIDevice_SetGPUThreadPriority_Proxy( + IDXGIDevice* This, + INT priority); +void __RPC_STUB IDXGIDevice_SetGPUThreadPriority_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +HRESULT STDMETHODCALLTYPE IDXGIDevice_GetGPUThreadPriority_Proxy( + IDXGIDevice* This, + INT *priority); +void __RPC_STUB IDXGIDevice_GetGPUThreadPriority_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); + +#endif /* __IDXGIDevice_INTERFACE_DEFINED__ */ + +typedef enum DXGI_ADAPTER_FLAG { + DXGI_ADAPTER_FLAG_NONE = 0, + DXGI_ADAPTER_FLAG_REMOTE = 1, + DXGI_ADAPTER_FLAG_FORCE_DWORD = 0xffffffff +} DXGI_ADAPTER_FLAG; +typedef struct DXGI_ADAPTER_DESC1 { + WCHAR Description[128]; + UINT VendorId; + UINT DeviceId; + UINT SubSysId; + UINT Revision; + SIZE_T DedicatedVideoMemory; + SIZE_T DedicatedSystemMemory; + SIZE_T SharedSystemMemory; + LUID AdapterLuid; + UINT Flags; +} DXGI_ADAPTER_DESC1; +/***************************************************************************** + * IDXGIAdapter1 interface + */ +#ifndef __IDXGIAdapter1_INTERFACE_DEFINED__ +#define __IDXGIAdapter1_INTERFACE_DEFINED__ + +DEFINE_GUID(IID_IDXGIAdapter1, 0x29038f61, 0x3839, 0x4626, 0x91,0xfd, 0x08,0x68,0x79,0x01,0x1a,0x05); +#if defined(__cplusplus) && !defined(CINTERFACE) +MIDL_INTERFACE("29038f61-3839-4626-91fd-086879011a05") +IDXGIAdapter1 : public IDXGIAdapter +{ + virtual HRESULT STDMETHODCALLTYPE GetDesc1( + DXGI_ADAPTER_DESC1 *pDesc) = 0; + +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IDXGIAdapter1, 0x29038f61, 0x3839, 0x4626, 0x91,0xfd, 0x08,0x68,0x79,0x01,0x1a,0x05) +#endif +#else +typedef struct IDXGIAdapter1Vtbl { + BEGIN_INTERFACE + + /*** IUnknown methods ***/ + HRESULT (STDMETHODCALLTYPE *QueryInterface)( + IDXGIAdapter1* This, + REFIID riid, + void **ppvObject); + + ULONG (STDMETHODCALLTYPE *AddRef)( + IDXGIAdapter1* This); + + ULONG (STDMETHODCALLTYPE *Release)( + IDXGIAdapter1* This); + + /*** IDXGIObject methods ***/ + HRESULT (STDMETHODCALLTYPE *SetPrivateData)( + IDXGIAdapter1* This, + REFGUID guid, + UINT data_size, + const void *data); + + HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)( + IDXGIAdapter1* This, + REFGUID guid, + const IUnknown *object); + + HRESULT (STDMETHODCALLTYPE *GetPrivateData)( + IDXGIAdapter1* This, + REFGUID guid, + UINT *data_size, + void *data); + + HRESULT (STDMETHODCALLTYPE *GetParent)( + IDXGIAdapter1* This, + REFIID riid, + void **parent); + + /*** IDXGIAdapter methods ***/ + HRESULT (STDMETHODCALLTYPE *EnumOutputs)( + IDXGIAdapter1* This, + UINT output_idx, + IDXGIOutput **output); + + HRESULT (STDMETHODCALLTYPE *GetDesc)( + IDXGIAdapter1* This, + DXGI_ADAPTER_DESC *desc); + + HRESULT (STDMETHODCALLTYPE *CheckInterfaceSupport)( + IDXGIAdapter1* This, + REFGUID guid, + LARGE_INTEGER *umd_version); + + /*** IDXGIAdapter1 methods ***/ + HRESULT (STDMETHODCALLTYPE *GetDesc1)( + IDXGIAdapter1* This, + DXGI_ADAPTER_DESC1 *pDesc); + + END_INTERFACE +} IDXGIAdapter1Vtbl; +interface IDXGIAdapter1 { + CONST_VTBL IDXGIAdapter1Vtbl* lpVtbl; +}; + +#ifdef COBJMACROS +#ifndef WIDL_C_INLINE_WRAPPERS +/*** IUnknown methods ***/ +#define IDXGIAdapter1_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) +#define IDXGIAdapter1_AddRef(This) (This)->lpVtbl->AddRef(This) +#define IDXGIAdapter1_Release(This) (This)->lpVtbl->Release(This) +/*** IDXGIObject methods ***/ +#define IDXGIAdapter1_SetPrivateData(This,guid,data_size,data) (This)->lpVtbl->SetPrivateData(This,guid,data_size,data) +#define IDXGIAdapter1_SetPrivateDataInterface(This,guid,object) (This)->lpVtbl->SetPrivateDataInterface(This,guid,object) +#define IDXGIAdapter1_GetPrivateData(This,guid,data_size,data) (This)->lpVtbl->GetPrivateData(This,guid,data_size,data) +#define IDXGIAdapter1_GetParent(This,riid,parent) (This)->lpVtbl->GetParent(This,riid,parent) +/*** IDXGIAdapter methods ***/ +#define IDXGIAdapter1_EnumOutputs(This,output_idx,output) (This)->lpVtbl->EnumOutputs(This,output_idx,output) +#define IDXGIAdapter1_GetDesc(This,desc) (This)->lpVtbl->GetDesc(This,desc) +#define IDXGIAdapter1_CheckInterfaceSupport(This,guid,umd_version) (This)->lpVtbl->CheckInterfaceSupport(This,guid,umd_version) +/*** IDXGIAdapter1 methods ***/ +#define IDXGIAdapter1_GetDesc1(This,pDesc) (This)->lpVtbl->GetDesc1(This,pDesc) +#else +/*** IUnknown methods ***/ +static FORCEINLINE HRESULT IDXGIAdapter1_QueryInterface(IDXGIAdapter1* This,REFIID riid,void **ppvObject) { + return This->lpVtbl->QueryInterface(This,riid,ppvObject); +} +static FORCEINLINE ULONG IDXGIAdapter1_AddRef(IDXGIAdapter1* This) { + return This->lpVtbl->AddRef(This); +} +static FORCEINLINE ULONG IDXGIAdapter1_Release(IDXGIAdapter1* This) { + return This->lpVtbl->Release(This); +} +/*** IDXGIObject methods ***/ +static FORCEINLINE HRESULT IDXGIAdapter1_SetPrivateData(IDXGIAdapter1* This,REFGUID guid,UINT data_size,const void *data) { + return This->lpVtbl->SetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIAdapter1_SetPrivateDataInterface(IDXGIAdapter1* This,REFGUID guid,const IUnknown *object) { + return This->lpVtbl->SetPrivateDataInterface(This,guid,object); +} +static FORCEINLINE HRESULT IDXGIAdapter1_GetPrivateData(IDXGIAdapter1* This,REFGUID guid,UINT *data_size,void *data) { + return This->lpVtbl->GetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIAdapter1_GetParent(IDXGIAdapter1* This,REFIID riid,void **parent) { + return This->lpVtbl->GetParent(This,riid,parent); +} +/*** IDXGIAdapter methods ***/ +static FORCEINLINE HRESULT IDXGIAdapter1_EnumOutputs(IDXGIAdapter1* This,UINT output_idx,IDXGIOutput **output) { + return This->lpVtbl->EnumOutputs(This,output_idx,output); +} +static FORCEINLINE HRESULT IDXGIAdapter1_GetDesc(IDXGIAdapter1* This,DXGI_ADAPTER_DESC *desc) { + return This->lpVtbl->GetDesc(This,desc); +} +static FORCEINLINE HRESULT IDXGIAdapter1_CheckInterfaceSupport(IDXGIAdapter1* This,REFGUID guid,LARGE_INTEGER *umd_version) { + return This->lpVtbl->CheckInterfaceSupport(This,guid,umd_version); +} +/*** IDXGIAdapter1 methods ***/ +static FORCEINLINE HRESULT IDXGIAdapter1_GetDesc1(IDXGIAdapter1* This,DXGI_ADAPTER_DESC1 *pDesc) { + return This->lpVtbl->GetDesc1(This,pDesc); +} +#endif +#endif + +#endif + +HRESULT STDMETHODCALLTYPE IDXGIAdapter1_GetDesc1_Proxy( + IDXGIAdapter1* This, + DXGI_ADAPTER_DESC1 *pDesc); +void __RPC_STUB IDXGIAdapter1_GetDesc1_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); + +#endif /* __IDXGIAdapter1_INTERFACE_DEFINED__ */ + +/***************************************************************************** + * IDXGIFactory1 interface + */ +#ifndef __IDXGIFactory1_INTERFACE_DEFINED__ +#define __IDXGIFactory1_INTERFACE_DEFINED__ + +DEFINE_GUID(IID_IDXGIFactory1, 0x770aae78, 0xf26f, 0x4dba, 0xa8,0x29, 0x25,0x3c,0x83,0xd1,0xb3,0x87); +#if defined(__cplusplus) && !defined(CINTERFACE) +MIDL_INTERFACE("770aae78-f26f-4dba-a829-253c83d1b387") +IDXGIFactory1 : public IDXGIFactory +{ + virtual HRESULT STDMETHODCALLTYPE EnumAdapters1( + UINT Adapter, + IDXGIAdapter1 **ppAdapter) = 0; + + virtual WINBOOL STDMETHODCALLTYPE IsCurrent( + ) = 0; + +}; +#ifdef __CRT_UUID_DECL +__CRT_UUID_DECL(IDXGIFactory1, 0x770aae78, 0xf26f, 0x4dba, 0xa8,0x29, 0x25,0x3c,0x83,0xd1,0xb3,0x87) +#endif +#else +typedef struct IDXGIFactory1Vtbl { + BEGIN_INTERFACE + + /*** IUnknown methods ***/ + HRESULT (STDMETHODCALLTYPE *QueryInterface)( + IDXGIFactory1* This, + REFIID riid, + void **ppvObject); + + ULONG (STDMETHODCALLTYPE *AddRef)( + IDXGIFactory1* This); + + ULONG (STDMETHODCALLTYPE *Release)( + IDXGIFactory1* This); + + /*** IDXGIObject methods ***/ + HRESULT (STDMETHODCALLTYPE *SetPrivateData)( + IDXGIFactory1* This, + REFGUID guid, + UINT data_size, + const void *data); + + HRESULT (STDMETHODCALLTYPE *SetPrivateDataInterface)( + IDXGIFactory1* This, + REFGUID guid, + const IUnknown *object); + + HRESULT (STDMETHODCALLTYPE *GetPrivateData)( + IDXGIFactory1* This, + REFGUID guid, + UINT *data_size, + void *data); + + HRESULT (STDMETHODCALLTYPE *GetParent)( + IDXGIFactory1* This, + REFIID riid, + void **parent); + + /*** IDXGIFactory methods ***/ + HRESULT (STDMETHODCALLTYPE *EnumAdapters)( + IDXGIFactory1* This, + UINT adapter_idx, + IDXGIAdapter **adapter); + + HRESULT (STDMETHODCALLTYPE *MakeWindowAssociation)( + IDXGIFactory1* This, + HWND window, + UINT flags); + + HRESULT (STDMETHODCALLTYPE *GetWindowAssociation)( + IDXGIFactory1* This, + HWND *window); + + HRESULT (STDMETHODCALLTYPE *CreateSwapChain)( + IDXGIFactory1* This, + IUnknown *device, + DXGI_SWAP_CHAIN_DESC *desc, + IDXGISwapChain **swapchain); + + HRESULT (STDMETHODCALLTYPE *CreateSoftwareAdapter)( + IDXGIFactory1* This, + HMODULE swrast, + IDXGIAdapter **adapter); + + /*** IDXGIFactory1 methods ***/ + HRESULT (STDMETHODCALLTYPE *EnumAdapters1)( + IDXGIFactory1* This, + UINT Adapter, + IDXGIAdapter1 **ppAdapter); + + WINBOOL (STDMETHODCALLTYPE *IsCurrent)( + IDXGIFactory1* This); + + END_INTERFACE +} IDXGIFactory1Vtbl; +interface IDXGIFactory1 { + CONST_VTBL IDXGIFactory1Vtbl* lpVtbl; +}; + +#ifdef COBJMACROS +#ifndef WIDL_C_INLINE_WRAPPERS +/*** IUnknown methods ***/ +#define IDXGIFactory1_QueryInterface(This,riid,ppvObject) (This)->lpVtbl->QueryInterface(This,riid,ppvObject) +#define IDXGIFactory1_AddRef(This) (This)->lpVtbl->AddRef(This) +#define IDXGIFactory1_Release(This) (This)->lpVtbl->Release(This) +/*** IDXGIObject methods ***/ +#define IDXGIFactory1_SetPrivateData(This,guid,data_size,data) (This)->lpVtbl->SetPrivateData(This,guid,data_size,data) +#define IDXGIFactory1_SetPrivateDataInterface(This,guid,object) (This)->lpVtbl->SetPrivateDataInterface(This,guid,object) +#define IDXGIFactory1_GetPrivateData(This,guid,data_size,data) (This)->lpVtbl->GetPrivateData(This,guid,data_size,data) +#define IDXGIFactory1_GetParent(This,riid,parent) (This)->lpVtbl->GetParent(This,riid,parent) +/*** IDXGIFactory methods ***/ +#define IDXGIFactory1_EnumAdapters(This,adapter_idx,adapter) (This)->lpVtbl->EnumAdapters(This,adapter_idx,adapter) +#define IDXGIFactory1_MakeWindowAssociation(This,window,flags) (This)->lpVtbl->MakeWindowAssociation(This,window,flags) +#define IDXGIFactory1_GetWindowAssociation(This,window) (This)->lpVtbl->GetWindowAssociation(This,window) +#define IDXGIFactory1_CreateSwapChain(This,device,desc,swapchain) (This)->lpVtbl->CreateSwapChain(This,device,desc,swapchain) +#define IDXGIFactory1_CreateSoftwareAdapter(This,swrast,adapter) (This)->lpVtbl->CreateSoftwareAdapter(This,swrast,adapter) +/*** IDXGIFactory1 methods ***/ +#define IDXGIFactory1_EnumAdapters1(This,Adapter,ppAdapter) (This)->lpVtbl->EnumAdapters1(This,Adapter,ppAdapter) +#define IDXGIFactory1_IsCurrent(This) (This)->lpVtbl->IsCurrent(This) +#else +/*** IUnknown methods ***/ +static FORCEINLINE HRESULT IDXGIFactory1_QueryInterface(IDXGIFactory1* This,REFIID riid,void **ppvObject) { + return This->lpVtbl->QueryInterface(This,riid,ppvObject); +} +static FORCEINLINE ULONG IDXGIFactory1_AddRef(IDXGIFactory1* This) { + return This->lpVtbl->AddRef(This); +} +static FORCEINLINE ULONG IDXGIFactory1_Release(IDXGIFactory1* This) { + return This->lpVtbl->Release(This); +} +/*** IDXGIObject methods ***/ +static FORCEINLINE HRESULT IDXGIFactory1_SetPrivateData(IDXGIFactory1* This,REFGUID guid,UINT data_size,const void *data) { + return This->lpVtbl->SetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIFactory1_SetPrivateDataInterface(IDXGIFactory1* This,REFGUID guid,const IUnknown *object) { + return This->lpVtbl->SetPrivateDataInterface(This,guid,object); +} +static FORCEINLINE HRESULT IDXGIFactory1_GetPrivateData(IDXGIFactory1* This,REFGUID guid,UINT *data_size,void *data) { + return This->lpVtbl->GetPrivateData(This,guid,data_size,data); +} +static FORCEINLINE HRESULT IDXGIFactory1_GetParent(IDXGIFactory1* This,REFIID riid,void **parent) { + return This->lpVtbl->GetParent(This,riid,parent); +} +/*** IDXGIFactory methods ***/ +static FORCEINLINE HRESULT IDXGIFactory1_EnumAdapters(IDXGIFactory1* This,UINT adapter_idx,IDXGIAdapter **adapter) { + return This->lpVtbl->EnumAdapters(This,adapter_idx,adapter); +} +static FORCEINLINE HRESULT IDXGIFactory1_MakeWindowAssociation(IDXGIFactory1* This,HWND window,UINT flags) { + return This->lpVtbl->MakeWindowAssociation(This,window,flags); +} +static FORCEINLINE HRESULT IDXGIFactory1_GetWindowAssociation(IDXGIFactory1* This,HWND *window) { + return This->lpVtbl->GetWindowAssociation(This,window); +} +static FORCEINLINE HRESULT IDXGIFactory1_CreateSwapChain(IDXGIFactory1* This,IUnknown *device,DXGI_SWAP_CHAIN_DESC *desc,IDXGISwapChain **swapchain) { + return This->lpVtbl->CreateSwapChain(This,device,desc,swapchain); +} +static FORCEINLINE HRESULT IDXGIFactory1_CreateSoftwareAdapter(IDXGIFactory1* This,HMODULE swrast,IDXGIAdapter **adapter) { + return This->lpVtbl->CreateSoftwareAdapter(This,swrast,adapter); +} +/*** IDXGIFactory1 methods ***/ +static FORCEINLINE HRESULT IDXGIFactory1_EnumAdapters1(IDXGIFactory1* This,UINT Adapter,IDXGIAdapter1 **ppAdapter) { + return This->lpVtbl->EnumAdapters1(This,Adapter,ppAdapter); +} +static FORCEINLINE WINBOOL IDXGIFactory1_IsCurrent(IDXGIFactory1* This) { + return This->lpVtbl->IsCurrent(This); +} +#endif +#endif + +#endif + +HRESULT STDMETHODCALLTYPE IDXGIFactory1_EnumAdapters1_Proxy( + IDXGIFactory1* This, + UINT Adapter, + IDXGIAdapter1 **ppAdapter); +void __RPC_STUB IDXGIFactory1_EnumAdapters1_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); +WINBOOL STDMETHODCALLTYPE IDXGIFactory1_IsCurrent_Proxy( + IDXGIFactory1* This); +void __RPC_STUB IDXGIFactory1_IsCurrent_Stub( + IRpcStubBuffer* This, + IRpcChannelBuffer* pRpcChannelBuffer, + PRPC_MESSAGE pRpcMessage, + DWORD* pdwStubPhase); + +#endif /* __IDXGIFactory1_INTERFACE_DEFINED__ */ + +/* Begin additional prototypes for all interfaces */ + + +/* End additional prototypes */ + +#ifdef __cplusplus +} +#endif + +#endif /* __dxgi_h__ */ diff --git a/libobs-d3d9/.gitignore b/libobs-d3d9/.gitignore new file mode 100644 index 000000000..e69de29bb diff --git a/libobs-opengl/.gitignore b/libobs-opengl/.gitignore new file mode 100644 index 000000000..e69de29bb diff --git a/libobs/graphics/axisang.c b/libobs/graphics/axisang.c new file mode 100644 index 000000000..4ec07f011 --- /dev/null +++ b/libobs/graphics/axisang.c @@ -0,0 +1,38 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "axisang.h" +#include "quat.h" + +void axisang_from_quat(struct axisang *dst, const struct quat *q) +{ + float len, leni; + + len = q->x*q->x + q->y*q->y + q->z*q->z; + if (!close_float(len, 0.0f, EPSILON)) { + leni = 1.0f/sqrtf(len); + dst->x = q->x * leni; + dst->y = q->y * leni; + dst->z = q->z * leni; + dst->w = acosf(q->w)*2.0f; + } else { + dst->x = 0.0f; + dst->y = 0.0f; + dst->z = 0.0f; + dst->w = 0.0f; + } +} diff --git a/libobs/graphics/axisang.h b/libobs/graphics/axisang.h new file mode 100644 index 000000000..8483713dc --- /dev/null +++ b/libobs/graphics/axisang.h @@ -0,0 +1,67 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef AXISANG_H +#define AXISANG_H + +#include "../util/c99defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct quat; + +struct axisang { + union { + struct {float x, y, z, w;}; + float ptr[4]; + }; +}; + +static inline void axisang_zero(struct axisang *dst) +{ + dst->x = 0.0f; + dst->y = 0.0f; + dst->z = 0.0f; + dst->w = 0.0f; +} + +static inline void axisang_copy(struct axisang *dst, struct axisang *aa) +{ + dst->x = aa->x; + dst->y = aa->y; + dst->z = aa->z; + dst->w = aa->w; +} + +static inline void axisang_set(struct axisang *dst, float x, float y, float z, + float w) +{ + dst->x = x; + dst->y = y; + dst->z = z; + dst->w = w; +} + +EXPORT void axisang_from_quat(struct axisang *dst, const struct quat *q); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/basemath.hpp b/libobs/graphics/basemath.hpp new file mode 100644 index 000000000..415b524c2 --- /dev/null +++ b/libobs/graphics/basemath.hpp @@ -0,0 +1,3 @@ +#pragma once + +/* TODO: C++ math wrappers */ diff --git a/libobs/graphics/bounds.c b/libobs/graphics/bounds.c new file mode 100644 index 000000000..4afb6b6c6 --- /dev/null +++ b/libobs/graphics/bounds.c @@ -0,0 +1,263 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "bounds.h" +#include "matrix3.h" +#include "plane.h" + +void bounds_move(struct bounds *dst, const struct bounds *b, + const struct vec3 *v) +{ + vec3_add(&dst->min, &b->min, v); + vec3_add(&dst->max, &b->max, v); +} + +void bounds_scale(struct bounds *dst, const struct bounds *b, + const struct vec3 *v) +{ + vec3_mul(&dst->min, &b->min, v); + vec3_mul(&dst->max, &b->max, v); +} + +void bounds_merge(struct bounds *dst, const struct bounds *b1, + const struct bounds *b2) +{ + vec3_min(&dst->min, &b1->min, &b2->min); + vec3_max(&dst->max, &b1->max, &b2->max); +} + +void bounds_merge_point(struct bounds *dst, const struct bounds *b, + const struct vec3 *v) +{ + vec3_min(&dst->min, &b->min, v); + vec3_max(&dst->max, &b->max, v); +} + +void bounds_get_point(struct vec3 *dst, const struct bounds *b, + unsigned int i) +{ + if (i > 8) + return; + + /* + * Note: + * 0 = min.x,min.y,min.z + * 1 = min.x,min.y,MAX.z + * 2 = min.x,MAX.y,min.z + * 3 = min.x,MAX.y,MAX.z + * 4 = MAX.x,min.y,min.z + * 5 = MAX.x,min.y,MAX.z + + * 6 = MAX.x,MAX.y,min.z + * 7 = MAX.x,MAX.y,MAX.z + */ + + if(i > 3) {dst->x = b->max.x; i -= 4;} + else {dst->x = b->min.x;} + + if(i > 1) {dst->y = b->max.y; i -= 2;} + else {dst->y = b->min.y;} + + dst->z = (i == 1) ? b->max.z : b->min.z; +} + +void bounds_get_center(struct vec3 *dst, const struct bounds *b) +{ + vec3_sub(dst, &b->max, &b->min); + vec3_mulf(dst, dst, 0.5f); + vec3_add(dst, dst, &b->min); +} + +void bounds_transform(struct bounds *dst, const struct bounds *b, + const struct matrix3 *m) +{ + struct bounds temp; + bool b_init = false; + int i; + + for (i = 0; i < 8; i++) { + struct vec3 p; + bounds_get_point(&p, b, i); + vec3_transform(&p, &p, m); + + if (!b_init) { + vec3_copy(&temp.min, &p); + vec3_copy(&temp.max, &p); + b_init = true; + } else { + if (p.x < temp.min.x) + temp.min.x = p.x; + else if(p.x > temp.max.x) + temp.max.x = p.x; + + if(p.y < temp.min.y) + temp.min.y = p.y; + else if(p.y > temp.max.y) + temp.max.y = p.y; + + if(p.z < temp.min.z) + temp.min.z = p.z; + else if(p.z > temp.max.z) + temp.max.z = p.z; + } + } + + bounds_copy(dst, &temp); +} + +bool bounds_intersection_ray(const struct bounds *b, const struct vec3 *orig, + const struct vec3 *dir, float *t) +{ + float t_max = M_INFINITE; + float t_min = -M_INFINITE; + struct vec3 center, max_offset, box_offset; + int i; + + bounds_get_center(¢er, b); + vec3_sub(&max_offset, &b->max, ¢er); + vec3_sub(&box_offset, ¢er, orig); + + for (i = 0; i < 3; i++) { + float e = box_offset.ptr[i]; + float f = dir->ptr[i]; + + if (fabsf(f) > 0.0f) { + float fi = 1.0f/f; + float t1 = (e+max_offset.ptr[i])*fi; + float t2 = (e-max_offset.ptr[i])*fi; + if (t1 > t2) { + if (t2 > t_min) t_min = t2; + if (t1 < t_max) t_max = t1; + } else { + if (t1 > t_min) t_min = t1; + if (t2 < t_max) t_max = t2; + } + if (t_min > t_max) + return false; + if (t_max < 0.0f) + return false; + } else if ((-e - max_offset.ptr[i]) > 0.0f || + (-e + max_offset.ptr[i]) < 0.0f) { + return false; + } + } + + *t = (t_min > 0.0f) ? t_min : t_max; + return true; +} + +bool bounds_intersection_line(const struct bounds *b, const struct vec3 *p1, + const struct vec3 *p2, float *t) +{ + struct vec3 dir; + float length; + + vec3_sub(&dir, p2, p1); + length = vec3_len(&dir); + if (length <= TINY_EPSILON) + return false; + + vec3_mulf(&dir, &dir, 1.0f/length); + + if (!bounds_intersection_ray(b, p1, &dir, t)) + return false; + + *t /= length; + return true; +} + +bool bounds_plane_test(const struct bounds *b, const struct plane *p) +{ + struct vec3 vmin, vmax; + int i; + + for (i = 0; i < 3; i++) { + if (p->dir.ptr[i] >= 0.0f) { + vmin.ptr[i] = b->min.ptr[i]; + vmax.ptr[i] = b->max.ptr[i]; + } else { + vmin.ptr[i] = b->max.ptr[i]; + vmax.ptr[i] = b->min.ptr[i]; + } + } + + if (vec3_plane_dist(&vmin, p) > 0.0f) + return BOUNDS_OUTSIDE; + + if (vec3_plane_dist(&vmax, p) >= 0.0f) + return BOUNDS_PARTIAL; + + return BOUNDS_INSIDE; +} + +bool bounds_under_plane(const struct bounds *b, const struct plane *p) +{ + struct vec3 vmin; + + vmin.x = (p->dir.x < 0.0f) ? b->max.x : b->min.x; + vmin.y = (p->dir.y < 0.0f) ? b->max.y : b->min.y; + vmin.z = (p->dir.z < 0.0f) ? b->max.z : b->min.z; + + return (vec3_dot(&vmin, &p->dir) <= p->dist); +} + +bool bounds_intersects(const struct bounds *b, const struct bounds *test, + float epsilon) +{ + return ((b->min.x - test->max.x) <= epsilon) && + ((test->min.x - b->max.x) <= epsilon) && + ((b->min.y - test->max.y) <= epsilon) && + ((test->min.y - b->max.y) <= epsilon) && + ((b->min.z - test->max.z) <= epsilon) && + ((test->min.z - b->max.z) <= epsilon); +} + +bool bounds_intersects_obb(const struct bounds *b, const struct bounds *test, + const struct matrix3 *m, float epsilon) +{ + struct bounds b_tr, test_tr; + struct matrix3 m_inv; + + matrix3_transpose(&m_inv, m); + + bounds_transform(&b_tr, b, m); + bounds_transform(&test_tr, test, &m_inv); + + return bounds_intersects(b, &test_tr, epsilon) && + bounds_intersects(&b_tr, test, epsilon); +} + +static inline float vec3or_offset_len(const struct bounds *b, + const struct vec3 *v) +{ + struct vec3 temp1, temp2; + vec3_sub(&temp1, &b->max, &b->min); + vec3_abs(&temp2, v); + return vec3_dot(&temp1, &temp2); +} + +float bounds_min_dist(const struct bounds *b, const struct plane *p) +{ + struct vec3 center; + float vec_len = vec3or_offset_len(b, &p->dir) * 0.5f; + float center_dist; + + bounds_get_center(¢er, b); + center_dist = vec3_plane_dist(¢er, p); + + return p->dist + center_dist - vec_len; +} diff --git a/libobs/graphics/bounds.h b/libobs/graphics/bounds.h new file mode 100644 index 000000000..9e10b0fa7 --- /dev/null +++ b/libobs/graphics/bounds.h @@ -0,0 +1,135 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef BOUNDS_H +#define BOUNDS_H + +#include "math-defs.h" +#include "vec3.h" + +/* + * Axis Aligned Bounding Box + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define BOUNDS_MAX_X 1 +#define BOUNDS_MAX_Y 2 +#define BOUNDS_MAX_Z 4 + +#define BOUNDS_OUTSIDE 1 +#define BOUNDS_INSIDE 2 +#define BOUNDS_PARTIAL 3 + +struct bounds { + struct vec3 min, max; +}; + +static inline void bounds_zero(struct bounds *dst) +{ + vec3_zero(&dst->min); + vec3_zero(&dst->max); +} + +static inline void bounds_copy(struct bounds *dst, const struct bounds *b) +{ + vec3_copy(&dst->min, &b->min); + vec3_copy(&dst->max, &b->max); +} + +EXPORT void bounds_move(struct bounds *dst, const struct bounds *b, + const struct vec3 *v); + +EXPORT void bounds_scale(struct bounds *dst, const struct bounds *b, + const struct vec3 *v); + +EXPORT void bounds_merge(struct bounds *dst, const struct bounds *b1, + const struct bounds *b2); +EXPORT void bounds_merge_point(struct bounds *dst, const struct bounds *b, + const struct vec3 *v); + +EXPORT void bounds_get_point(struct vec3 *dst, const struct bounds *b, + unsigned int i); +EXPORT void bounds_get_center(struct vec3 *dst, const struct bounds *b); + +/** + * Note: transforms as OBB, then converts back to AABB, which can result in + * the actual size becoming larger than it originally was. + */ +EXPORT void bounds_transform(struct bounds *dst, const struct bounds *b, + const struct matrix3 *m); + +EXPORT bool bounds_intersection_ray(const struct bounds *b, + const struct vec3 *orig, const struct vec3 *dir, float *t); +EXPORT bool bounds_intersection_line(const struct bounds *b, + const struct vec3 *p1, const struct vec3 *p2, float *t); + +EXPORT bool bounds_plane_test(const struct bounds *b, const struct plane *p); +EXPORT bool bounds_under_plane(const struct bounds *b, + const struct plane *p); + +static inline bool bounds_inside(const struct bounds *b, + const struct bounds *test) +{ + return test->min.x >= b->min.x && + test->min.y >= b->min.y && + test->min.z >= b->min.z && + test->max.x <= b->max.x && + test->max.y <= b->max.y && + test->max.z <= b->max.z; +} + +static inline bool bounds_vec3_inside(const struct bounds *b, + const struct vec3 *v) +{ + return v->x >= (b->min.x-EPSILON) && + v->x <= (b->max.x+EPSILON) && + v->y >= (b->min.y-EPSILON) && + v->y <= (b->max.y+EPSILON) && + v->z >= (b->min.z-EPSILON) && + v->z <= (b->max.z+EPSILON); +} + +EXPORT bool bounds_intersects(const struct bounds *b, + const struct bounds *test, float epsilon); +EXPORT bool bounds_intersects_obb(const struct bounds *b, + const struct bounds *test, const struct matrix3 *m, + float epsilon); + +static inline bool bounds_intersects_ray(const struct bounds *b, + const struct vec3 *orig, const struct vec3 *dir) +{ + float t; + return bounds_intersection_ray(b, orig, dir, &t); +} + +static inline bool bounds_intersects_line(const struct bounds *b, + const struct vec3 *p1, const struct vec3 *p2) +{ + float t; + return bounds_intersection_line(b, p1, p2, &t); +} + +EXPORT float bounds_min_dist(const struct bounds *b, const struct plane *p); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/effect-parser.c b/libobs/graphics/effect-parser.c new file mode 100644 index 000000000..b51836975 --- /dev/null +++ b/libobs/graphics/effect-parser.c @@ -0,0 +1,1459 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include +#include "effect-parser.h" +#include "effect.h" + +void ep_free(struct effect_parser *ep) +{ + size_t i; + for (i = 0; i < ep->params.num; i++) + ep_param_free(ep->params.array+i); + for (i = 0; i < ep->structs.num; i++) + ep_struct_free(ep->structs.array+i); + for (i = 0; i < ep->funcs.num; i++) + ep_func_free(ep->funcs.array+i); + for (i = 0; i < ep->samplers.num; i++) + ep_sampler_free(ep->samplers.array+i); + for (i = 0; i < ep->techniques.num; i++) + ep_technique_free(ep->techniques.array+i); + + ep->cur_pass = NULL; + cf_parser_free(&ep->cfp); + da_free(ep->params); + da_free(ep->structs); + da_free(ep->funcs); + da_free(ep->samplers); + da_free(ep->techniques); +} + +static inline struct ep_func *ep_getfunc(struct effect_parser *ep, + const char *name) +{ + size_t i; + for (i = 0; i < ep->funcs.num; i++) { + if (strcmp(name, ep->funcs.array[i].name) == 0) + return ep->funcs.array+i; + } + + return NULL; +} + +static inline struct ep_struct *ep_getstruct(struct effect_parser *ep, + const char *name) +{ + size_t i; + for (i = 0; i < ep->structs.num; i++) { + if (strcmp(name, ep->structs.array[i].name) == 0) + return ep->structs.array+i; + } + + return NULL; +} + +static inline struct ep_sampler *ep_getsampler(struct effect_parser *ep, + const char *name) +{ + size_t i; + for (i = 0; i < ep->samplers.num; i++) { + if (strcmp(name, ep->samplers.array[i].name) == 0) + return ep->samplers.array+i; + } + + return NULL; +} + +static inline struct ep_param *ep_getparam(struct effect_parser *ep, + const char *name) +{ + size_t i; + for (i = 0; i < ep->params.num; i++) { + if (strcmp(name, ep->params.array[i].name) == 0) + return ep->params.array+i; + } + + return NULL; +} + +static inline struct ep_func *ep_getfunc_strref(struct effect_parser *ep, + const struct strref *ref) +{ + size_t i; + for (i = 0; i < ep->funcs.num; i++) { + if (strref_cmp(ref, ep->funcs.array[i].name) == 0) + return ep->funcs.array+i; + } + + return NULL; +} + +static inline struct ep_struct *ep_getstruct_strref(struct effect_parser *ep, + const struct strref *ref) +{ + size_t i; + for (i = 0; i < ep->structs.num; i++) { + if (strref_cmp(ref, ep->structs.array[i].name) == 0) + return ep->structs.array+i; + } + + return NULL; +} + +static inline struct ep_sampler *ep_getsampler_strref(struct effect_parser *ep, + const struct strref *ref) +{ + size_t i; + for (i = 0; i < ep->samplers.num; i++) { + if (strref_cmp(ref, ep->samplers.array[i].name) == 0) + return ep->samplers.array+i; + } + + return NULL; +} + +static inline struct ep_param *ep_getparam_strref(struct effect_parser *ep, + const struct strref *ref) +{ + size_t i; + for (i = 0; i < ep->params.num; i++) { + if (strref_cmp(ref, ep->params.array[i].name) == 0) + return ep->params.array+i; + } + + return NULL; +} + +static inline int ep_parse_struct_var(struct effect_parser *ep, + struct ep_var *var) +{ + int errcode; + + /* -------------------------------------- */ + /* variable type */ + + if (!next_valid_token(&ep->cfp)) return PARSE_EOF; + + if (token_is(&ep->cfp, ";")) return PARSE_CONTINUE; + if (token_is(&ep->cfp, "}")) return PARSE_BREAK; + + errcode = token_is_type(&ep->cfp, CFTOKEN_NAME, "type name", ";"); + if (errcode != PARSE_SUCCESS) + return errcode; + + copy_token(&ep->cfp, &var->type); + + /* -------------------------------------- */ + /* variable name */ + + if (!next_valid_token(&ep->cfp)) return PARSE_EOF; + + if (token_is(&ep->cfp, ";")) return PARSE_UNEXPECTED_CONTINUE; + if (token_is(&ep->cfp, "}")) return PARSE_UNEXPECTED_BREAK; + + errcode = token_is_type(&ep->cfp, CFTOKEN_NAME, "variable name", ";"); + if (errcode != PARSE_SUCCESS) + return errcode; + + copy_token(&ep->cfp, &var->name); + + /* -------------------------------------- */ + /* variable mapping if any (POSITION, TEXCOORD, etc) */ + + if (!next_valid_token(&ep->cfp)) return PARSE_EOF; + + if (token_is(&ep->cfp, ":")) { + if (!next_valid_token(&ep->cfp)) return PARSE_EOF; + + if (token_is(&ep->cfp, ";")) return PARSE_UNEXPECTED_CONTINUE; + if (token_is(&ep->cfp, "}")) return PARSE_UNEXPECTED_BREAK; + + errcode = token_is_type(&ep->cfp, CFTOKEN_NAME, + "mapping name", ";"); + if (errcode != PARSE_SUCCESS) + return errcode; + + copy_token(&ep->cfp, &var->mapping); + + if (!next_valid_token(&ep->cfp)) return PARSE_EOF; + } + + /* -------------------------------------- */ + + if (!token_is(&ep->cfp, ";")) { + if (!go_to_valid_token(&ep->cfp, ";", "}")) + return PARSE_EOF; + return PARSE_CONTINUE; + } + + return PARSE_SUCCESS; +} + +static void ep_parse_struct(struct effect_parser *ep) +{ + struct ep_struct eps; + ep_struct_init(&eps); + + if (next_name(&ep->cfp, &eps.name, "name", ";") != PARSE_SUCCESS) + goto error; + if (next_token_should_be(&ep->cfp, "{", ";", NULL) != PARSE_SUCCESS) + goto error; + + /* get structure variables */ + while (true) { + bool do_break = false; + struct ep_var var; + + ep_var_init(&var); + + switch (ep_parse_struct_var(ep, &var)) { + + case PARSE_UNEXPECTED_CONTINUE: + cf_adderror_syntax_error(&ep->cfp); + case PARSE_CONTINUE: + ep_var_free(&var); + continue; + + case PARSE_UNEXPECTED_BREAK: + cf_adderror_syntax_error(&ep->cfp); + case PARSE_BREAK: + ep_var_free(&var); + do_break = true; + break; + + case PARSE_EOF: + ep_var_free(&var); + goto error; + } + + if (do_break) + break; + + da_push_back(eps.vars, &var); + } + + if (next_token_should_be(&ep->cfp, ";", NULL, NULL) != PARSE_SUCCESS) + goto error; + + da_push_back(ep->structs, &eps); + return; + +error: + ep_struct_free(&eps); +} + +static inline int ep_parse_pass_command_call(struct effect_parser *ep, + struct darray *call) +{ + struct cf_token end_token; + cf_token_clear(&end_token); + + while (!token_is(&ep->cfp, ";")) { + if (token_is(&ep->cfp, "}")) { + cf_adderror_expecting(&ep->cfp, ";"); + return PARSE_CONTINUE; + } + + darray_push_back(sizeof(struct cf_token), call, + ep->cfp.cur_token); + if (!next_valid_token(&ep->cfp)) return PARSE_EOF; + } + + darray_push_back(sizeof(struct cf_token), call, ep->cfp.cur_token); + darray_push_back(sizeof(struct cf_token), call, &end_token); + return PARSE_SUCCESS; +} + +static int ep_parse_pass_command(struct effect_parser *ep, struct ep_pass *pass) +{ + struct darray *call; /* struct cf_token */ + + if (!next_valid_token(&ep->cfp)) return PARSE_EOF; + + if (token_is(&ep->cfp, "vertex_shader") || + token_is(&ep->cfp, "vertex_program")) { + call = &pass->vertex_program.da; + + } else if (token_is(&ep->cfp, "pixel_shader") || + token_is(&ep->cfp, "pixel_program")) { + call = &pass->fragment_program.da; + + } else { + cf_adderror_syntax_error(&ep->cfp); + if (!go_to_valid_token(&ep->cfp, ";", "}")) return PARSE_EOF; + return PARSE_CONTINUE; + } + + if (next_token_should_be(&ep->cfp, "=", ";", "}") != PARSE_SUCCESS) + return PARSE_CONTINUE; + + if (!next_valid_token(&ep->cfp)) return PARSE_EOF; + if (token_is(&ep->cfp, "compile")) { + cf_adderror(&ep->cfp, "compile keyword not necessary", + LEVEL_WARNING, NULL, NULL, NULL); + if (!next_valid_token(&ep->cfp)) return PARSE_EOF; + } + + return ep_parse_pass_command_call(ep, call); +} + +static int ep_parse_pass(struct effect_parser *ep, struct ep_pass *pass) +{ + struct cf_token peek; + + if (!token_is(&ep->cfp, "pass")) + return PARSE_UNEXPECTED_CONTINUE; + + if (!next_valid_token(&ep->cfp)) return PARSE_EOF; + + if (!token_is(&ep->cfp, "{")) { + pass->name = bstrdup_n(ep->cfp.cur_token->str.array, + ep->cfp.cur_token->str.len); + if (!next_valid_token(&ep->cfp)) return PARSE_EOF; + } + + if (!peek_valid_token(&ep->cfp, &peek)) return PARSE_EOF; + + while (strref_cmp(&peek.str, "}") != 0) { + int ret = ep_parse_pass_command(ep, pass); + if (ret < 0 && ret != PARSE_CONTINUE) + return ret; + + if (!peek_valid_token(&ep->cfp, &peek)) + return PARSE_EOF; + } + + /* token is '}' */ + next_token(&ep->cfp); + + return PARSE_SUCCESS; +} + +static void ep_parse_technique(struct effect_parser *ep) +{ + struct ep_technique ept; + ep_technique_init(&ept); + + if (next_name(&ep->cfp, &ept.name, "name", ";") != PARSE_SUCCESS) + goto error; + if (next_token_should_be(&ep->cfp, "{", ";", NULL) != PARSE_SUCCESS) + goto error; + + if (!next_valid_token(&ep->cfp)) + goto error; + + while (!token_is(&ep->cfp, "}")) { + struct ep_pass pass; + ep_pass_init(&pass); + + switch (ep_parse_pass(ep, &pass)) { + case PARSE_UNEXPECTED_CONTINUE: + ep_pass_free(&pass); + if (!go_to_token(&ep->cfp, "}", NULL)) + goto error; + continue; + case PARSE_EOF: + ep_pass_free(&pass); + goto error; + } + + da_push_back(ept.passes, &pass); + + if (!next_valid_token(&ep->cfp)) + goto error; + } + + /* pass the current token (which is '}') if we reached here */ + next_token(&ep->cfp); + + da_push_back(ep->techniques, &ept); + return; + +error: + next_token(&ep->cfp); + ep_technique_free(&ept); +} + +static int ep_parse_sampler_state_item(struct effect_parser *ep, + struct ep_sampler *eps) +{ + int ret; + char *state = NULL, *value = NULL; + + ret = next_name(&ep->cfp, &state, "state name", ";"); + if (ret != PARSE_SUCCESS) goto fail; + + ret = next_token_should_be(&ep->cfp, "=", ";", NULL); + if (ret != PARSE_SUCCESS) goto fail; + + ret = next_name(&ep->cfp, &value, "value name", ";"); + if (ret != PARSE_SUCCESS) goto fail; + + ret = next_token_should_be(&ep->cfp, ";", ";", NULL); + if (ret != PARSE_SUCCESS) goto fail; + + da_push_back(eps->states, &state); + da_push_back(eps->values, &value); + return ret; + +fail: + bfree(state); + bfree(value); + return ret; +} + +static void ep_parse_sampler_state(struct effect_parser *ep) +{ + struct ep_sampler eps; + struct cf_token peek; + ep_sampler_init(&eps); + + if (next_name(&ep->cfp, &eps.name, "name", ";") != PARSE_SUCCESS) + goto error; + if (next_token_should_be(&ep->cfp, "{", ";", NULL) != PARSE_SUCCESS) + goto error; + + if (!peek_valid_token(&ep->cfp, &peek)) + goto error; + + while (strref_cmp(&peek.str, "}") != 0) { + int ret = ep_parse_sampler_state_item(ep, &eps); + if (ret == PARSE_EOF) + goto error; + + if (!peek_valid_token(&ep->cfp, &peek)) + goto error; + } + + if (next_token_should_be(&ep->cfp, "}", ";", NULL) != PARSE_SUCCESS) + goto error; + if (next_token_should_be(&ep->cfp, ";", NULL, NULL) != PARSE_SUCCESS) + goto error; + + da_push_back(ep->samplers, &eps); + return; + +error: + ep_sampler_free(&eps); +} + +static inline int ep_check_for_keyword(struct effect_parser *ep, + const char *keyword, bool *val) +{ + bool new_val = token_is(&ep->cfp, keyword); + if (new_val) { + if (!next_valid_token(&ep->cfp)) + return PARSE_EOF; + + if (new_val && *val) + cf_adderror(&ep->cfp, "'$1' keyword already specified", + LEVEL_WARNING, keyword, NULL, NULL); + *val = new_val; + + return PARSE_CONTINUE; + } + + return PARSE_SUCCESS; +} + +static inline int ep_parse_func_param(struct effect_parser *ep, + struct ep_func *func, struct ep_var *var) +{ + int errcode; + + if (!next_valid_token(&ep->cfp)) + return PARSE_EOF; + + errcode = ep_check_for_keyword(ep, "uniform", &var->uniform); + if (errcode == PARSE_EOF) + return PARSE_EOF; + + errcode = get_name(&ep->cfp, &var->type, "type", ")"); + if (errcode != PARSE_SUCCESS) + return errcode; + + errcode = next_name(&ep->cfp, &var->name, "name", ")"); + if (errcode != PARSE_SUCCESS) + return errcode; + + if (!next_valid_token(&ep->cfp)) + return PARSE_EOF; + + if (token_is(&ep->cfp, ":")) { + errcode = next_name(&ep->cfp, &var->mapping, + "mapping specifier", ")"); + if (errcode != PARSE_SUCCESS) + return errcode; + + if (!next_valid_token(&ep->cfp)) + return PARSE_EOF; + } + + if (ep_getstruct(ep, var->type) != NULL) + da_push_back(func->struct_deps, &var->type); + else if (ep_getsampler(ep, var->type) != NULL) + da_push_back(func->sampler_deps, &var->type); + + return PARSE_SUCCESS; +} + +static bool ep_parse_func_params(struct effect_parser *ep, struct ep_func *func) +{ + struct cf_token peek; + int errcode; + + cf_token_clear(&peek); + + if (!peek_valid_token(&ep->cfp, &peek)) + return false; + + if (*peek.str.array == ')') { + next_token(&ep->cfp); + goto exit; + } + + do { + struct ep_var var; + ep_var_init(&var); + + if (!token_is(&ep->cfp, "(") && !token_is(&ep->cfp, ",")) + cf_adderror_syntax_error(&ep->cfp); + + errcode = ep_parse_func_param(ep, func, &var); + if (errcode != PARSE_SUCCESS) { + ep_var_free(&var); + + if (errcode == PARSE_CONTINUE) + goto exit; + else if (errcode == PARSE_EOF) + return false; + } + + da_push_back(func->param_vars, &var); + } while (!token_is(&ep->cfp, ")")); + +exit: + return true; +} + +static inline bool ep_process_struct_dep(struct effect_parser *ep, + struct ep_func *func) +{ + struct ep_struct *val = ep_getstruct_strref(ep, + &ep->cfp.cur_token->str); + if (val) + da_push_back(func->struct_deps, &val->name); + return val != NULL; +} + +static inline bool ep_process_func_dep(struct effect_parser *ep, + struct ep_func *func) +{ + struct ep_func *val = ep_getfunc_strref(ep, + &ep->cfp.cur_token->str); + if (val) + da_push_back(func->func_deps, &val->name); + return val != NULL; +} + +static inline bool ep_process_sampler_dep(struct effect_parser *ep, + struct ep_func *func) +{ + struct ep_sampler *val = ep_getsampler_strref(ep, + &ep->cfp.cur_token->str); + if (val) + da_push_back(func->sampler_deps, &val->name); + return val != NULL; +} + +static inline bool ep_process_param_dep(struct effect_parser *ep, + struct ep_func *func) +{ + struct ep_param *val = ep_getparam_strref(ep, &ep->cfp.cur_token->str); + if (val) + da_push_back(func->param_deps, &val->name); + return val != NULL; +} + +static inline bool ep_parse_func_contents(struct effect_parser *ep, + struct ep_func *func) +{ + int braces = 1; + + dstr_cat_strref(&func->contents, &ep->cfp.cur_token->str); + + while (braces > 0) { + if ((ep->cfp.cur_token++)->type == CFTOKEN_NONE) + return false; + + if (ep->cfp.cur_token->type == CFTOKEN_SPACETAB || + ep->cfp.cur_token->type == CFTOKEN_NEWLINE) { + } else if (token_is(&ep->cfp, "{")) { + braces++; + } else if (token_is(&ep->cfp, "}")) { + braces--; + } else if (ep_process_struct_dep(ep, func) || + ep_process_func_dep(ep, func) || + ep_process_sampler_dep(ep, func) || + ep_process_param_dep(ep, func)) { + } + + dstr_cat_strref(&func->contents, &ep->cfp.cur_token->str); + } + + return true; +} + +static void ep_parse_function(struct effect_parser *ep, + char *type, char *name) +{ + struct ep_func func; + int errcode; + + ep_func_init(&func, type, name); + if (ep_getstruct(ep, type)) + da_push_back(func.struct_deps, &func.ret_type); + + if (!ep_parse_func_params(ep, &func)) + goto error; + + if (!next_valid_token(&ep->cfp)) + goto error; + + /* if function is mapped to something, for example COLOR */ + if (token_is(&ep->cfp, ":")) { + errcode = next_name(&ep->cfp, &func.mapping, + "mapping specifier", "{"); + if (errcode == PARSE_EOF) + goto error; + else if (errcode != PARSE_CONTINUE) { + if (!next_valid_token(&ep->cfp)) + goto error; + } + } + + if (!token_is(&ep->cfp, "{")) { + cf_adderror_expecting(&ep->cfp, "{"); + goto error; + } + + if (!ep_parse_func_contents(ep, &func)) + goto error; + + /* it is established that the current token is '}' if we reach this */ + next_token(&ep->cfp); + + da_push_back(ep->funcs, &func); + return; + +error: + ep_func_free(&func); +} + +/* parses "array[count]" */ +static bool ep_parse_param_array(struct effect_parser *ep, + struct ep_param *param) +{ + if (!next_valid_token(&ep->cfp)) + return false; + + if (ep->cfp.cur_token->type != CFTOKEN_NUM || + !valid_int_str(ep->cfp.cur_token->str.array, + ep->cfp.cur_token->str.len)) + return false; + + param->array_count = strtol(ep->cfp.cur_token->str.array, NULL, 10); + + if (next_token_should_be(&ep->cfp, "]", ";", NULL) == PARSE_EOF) + return false; + + if (!next_valid_token(&ep->cfp)) + return false; + + return true; +} + +static inline int ep_parse_param_assign_texture(struct effect_parser *ep, + struct ep_param *param) +{ + int errcode; + char *str; + + if (!next_valid_token(&ep->cfp)) + return PARSE_EOF; + + errcode = token_is_type(&ep->cfp, CFTOKEN_STRING, + "texture path string", ";"); + if (errcode != PARSE_SUCCESS) + return errcode; + + str = cf_literal_to_str(ep->cfp.cur_token->str.array, + ep->cfp.cur_token->str.len); + + if (str) { + da_copy_array(param->default_val, str, strlen(str) + 1); + bfree(str); + } + + return PARSE_SUCCESS; +} + +static inline int ep_parse_param_assign_intfloat(struct effect_parser *ep, + struct ep_param *param, bool is_float) +{ + int errcode; + + if (!next_valid_token(&ep->cfp)) + return PARSE_EOF; + + errcode = token_is_type(&ep->cfp, CFTOKEN_NUM, "numeric value", ";"); + if (errcode != PARSE_SUCCESS) + return errcode; + + if (is_float) { + float f = (float)strtod(ep->cfp.cur_token->str.array, NULL); + da_push_back_array(param->default_val, &f, sizeof(float)); + } else { + long l = strtol(ep->cfp.cur_token->str.array, NULL, 10); + da_push_back_array(param->default_val, &l, sizeof(long)); + } + + return PARSE_SUCCESS; +} + +/* + * parses assignment for float1, float2, float3, float4, and any combination + * for float3x3, float4x4, etc + */ +static inline int ep_parse_param_assign_float_array(struct effect_parser *ep, + struct ep_param *param) +{ + const char *float_type = param->type+5; + int float_count = 0, errcode, i; + + /* -------------------------------------------- */ + + if (float_type[0] < '1' || float_type[0] > '4') + cf_adderror(&ep->cfp, "Invalid row count", LEVEL_ERROR, + NULL, NULL, NULL); + + float_count = float_type[0]-'0'; + + if (float_type[1] == 'x') { + if (float_type[2] < '1' || float_type[2] > '4') + cf_adderror(&ep->cfp, "Invalid column count", + LEVEL_ERROR, NULL, NULL, NULL); + + float_count *= float_type[2]-'0'; + } + + /* -------------------------------------------- */ + + errcode = next_token_should_be(&ep->cfp, "{", ";", NULL); + if (errcode != PARSE_SUCCESS) return errcode; + + for (i = 0; i < float_count; i++) { + char *next = ((i+1) < float_count) ? "," : "}"; + + errcode = ep_parse_param_assign_intfloat(ep, param, true); + if (errcode != PARSE_SUCCESS) return errcode; + + errcode = next_token_should_be(&ep->cfp, next, ";", NULL); + if (errcode != PARSE_SUCCESS) return errcode; + } + + return PARSE_SUCCESS; +} + +static int ep_parse_param_assignment_val(struct effect_parser *ep, + struct ep_param *param) +{ + if (param->is_texture) + return ep_parse_param_assign_texture(ep, param); + else if (strcmp(param->type, "int") == 0) + return ep_parse_param_assign_intfloat(ep, param, false); + else if (strcmp(param->type, "float") == 0) + return ep_parse_param_assign_intfloat(ep, param, true); + else if (astrcmp_n(param->type, "float", 5) == 0) + return ep_parse_param_assign_float_array(ep, param); + + cf_adderror(&ep->cfp, "Invalid type '$1' used for assignment", + LEVEL_ERROR, param->type, NULL, NULL); + + return PARSE_CONTINUE; +} + +static inline bool ep_parse_param_assignment(struct effect_parser *ep, + struct ep_param *param) +{ + if (ep_parse_param_assignment_val(ep, param) != PARSE_SUCCESS) + return false; + + if (!next_valid_token(&ep->cfp)) + return false; + + return true; +} + +/* static bool ep_parse_param_property(struct effect_parser *ep, + struct ep_param *param) +{ +} */ + +static void ep_parse_param(struct effect_parser *ep, + char *type, char *name, + bool is_property, bool is_const, bool is_uniform) +{ + struct ep_param param; + ep_param_init(¶m, type, name, is_property, is_const); + + if (token_is(&ep->cfp, ";")) + goto complete; + if (token_is(&ep->cfp, "[") && !ep_parse_param_array(ep, ¶m)) + goto error; + if (token_is(&ep->cfp, "=") && !ep_parse_param_assignment(ep, ¶m)) + goto error; + /*if (token_is(&ep->cfp, "<") && !ep_parse_param_property(ep, ¶m)) + goto error; */ + if (!token_is(&ep->cfp, ";")) + goto error; + +complete: + da_push_back(ep->params, ¶m); + return; + +error: + ep_param_free(¶m); +} + +static bool ep_get_var_specifiers(struct effect_parser *ep, + bool *is_property, bool *is_const, bool *is_uniform) +{ + while(true) { + int errcode; + errcode = ep_check_for_keyword(ep, "property", is_property); + if (errcode == PARSE_EOF) + return false; + else if (errcode == PARSE_CONTINUE) + continue; + + errcode = ep_check_for_keyword(ep, "const", is_const); + if (errcode == PARSE_EOF) + return false; + else if (errcode == PARSE_CONTINUE) + continue; + + errcode = ep_check_for_keyword(ep, "uniform", is_uniform); + if (errcode == PARSE_EOF) + return false; + else if (errcode == PARSE_CONTINUE) + continue; + + break; + } + + return true; +} + +static inline void report_invalid_func_keyword(struct effect_parser *ep, + const char *name, bool val) +{ + if (val) + cf_adderror(&ep->cfp, "'$1' keyword cannot be used with a " + "function", LEVEL_ERROR, + name, NULL, NULL); +} + +static void ep_parse_other(struct effect_parser *ep) +{ + bool is_property = false, is_const = false, is_uniform = false; + char *type = NULL, *name = NULL; + + if (!ep_get_var_specifiers(ep, &is_property, &is_const, &is_uniform)) + goto error; + + if (get_name(&ep->cfp, &type, "type", ";") != PARSE_SUCCESS) + goto error; + if (next_name(&ep->cfp, &name, "name", ";") != PARSE_SUCCESS) + goto error; + + if (!next_valid_token(&ep->cfp)) + goto error; + + if (token_is(&ep->cfp, "(")) { + report_invalid_func_keyword(ep, "property", is_property); + report_invalid_func_keyword(ep, "const", is_const); + report_invalid_func_keyword(ep, "uniform", is_uniform); + + ep_parse_function(ep, type, name); + return; + } else { + ep_parse_param(ep, type, name, is_property, is_const, + is_uniform); + return; + } + +error: + bfree(type); + bfree(name); +} + +static bool ep_compile(struct effect_parser *ep); + +bool ep_parse(struct effect_parser *ep, effect_t effect, + const char *effect_string, const char *file) +{ + bool success; + + ep->effect = effect; + if (!cf_parser_parse(&ep->cfp, effect_string, file)) + return false; + + while (ep->cfp.cur_token && ep->cfp.cur_token->type != CFTOKEN_NONE) { + if (token_is(&ep->cfp, ";") || + is_whitespace(*ep->cfp.cur_token->str.array)) { + /* do nothing */ + ep->cfp.cur_token++; + + } else if (token_is(&ep->cfp, "struct")) { + ep_parse_struct(ep); + + } else if (token_is(&ep->cfp, "technique")) { + ep_parse_technique(ep); + + } else if (token_is(&ep->cfp, "sampler_state")) { + ep_parse_sampler_state(ep); + + } else if (token_is(&ep->cfp, "{")) { + /* add error and pass braces */ + cf_adderror(&ep->cfp, "Unexpected code segment", + LEVEL_ERROR, NULL, NULL, NULL); + pass_pair(&ep->cfp, '{', '}'); + + } else { + /* parameters and functions */ + ep_parse_other(ep); + } + } + + success = !error_data_has_errors(&ep->cfp.error_list); + if (success) + success = ep_compile(ep); + + return success; +} + +/* ------------------------------------------------------------------------- */ + +static inline void ep_write_param(struct dstr *shader, struct ep_param *param, + struct darray *used_params) +{ + if (param->written) + return; + + if (param->is_const) { + dstr_cat(shader, "const "); + } else { + struct dstr new; + dstr_init_copy(&new, param->name); + darray_push_back(sizeof(struct dstr), used_params, &new); + + dstr_cat(shader, "uniform "); + } + + dstr_cat(shader, param->type); + dstr_cat(shader, " "); + dstr_cat(shader, param->name); + + if (param->array_count) + dstr_catf(shader, "[%u]", param->array_count); + + dstr_cat(shader, ";\n"); + + param->written = true; +} + +static inline void ep_write_func_param_deps(struct effect_parser *ep, + struct dstr *shader, struct ep_func *func, + struct darray *used_params) +{ + size_t i; + for (i = 0; i < func->param_deps.num; i++) { + const char *name = func->param_deps.array[i]; + struct ep_param *param = ep_getparam(ep, name); + ep_write_param(shader, param, used_params); + } + + if (func->param_deps.num) + dstr_cat(shader, "\n\n"); +} + +static void ep_write_sampler(struct dstr *shader, struct ep_sampler *sampler) +{ + size_t i; + + if (sampler->written) + return; + + dstr_cat(shader, "sampler_state "); + dstr_cat(shader, sampler->name); + dstr_cat(shader, " {"); + + for (i = 0; i values.num; i++) { + dstr_cat(shader, "\n\t"); + dstr_cat(shader, sampler->states.array[i]); + dstr_cat(shader, " = "); + dstr_cat(shader, sampler->values.array[i]); + dstr_cat(shader, ";\n"); + } + + dstr_cat(shader, "\n};\n"); + sampler->written = true; +} + +static inline void ep_write_func_sampler_deps(struct effect_parser *ep, + struct dstr *shader, struct ep_func *func) +{ + size_t i; + for (i = 0; i < func->sampler_deps.num; i++) { + const char *name = func->sampler_deps.array[i]; + + struct ep_sampler *sampler = ep_getsampler(ep, name); + ep_write_sampler(shader, sampler); + dstr_cat(shader, "\n"); + } +} + +static inline void ep_write_var(struct dstr *shader, struct ep_var *var) +{ + if (var->uniform) + dstr_cat(shader, "uniform "); + + dstr_cat(shader, var->type); + dstr_cat(shader, " "); + dstr_cat(shader, var->name); + + if (var->mapping) { + dstr_cat(shader, " : "); + dstr_cat(shader, var->mapping); + } +} + +static void ep_write_struct(struct dstr *shader, struct ep_struct *st) +{ + size_t i; + + if (st->written) + return; + + dstr_cat(shader, "struct "); + dstr_cat(shader, st->name); + dstr_cat(shader, " {"); + + for (i = 0; i < st->vars.num; i++) { + dstr_cat(shader, "\n\t"); + ep_write_var(shader, st->vars.array+i); + dstr_cat(shader, ";"); + } + + dstr_cat(shader, "\n};\n"); + st->written = true; +} + +static inline void ep_write_func_struct_deps(struct effect_parser *ep, + struct dstr *shader, struct ep_func *func) +{ + size_t i; + for (i = 0; i < func->struct_deps.num; i++) { + const char *name = func->struct_deps.array[i]; + struct ep_struct *st = ep_getstruct(ep, name); + + if (!st->written) { + ep_write_struct(shader, st); + dstr_cat(shader, "\n"); + st->written = true; + } + } +} + +static void ep_write_func(struct effect_parser *ep, struct dstr *shader, + struct ep_func *func, struct darray *used_params); + +static inline void ep_write_func_func_deps(struct effect_parser *ep, + struct dstr *shader, struct ep_func *func, + struct darray *used_params) +{ + size_t i; + for (i = 0; i < func->func_deps.num; i++) { + const char *name = func->func_deps.array[i]; + struct ep_func *func = ep_getfunc(ep, name); + + if (!func->written) { + ep_write_func(ep, shader, func, used_params); + dstr_cat(shader, "\n\n"); + } + } +} + +static void ep_write_func(struct effect_parser *ep, struct dstr *shader, + struct ep_func *func, struct darray *used_params) +{ + size_t i; + + func->written = true; + + ep_write_func_param_deps(ep, shader, func, used_params); + ep_write_func_sampler_deps(ep, shader, func); + ep_write_func_struct_deps(ep, shader, func); + ep_write_func_func_deps(ep, shader, func, used_params); + + /* ------------------------------------ */ + + dstr_cat(shader, func->ret_type); + dstr_cat(shader, " "); + dstr_cat(shader, func->name); + dstr_cat(shader, "("); + + for (i = 0; i < func->param_vars.num; i++) { + struct ep_var *var = func->param_vars.array+i; + + if (i) + dstr_cat(shader, ", "); + ep_write_var(shader, var); + } + + dstr_cat(shader, ")\n"); + dstr_cat_dstr(shader, &func->contents); + dstr_cat(shader, "\n"); +} + +/* writes mapped vars used by the call as parameters for main */ +static void ep_write_main_params(struct effect_parser *ep, + struct dstr *shader, struct dstr *param_str, + struct ep_func *func) +{ + size_t i; + bool empty_params = dstr_isempty(param_str); + + for (i = 0; i < func->param_vars.num; i++) { + struct ep_var *var = func->param_vars.array+i; + struct ep_struct *st = NULL; + bool mapped = (var->mapping != NULL); + + if (!mapped) { + st = ep_getstruct(ep, var->type); + if (st) + mapped = ep_struct_mapped(st); + } + + if (mapped) { + dstr_cat(shader, var->type); + dstr_cat(shader, " "); + dstr_cat(shader, var->name); + + if (!st) { + dstr_cat(shader, " : "); + dstr_cat(shader, var->mapping); + } + + if (!dstr_isempty(param_str)) + dstr_cat(param_str, ", "); + dstr_cat(param_str, var->name); + } + } + + if (!empty_params) + dstr_cat(param_str, ", "); +} + +static void ep_write_main(struct effect_parser *ep, struct dstr *shader, + struct ep_func *func, struct dstr *call_str) +{ + struct dstr param_str; + struct dstr adjusted_call; + + dstr_init(¶m_str); + dstr_init_copy_dstr(&adjusted_call, call_str); + + dstr_cat(shader, "\n"); + dstr_cat(shader, func->ret_type); + dstr_cat(shader, " main("); + + ep_write_main_params(ep, shader, ¶m_str, func); + + dstr_cat(shader, ")"); + if (func->mapping) { + dstr_cat(shader, " : "); + dstr_cat(shader, func->mapping); + } + + dstr_cat(shader, "\n{\n\treturn "); + dstr_cat_dstr(shader, &adjusted_call); + dstr_cat(shader, "\n}\n"); + + dstr_free(&adjusted_call); + dstr_free(¶m_str); +} + +static inline void ep_reset_written(struct effect_parser *ep) +{ + size_t i; + for (i = 0; i params.num; i++) + ep->params.array[i].written = false; + for (i = 0; i structs.num; i++) + ep->structs.array[i].written = false; + for (i = 0; i funcs.num; i++) + ep->funcs.array[i].written = false; + for (i = 0; i samplers.num; i++) + ep->samplers.array[i].written = false; +} + +static void ep_makeshaderstring(struct effect_parser *ep, + struct dstr *shader, struct darray *shader_call, + struct darray *used_params) +{ + struct cf_token *token = shader_call->array; + struct cf_token *func_name; + struct ep_func *func; + struct dstr call_str; + + dstr_init(&call_str); + + while (token->type != CFTOKEN_NONE && is_whitespace(*token->str.array)) + token++; + + if (token->type == CFTOKEN_NONE || + strref_cmp(&token->str, "NULL") == 0) + return; + + func_name = token; + + while (token->type != CFTOKEN_NONE) { + struct ep_param *param = ep_getparam_strref(ep, &token->str); + if (param) + ep_write_param(shader, param, used_params); + + dstr_cat_strref(&call_str, &token->str); + token++; + } + + func = ep_getfunc_strref(ep, &func_name->str); + if (!func) + return; + + ep_write_func(ep, shader, func, used_params); + ep_write_main(ep, shader, func, &call_str); + + dstr_free(&call_str); + + ep_reset_written(ep); +} + +static void ep_compile_param(struct effect_parser *ep, size_t idx) +{ + struct effect_param *param; + struct ep_param *param_in; + + param = ep->effect->params.array+idx; + param_in = ep->params.array+idx; + param_in->param = param; + + param->name = bstrdup(param_in->name); + param->section = EFFECT_PARAM; + da_move(param->default_val, param_in->default_val); + + if (strcmp(param_in->type, "bool") == 0) + param->type = SHADER_PARAM_BOOL; + else if (strcmp(param_in->type, "float") == 0) + param->type = SHADER_PARAM_FLOAT; + else if (strcmp(param_in->type, "int") == 0) + param->type = SHADER_PARAM_INT; + else if (strcmp(param_in->type, "float2") == 0) + param->type = SHADER_PARAM_VEC2; + else if (strcmp(param_in->type, "float3") == 0) + param->type = SHADER_PARAM_VEC3; + else if (strcmp(param_in->type, "float4") == 0) + param->type = SHADER_PARAM_VEC4; + else if (strcmp(param_in->type, "float3x3") == 0) + param->type = SHADER_PARAM_MATRIX3X3; + else if (strcmp(param_in->type, "float4x4") == 0) + param->type = SHADER_PARAM_MATRIX4X4; + else if (param_in->is_texture) + param->type = SHADER_PARAM_TEXTURE; + + if (strcmp(param_in->name, "ViewProj") == 0) + ep->effect->view_proj = param; + else if (strcmp(param_in->name, "World") == 0) + ep->effect->world = param; +} + +static inline void ep_compile_pass_shaderparams(struct effect_parser *ep, + struct darray *pass_params, struct darray *used_params, + shader_t shader) +{ + size_t i; + darray_resize(sizeof(struct pass_shaderparam), pass_params, + used_params->num); + + for (i = 0; i < pass_params->num; i++) { + struct dstr *param_name; + struct pass_shaderparam *param; + + param_name = darray_item(sizeof(struct dstr), used_params, i); + param = darray_item(sizeof(struct pass_shaderparam), + pass_params, i); + + param->eparam = effect_getparambyname(ep->effect, + param_name->array); + param->sparam = shader_getparambyname(shader, + param_name->array); + } +} + +static inline bool ep_compile_pass_shader(struct effect_parser *ep, + struct effect_technique *tech, + struct effect_pass *pass, struct ep_pass *pass_in, + size_t pass_idx, enum shader_type type) +{ + struct dstr shader_str; + struct dstr location; + struct darray used_params; /* struct dstr */ + struct darray *pass_params; /* struct pass_shaderparam */ + shader_t shader; + + dstr_init(&shader_str); + darray_init(&used_params); + dstr_init(&location); + + dstr_copy(&location, ep->cfp.lex.file); + if (type == SHADER_VERTEX) + dstr_cat(&location, " (Vertex "); + else if (type == SHADER_PIXEL) + dstr_cat(&location, " (Pixel "); + else if (type == SHADER_GEOMETRY) + dstr_cat(&location, " (Geometry "); + + dstr_catf(&location, "shader, technique %s, pass %u)", tech->name, + pass_idx); + + if (type == SHADER_VERTEX) { + ep_makeshaderstring(ep, &shader_str, + &pass_in->vertex_program.da, &used_params); + + pass->vertshader = gs_create_vertexshader(shader_str.array, + location.array, NULL); + + shader = pass->vertshader; + pass_params = &pass->vertshader_params.da; + } else if (type == SHADER_PIXEL) { + ep_makeshaderstring(ep, &shader_str, + &pass_in->fragment_program.da, &used_params); + + pass->pixelshader = gs_create_pixelshader(shader_str.array, + location.array, NULL); + + shader = pass->pixelshader; + pass_params = &pass->pixelshader_params.da; + } + + blog(LOG_DEBUG, "+++++++++++++++++++++++++++++++++++"); + blog(LOG_DEBUG, " %s", location.array); + blog(LOG_DEBUG, "-----------------------------------"); + blog(LOG_DEBUG, "%s", shader_str.array); + blog(LOG_DEBUG, "+++++++++++++++++++++++++++++++++++"); + + if (shader) + ep_compile_pass_shaderparams(ep, pass_params, &used_params, + shader); + + dstr_free(&location); + dstr_array_free(used_params.array, used_params.num); + darray_free(&used_params); + dstr_free(&shader_str); + + return shader != NULL; +} + +static bool ep_compile_pass(struct effect_parser *ep, + struct effect_technique *tech, + struct ep_technique *tech_in, + size_t idx) +{ + struct effect_pass *pass; + struct ep_pass *pass_in; + bool success = true; + + pass = tech->passes.array+idx; + pass_in = tech_in->passes.array+idx; + + pass->name = bstrdup(pass_in->name); + pass->section = EFFECT_PASS; + + if (!ep_compile_pass_shader(ep, tech, pass, pass_in, idx, + SHADER_VERTEX)) + success = false; + + if (!ep_compile_pass_shader(ep, tech, pass, pass_in, idx, + SHADER_PIXEL)) + success = false; + + return success; +} + +static inline bool ep_compile_technique(struct effect_parser *ep, size_t idx) +{ + struct effect_technique *tech; + struct ep_technique *tech_in; + bool success = true; + size_t i; + + tech = ep->effect->techniques.array+idx; + tech_in = ep->techniques.array+idx; + + tech->name = bstrdup(tech_in->name); + tech->section = EFFECT_TECHNIQUE; + tech->effect = ep->effect; + + da_resize(tech->passes, tech_in->passes.num); + + for (i = 0; i < tech->passes.num; i++) { + if (!ep_compile_pass(ep, tech, tech_in, i)) + success = false; + } + + return success; +} + +static bool ep_compile(struct effect_parser *ep) +{ + bool success = true; + size_t i; + + assert(ep->effect); + + da_resize(ep->effect->params, ep->params.num); + da_resize(ep->effect->techniques, ep->techniques.num); + + for (i = 0; i < ep->params.num; i++) + ep_compile_param(ep, i); + for (i = 0; i < ep->techniques.num; i++) { + if (!ep_compile_technique(ep, i)) + success = false; + } + + return success; +} diff --git a/libobs/graphics/effect-parser.h b/libobs/graphics/effect-parser.h new file mode 100644 index 000000000..f2f177d5c --- /dev/null +++ b/libobs/graphics/effect-parser.h @@ -0,0 +1,285 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef EFFECT_PARSER_H +#define EFFECT_PARSER_H + +#include "../util/darray.h" +#include "../util/cf-parser.h" +#include "graphics.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct dstr; + +/* + * The effect parser takes an effect file and converts it into individual + * shaders for each technique's pass. It automatically writes all dependent + * structures/functions/parameters to the shader and builds shader text for + * each shader component of each pass. + */ + +/* ------------------------------------------------------------------------- */ +/* effect parser var data */ + +struct ep_var { + char *type, *name, *mapping; + bool uniform; +}; + +static inline void ep_var_init(struct ep_var *epv) +{ + memset(epv, 0, sizeof(struct ep_var)); +} + +static inline void ep_var_free(struct ep_var *epv) +{ + bfree(epv->type); + bfree(epv->name); + bfree(epv->mapping); +} + +/* ------------------------------------------------------------------------- */ +/* effect parser param data */ + +struct ep_param { + char *type, *name; + DARRAY(uint8_t) default_val; + DARRAY(char*) properties; + struct effect_param *param; + bool is_const, is_property, is_texture, written; + int writeorder, array_count; +}; + +extern void ep_param_writevar(struct dstr *dst, struct darray *use_params); + +static inline void ep_param_init(struct ep_param *epp, + char *type, char *name, + bool is_property, bool is_const) +{ + epp->type = type; + epp->name = name; + epp->is_property = is_property; + epp->is_const = is_const; + epp->is_texture = (astrcmp_n(epp->type, "texture", 7) == 0); + epp->written = false; + epp->writeorder = false; + epp->array_count = 0; + da_init(epp->default_val); + da_init(epp->properties); +} + +static inline void ep_param_free(struct ep_param *epp) +{ + bfree(epp->type); + bfree(epp->name); + da_free(epp->default_val); + da_free(epp->properties); +} + +/* ------------------------------------------------------------------------- */ +/* effect parser struct data */ + +struct ep_struct { + char *name; + DARRAY(struct ep_var) vars; /* struct ep_var */ + bool written; +}; + +static inline bool ep_struct_mapped(struct ep_struct *eps) +{ + if (eps->vars.num > 0) + return eps->vars.array[0].mapping != NULL; + + return false; +} + +static inline void ep_struct_init(struct ep_struct *eps) +{ + memset(eps, 0, sizeof(struct ep_struct)); +} + +static inline void ep_struct_free(struct ep_struct *eps) +{ + size_t i; + + bfree(eps->name); + for (i = 0; i < eps->vars.num; i++) + ep_var_free(eps->vars.array+i); + da_free(eps->vars); +} + +/* ------------------------------------------------------------------------- */ +/* effect parser sampler data */ + +struct ep_sampler { + char *name; + DARRAY(char*) states; + DARRAY(char*) values; + + bool written; +}; + +static inline void ep_sampler_init(struct ep_sampler *eps) +{ + memset(eps, 0, sizeof(struct ep_sampler)); +} + +static inline void ep_sampler_free(struct ep_sampler *eps) +{ + size_t i; + + for (i = 0; i < eps->states.num; i++) + bfree(eps->states.array[i]); + for (i = 0; i < eps->values.num; i++) + bfree(eps->values.array[i]); + + bfree(eps->name); + da_free(eps->states); + da_free(eps->values); +} + +/* ------------------------------------------------------------------------- */ +/* effect parser pass data */ + +struct ep_pass { + char *name; + DARRAY(struct cf_token) vertex_program; + DARRAY(struct cf_token) fragment_program; + struct effect_pass *pass; +}; + +static inline void ep_pass_init(struct ep_pass *epp) +{ + memset(epp, 0, sizeof(struct ep_pass)); +} + +static inline void ep_pass_free(struct ep_pass *epp) +{ + bfree(epp->name); + da_free(epp->vertex_program); + da_free(epp->fragment_program); +} + +/* ------------------------------------------------------------------------- */ +/* effect parser technique data */ + +struct ep_technique { + char *name; + DARRAY(struct ep_pass) passes; /* struct ep_pass */ +}; + +static inline void ep_technique_init(struct ep_technique *ept) +{ + memset(ept, 0, sizeof(struct ep_technique)); +} + +static inline void ep_technique_free(struct ep_technique *ept) +{ + size_t i; + + for (i = 0; i < ept->passes.num; i++) + ep_pass_free(ept->passes.array+i); + + bfree(ept->name); + da_free(ept->passes); +} + +/* ------------------------------------------------------------------------- */ +/* effect parser function data */ + +struct ep_func { + char *name, *ret_type, *mapping; + struct dstr contents; + DARRAY(struct ep_var) param_vars; + DARRAY(const char*) func_deps; + DARRAY(const char*) struct_deps; + DARRAY(const char*) param_deps; + DARRAY(const char*) sampler_deps; + bool written; +}; + +static inline void ep_func_init(struct ep_func *epf, char *ret_type, + char *name) +{ + memset(epf, 0, sizeof(struct ep_func)); + epf->name = name; + epf->ret_type = ret_type; +} + +static inline void ep_func_free(struct ep_func *epf) +{ + size_t i; + for (i = 0; i < epf->param_vars.num; i++) + ep_var_free(epf->param_vars.array+i); + + bfree(epf->name); + bfree(epf->ret_type); + bfree(epf->mapping); + dstr_free(&epf->contents); + da_free(epf->param_vars); + da_free(epf->func_deps); + da_free(epf->struct_deps); + da_free(epf->param_deps); + da_free(epf->sampler_deps); +} + +/* ------------------------------------------------------------------------- */ + +struct effect_parser { + effect_t effect; + + DARRAY(struct ep_param) params; + DARRAY(struct ep_struct) structs; + DARRAY(struct ep_func) funcs; + DARRAY(struct ep_sampler) samplers; + DARRAY(struct ep_technique) techniques; + + /* internal vars */ + DARRAY(struct cf_lexer) files; + DARRAY(struct cf_token) tokens; + struct effect_pass *cur_pass; + + struct cf_parser cfp; +}; + +static inline void ep_init(struct effect_parser *ep) +{ + da_init(ep->params); + da_init(ep->structs); + da_init(ep->funcs); + da_init(ep->samplers); + da_init(ep->techniques); + da_init(ep->files); + da_init(ep->tokens); + + ep->cur_pass = NULL; + cf_parser_init(&ep->cfp); +} + +extern void ep_free(struct effect_parser *ep); + +extern bool ep_parse(struct effect_parser *ep, effect_t effect, + const char *effect_string, const char *file); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/effect.c b/libobs/graphics/effect.c new file mode 100644 index 000000000..b4b351c19 --- /dev/null +++ b/libobs/graphics/effect.c @@ -0,0 +1,313 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "effect.h" +#include "graphics-internal.h" +#include "vec2.h" +#include "vec3.h" +#include "vec4.h" + +void effect_destroy(effect_t effect) +{ + if (effect) { + effect_free(effect); + bfree(effect); + } +} + +technique_t effect_gettechnique(effect_t effect, const char *name) +{ + size_t i; + struct effect_technique *array = effect->techniques.array; + + for (i = 0; i < effect->techniques.num; i++) { + struct effect_technique *tech = array+i; + if (strcmp(tech->name, name) == 0) + return tech; + } + + return NULL; +} + +int technique_begin(technique_t tech) +{ + tech->effect->cur_technique = tech; + tech->effect->graphics->cur_effect = tech->effect; + + return (int)tech->passes.num; +} + +void technique_end(technique_t tech) +{ + struct gs_effect *effect = tech->effect; + struct effect_param *params = effect->params.array; + size_t i; + + gs_load_vertexshader(NULL); + gs_load_pixelshader(NULL); + + tech->effect->cur_technique = NULL; + tech->effect->graphics->cur_effect = NULL; + + for (i = 0; i < effect->params.num; i++) { + struct effect_param *param = params+i; + + da_free(param->cur_val); + param->changed = false; + } +} + +static inline void reset_params(struct darray *shaderparams) +{ + struct pass_shaderparam *params = shaderparams->array; + size_t i; + + for (i = 0; i < shaderparams->num; i++) + params[i].eparam->changed = false; +} + +static void upload_shader_params(shader_t shader, struct darray *pass_params, + bool changed_only) +{ + struct pass_shaderparam *params = pass_params->array; + size_t i; + + for (i = 0; i < pass_params->num; i++) { + struct pass_shaderparam *param = params+i; + struct effect_param *eparam = param->eparam; + sparam_t sparam = param->sparam; + + if (changed_only && !eparam->changed) + continue; + + if (!eparam->cur_val.num) { + if (eparam->default_val.num) + da_copy(eparam->cur_val, eparam->default_val); + else + continue; + } + + shader_setval(shader, sparam, eparam->cur_val.array, + eparam->cur_val.num); + } +} + +static inline void upload_parameters(struct gs_effect *effect, + bool changed_only) +{ + struct darray *vshader_params, *pshader_params; + + if (!effect->cur_pass) + return; + + vshader_params = &effect->cur_pass->vertshader_params.da; + pshader_params = &effect->cur_pass->pixelshader_params.da; + + upload_shader_params(effect->cur_pass->vertshader, vshader_params, + changed_only); + upload_shader_params(effect->cur_pass->pixelshader, pshader_params, + changed_only); + reset_params(vshader_params); + reset_params(pshader_params); +} + +void effect_updateparams(effect_t effect) +{ + upload_parameters(effect, true); +} + +bool technique_beginpass(technique_t tech, size_t idx) +{ + struct effect_pass *passes; + struct effect_pass *cur_pass; + + if (idx >= tech->passes.num) + return false; + + passes = tech->passes.array; + cur_pass = passes+idx; + + tech->effect->cur_pass = cur_pass; + gs_load_vertexshader(cur_pass->vertshader); + gs_load_pixelshader(cur_pass->pixelshader); + upload_parameters(tech->effect, false); + + return true; +} + +bool technique_beginpassbyname(technique_t tech, + const char *name) +{ + size_t i; + for (i = 0; i < tech->passes.num; i++) { + struct effect_pass *pass = tech->passes.array+i; + if (strcmp(pass->name, name) == 0) { + technique_beginpass(tech, (int)i); + return true; + } + } + + return false; +} + +static inline void clear_tex_params(shader_t shader, struct darray *in_params) +{ + struct pass_shaderparam *params = in_params->array; + size_t i; + + for (i = 0; i < in_params->num; i++) { + struct pass_shaderparam *param = params+i; + struct shader_param_info info; + + shader_getparaminfo(shader, param->sparam, &info); + if (info.type == SHADER_PARAM_TEXTURE) + shader_settexture(shader, param->sparam, NULL); + } +} + +void technique_endpass(technique_t tech) +{ + struct effect_pass *pass = tech->effect->cur_pass; + if (!pass) + return; + + clear_tex_params(pass->vertshader, &pass->vertshader_params.da); + clear_tex_params(pass->pixelshader, &pass->pixelshader_params.da); + tech->effect->cur_pass = NULL; +} + +int effect_numparams(effect_t effect) +{ + return (int)effect->params.num; +} + +eparam_t effect_getparambyidx(effect_t effect, size_t param) +{ + struct effect_param *params = effect->params.array; + + if (param >= effect->params.num) + return NULL; + + return params+param; +} + +eparam_t effect_getparambyname(effect_t effect, const char *name) +{ + struct effect_param *params = effect->params.array; + size_t i; + + for (i = 0; i < effect->params.num; i++) { + struct effect_param *param = params+i; + + if (strcmp(param->name, name) == 0) + return param; + } + + return NULL; +} + +void effect_getparaminfo(effect_t effect, eparam_t param, + struct effect_param_info *info) +{ + info->name = param->name; + info->type = param->type; +} + +eparam_t effect_getviewprojmatrix(effect_t effect) +{ + return effect->view_proj; +} + +eparam_t effect_getworldmatrix(effect_t effect) +{ + return effect->world; +} + +static inline void effect_setval_inline(effect_t effect, eparam_t param, + const void *data, size_t size) +{ + bool size_changed = param->cur_val.num != size; + if (size_changed) + da_resize(param->cur_val, size); + + if (size_changed || memcmp(param->cur_val.array, data, size) != 0) { + memcpy(param->cur_val.array, data, size); + param->changed = true; + } +} + +void effect_setbool(effect_t effect, eparam_t param, bool val) +{ + effect_setval_inline(effect, param, &val, sizeof(bool)); +} + +void effect_setfloat(effect_t effect, eparam_t param, float val) +{ + effect_setval_inline(effect, param, &val, sizeof(float)); +} + +void effect_setint(effect_t effect, eparam_t param, int val) +{ + effect_setval_inline(effect, param, &val, sizeof(int)); +} + +void effect_setmatrix3(effect_t effect, eparam_t param, + const struct matrix3 *val) +{ + effect_setval_inline(effect, param, val, sizeof(struct matrix3)); +} + +void effect_setmatrix4(effect_t effect, eparam_t param, + const struct matrix4 *val) +{ + effect_setval_inline(effect, param, val, sizeof(struct matrix4)); +} + +void effect_setvec2(effect_t effect, eparam_t param, + const struct vec2 *val) +{ + effect_setval_inline(effect, param, val, sizeof(struct vec2)); +} + +void effect_setvec3(effect_t effect, eparam_t param, + const struct vec3 *val) +{ + effect_setval_inline(effect, param, val, sizeof(float) * 3); +} + +void effect_setvec4(effect_t effect, eparam_t param, + const struct vec4 *val) +{ + effect_setval_inline(effect, param, val, sizeof(struct vec4)); +} + +void effect_settexture(effect_t effect, eparam_t param, texture_t val) +{ + effect_setval_inline(effect, param, &val, sizeof(texture_t)); +} + +void effect_setval(effect_t effect, eparam_t param, const void *val, + size_t size) +{ + effect_setval_inline(effect, param, val, size); +} + +void effect_setdefault(effect_t effect, eparam_t param) +{ + effect_setval_inline(effect, param, param->default_val.array, + param->default_val.num); +} diff --git a/libobs/graphics/effect.h b/libobs/graphics/effect.h new file mode 100644 index 000000000..3da3df9b8 --- /dev/null +++ b/libobs/graphics/effect.h @@ -0,0 +1,181 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef EFFECT_H +#define EFFECT_H + +#include "effect-parser.h" +#include "graphics.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Effects introduce a means of bundling together shader text into one + * file with shared functions and parameters. This is done because often + * shaders must be duplicated when you need to alter minor aspects of the code + * that cannot be done via constants. Effects allow developers to easily + * switch shaders and set constants that can be used between shaders. + * + * Effects are built via the effect parser, and shaders are automatically + * generated for each technique's pass. + */ + +/* ------------------------------------------------------------------------- */ + +enum effect_section { + EFFECT_PARAM, + EFFECT_TECHNIQUE, + EFFECT_SAMPLER, + EFFECT_PASS +}; + +/* ------------------------------------------------------------------------- */ + +struct effect_param { + char *name; + enum effect_section section; + + enum shader_param_type type; + + bool changed; + DARRAY(uint8_t) cur_val; + DARRAY(uint8_t) default_val; + + /*char *full_name; + float scroller_min, scroller_max, scroller_inc, scroller_mul;*/ +}; + +static inline void effect_param_init(struct effect_param *param) +{ + memset(param, 0, sizeof(struct effect_param)); +} + +static inline void effect_param_free(struct effect_param *param) +{ + bfree(param->name); + //bfree(param->full_name); + da_free(param->cur_val); + da_free(param->default_val); +} + +EXPORT void effect_param_parse_property(eparam_t param, + const char *property); + +/* ------------------------------------------------------------------------- */ + +struct pass_shaderparam { + struct effect_param *eparam; + sparam_t sparam; +}; + +struct effect_pass { + char *name; + enum effect_section section; + + shader_t vertshader; + shader_t pixelshader; + DARRAY(struct pass_shaderparam) vertshader_params; + DARRAY(struct pass_shaderparam) pixelshader_params; +}; + +static inline void effect_pass_init(struct effect_pass *pass) +{ + memset(pass, 0, sizeof(struct effect_pass)); +} + +static inline void effect_pass_free(struct effect_pass *pass) +{ + bfree(pass->name); + da_free(pass->vertshader_params); + da_free(pass->pixelshader_params); + shader_destroy(pass->vertshader); + shader_destroy(pass->pixelshader); +} + +/* ------------------------------------------------------------------------- */ + +struct effect_technique { + char *name; + enum effect_section section; + struct gs_effect *effect; + + DARRAY(struct effect_pass) passes; +}; + +static inline void effect_technique_init(struct effect_technique *t) +{ + memset(t, 0, sizeof(struct effect_technique)); +} + +static inline void effect_technique_free(struct effect_technique *t) +{ + size_t i; + for (i = 0; i < t->passes.num; i++) + effect_pass_free(t->passes.array+i); + da_free(t->passes); + bfree(t->name); +} + +/* ------------------------------------------------------------------------- */ + +struct gs_effect { + bool processing; + char *effect_path, *effect_dir; + + DARRAY(struct effect_param) params; + DARRAY(struct effect_technique) techniques; + + struct effect_technique *cur_technique; + struct effect_pass *cur_pass; + + eparam_t view_proj, world, scale; + graphics_t graphics; +}; + +static inline void effect_init(effect_t effect) +{ + memset(effect, 0, sizeof(struct gs_effect)); +} + +static inline void effect_free(effect_t effect) +{ + size_t i; + for (i = 0; i < effect->params.num; i++) + effect_param_free(effect->params.array+i); + for (i = 0; i < effect->techniques.num; i++) + effect_technique_free(effect->techniques.array+i); + + da_free(effect->params); + da_free(effect->techniques); + + bfree(effect->effect_path); + bfree(effect->effect_dir); + effect->effect_path = NULL; + effect->effect_dir = NULL; +} + +EXPORT void effect_upload_params(effect_t effect, bool changed_only); +EXPORT void effect_upload_shader_params(effect_t effect, shader_t shader, + struct darray *pass_params, bool changed_only); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/graphics-imports.c b/libobs/graphics/graphics-imports.c new file mode 100644 index 000000000..b790552eb --- /dev/null +++ b/libobs/graphics/graphics-imports.c @@ -0,0 +1,162 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "../util/base.h" +#include "../util/dstr.h" +#include "../util/platform.h" +#include "graphics-internal.h" + +#define GRAPHICS_IMPORT(func) \ + do { \ + exports->func = os_dlsym(module, #func); \ + if (!exports->func) { \ + success = false; \ + blog(LOG_ERROR, "Could not load function '%s' from " \ + "module '%s'", #func, module_name); \ + } \ + } while (false) + +bool load_graphics_imports(struct gs_exports *exports, void *module, + const char *module_name) +{ + bool success = true; + + GRAPHICS_IMPORT(device_create); + GRAPHICS_IMPORT(device_destroy); + GRAPHICS_IMPORT(device_create_swapchain); + GRAPHICS_IMPORT(device_resize); + GRAPHICS_IMPORT(device_getsize); + GRAPHICS_IMPORT(device_getwidth); + GRAPHICS_IMPORT(device_getheight); + GRAPHICS_IMPORT(device_create_texture); + GRAPHICS_IMPORT(device_create_cubetexture); + GRAPHICS_IMPORT(device_create_volumetexture); + GRAPHICS_IMPORT(device_create_zstencil); + GRAPHICS_IMPORT(device_create_stagesurface); + GRAPHICS_IMPORT(device_create_samplerstate); + GRAPHICS_IMPORT(device_create_vertexshader); + GRAPHICS_IMPORT(device_create_pixelshader); + GRAPHICS_IMPORT(device_create_vertexbuffer); + GRAPHICS_IMPORT(device_create_indexbuffer); + GRAPHICS_IMPORT(device_gettexturetype); + GRAPHICS_IMPORT(device_load_vertexbuffer); + GRAPHICS_IMPORT(device_load_indexbuffer); + GRAPHICS_IMPORT(device_load_texture); + GRAPHICS_IMPORT(device_load_samplerstate); + GRAPHICS_IMPORT(device_load_vertexshader); + GRAPHICS_IMPORT(device_load_pixelshader); + GRAPHICS_IMPORT(device_load_defaultsamplerstate); + GRAPHICS_IMPORT(device_getvertexshader); + GRAPHICS_IMPORT(device_getpixelshader); + GRAPHICS_IMPORT(device_getrendertarget); + GRAPHICS_IMPORT(device_getzstenciltarget); + GRAPHICS_IMPORT(device_setrendertarget); + GRAPHICS_IMPORT(device_setcuberendertarget); + GRAPHICS_IMPORT(device_copy_texture); + GRAPHICS_IMPORT(device_stage_texture); + GRAPHICS_IMPORT(device_beginscene); + GRAPHICS_IMPORT(device_draw); + GRAPHICS_IMPORT(device_load_swapchain); + GRAPHICS_IMPORT(device_endscene); + GRAPHICS_IMPORT(device_clear); + GRAPHICS_IMPORT(device_present); + GRAPHICS_IMPORT(device_setcullmode); + GRAPHICS_IMPORT(device_getcullmode); + GRAPHICS_IMPORT(device_enable_blending); + GRAPHICS_IMPORT(device_enable_depthtest); + GRAPHICS_IMPORT(device_enable_stenciltest); + GRAPHICS_IMPORT(device_enable_stencilwrite); + GRAPHICS_IMPORT(device_enable_color); + GRAPHICS_IMPORT(device_blendfunction); + GRAPHICS_IMPORT(device_depthfunction); + GRAPHICS_IMPORT(device_stencilfunction); + GRAPHICS_IMPORT(device_stencilop); + GRAPHICS_IMPORT(device_enable_fullscreen); + GRAPHICS_IMPORT(device_fullscreen_enabled); + GRAPHICS_IMPORT(device_setdisplaymode); + GRAPHICS_IMPORT(device_getdisplaymode); + GRAPHICS_IMPORT(device_setcolorramp); + GRAPHICS_IMPORT(device_setviewport); + GRAPHICS_IMPORT(device_getviewport); + GRAPHICS_IMPORT(device_setscissorrect); + GRAPHICS_IMPORT(device_ortho); + GRAPHICS_IMPORT(device_frustum); + GRAPHICS_IMPORT(device_perspective); + GRAPHICS_IMPORT(device_projection_push); + GRAPHICS_IMPORT(device_projection_pop); + + GRAPHICS_IMPORT(swapchain_destroy); + + GRAPHICS_IMPORT(texture_destroy); + GRAPHICS_IMPORT(texture_getwidth); + GRAPHICS_IMPORT(texture_getheight); + GRAPHICS_IMPORT(texture_getcolorformat); + GRAPHICS_IMPORT(texture_map); + GRAPHICS_IMPORT(texture_unmap); + + GRAPHICS_IMPORT(cubetexture_destroy); + GRAPHICS_IMPORT(cubetexture_getsize); + GRAPHICS_IMPORT(cubetexture_getcolorformat); + + GRAPHICS_IMPORT(volumetexture_destroy); + GRAPHICS_IMPORT(volumetexture_getwidth); + GRAPHICS_IMPORT(volumetexture_getheight); + GRAPHICS_IMPORT(volumetexture_getdepth); + GRAPHICS_IMPORT(volumetexture_getcolorformat); + + GRAPHICS_IMPORT(stagesurface_destroy); + GRAPHICS_IMPORT(stagesurface_getwidth); + GRAPHICS_IMPORT(stagesurface_getheight); + GRAPHICS_IMPORT(stagesurface_getcolorformat); + GRAPHICS_IMPORT(stagesurface_map); + GRAPHICS_IMPORT(stagesurface_unmap); + + GRAPHICS_IMPORT(zstencil_destroy); + + GRAPHICS_IMPORT(samplerstate_destroy); + + GRAPHICS_IMPORT(vertexbuffer_destroy); + GRAPHICS_IMPORT(vertexbuffer_flush); + GRAPHICS_IMPORT(vertexbuffer_getdata); + + GRAPHICS_IMPORT(indexbuffer_destroy); + GRAPHICS_IMPORT(indexbuffer_flush); + GRAPHICS_IMPORT(indexbuffer_getdata); + GRAPHICS_IMPORT(indexbuffer_numindices); + GRAPHICS_IMPORT(indexbuffer_gettype); + + GRAPHICS_IMPORT(shader_destroy); + GRAPHICS_IMPORT(shader_numparams); + GRAPHICS_IMPORT(shader_getparambyidx); + GRAPHICS_IMPORT(shader_getparambyname); + GRAPHICS_IMPORT(shader_getparaminfo); + GRAPHICS_IMPORT(shader_getviewprojmatrix); + GRAPHICS_IMPORT(shader_getworldmatrix); + GRAPHICS_IMPORT(shader_setbool); + GRAPHICS_IMPORT(shader_setfloat); + GRAPHICS_IMPORT(shader_setint); + GRAPHICS_IMPORT(shader_setmatrix3); + GRAPHICS_IMPORT(shader_setmatrix4); + GRAPHICS_IMPORT(shader_setvec2); + GRAPHICS_IMPORT(shader_setvec3); + GRAPHICS_IMPORT(shader_setvec4); + GRAPHICS_IMPORT(shader_settexture); + GRAPHICS_IMPORT(shader_setval); + GRAPHICS_IMPORT(shader_setdefault); + + return success; +} diff --git a/libobs/graphics/graphics-internal.h b/libobs/graphics/graphics-internal.h new file mode 100644 index 000000000..95c9a3fa6 --- /dev/null +++ b/libobs/graphics/graphics-internal.h @@ -0,0 +1,229 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef GRAPHICS_INTERNAL_H +#define GRAPHICS_INTERNAL_H + +#include "../util/darray.h" +#include "graphics.h" +#include "matrix3.h" +#include "matrix4.h" + +struct gs_exports { + device_t (*device_create)(struct gs_init_data *data); + void (*device_destroy)(device_t device); + swapchain_t (*device_create_swapchain)(device_t device, + struct gs_init_data *data); + void (*device_resize)(device_t device, uint32_t x, uint32_t y); + void (*device_getsize)(device_t device, uint32_t *x, uint32_t *y); + uint32_t (*device_getwidth)(device_t device); + uint32_t (*device_getheight)(device_t device); + texture_t (*device_create_texture)(device_t device, uint32_t width, + uint32_t height, enum gs_color_format color_format, + void *data, uint32_t flags); + texture_t (*device_create_cubetexture)(device_t device, uint32_t size, + enum gs_color_format color_format, void *data[6], + uint32_t flags); + texture_t (*device_create_volumetexture)(device_t device, + uint32_t width, uint32_t height, uint32_t depth, + enum gs_color_format color_format, void *data, + uint32_t flags); + zstencil_t (*device_create_zstencil)(device_t device, + uint32_t width, uint32_t height, + enum gs_zstencil_format format); + stagesurf_t (*device_create_stagesurface)(device_t device, + uint32_t width, uint32_t height, + enum gs_color_format color_format); + samplerstate_t (*device_create_samplerstate)(device_t device, + struct gs_sampler_info *info); + shader_t (*device_create_vertexshader)(device_t device, + const char *shader, const char *file, + char **error_string); + shader_t (*device_create_pixelshader)(device_t device, + const char *shader, const char *file, + char **error_string); + vertbuffer_t (*device_create_vertexbuffer)(device_t device, + struct vb_data *data, uint32_t flags); + indexbuffer_t (*device_create_indexbuffer)(device_t device, + enum gs_index_type type, void *indices, size_t num, + uint32_t flags); + enum gs_texture_type (*device_gettexturetype)(device_t device, + texture_t texture); + void (*device_load_vertexbuffer)(device_t device, + vertbuffer_t vertbuffer); + void (*device_load_indexbuffer)(device_t device, + indexbuffer_t indexbuffer); + void (*device_load_texture)(device_t device, texture_t tex, int unit); + void (*device_load_samplerstate)(device_t device, + samplerstate_t samplerstate, int unit); + void (*device_load_vertexshader)(device_t device, shader_t vertshader); + void (*device_load_pixelshader)(device_t device, shader_t pixelshader); + void (*device_load_defaultsamplerstate)(device_t device, bool b_3d, + int unit); + shader_t (*device_getvertexshader)(device_t device); + shader_t (*device_getpixelshader)(device_t device); + texture_t (*device_getrendertarget)(device_t device); + zstencil_t (*device_getzstenciltarget)(device_t device); + void (*device_setrendertarget)(device_t device, texture_t tex, + zstencil_t zstencil); + void (*device_setcuberendertarget)(device_t device, texture_t cubetex, + int side, zstencil_t zstencil); + void (*device_copy_texture)(device_t device, texture_t dst, + texture_t src); + void (*device_stage_texture)(device_t device, stagesurf_t dst, + texture_t src); + void (*device_beginscene)(device_t device); + void (*device_draw)(device_t device, enum gs_draw_mode draw_mode, + uint32_t start_vert, uint32_t num_verts); + void (*device_endscene)(device_t device); + void (*device_load_swapchain)(device_t device, swapchain_t swaphchain); + void (*device_clear)(device_t device, uint32_t clear_flags, + struct vec4 *color, float depth, uint8_t stencil); + void (*device_present)(device_t device); + void (*device_setcullmode)(device_t device, enum gs_cull_mode mode); + enum gs_cull_mode (*device_getcullmode)(device_t device); + void (*device_enable_blending)(device_t device, bool enable); + void (*device_enable_depthtest)(device_t device, bool enable); + void (*device_enable_stenciltest)(device_t device, bool enable); + void (*device_enable_stencilwrite)(device_t device, bool enable); + void (*device_enable_color)(device_t device, bool red, bool blue, + bool green, bool alpha); + void (*device_blendfunction)(device_t device, enum gs_blend_type src, + enum gs_blend_type dest); + void (*device_depthfunction)(device_t device, enum gs_depth_test test); + void (*device_stencilfunction)(device_t device, + enum gs_stencil_side side, enum gs_depth_test test); + void (*device_stencilop)(device_t device, enum gs_stencil_side side, + enum gs_stencil_op fail, enum gs_stencil_op zfail, + enum gs_stencil_op zpass); + void (*device_enable_fullscreen)(device_t device, bool enable); + int (*device_fullscreen_enabled)(device_t device); + void (*device_setdisplaymode)(device_t device, + const struct gs_display_mode *mode); + void (*device_getdisplaymode)(device_t device, + struct gs_display_mode *mode); + void (*device_setcolorramp)(device_t device, float gamma, + float brightness, float contrast); + void (*device_setviewport)(device_t device, int x, int y, int width, + int height); + void (*device_getviewport)(device_t device, struct gs_rect *rect); + void (*device_setscissorrect)(device_t device, struct gs_rect *rect); + void (*device_ortho)(device_t device, float left, float right, + float top, float bottom, float znear, float zfar); + void (*device_frustum)(device_t device, float left, float right, + float top, float bottom, float znear, float zfar); + void (*device_perspective)(device_t device, float fovy, float aspect, + float znear, float zfar); + void (*device_projection_push)(device_t device); + void (*device_projection_pop)(device_t device); + + void (*swapchain_destroy)(swapchain_t swapchain); + + void (*texture_destroy)(texture_t tex); + uint32_t (*texture_getwidth)(texture_t tex); + uint32_t (*texture_getheight)(texture_t tex); + enum gs_color_format (*texture_getcolorformat)(texture_t tex); + bool (*texture_map)(texture_t tex, void **ptr, + uint32_t *byte_width); + void (*texture_unmap)(texture_t tex); + + void (*cubetexture_destroy)(texture_t cubetex); + uint32_t (*cubetexture_getsize)(texture_t cubetex); + enum gs_color_format (*cubetexture_getcolorformat)(texture_t cubetex); + + void (*volumetexture_destroy)(texture_t voltex); + uint32_t (*volumetexture_getwidth)(texture_t voltex); + uint32_t (*volumetexture_getheight)(texture_t voltex); + uint32_t (*volumetexture_getdepth)(texture_t voltex); + enum gs_color_format (*volumetexture_getcolorformat)(texture_t voltex); + + void (*stagesurface_destroy)(stagesurf_t stagesurf); + uint32_t (*stagesurface_getwidth)(stagesurf_t stagesurf); + uint32_t (*stagesurface_getheight)(stagesurf_t stagesurf); + enum gs_color_format (*stagesurface_getcolorformat)( + stagesurf_t stagesurf); + bool (*stagesurface_map)(stagesurf_t stagesurf, const void **data, + uint32_t *byte_width); + void (*stagesurface_unmap)(stagesurf_t stagesurf); + + void (*zstencil_destroy)(zstencil_t zstencil); + + void (*samplerstate_destroy)(samplerstate_t samplerstate); + + void (*vertexbuffer_destroy)(vertbuffer_t vertbuffer); + void (*vertexbuffer_flush)(vertbuffer_t vertbuffer, bool rebuild); + struct vb_data *(*vertexbuffer_getdata)(vertbuffer_t vertbuffer); + + void (*indexbuffer_destroy)(indexbuffer_t indexbuffer); + void (*indexbuffer_flush)(indexbuffer_t indexbuffer); + void *(*indexbuffer_getdata)(indexbuffer_t indexbuffer); + size_t (*indexbuffer_numindices)(indexbuffer_t indexbuffer); + enum gs_index_type (*indexbuffer_gettype)(indexbuffer_t indexbuffer); + + void (*shader_destroy)(shader_t shader); + int (*shader_numparams)(shader_t shader); + sparam_t (*shader_getparambyidx)(shader_t shader, int param); + sparam_t (*shader_getparambyname)(shader_t shader, const char *name); + void (*shader_getparaminfo)(shader_t shader, sparam_t param, + struct shader_param_info *info); + sparam_t (*shader_getviewprojmatrix)(shader_t shader); + sparam_t (*shader_getworldmatrix)(shader_t shader); + void (*shader_setbool)(shader_t shader, sparam_t param, bool val); + void (*shader_setfloat)(shader_t shader, sparam_t param, float val); + void (*shader_setint)(shader_t shader, sparam_t param, int val); + void (*shader_setmatrix3)(shader_t shader, sparam_t param, + const struct matrix3 *val); + void (*shader_setmatrix4)(shader_t shader, sparam_t param, + const struct matrix4 *val); + void (*shader_setvec2)(shader_t shader, sparam_t param, + const struct vec2 *val); + void (*shader_setvec3)(shader_t shader, sparam_t param, + const struct vec3 *val); + void (*shader_setvec4)(shader_t shader, sparam_t param, + const struct vec4 *val); + void (*shader_settexture)(shader_t shader, sparam_t param, + texture_t val); + void (*shader_setval)(shader_t shader, sparam_t param, const void *val, + size_t size); + void (*shader_setdefault)(shader_t shader, sparam_t param); +}; + +struct graphics_subsystem { + void *module; + device_t device; + struct gs_exports exports; + + DARRAY(struct gs_rect) viewport_stack; + + DARRAY(struct matrix3) matrix_stack; + size_t cur_matrix; + + struct matrix4 projection; + struct gs_effect *cur_effect; + + vertbuffer_t sprite_buffer; + + bool using_immediate; + struct vb_data *vbd; + vertbuffer_t immediate_vertbuffer; + DARRAY(struct vec3) verts; + DARRAY(struct vec3) norms; + DARRAY(uint32_t) colors; + DARRAY(struct vec2) texverts[16]; +}; + +#endif diff --git a/libobs/graphics/graphics.c b/libobs/graphics/graphics.c new file mode 100644 index 000000000..eb72ee3a4 --- /dev/null +++ b/libobs/graphics/graphics.c @@ -0,0 +1,1397 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include + +#include "../util/base.h" +#include "../util/bmem.h" +#include "../util/platform.h" +#include "graphics-internal.h" +#include "vec2.h" +#include "vec3.h" +#include "quat.h" +#include "axisang.h" +#include "effect-parser.h" +#include "effect.h" + +#if 0 + +#ifdef _MSC_VER +static __declspec(thread) graphics_t thread_graphics = NULL; +#else /* assume GCC or that other compiler we dare not mention */ +static __thread graphics_t thread_graphics = NULL; +#endif + +#else +static graphics_t thread_graphics = NULL; +#endif + +#define IMMEDIATE_VERTEX_COUNT 512 + +bool load_graphics_imports(struct gs_exports *exports, void *module, + const char *module_name); + +static bool graphics_init(struct graphics_subsystem *graphics) +{ + struct matrix3 top_mat; + struct vb_data *vbd; + + matrix3_identity(&top_mat); + da_push_back(graphics->matrix_stack, &top_mat); + + vbd = vbdata_create(); + vbd->num = IMMEDIATE_VERTEX_COUNT; + vbd->points = bmalloc(sizeof(struct vec3) * IMMEDIATE_VERTEX_COUNT); + vbd->normals = bmalloc(sizeof(struct vec3) * IMMEDIATE_VERTEX_COUNT); + vbd->colors = bmalloc(sizeof(uint32_t) * IMMEDIATE_VERTEX_COUNT); + vbd->num_tex = 1; + vbd->tvarray = bmalloc(sizeof(struct tvertarray)); + vbd->tvarray[0].width = 2; + vbd->tvarray[0].array = + bmalloc(sizeof(struct vec2) * IMMEDIATE_VERTEX_COUNT); + + graphics->immediate_vertbuffer = graphics->exports. + device_create_vertexbuffer(graphics->device, vbd, GS_DYNAMIC); + if (!graphics->immediate_vertbuffer) + return false; + + vbd = vbdata_create(); + vbd->num = 4; + vbd->points = bmalloc(sizeof(struct vec3) * 4); + vbd->num_tex = 1; + vbd->tvarray = bmalloc(sizeof(struct tvertarray)); + vbd->tvarray[0].width = 2; + vbd->tvarray[0].array = bmalloc(sizeof(struct vec2) * 4); + + memset(vbd->points, 0, sizeof(struct vec3) * 4); + memset(vbd->tvarray[0].array, 0, sizeof(struct vec2) * 4); + + graphics->sprite_buffer = graphics->exports. + device_create_vertexbuffer(graphics->device, vbd, GS_DYNAMIC); + if (!graphics->sprite_buffer) + return false; + + return true; +} + +int gs_create(graphics_t *pgraphics, const char *module, + struct gs_init_data *data) +{ + int errcode = GS_ERROR_FAIL; + + graphics_t graphics = bmalloc(sizeof(struct graphics_subsystem)); + memset(graphics, 0, sizeof(struct graphics_subsystem)); + + graphics->module = os_dlopen(module); + if (!graphics->module) { + errcode = GS_ERROR_MODULENOTFOUND; + goto error; + } + + if (!load_graphics_imports(&graphics->exports, graphics->module, + module)) + goto error; + + graphics->device = graphics->exports.device_create(data); + if (!graphics->device) + goto error; + + if (!graphics_init(graphics)) + goto error; + + *pgraphics = graphics; + return GS_SUCCESS; + +error: + gs_destroy(graphics); + return errcode; +} + +void gs_destroy(graphics_t graphics) +{ + if (!graphics) + return; + + if (graphics->module) { + graphics->exports.vertexbuffer_destroy(graphics->sprite_buffer); + graphics->exports.vertexbuffer_destroy( + graphics->immediate_vertbuffer); + graphics->exports.device_destroy(graphics->device); + } + + da_free(graphics->matrix_stack); + da_free(graphics->viewport_stack); + os_dlclose(graphics->module); + bfree(graphics); + + if (thread_graphics == graphics) + thread_graphics = NULL; +} + +void gs_setcontext(graphics_t graphics) +{ + thread_graphics = graphics; +} + +graphics_t gs_getcontext(void) +{ + return thread_graphics; +} + +static inline struct matrix3 *top_matrix(graphics_t graphics) +{ + return graphics->matrix_stack.array + graphics->cur_matrix; +} + +void gs_matrix_push(void) +{ + graphics_t graphics = thread_graphics; + struct matrix3 mat, *top_mat = top_matrix(graphics); + + memcpy(&mat, top_mat, sizeof(struct matrix3)); + da_push_back(graphics->matrix_stack, &mat); + graphics->cur_matrix++; +} + +void gs_matrix_pop(void) +{ + graphics_t graphics = thread_graphics; + + if (graphics->cur_matrix == 0) { + blog(LOG_ERROR, "Tried to pop last matrix on stack"); + return; + } + + da_erase(graphics->matrix_stack, graphics->cur_matrix); + graphics->cur_matrix--; +} + +void gs_matrix_identity(void) +{ + struct matrix3 *top_mat = top_matrix(thread_graphics); + matrix3_identity(top_mat); +} + +void gs_matrix_transpose(void) +{ + struct matrix3 *top_mat = top_matrix(thread_graphics); + matrix3_transpose(top_mat, top_mat); +} + +void gs_matrix_set(const struct matrix3 *matrix) +{ + struct matrix3 *top_mat = top_matrix(thread_graphics); + matrix3_copy(top_mat, matrix); +} + +void gs_matrix_get(struct matrix3 *dst) +{ + struct matrix3 *top_mat = top_matrix(thread_graphics); + matrix3_copy(dst, top_mat); +} + +void gs_matrix_mul(const struct matrix3 *matrix) +{ + struct matrix3 *top_mat = top_matrix(thread_graphics); + matrix3_mul(top_mat, top_mat, matrix); +} + +void gs_matrix_rotquat(const struct quat *rot) +{ + struct matrix3 *top_mat = top_matrix(thread_graphics); + matrix3_rotate(top_mat, top_mat, rot); +} + +void gs_matrix_rotaa(const struct axisang *rot) +{ + struct matrix3 *top_mat = top_matrix(thread_graphics); + matrix3_rotate_aa(top_mat, top_mat, rot); +} + +void gs_matrix_translate(const struct vec3 *pos) +{ + struct matrix3 *top_mat = top_matrix(thread_graphics); + matrix3_translate(top_mat, top_mat, pos); +} + +void gs_matrix_scale(const struct vec3 *scale) +{ + struct matrix3 *top_mat = top_matrix(thread_graphics); + matrix3_scale(top_mat, top_mat, scale); +} + +void gs_matrix_rotaa4f(float x, float y, float z, float angle) +{ + struct matrix3 *top_mat = top_matrix(thread_graphics); + struct axisang aa; + + axisang_set(&aa, x, y, z, angle); + matrix3_rotate_aa(top_mat, top_mat, &aa); +} + +void gs_matrix_translate3f(float x, float y, float z) +{ + struct matrix3 *top_mat = top_matrix(thread_graphics); + struct vec3 p; + + vec3_set(&p, x, y, z); + matrix3_translate(top_mat, top_mat, &p); +} + +void gs_matrix_scale3f(float x, float y, float z) +{ + struct matrix3 *top_mat = top_matrix(thread_graphics); + struct vec3 p; + + vec3_set(&p, x, y, z); + matrix3_scale(top_mat, top_mat, &p); +} + +static inline void reset_immediate_arrays(graphics_t graphics) +{ + size_t i; + + da_init(graphics->verts); + da_init(graphics->norms); + da_init(graphics->colors); + for (i = 0; i < 16; i++) + da_init(graphics->texverts[i]); +} + +void gs_renderstart(bool b_new) +{ + graphics_t graphics = thread_graphics; + + graphics->using_immediate = !b_new; + reset_immediate_arrays(graphics); + + if (b_new) { + graphics->vbd = vbdata_create(); + } else { + graphics->vbd = vertexbuffer_getdata( + graphics->immediate_vertbuffer); + memset(graphics->vbd->colors, 0xFF, + sizeof(uint32_t) * IMMEDIATE_VERTEX_COUNT); + + graphics->verts.array = graphics->vbd->points; + graphics->norms.array = graphics->vbd->normals; + graphics->colors.array = graphics->vbd->colors; + graphics->texverts[0].array = graphics->vbd->tvarray[0].array; + + graphics->verts.capacity = IMMEDIATE_VERTEX_COUNT; + graphics->norms.capacity = IMMEDIATE_VERTEX_COUNT; + graphics->colors.capacity = IMMEDIATE_VERTEX_COUNT; + graphics->texverts[0].capacity = IMMEDIATE_VERTEX_COUNT; + } +} + +static inline size_t min_size(const size_t a, const size_t b) +{ + return (a < b) ? a : b; +} + +void gs_renderstop(enum gs_draw_mode mode) +{ + graphics_t graphics = thread_graphics; + size_t i, num = graphics->verts.num; + + if (!num) { + if (!graphics->using_immediate) { + da_free(graphics->verts); + da_free(graphics->norms); + da_free(graphics->colors); + for (i = 0; i < 16; i++) + da_free(graphics->texverts[i]); + vbdata_destroy(graphics->vbd); + } + + return; + } + + if (graphics->norms.num && + (graphics->norms.num != graphics->verts.num)) { + blog(LOG_WARNING, "gs_renderstop: normal count does " + "not match vertex count"); + num = min_size(num, graphics->norms.num); + } + + if (graphics->colors.num && + (graphics->colors.num != graphics->verts.num)) { + blog(LOG_WARNING, "gs_renderstop: color count does " + "not match vertex count"); + num = min_size(num, graphics->colors.num); + } + + if (graphics->texverts[0].num && + (graphics->texverts[0].num != graphics->verts.num)) { + blog(LOG_WARNING, "gs_renderstop: texture vertex count does " + "not match vertex count"); + num = min_size(num, graphics->texverts[0].num); + } + + if (graphics->using_immediate) { + vertexbuffer_flush(graphics->immediate_vertbuffer, false); + + gs_load_vertexbuffer(graphics->immediate_vertbuffer); + gs_load_indexbuffer(NULL); + gs_draw(mode, 0, (uint32_t)num); + + reset_immediate_arrays(graphics); + } else { + vertbuffer_t vb = gs_rendersave(); + + gs_load_vertexbuffer(vb); + gs_load_indexbuffer(NULL); + gs_draw(mode, 0, 0); + + vertexbuffer_destroy(vb); + } + + graphics->vbd = NULL; +} + +vertbuffer_t gs_rendersave(void) +{ + graphics_t graphics = thread_graphics; + size_t num_tex, i; + + if (graphics->using_immediate) + return NULL; + + if (!graphics->vbd->num) { + vbdata_destroy(graphics->vbd); + return NULL; + } + + for (num_tex = 0; num_tex < 16; num_tex++) { + if (!graphics->texverts[num_tex].num) + break; + } + + graphics->vbd->points = graphics->verts.array; + graphics->vbd->normals = graphics->norms.array; + graphics->vbd->colors = graphics->colors.array; + graphics->vbd->num = graphics->verts.num; + graphics->vbd->num_tex = num_tex; + graphics->vbd->tvarray = bmalloc(sizeof(struct tvertarray) * num_tex); + for (i = 0; i < num_tex; i++) { + graphics->vbd->tvarray[i].width = 2; + graphics->vbd->tvarray[i].array = graphics->texverts[i].array; + } + + reset_immediate_arrays(graphics); + + return gs_create_vertexbuffer(graphics->vbd, 0); +} + +void gs_vertex2f(float x, float y) +{ + struct vec3 v3; + + vec3_set(&v3, x, y, 0.0f); + gs_vertex3v(&v3); +} + +void gs_vertex3f(float x, float y, float z) +{ + struct vec3 v3; + + vec3_set(&v3, x, y, z); + gs_vertex3v(&v3); +} + +void gs_normal3f(float x, float y, float z) +{ + struct vec3 v3; + + vec3_set(&v3, x, y, z); + gs_normal3v(&v3); +} + +static inline bool validvertsize(graphics_t graphics, size_t num, + const char *name) +{ + if (graphics->using_immediate && + graphics->colors.num == IMMEDIATE_VERTEX_COUNT) { + blog(LOG_WARNING, "%s: tried to use over %u " + "for immediate rendering", + name, IMMEDIATE_VERTEX_COUNT); + return false; + } + + return true; +} + +void gs_color(uint32_t color) +{ + graphics_t graphics = thread_graphics; + if (!validvertsize(graphics, graphics->colors.num, "gs_color")) + return; + + da_push_back(graphics->colors, &color); +} + +void gs_texcoord(float x, float y, int unit) +{ + struct vec2 v2; + + vec2_set(&v2, x, y); + gs_texcoord2v(&v2, unit); +} + +void gs_vertex2v(const struct vec2 *v) +{ + struct vec3 v3; + + vec3_set(&v3, v->x, v->y, 0.0f); + gs_vertex3v(&v3); +} + +void gs_vertex3v(const struct vec3 *v) +{ + graphics_t graphics = thread_graphics; + if (!validvertsize(graphics, graphics->verts.num, "gs_vertex")) + return; + + da_push_back(graphics->verts, v); +} + +void gs_normal3v(const struct vec3 *v) +{ + graphics_t graphics = thread_graphics; + if (!validvertsize(graphics, graphics->norms.num, "gs_normal")) + return; + + da_push_back(graphics->norms, v); +} + +void gs_color4v(const struct vec4 *v) +{ + /* TODO */ +} + +void gs_texcoord2v(const struct vec2 *v, int unit) +{ + graphics_t graphics = thread_graphics; + if (!validvertsize(graphics, graphics->texverts[unit].num, + "gs_texcoord")) + return; + + da_push_back(graphics->texverts[unit], v); +} + +input_t gs_getinput(void) +{ + /* TODO */ + return NULL; +} + +effect_t gs_geteffect(void) +{ + return thread_graphics->cur_effect; +} + +effect_t gs_create_effect_from_file(const char *file, char **error_string) +{ + char *file_string; + effect_t effect = NULL; + + file_string = os_quick_read_utf8_file(file); + if (!file_string) { + blog(LOG_WARNING, "Could not load effect file '%s'", file); + return NULL; + } + + effect = gs_create_effect(file_string, file, error_string); + bfree(file_string); + + return effect; +} + +effect_t gs_create_effect(const char *effect_string, const char *filename, + char **error_string) +{ + struct gs_effect *effect = bmalloc(sizeof(struct gs_effect)); + struct effect_parser parser; + bool success; + + memset(effect, 0, sizeof(struct gs_effect)); + effect->graphics = thread_graphics; + + ep_init(&parser); + success = ep_parse(&parser, effect, effect_string, filename); + if (!success) { + *error_string = error_data_buildstring( + &parser.cfp.error_list); + effect_destroy(effect); + effect = NULL; + } + + ep_free(&parser); + return effect; +} + +shader_t gs_create_vertexshader_from_file(const char *file, + char **error_string) +{ + char *file_string; + shader_t shader = NULL; + + file_string = os_quick_read_utf8_file(file); + if (!file_string) { + blog(LOG_WARNING, "Could not load vertex shader file '%s'", + file); + return NULL; + } + + shader = gs_create_vertexshader(file_string, file, error_string); + bfree(file_string); + + return shader; +} + +shader_t gs_create_pixelshader_from_file(const char *file, + char **error_string) +{ + char *file_string; + shader_t shader = NULL; + + file_string = os_quick_read_utf8_file(file); + if (!file_string) { + blog(LOG_WARNING, "Could not load pixel shader file '%s'", + file); + return NULL; + } + + shader = gs_create_pixelshader(file_string, file, error_string); + bfree(file_string); + + return shader; +} + +texture_t gs_create_texture_from_file(const char *file, uint32_t flags) +{ + /* TODO */ + return NULL; +} + +texture_t gs_create_cubetexture_from_file(const char *flie, uint32_t flags) +{ + /* TODO */ + return NULL; +} + +texture_t gs_create_volumetexture_from_file(const char *flie, uint32_t flags) +{ + /* TODO */ + return NULL; +} + +void gs_draw_sprite(texture_t tex) +{ + graphics_t graphics = thread_graphics; + float fcx, fcy; + struct vb_data *data; + struct vec2 *tvarray; + + assert(tex); + + if (gs_gettexturetype(tex) != GS_TEXTURE_2D) { + blog(LOG_ERROR, "A sprite must be a 2D texture"); + return; + } + + fcx = (float)texture_getwidth(tex); + fcy = (float)texture_getheight(tex); + + data = vertexbuffer_getdata(graphics->sprite_buffer); + tvarray = data->tvarray[0].array; + vec3_zero(data->points); + vec3_set(data->points+1, fcx, 0.0f, 0.0f); + vec3_set(data->points+2, 0.0f, fcy, 0.0f); + vec3_set(data->points+3, fcx, fcy, 0.0f); + vec2_zero(tvarray); + vec2_set(tvarray+1, 1.0f, 0.0f); + vec2_set(tvarray+2, 0.0f, 1.0f); + vec2_set(tvarray+3, 1.0f, 1.0f); + vertexbuffer_flush(graphics->sprite_buffer, false); + gs_load_vertexbuffer(graphics->sprite_buffer); + + gs_draw(GS_TRISTRIP, 0, 0); +} + +void gs_draw_cube_backdrop(texture_t cubetex, const struct quat *rot, + float left, float right, float top, float bottom, float znear) +{ + /* TODO */ +} + +void gs_resetviewport(void) +{ + uint32_t cx, cy; + gs_getsize(&cx, &cy); + gs_setviewport(0, 0, cx, cy); +} + +void gs_set2dmode(void) +{ + uint32_t cx, cy; + gs_getsize(&cx, &cy); + + gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -1.0, -1024.0f); +} + +void gs_set3dmode(double fovy, double znear, double zvar) +{ + /* TODO */ +} + +void gs_viewport_push(void) +{ + struct gs_rect *rect = da_push_back_new( + thread_graphics->viewport_stack); + gs_getviewport(rect); +} + +void gs_viewport_pop(void) +{ + struct gs_rect *rect; + if (!thread_graphics->viewport_stack.num) + return; + + rect = da_end(thread_graphics->viewport_stack); + gs_setviewport(rect->x, rect->y, rect->cx, rect->cy); + da_pop_back(thread_graphics->viewport_stack); +} + +void texture_setimage(texture_t tex, const void *data, uint32_t byte_width) +{ + /* TODO */ +} + +void cubetexture_setimage(texture_t cubetex, uint32_t side, const void *data, + uint32_t byte_width) +{ + /* TODO */ +} + +/* ------------------------------------------------------------------------- */ + +swapchain_t gs_create_swapchain(struct gs_init_data *data) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_create_swapchain(graphics->device, + data); +} + +void gs_resize(uint32_t x, uint32_t y) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_resize(graphics->device, x, y); +} + +void gs_getsize(uint32_t *x, uint32_t *y) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_getsize(graphics->device, x, y); +} + +uint32_t gs_getwidth(void) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_getwidth(graphics->device); +} + +uint32_t gs_getheight(void) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_getheight(graphics->device); +} + +texture_t gs_create_texture(uint32_t width, uint32_t height, + enum gs_color_format color_format, void *data, uint32_t flags) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_create_texture(graphics->device, + width, height, color_format, data, flags); +} + +texture_t gs_create_cubetexture(uint32_t size, + enum gs_color_format color_format, void *data[6], + uint32_t flags) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_create_cubetexture(graphics->device, + size, color_format, data, flags); +} + +texture_t gs_create_volumetexture(uint32_t width, uint32_t height, + uint32_t depth, enum gs_color_format color_format, void *data, + uint32_t flags) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_create_volumetexture(graphics->device, + width, height, depth, color_format, data, flags); +} + +zstencil_t gs_create_zstencil(uint32_t width, uint32_t height, + enum gs_zstencil_format format) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_create_zstencil(graphics->device, + width, height, format); +} + +stagesurf_t gs_create_stagesurface(uint32_t width, uint32_t height, + enum gs_color_format color_format) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_create_stagesurface(graphics->device, + width, height, color_format); +} + +samplerstate_t gs_create_samplerstate(struct gs_sampler_info *info) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_create_samplerstate(graphics->device, + info); +} + +shader_t gs_create_vertexshader(const char *shader, const char *file, + char **error_string) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_create_vertexshader(graphics->device, + shader, file, error_string); +} + +shader_t gs_create_pixelshader(const char *shader, + const char *file, char **error_string) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_create_pixelshader(graphics->device, + shader, file, error_string); +} + +vertbuffer_t gs_create_vertexbuffer(struct vb_data *data, + uint32_t flags) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_create_vertexbuffer(graphics->device, + data, flags); +} + +indexbuffer_t gs_create_indexbuffer(enum gs_index_type type, + void *indices, size_t num, uint32_t flags) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_create_indexbuffer(graphics->device, + type, indices, num, flags); +} + +enum gs_texture_type gs_gettexturetype(texture_t texture) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_gettexturetype(graphics->device, + texture); +} + +void gs_load_vertexbuffer(vertbuffer_t vertbuffer) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_load_vertexbuffer(graphics->device, + vertbuffer); +} + +void gs_load_indexbuffer(indexbuffer_t indexbuffer) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_load_indexbuffer(graphics->device, + indexbuffer); +} + +void gs_load_texture(texture_t tex, int unit) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_load_texture(graphics->device, tex, unit); +} + +void gs_load_samplerstate(samplerstate_t samplerstate, int unit) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_load_samplerstate(graphics->device, + samplerstate, unit); +} + +void gs_load_vertexshader(shader_t vertshader) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_load_vertexshader(graphics->device, + vertshader); +} + +void gs_load_pixelshader(shader_t pixelshader) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_load_pixelshader(graphics->device, + pixelshader); +} + +void gs_load_defaultsamplerstate(bool b_3d, int unit) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_load_defaultsamplerstate(graphics->device, + b_3d, unit); +} + +shader_t gs_getvertexshader(void) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_getvertexshader(graphics->device); +} + +shader_t gs_getpixelshader(void) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_getpixelshader(graphics->device); +} + +texture_t gs_getrendertarget(void) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_getrendertarget(graphics->device); +} + +zstencil_t gs_getzstenciltarget(void) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_getzstenciltarget(graphics->device); +} + +void gs_setrendertarget(texture_t tex, zstencil_t zstencil) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_setrendertarget(graphics->device, tex, + zstencil); +} + +void gs_setcuberendertarget(texture_t cubetex, int side, zstencil_t zstencil) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_setcuberendertarget(graphics->device, cubetex, + side, zstencil); +} + +void gs_copy_texture(texture_t dst, texture_t src) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_copy_texture(graphics->device, dst, src); +} + +void gs_stage_texture(stagesurf_t dst, texture_t src) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_stage_texture(graphics->device, dst, src); +} + +void gs_beginscene(void) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_beginscene(graphics->device); +} + +void gs_draw(enum gs_draw_mode draw_mode, uint32_t start_vert, + uint32_t num_verts) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_draw(graphics->device, draw_mode, + start_vert, num_verts); +} + +void gs_endscene(void) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_endscene(graphics->device); +} + +void gs_load_swapchain(swapchain_t swapchain) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_load_swapchain(graphics->device, swapchain); +} + +void gs_clear(uint32_t clear_flags, struct vec4 *color, float depth, + uint8_t stencil) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_clear(graphics->device, clear_flags, color, + depth, stencil); +} + +void gs_present(void) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_present(graphics->device); +} + +void gs_setcullmode(enum gs_cull_mode mode) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_setcullmode(graphics->device, mode); +} + +enum gs_cull_mode gs_getcullmode(void) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_getcullmode(graphics->device); +} + +void gs_enable_blending(bool enable) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_enable_blending(graphics->device, enable); +} + +void gs_enable_depthtest(bool enable) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_enable_depthtest(graphics->device, enable); +} + +void gs_enable_stenciltest(bool enable) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_enable_stenciltest(graphics->device, enable); +} + +void gs_enable_stencilwrite(bool enable) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_enable_stencilwrite(graphics->device, enable); +} + +void gs_enable_color(bool red, bool blue, bool green, bool alpha) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_enable_color(graphics->device, red, blue, + green, alpha); +} + +void gs_blendfunction(enum gs_blend_type src, enum gs_blend_type dest) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_blendfunction(graphics->device, src, dest); +} + +void gs_depthfunction(enum gs_depth_test test) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_depthfunction(graphics->device, test); +} + +void gs_stencilfunction(enum gs_stencil_side side, enum gs_depth_test test) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_stencilfunction(graphics->device, side, test); +} + +void gs_stencilop(enum gs_stencil_side side, enum gs_stencil_op fail, + enum gs_stencil_op zfail, enum gs_stencil_op zpass) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_stencilop(graphics->device, side, fail, zfail, + zpass); +} + +void gs_enable_fullscreen(bool enable) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_enable_fullscreen(graphics->device, enable); +} + +int gs_fullscreen_enabled(void) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.device_fullscreen_enabled(graphics->device); +} + +void gs_setdisplaymode(const struct gs_display_mode *mode) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_setdisplaymode(graphics->device, mode); +} + +void gs_getdisplaymode(struct gs_display_mode *mode) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_getdisplaymode(graphics->device, mode); +} + +void gs_setcolorramp(float gamma, float brightness, float contrast) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_setcolorramp(graphics->device, gamma, + brightness, contrast); +} + +void gs_setviewport(int x, int y, int width, int height) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_setviewport(graphics->device, x, y, width, + height); +} + +void gs_getviewport(struct gs_rect *rect) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_getviewport(graphics->device, rect); +} + +void gs_setscissorrect(struct gs_rect *rect) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_setscissorrect(graphics->device, rect); +} + +void gs_ortho(float left, float right, float top, float bottom, float znear, + float zfar) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_ortho(graphics->device, left, right, top, + bottom, znear, zfar); +} + +void gs_frustum(float left, float right, float top, float bottom, float znear, + float zfar) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_frustum(graphics->device, left, right, top, + bottom, znear, zfar); +} + +void gs_perspective(float fovy, float aspect, float znear, float zfar) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_perspective(graphics->device, fovy, aspect, + znear, zfar); +} + +void gs_projection_push(void) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_projection_push(graphics->device); +} + +void gs_projection_pop(void) +{ + graphics_t graphics = thread_graphics; + graphics->exports.device_projection_pop(graphics->device); +} + +void swapchain_destroy(swapchain_t swapchain) +{ + graphics_t graphics = thread_graphics; + graphics->exports.swapchain_destroy(swapchain); +} + +void shader_destroy(shader_t shader) +{ + graphics_t graphics = thread_graphics; + graphics->exports.shader_destroy(shader); +} + +int shader_numparams(shader_t shader) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.shader_numparams(shader); +} + +sparam_t shader_getparambyidx(shader_t shader, int param) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.shader_getparambyidx(shader, param); +} + +sparam_t shader_getparambyname(shader_t shader, const char *name) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.shader_getparambyname(shader, name); +} + +void shader_getparaminfo(shader_t shader, sparam_t param, + struct shader_param_info *info) +{ + graphics_t graphics = thread_graphics; + graphics->exports.shader_getparaminfo(shader, param, info); +} + +sparam_t shader_getviewprojmatrix(shader_t shader) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.shader_getviewprojmatrix(shader); +} + +sparam_t shader_getworldmatrix(shader_t shader) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.shader_getworldmatrix(shader); +} + +void shader_setbool(shader_t shader, sparam_t param, bool val) +{ + graphics_t graphics = thread_graphics; + graphics->exports.shader_setbool(shader, param, val); +} + +void shader_setfloat(shader_t shader, sparam_t param, float val) +{ + graphics_t graphics = thread_graphics; + graphics->exports.shader_setfloat(shader, param, val); +} + +void shader_setint(shader_t shader, sparam_t param, int val) +{ + graphics_t graphics = thread_graphics; + graphics->exports.shader_setint(shader, param, val); +} + +void shader_setmatrix3(shader_t shader, sparam_t param, + const struct matrix3 *val) +{ + graphics_t graphics = thread_graphics; + graphics->exports.shader_setmatrix3(shader, param, val); +} + +void shader_setmatrix4(shader_t shader, sparam_t param, + const struct matrix4 *val) +{ + graphics_t graphics = thread_graphics; + graphics->exports.shader_setmatrix4(shader, param, val); +} + +void shader_setvec2(shader_t shader, sparam_t param, + const struct vec2 *val) +{ + graphics_t graphics = thread_graphics; + graphics->exports.shader_setvec2(shader, param, val); +} + +void shader_setvec3(shader_t shader, sparam_t param, + const struct vec3 *val) +{ + graphics_t graphics = thread_graphics; + graphics->exports.shader_setvec3(shader, param, val); +} + +void shader_setvec4(shader_t shader, sparam_t param, + const struct vec4 *val) +{ + graphics_t graphics = thread_graphics; + graphics->exports.shader_setvec4(shader, param, val); +} + +void shader_settexture(shader_t shader, sparam_t param, texture_t val) +{ + graphics_t graphics = thread_graphics; + graphics->exports.shader_settexture(shader, param, val); +} + +void shader_setval(shader_t shader, sparam_t param, const void *val, + size_t size) +{ + graphics_t graphics = thread_graphics; + graphics->exports.shader_setval(shader, param, val, size); +} + +void shader_setdefault(shader_t shader, sparam_t param) +{ + graphics_t graphics = thread_graphics; + graphics->exports.shader_setdefault(shader, param); +} + +void texture_destroy(texture_t tex) +{ + graphics_t graphics = thread_graphics; + graphics->exports.texture_destroy(tex); +} + +uint32_t texture_getwidth(texture_t tex) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.texture_getwidth(tex); +} + +uint32_t texture_getheight(texture_t tex) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.texture_getheight(tex); +} + +enum gs_color_format texture_getcolorformat(texture_t tex) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.texture_getcolorformat(tex); +} + +bool texture_map(texture_t tex, void **ptr, uint32_t *byte_width) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.texture_map(tex, ptr, byte_width); +} + +void texture_unmap(texture_t tex) +{ + graphics_t graphics = thread_graphics; + graphics->exports.texture_unmap(tex); +} + +void cubetexture_destroy(texture_t cubetex) +{ + graphics_t graphics = thread_graphics; + graphics->exports.cubetexture_destroy(cubetex); +} + +uint32_t cubetexture_getsize(texture_t cubetex) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.cubetexture_getsize(cubetex); +} + +enum gs_color_format cubetexture_getcolorformat(texture_t cubetex) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.cubetexture_getcolorformat(cubetex); +} + +void volumetexture_destroy(texture_t voltex) +{ + graphics_t graphics = thread_graphics; + graphics->exports.volumetexture_destroy(voltex); +} + +uint32_t volumetexture_getwidth(texture_t voltex) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.volumetexture_getwidth(voltex); +} + +uint32_t volumetexture_getheight(texture_t voltex) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.volumetexture_getheight(voltex); +} + +uint32_t volumetexture_getdepth(texture_t voltex) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.volumetexture_getdepth(voltex); +} + +enum gs_color_format volumetexture_getcolorformat(texture_t voltex) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.volumetexture_getcolorformat(voltex); +} + +void stagesurface_destroy(stagesurf_t stagesurf) +{ + graphics_t graphics = thread_graphics; + graphics->exports.stagesurface_destroy(stagesurf); +} + +uint32_t stagesurface_getwidth(stagesurf_t stagesurf) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.stagesurface_getwidth(stagesurf); +} + +uint32_t stagesurface_getheight(stagesurf_t stagesurf) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.stagesurface_getheight(stagesurf); +} + +enum gs_color_format stagesurface_getcolorformat(stagesurf_t stagesurf) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.stagesurface_getcolorformat(stagesurf); +} + +bool stagesurface_map(stagesurf_t stagesurf, const void **data, + uint32_t *byte_width) +{ + graphics_t graphics = thread_graphics; + return graphics->exports.stagesurface_map(stagesurf, data, byte_width); +} + +void stagesurface_unmap(stagesurf_t stagesurf) +{ + graphics_t graphics = thread_graphics; + graphics->exports.stagesurface_unmap(stagesurf); +} + +void zstencil_destroy(zstencil_t zstencil) +{ + thread_graphics->exports.zstencil_destroy(zstencil); +} + +void samplerstate_destroy(samplerstate_t samplerstate) +{ + thread_graphics->exports.samplerstate_destroy(samplerstate); +} + +void vertexbuffer_destroy(vertbuffer_t vertbuffer) +{ + graphics_t graphics = thread_graphics; + graphics->exports.vertexbuffer_destroy(vertbuffer); +} + +void vertexbuffer_flush(vertbuffer_t vertbuffer, bool rebuild) +{ + thread_graphics->exports.vertexbuffer_flush(vertbuffer, rebuild); +} + +struct vb_data *vertexbuffer_getdata(vertbuffer_t vertbuffer) +{ + return thread_graphics->exports.vertexbuffer_getdata(vertbuffer); +} + +void indexbuffer_destroy(indexbuffer_t indexbuffer) +{ + graphics_t graphics = thread_graphics; + graphics->exports.indexbuffer_destroy(indexbuffer); +} + +void indexbuffer_flush(indexbuffer_t indexbuffer) +{ + thread_graphics->exports.indexbuffer_flush(indexbuffer); +} + +void *indexbuffer_getdata(indexbuffer_t indexbuffer) +{ + return thread_graphics->exports.indexbuffer_getdata(indexbuffer); +} + +size_t indexbuffer_numindices(indexbuffer_t indexbuffer) +{ + return thread_graphics->exports.indexbuffer_numindices(indexbuffer); +} + +enum gs_index_type indexbuffer_gettype(indexbuffer_t indexbuffer) +{ + return thread_graphics->exports.indexbuffer_gettype(indexbuffer); +} diff --git a/libobs/graphics/graphics.h b/libobs/graphics/graphics.h new file mode 100644 index 000000000..1c72d0a66 --- /dev/null +++ b/libobs/graphics/graphics.h @@ -0,0 +1,664 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef GRAPHICS_H +#define GRAPHICS_H + +#include "../util/bmem.h" +#include "input.h" + +/* + * This is an API-independent graphics subsystem wrapper. + * + * This allows the use of OpenGL and different Direct3D versions through + * one shared interface. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +struct vec2; +struct vec3; +struct vec4; +struct quat; +struct axisang; +struct plane; +struct matrix3; +struct matrix4; + +enum gs_draw_mode { + GS_POINTS, + GS_LINES, + GS_LINESTRIP, + GS_TRIS, + GS_TRISTRIP +}; + +enum gs_color_format { + GS_UNKNOWN, + GS_A8, + GS_R8, + GS_RGBA, + GS_BGRX, + GS_BGRA, + GS_R10G10B10A2, + GS_RGBA16, + GS_R16, + GS_RGBA16F, + GS_RGBA32F, + GS_RG16F, + GS_RG32F, + GS_R16F, + GS_R32F, + GS_DXT1, + GS_DXT3, + GS_DXT5 +}; + +enum gs_zstencil_format { + GS_ZS_NONE, + GS_Z16, + GS_Z24_S8, + GS_Z32F, + GS_Z32F_S8X24 +}; + +enum gs_index_type { + GS_UNSIGNED_SHORT, + GS_UNSIGNED_LONG +}; + +enum gs_cull_mode { + GS_BACK, + GS_FRONT, + GS_NEITHER +}; + +enum gs_blend_type { + GS_BLEND_ZERO, + GS_BLEND_ONE, + GS_BLEND_SRCCOLOR, + GS_BLEND_INVSRCCOLOR, + GS_BLEND_SRCALPHA, + GS_BLEND_INVSRCALPHA, + GS_BLEND_DSTCOLOR, + GS_BLEND_INVDSTCOLOR, + GS_BLEND_DSTALPHA, + GS_BLEND_INVDSTALPHA, + GS_BLEND_SRCALPHASAT +}; + +enum gs_depth_test { + GS_NEVER, + GS_LESS, + GS_LEQUAL, + GS_EQUAL, + GS_GEQUAL, + GS_GREATER, + GS_NOTEQUAL, + GS_ALWAYS +}; + +enum gs_stencil_side { + GS_STENCIL_FRONT=1, + GS_STENCIL_BACK, + GS_STENCIL_BOTH +}; + +enum gs_stencil_op { + GS_KEEP, + GS_ZERO, + GS_REPLACE, + GS_INCR, + GS_DECR, + GS_INVERT +}; + +enum gs_cube_sides { + GS_POSITIVE_X, + GS_NEGATIVE_X, + GS_POSITIVE_Y, + GS_NEGATIVE_Y, + GS_POSITIVE_Z, + GS_NEGATIVE_Z +}; + +enum gs_sample_filter { + GS_FILTER_POINT, + GS_FILTER_LINEAR, + GS_FILTER_ANISOTROPIC, + GS_FILTER_MIN_MAG_POINT_MIP_LINEAR, + GS_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT, + GS_FILTER_MIN_POINT_MAG_MIP_LINEAR, + GS_FILTER_MIN_LINEAR_MAG_MIP_POINT, + GS_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR, + GS_FILTER_MIN_MAG_LINEAR_MIP_POINT, +}; + +enum gs_address_mode { + GS_ADDRESS_CLAMP, + GS_ADDRESS_WRAP, + GS_ADDRESS_MIRROR, + GS_ADDRESS_BORDER, + GS_ADDRESS_MIRRORONCE +}; + +enum gs_texture_type { + GS_TEXTURE_2D, + GS_TEXTURE_3D, + GS_TEXTURE_CUBE +}; + +struct tvertarray { + size_t width; + void *array; +}; + +struct vb_data { + size_t num; + struct vec3 *points; + struct vec3 *normals; + struct vec3 *tangents; + uint32_t *colors; + + size_t num_tex; + struct tvertarray *tvarray; +}; + +static inline struct vb_data *vbdata_create(void) +{ + struct vb_data *vbd = (struct vb_data*)bmalloc(sizeof(struct vb_data)); + memset(vbd, 0, sizeof(struct vb_data)); + return vbd; +} + +static inline void vbdata_destroy(struct vb_data *data) +{ + uint32_t i; + if (!data) + return; + + bfree(data->points); + bfree(data->normals); + bfree(data->tangents); + bfree(data->colors); + for (i = 0; i < data->num_tex; i++) + bfree(data->tvarray[i].array); + bfree(data->tvarray); + bfree(data); +} + +struct gs_sampler_info { + enum gs_sample_filter filter; + enum gs_address_mode address_u; + enum gs_address_mode address_v; + enum gs_address_mode address_w; + int max_anisotropy; + uint32_t border_color; +}; + +struct gs_display_mode { + uint32_t width; + uint32_t height; + uint32_t bits; + uint32_t freq; +}; + +struct gs_rect { + int x; + int y; + int cx; + int cy; +}; + +/* wrapped opaque data types */ + +struct gs_texture; +struct gs_stage_surface; +struct gs_zstencil_buffer; +struct gs_vertex_buffer; +struct gs_index_buffer; +struct gs_sampler_state; +struct gs_shader; +struct gs_swap_chain; +struct gs_texrender; +struct shader_param; +struct gs_effect; +struct effect_technique; +struct effect_pass; +struct effect_param; +struct gs_device; +struct graphics_subsystem; + +typedef struct gs_texture *texture_t; +typedef struct gs_stage_surface *stagesurf_t; +typedef struct gs_zstencil_buffer *zstencil_t; +typedef struct gs_vertex_buffer *vertbuffer_t; +typedef struct gs_index_buffer *indexbuffer_t; +typedef struct gs_sampler_state *samplerstate_t; +typedef struct gs_swap_chain *swapchain_t; +typedef struct gs_texture_render *texrender_t; +typedef struct gs_shader *shader_t; +typedef struct shader_param *sparam_t; +typedef struct gs_effect *effect_t; +typedef struct effect_technique *technique_t; +typedef struct effect_param *eparam_t; +typedef struct gs_device *device_t; +typedef struct graphics_subsystem *graphics_t; + +/* --------------------------------------------------- + * shader functions + * --------------------------------------------------- */ + +enum shader_param_type { + SHADER_PARAM_UNKNOWN, + SHADER_PARAM_BOOL, + SHADER_PARAM_FLOAT, + SHADER_PARAM_INT, + SHADER_PARAM_STRING, + SHADER_PARAM_VEC2, + SHADER_PARAM_VEC3, + SHADER_PARAM_VEC4, + SHADER_PARAM_MATRIX3X3, + SHADER_PARAM_MATRIX4X4, + SHADER_PARAM_TEXTURE, +}; + +struct shader_param_info { + enum shader_param_type type; + const char *name; +}; + +enum shader_type { + SHADER_VERTEX, + SHADER_PIXEL, + SHADER_GEOMETRY +}; + +EXPORT void shader_destroy(shader_t shader); + +EXPORT int shader_numparams(shader_t shader); +EXPORT sparam_t shader_getparambyidx(shader_t shader, int param); +EXPORT sparam_t shader_getparambyname(shader_t shader, const char *name); +EXPORT void shader_getparaminfo(shader_t shader, sparam_t param, + struct shader_param_info *info); + +EXPORT sparam_t shader_getviewprojmatrix(shader_t shader); +EXPORT sparam_t shader_getworldmatrix(shader_t shader); + +EXPORT void shader_setbool(shader_t shader, sparam_t param, bool val); +EXPORT void shader_setfloat(shader_t shader, sparam_t param, float val); +EXPORT void shader_setint(shader_t shader, sparam_t param, int val); +EXPORT void shader_setmatrix3(shader_t shader, sparam_t param, + const struct matrix3 *val); +EXPORT void shader_setmatrix4(shader_t shader, sparam_t param, + const struct matrix4 *val); +EXPORT void shader_setvec2(shader_t shader, sparam_t param, + const struct vec2 *val); +EXPORT void shader_setvec3(shader_t shader, sparam_t param, + const struct vec3 *val); +EXPORT void shader_setvec4(shader_t shader, sparam_t param, + const struct vec4 *val); +EXPORT void shader_settexture(shader_t shader, sparam_t param, texture_t val); +EXPORT void shader_setval(shader_t shader, sparam_t param, const void *val, + size_t size); +EXPORT void shader_setdefault(shader_t shader, sparam_t param); + +/* --------------------------------------------------- + * effect functions + * --------------------------------------------------- */ + +/*enum effect_property_type { + EFFECT_NONE, + EFFECT_BOOL, + EFFECT_FLOAT, + EFFECT_COLOR, + EFFECT_TEXTURE +};*/ + +struct effect_param_info { + const char *name; + enum shader_param_type type; + + /* const char *full_name; + enum effect_property_type prop_type; + + float min, max, inc, mul; */ +}; + +EXPORT void effect_destroy(effect_t effect); + +EXPORT technique_t effect_gettechnique(effect_t effect, const char *name); + +EXPORT int technique_begin(technique_t technique); +EXPORT void technique_end(technique_t technique); +EXPORT bool technique_beginpass(technique_t technique, size_t pass); +EXPORT bool technique_beginpassbyname(technique_t technique, + const char *name); +EXPORT void technique_endpass(technique_t technique); + +EXPORT int effect_numparams(effect_t effect); +EXPORT eparam_t effect_getparambyidx(effect_t effect, size_t param); +EXPORT eparam_t effect_getparambyname(effect_t effect, const char *name); +EXPORT void effect_getparaminfo(effect_t effect, eparam_t param, + struct effect_param_info *info); + +/** used internally */ +EXPORT void effect_updateparams(effect_t effect); + +EXPORT eparam_t effect_getviewprojmatrix(effect_t effect); +EXPORT eparam_t effect_getworldmatrix(effect_t effect); + +EXPORT void effect_setbool(effect_t effect, eparam_t param, bool val); +EXPORT void effect_setfloat(effect_t effect, eparam_t param, float val); +EXPORT void effect_setint(effect_t effect, eparam_t param, int val); +EXPORT void effect_setmatrix3(effect_t effect, eparam_t param, + const struct matrix3 *val); +EXPORT void effect_setmatrix4(effect_t effect, eparam_t param, + const struct matrix4 *val); +EXPORT void effect_setvec2(effect_t effect, eparam_t param, + const struct vec2 *val); +EXPORT void effect_setvec3(effect_t effect, eparam_t param, + const struct vec3 *val); +EXPORT void effect_setvec4(effect_t effect, eparam_t param, + const struct vec4 *val); +EXPORT void effect_settexture(effect_t effect, eparam_t param, texture_t val); +EXPORT void effect_setval(effect_t shader, eparam_t param, const void *val, + size_t size); +EXPORT void effect_setdefault(effect_t effect, eparam_t param); + +/* --------------------------------------------------- + * texture render helper functions + * --------------------------------------------------- */ + +EXPORT texrender_t texrender_create(enum gs_color_format format, + enum gs_zstencil_format zsformat); +EXPORT void texrender_destroy(texrender_t texrender); +EXPORT bool texrender_begin(texrender_t texrender, int cx, int cy); +EXPORT void texrender_end(texrender_t texrender); +EXPORT void texrender_reset(texrender_t texrender); +EXPORT texture_t texrender_gettexture(texrender_t texrender); + +/* --------------------------------------------------- + * graphics subsystem + * --------------------------------------------------- */ + +#define GS_BUILDMIPMAPS (1<<0) +#define GS_DYNAMIC (1<<1) +#define GS_RENDERTARGET (1<<2) + +/* ---------------- */ +/* global functions */ + +#define GS_SUCCESS 0 +#define GS_ERROR_MODULENOTFOUND -1 +#define GS_ERROR_FAIL -2 + +struct gs_init_data { +#if defined(_WIN32) + void *hwnd; +#elif defined(__APPLE__) + /* TODO */ +#elif defined(__posix__) + /* TODO */ +#endif + uint32_t cx, cy; + uint32_t num_backbuffers; + enum gs_color_format format; + enum gs_zstencil_format zsformat; + uint32_t adapter; +}; + + +EXPORT int gs_create(graphics_t *graphics, const char *module, + struct gs_init_data *data); +EXPORT void gs_destroy(graphics_t graphics); + +EXPORT void gs_setcontext(graphics_t graphics); +EXPORT graphics_t gs_getcontext(void); + +EXPORT void gs_matrix_push(void); +EXPORT void gs_matrix_pop(void); +EXPORT void gs_matrix_identity(void); +EXPORT void gs_matrix_transpose(void); +EXPORT void gs_matrix_set(const struct matrix3 *matrix); +EXPORT void gs_matrix_get(struct matrix3 *dst); +EXPORT void gs_matrix_mul(const struct matrix3 *matrix); +EXPORT void gs_matrix_rotquat(const struct quat *rot); +EXPORT void gs_matrix_rotaa(const struct axisang *rot); +EXPORT void gs_matrix_translate(const struct vec3 *pos); +EXPORT void gs_matrix_scale(const struct vec3 *scale); +EXPORT void gs_matrix_rotaa4f(float x, float y, float z, float angle); +EXPORT void gs_matrix_translate3f(float x, float y, float z); +EXPORT void gs_matrix_scale3f(float x, float y, float z); + +EXPORT void gs_renderstart(bool b_new); +EXPORT void gs_renderstop(enum gs_draw_mode mode); +EXPORT vertbuffer_t gs_rendersave(void); +EXPORT void gs_vertex2f(float x, float y); +EXPORT void gs_vertex3f(float x, float y, float z); +EXPORT void gs_normal3f(float x, float y, float z); +EXPORT void gs_color(uint32_t color); +EXPORT void gs_texcoord(float x, float y, int unit); +EXPORT void gs_vertex2v(const struct vec2 *v); +EXPORT void gs_vertex3v(const struct vec3 *v); +EXPORT void gs_normal3v(const struct vec3 *v); +EXPORT void gs_color4v(const struct vec4 *v); +EXPORT void gs_texcoord2v(const struct vec2 *v, int unit); + +EXPORT input_t gs_getinput(void); +EXPORT effect_t gs_geteffect(void); + +EXPORT effect_t gs_create_effect_from_file(const char *file, + char **error_string); +EXPORT effect_t gs_create_effect(const char *effect_string, + const char *filename, char **error_string); + +EXPORT shader_t gs_create_vertexshader_from_file(const char *file, + char **error_string); +EXPORT shader_t gs_create_pixelshader_from_file(const char *file, + char **error_string); + +EXPORT texture_t gs_create_texture_from_file(const char *file, + uint32_t flags); +EXPORT texture_t gs_create_cubetexture_from_file(const char *flie, + uint32_t flags); +EXPORT texture_t gs_create_volumetexture_from_file(const char *flie, + uint32_t flags); + +EXPORT void gs_draw_sprite(texture_t tex); + +EXPORT void gs_draw_cube_backdrop(texture_t cubetex, const struct quat *rot, + float left, float right, float top, float bottom, float znear); + +/** sets the viewport to current swap chain size */ +EXPORT void gs_resetviewport(void); + +/** sets default screen-sized orthographich mode */ +EXPORT void gs_set2dmode(void); +/** sets default screen-sized perspective mode */ +EXPORT void gs_set3dmode(double fovy, double znear, double zvar); + +EXPORT void gs_viewport_push(void); +EXPORT void gs_viewport_pop(void); + +EXPORT void texture_setimage(texture_t tex, const void *data, + uint32_t byte_width); +EXPORT void cubetexture_setimage(texture_t cubetex, uint32_t side, + const void *data, uint32_t byte_width); + +/* -------------------------- */ +/* library-specific functions */ + +EXPORT swapchain_t gs_create_swapchain(struct gs_init_data *data); + +EXPORT void gs_resize(uint32_t x, uint32_t y); +EXPORT void gs_getsize(uint32_t *x, uint32_t *y); +EXPORT uint32_t gs_getwidth(void); +EXPORT uint32_t gs_getheight(void); + +EXPORT texture_t gs_create_texture(uint32_t width, uint32_t height, + enum gs_color_format color_format, void *data, uint32_t flags); +EXPORT texture_t gs_create_cubetexture(uint32_t size, + enum gs_color_format color_format, void *data[6], + uint32_t flags); +EXPORT texture_t gs_create_volumetexture(uint32_t width, uint32_t height, + uint32_t depth, enum gs_color_format color_format, void *data, + uint32_t flags); + +EXPORT zstencil_t gs_create_zstencil(uint32_t width, uint32_t height, + enum gs_zstencil_format format); + +EXPORT stagesurf_t gs_create_stagesurface(uint32_t width, uint32_t height, + enum gs_color_format color_format); + +EXPORT samplerstate_t gs_create_samplerstate(struct gs_sampler_info *info); + +EXPORT shader_t gs_create_vertexshader(const char *shader, + const char *file, char **error_string); +EXPORT shader_t gs_create_pixelshader(const char *shader, + const char *file, char **error_string); + +EXPORT vertbuffer_t gs_create_vertexbuffer(struct vb_data *data, + uint32_t flags); +EXPORT indexbuffer_t gs_create_indexbuffer(enum gs_index_type type, + void *indices, size_t num, uint32_t flags); + +EXPORT enum gs_texture_type gs_gettexturetype(texture_t texture); + +EXPORT void gs_load_vertexbuffer(vertbuffer_t vertbuffer); +EXPORT void gs_load_indexbuffer(indexbuffer_t indexbuffer); +EXPORT void gs_load_texture(texture_t tex, int unit); +EXPORT void gs_load_samplerstate(samplerstate_t samplerstate, int unit); +EXPORT void gs_load_vertexshader(shader_t vertshader); +EXPORT void gs_load_pixelshader(shader_t pixelshader); + +EXPORT void gs_load_defaultsamplerstate(bool b_3d, int unit); + +EXPORT shader_t gs_getvertexshader(void); +EXPORT shader_t gs_getpixelshader(void); + +EXPORT texture_t gs_getrendertarget(void); +EXPORT zstencil_t gs_getzstenciltarget(void); + +EXPORT void gs_setrendertarget(texture_t tex, zstencil_t zstencil); +EXPORT void gs_setcuberendertarget(texture_t cubetex, int side, + zstencil_t zstencil); + +EXPORT void gs_copy_texture(texture_t dst, texture_t src); +EXPORT void gs_stage_texture(stagesurf_t dst, texture_t src); + +EXPORT void gs_beginscene(void); +EXPORT void gs_draw(enum gs_draw_mode draw_mode, uint32_t start_vert, + uint32_t num_verts); +EXPORT void gs_endscene(void); + +#define GS_CLEAR_COLOR (1<<0) +#define GS_CLEAR_DEPTH (1<<1) +#define GS_CLEAR_STENCIL (1<<2) + +EXPORT void gs_load_swapchain(swapchain_t swapchain); +EXPORT void gs_clear(uint32_t clear_flags, struct vec4 *color, + float depth, uint8_t stencil); +EXPORT void gs_present(void); + +EXPORT void gs_setcullmode(enum gs_cull_mode mode); +EXPORT enum gs_cull_mode gs_getcullmode(void); + +EXPORT void gs_enable_blending(bool enable); +EXPORT void gs_enable_depthtest(bool enable); +EXPORT void gs_enable_stenciltest(bool enable); +EXPORT void gs_enable_stencilwrite(bool enable); +EXPORT void gs_enable_color(bool red, bool blue, bool green, bool alpha); + +EXPORT void gs_blendfunction(enum gs_blend_type src, enum gs_blend_type dest); +EXPORT void gs_depthfunction(enum gs_depth_test test); + +EXPORT void gs_stencilfunction(enum gs_stencil_side side, + enum gs_depth_test test); +EXPORT void gs_stencilop(enum gs_stencil_side side, enum gs_stencil_op fail, + enum gs_stencil_op zfail, enum gs_stencil_op zpass); + +EXPORT void gs_setclip(struct plane *p); + +EXPORT void gs_enable_fullscreen(bool enable); +EXPORT int gs_fullscreen_enabled(void); +EXPORT void gs_setdisplaymode(const struct gs_display_mode *mode); +EXPORT void gs_getdisplaymode(struct gs_display_mode *mode); +EXPORT void gs_setcolorramp(float gamma, float brightness, float contrast); + +EXPORT void gs_setviewport(int x, int y, int width, int height); +EXPORT void gs_getviewport(struct gs_rect *rect); +EXPORT void gs_setscissorrect(struct gs_rect *rect); + +EXPORT void gs_ortho(float left, float right, float top, float bottom, + float znear, float zfar); +EXPORT void gs_frustum(float left, float right, float top, float bottom, + float znear, float zfar); +EXPORT void gs_perspective(float fovy, float aspect, float znear, + float zfar); + +EXPORT void gs_projection_push(void); +EXPORT void gs_projection_pop(void); + +EXPORT void swapchain_destroy(swapchain_t swapchain); + +EXPORT void texture_destroy(texture_t tex); +EXPORT uint32_t texture_getwidth(texture_t tex); +EXPORT uint32_t texture_getheight(texture_t tex); +EXPORT enum gs_color_format texture_getcolorformat(texture_t tex); +EXPORT bool texture_map(texture_t tex, void **ptr, uint32_t *byte_width); +EXPORT void texture_unmap(texture_t tex); + +EXPORT void cubetexture_destroy(texture_t cubetex); +EXPORT uint32_t cubetexture_getsize(texture_t cubetex); +EXPORT enum gs_color_format cubetexture_getcolorformat(texture_t cubetex); + +EXPORT void volumetexture_destroy(texture_t voltex); +EXPORT uint32_t volumetexture_getwidth(texture_t voltex); +EXPORT uint32_t volumetexture_getheight(texture_t voltex); +EXPORT uint32_t volumetexture_getdepth(texture_t voltex); +EXPORT enum gs_color_format volumetexture_getcolorformat(texture_t voltex); + +EXPORT void stagesurface_destroy(stagesurf_t stagesurf); +EXPORT uint32_t stagesurface_getwidth(stagesurf_t stagesurf); +EXPORT uint32_t stagesurface_getheight(stagesurf_t stagesurf); +EXPORT enum gs_color_format stagesurface_getcolorformat(stagesurf_t stagesurf); +EXPORT bool stagesurface_map(stagesurf_t stagesurf, const void **data, + uint32_t *byte_width); +EXPORT void stagesurface_unmap(stagesurf_t stagesurf); + +EXPORT void zstencil_destroy(zstencil_t zstencil); + +EXPORT void samplerstate_destroy(samplerstate_t samplerstate); + +EXPORT void vertexbuffer_destroy(vertbuffer_t vertbuffer); +EXPORT void vertexbuffer_flush(vertbuffer_t vertbuffer, bool rebuild); +EXPORT struct vb_data *vertexbuffer_getdata(vertbuffer_t vertbuffer); + +EXPORT void indexbuffer_destroy(indexbuffer_t indexbuffer); +EXPORT void indexbuffer_flush(indexbuffer_t indexbuffer); +EXPORT void *indexbuffer_getdata(indexbuffer_t indexbuffer); +EXPORT size_t indexbuffer_numindices(indexbuffer_t indexbuffer); +EXPORT enum gs_index_type indexbuffer_gettype(indexbuffer_t indexbuffer); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/input.h b/libobs/graphics/input.h new file mode 100644 index 000000000..5762f92d4 --- /dev/null +++ b/libobs/graphics/input.h @@ -0,0 +1,155 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef INPUT_H +#define INPUT_H + +/* TODO: incomplete/may not be necessary */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define KBC_ESCAPE 0x0 +#define KBC_1 0x1 +#define KBC_2 0x2 +#define KBC_3 0x3 +#define KBC_4 0x4 +#define KBC_5 0x5 +#define KBC_6 0x6 +#define KBC_7 0x7 +#define KBC_8 0x8 +#define KBC_9 0x9 +#define KBC_0 0xA +#define KBC_MINUS 0xB +#define KBC_EQUALS 0xC +#define KBC_BACK 0xD +#define KBC_TAB 0xE +#define KBC_Q 0xF +#define KBC_W 0x10 +#define KBC_E 0x11 +#define KBC_R 0x12 +#define KBC_T 0x13 +#define KBC_Y 0x14 +#define KBC_U 0x15 +#define KBC_I 0x16 +#define KBC_O 0x17 +#define KBC_P 0x18 +#define KBC_LBRACKET 0x19 +#define KBC_RBRACKET 0x1A +#define KBC_RETURN 0x1B +#define KBC_LCONTROL 0x1C +#define KBC_A 0x1D +#define KBC_S 0x1E +#define KBC_D 0x1F +#define KBC_F 0x20 +#define KBC_G 0x21 +#define KBC_H 0x22 +#define KBC_J 0x23 +#define KBC_K 0x24 +#define KBC_L 0x25 +#define KBC_SEMICOLON 0x26 +#define KBC_APOSTROPHE 0x27 +#define KBC_TILDE 0x28 +#define KBC_LSHIFT 0x29 +#define KBC_BACKSLASH 0x2A +#define KBC_Z 0x2B +#define KBC_X 0x2C +#define KBC_C 0x2D +#define KBC_V 0x2E +#define KBC_B 0x2F +#define KBC_N 0x30 +#define KBC_M 0x31 +#define KBC_COMMA 0x32 +#define KBC_PERIOD 0x33 +#define KBC_SLASH 0x34 +#define KBC_RSHIFT 0x35 +#define KBC_MULTIPLY 0x36 +#define KBC_LALT 0x37 +#define KBC_SPACE 0x38 +#define KBC_CAPSLOCK 0x39 +#define KBC_F1 0x3A +#define KBC_F2 0x3B +#define KBC_F3 0x3C +#define KBC_F4 0x3D +#define KBC_F5 0x3E +#define KBC_F6 0x3F +#define KBC_F7 0x40 +#define KBC_F8 0x41 +#define KBC_F9 0x42 +#define KBC_F10 0x43 +#define KBC_NUMLOCK 0x44 +#define KBC_SCROLLLOCK 0x45 +#define KBC_NUMPAD7 0x46 +#define KBC_NUMPAD8 0x47 +#define KBC_NUMPAD9 0x48 +#define KBC_SUBTRACT 0x49 +#define KBC_NUMPAD4 0x4A +#define KBC_NUMPAD5 0x4B +#define KBC_NUMPAD6 0x4C +#define KBC_ADD 0x4D +#define KBC_NUMPAD1 0x4E +#define KBC_NUMPAD2 0x4F +#define KBC_NUMPAD3 0x50 +#define KBC_NUMPAD0 0x51 +#define KBC_DECIMAL 0x52 +#define KBC_F11 0x53 +#define KBC_F12 0x54 +#define KBC_NUMPADENTER 0x55 +#define KBC_RCONTROL 0x56 +#define KBC_DIVIDE 0x57 +#define KBC_SYSRQ 0x58 +#define KBC_RALT 0x59 +#define KBC_PAUSE 0x5A +#define KBC_HOME 0x5B +#define KBC_UP 0x5C +#define KBC_PAGEDOWN 0x5D +#define KBC_LEFT 0x5E +#define KBC_RIGHT 0x5F +#define KBC_END 0x60 +#define KBC_DOWN 0x61 +#define KBC_PAGEUP 0x62 +#define KBC_INSERT 0x63 +#define KBC_DELETE 0x64 + +#define MOUSE_LEFTBUTTON 0x65 +#define MOUSE_MIDDLEBUTTON 0x66 +#define MOUSE_RIGHTBUTTON 0x67 +#define MOUSE_WHEEL 0x68 +#define MOUSE_MOVE 0x69 + +#define KBC_CONTROL 0xFFFFFFFE +#define KBC_ALT 0xFFFFFFFD +#define KBC_SHIFT 0xFFFFFFFC + +#define STATE_LBUTTONDOWN (1<<0) +#define STATE_RBUTTONDOWN (1<<1) +#define STATE_MBUTTONDOWN (1<<2) +#define STATE_X4BUTTONDOWN (1<<3) +#define STATE_X5BUTTONDOWN (1<<4) + +/* wrapped opaque data types */ +struct input_subsystem; +typedef struct input_subsystem* input_t; + +EXPORT int input_getbuttonstate(input_t input, uint32_t button); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/math-defs.h b/libobs/graphics/math-defs.h new file mode 100644 index 000000000..48951e5a8 --- /dev/null +++ b/libobs/graphics/math-defs.h @@ -0,0 +1,48 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef MATH_DEFS +#define MATH_DEFS + +#include "../util/c99defs.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef M_PI +#define M_PI 3.1415926535897932384626433832795f +#endif + +#define RAD(val) ((val)*0.0174532925199432957692369076848f) +#define DEG(val) ((val)*57.295779513082320876798154814105f) +#define LARGE_EPSILON 1e-2f +#define EPSILON 1e-4f +#define TINY_EPSILON 1e-5f +#define M_INFINITE 3.4e38f + +static inline bool close_float(float f1, float f2, float precision) +{ + return fabsf(f1-f2) <= precision; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/math-extra.c b/libobs/graphics/math-extra.c new file mode 100644 index 000000000..02111b027 --- /dev/null +++ b/libobs/graphics/math-extra.c @@ -0,0 +1,132 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include +#include "vec2.h" +#include "vec3.h" +#include "math-extra.h" + +void polar_to_cart(struct vec3 *dst, const struct vec3 *v) +{ + struct vec3 cart; + float sinx = cosf(v->x); + float sinx_z = v->z * sinx; + + cart.x = sinx_z * sinf(v->y); + cart.z = sinx_z * cosf(v->y); + cart.y = v->z * sinf(v->x); + + vec3_copy(dst, &cart); +} + +void cart_to_polar(struct vec3 *dst, const struct vec3 *v) +{ + struct vec3 polar; + polar.z = vec3_len(v); + + if (close_float(polar.z, 0.0f, EPSILON)) { + vec3_zero(&polar); + } else { + polar.x = asinf(v->y / polar.z); + polar.y = atan2f(v->x, v->z); + } + + vec3_copy(dst, &polar); +} + +void norm_to_polar(struct vec2 *dst, const struct vec3 *norm) +{ + dst->x = atan2f(norm->x, norm->z); + dst->y = asinf(norm->y); +} + +void polar_to_norm(struct vec3 *dst, const struct vec2 *polar) +{ + float sinx = sinf(polar->x); + + dst->x = sinx * cosf(polar->y); + dst->y = sinx * sinf(polar->y); + dst->z = cosf(polar->x); +} + +float calc_torquef(float val1, float val2, float torque, float min_adjust, + float t) +{ + float out = val1; + float dist; + bool over; + + if (val1 == val2) + return val1; + + dist = (val2-val1)*torque; + over = dist > 0.0f; + + if (over) { + if (dist < min_adjust) /* prevents from going too slow */ + dist = min_adjust; + out += dist*t; /* add torque */ + if (out > val2) /* clamp if overshoot */ + out = val2; + } else { + if (dist > -min_adjust) + dist = -min_adjust; + out += dist*t; + if (out < val2) + out = val2; + } + + return out; +} + +void calc_torque(struct vec3 *dst, const struct vec3 *v1, + const struct vec3 *v2, float torque, float min_adjust, + float t) +{ + struct vec3 line, dir; + float orig_dist, torque_dist, adjust_dist; + + if (vec3_close(v1, v2, EPSILON)) { + vec3_copy(dst, v1); + return; + } + + vec3_sub(&line, v2, v1); + orig_dist = vec3_len(&line); + vec3_mulf(&dir, &line, 1.0f/orig_dist); + + torque_dist = orig_dist*torque; /* use distance to determine speed */ + adjust_dist = torque_dist*t; + + if (torque_dist < min_adjust) /* prevent from going too slow */ + torque_dist = min_adjust; + + if (adjust_dist <= (orig_dist-LARGE_EPSILON)) { + vec3_mulf(dst, &dir, adjust_dist); + vec3_add(dst, dst, v1); /* add torque */ + } else { + vec3_copy(dst, v2); /* clamp if overshoot */ + } +} + +float rand_float(int positive_only) +{ + if (positive_only) + return (float)((double)rand()/(double)RAND_MAX); + else + return (float)(((double)rand()/(double)RAND_MAX*2.0)-1.0); +} diff --git a/libobs/graphics/math-extra.h b/libobs/graphics/math-extra.h new file mode 100644 index 000000000..41e72fe38 --- /dev/null +++ b/libobs/graphics/math-extra.h @@ -0,0 +1,66 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef MATH_EXTRA_H +#define MATH_EXTRA_H + +#include "../util/c99defs.h" + +/* + * A few general math functions that I couldn't really decide where to put. + * + * Polar/Cart conversion, torque functions (for smooth movement), percentage, + * random floats. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +struct vec2; +struct vec3; + +EXPORT void polar_to_cart(struct vec3 *dst, const struct vec3 *v); +EXPORT void cart_to_polar(struct vec3 *dst, const struct vec3 *v); + +EXPORT void norm_to_polar(struct vec2 *dst, const struct vec3 *norm); +EXPORT void polar_to_norm(struct vec3 *dst, const struct vec2 *polar); + +EXPORT float calc_torquef(float val1, float val2, float torque, + float min_adjust, float t); + +EXPORT void calc_torque(struct vec3 *dst, const struct vec3 *v1, + const struct vec3 *v2, float torque, float min_adjust, + float t); + +static inline float get_percentage(float start, float end, float mid) +{ + return (mid-start) / (end-start); +} + +static inline float get_percentagei(int start, int end, int mid) +{ + return (float)(mid-start) / (float)(end-start); +} + +EXPORT float rand_float(int positive_only); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/matrix3.c b/libobs/graphics/matrix3.c new file mode 100644 index 000000000..c12d116f8 --- /dev/null +++ b/libobs/graphics/matrix3.c @@ -0,0 +1,145 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include +#include "matrix3.h" +#include "matrix4.h" +#include "plane.h" +#include "quat.h" + + +void matrix3_from_quat(struct matrix3 *dst, const struct quat *q) +{ + float norm = quat_dot(q, q); + float s = (norm > 0.0f) ? (2.0f/norm) : 0.0f; + + float xx = q->x * q->x * s; + float yy = q->y * q->y * s; + float zz = q->z * q->z * s; + float xy = q->x * q->y * s; + float xz = q->x * q->z * s; + float yz = q->y * q->z * s; + float wx = q->w * q->x * s; + float wy = q->w * q->y * s; + float wz = q->w * q->z * s; + + dst->x.x = 1.0f - (yy + zz); + dst->x.y = xy + wz; + dst->x.z = xz - wy; + dst->x.w = 0.0f; + + dst->y.x = xy - wz; + dst->y.y = 1.0f - (xx + zz); + dst->y.z = yz + wx; + dst->y.w = 0.0f; + + dst->z.x = xz + wy; + dst->z.y = yz - wx; + dst->z.z = 1.0f - (xx + yy); + dst->z.w = 0.0f; + + vec3_zero(&dst->t); +} + +void matrix3_from_axisang(struct matrix3 *dst, const struct axisang *aa) +{ + struct quat q; + quat_from_axisang(&q, aa); + matrix3_from_quat(dst, &q); +} + +void matrix3_from_matrix4(struct matrix3 *dst, const struct matrix4 *m) +{ + dst->x.m = m->x.m; + dst->y.m = m->y.m; + dst->z.m = m->z.m; + dst->t.m = m->t.m; + dst->x.w = 0.0f; + dst->y.w = 0.0f; + dst->z.w = 0.0f; + dst->t.w = 0.0f; +} + +void matrix3_mul(struct matrix3 *dst, const struct matrix3 *m1, + const struct matrix3 *m2) +{ + vec3_rotate(&dst->x, &m1->x, m2); + vec3_rotate(&dst->y, &m1->y, m2); + vec3_rotate(&dst->z, &m1->z, m2); + vec3_transform(&dst->t, &m1->t, m2); +} + +void matrix3_rotate(struct matrix3 *dst, const struct matrix3 *m, + const struct quat *q) +{ + struct matrix3 temp; + matrix3_from_quat(&temp, q); + matrix3_mul(dst, m, &temp); +} + +void matrix3_rotate_aa(struct matrix3 *dst, const struct matrix3 *m, + const struct axisang *aa) +{ + struct matrix3 temp; + matrix3_from_axisang(&temp, aa); + matrix3_mul(dst, m, &temp); +} + +void matrix3_scale(struct matrix3 *dst, const struct matrix3 *m, + const struct vec3 *v) +{ + vec3_mul(&dst->x, &m->x, v); + vec3_mul(&dst->y, &m->y, v); + vec3_mul(&dst->z, &m->z, v); + vec3_mul(&dst->t, &m->t, v); +} + +void matrix3_transpose(struct matrix3 *dst, const struct matrix3 *m) +{ + __m128 tmp1, tmp2; + vec3_transform(&dst->t, &m->t, m); + vec3_neg(&dst->t, &dst->t); + + tmp1 = _mm_movelh_ps(m->x.m, m->y.m); + tmp2 = _mm_movehl_ps(m->y.m, m->x.m); + dst->x.m = _mm_shuffle_ps(tmp1, m->z.m, _MM_SHUFFLE(3, 0, 2, 0)); + dst->y.m = _mm_shuffle_ps(tmp1, m->z.m, _MM_SHUFFLE(3, 1, 3, 1)); + dst->z.m = _mm_shuffle_ps(tmp2, m->z.m, _MM_SHUFFLE(3, 2, 2, 0)); +} + +void matrix3_inv(struct matrix3 *dst, const struct matrix3 *m) +{ + matrix4_inv((struct matrix4*)dst, (struct matrix4*)m); +} + +void matrix3_mirror(struct matrix3 *dst, const struct matrix3 *m, + const struct plane *p) +{ + vec3_mirrorv(&dst->x, &m->x, &p->dir); + vec3_mirrorv(&dst->y, &m->y, &p->dir); + vec3_mirrorv(&dst->z, &m->z, &p->dir); + vec3_mirror(&dst->t, &m->t, p); +} + +void matrix3_mirrorv(struct matrix3 *dst, const struct matrix3 *m, + const struct vec3 *v) +{ + vec3_mirrorv(&dst->x, &m->x, v); + vec3_mirrorv(&dst->y, &m->y, v); + vec3_mirrorv(&dst->z, &m->z, v); + vec3_mirrorv(&dst->t, &m->t, v); +} diff --git a/libobs/graphics/matrix3.h b/libobs/graphics/matrix3.h new file mode 100644 index 000000000..4a79dc842 --- /dev/null +++ b/libobs/graphics/matrix3.h @@ -0,0 +1,87 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef MATRIX_H +#define MATRIX_H + +#include "vec3.h" + +/* 3x4 Matrix */ + +#ifdef __cplusplus +extern "C" { +#endif + +struct axisang; +struct matrix4; + +struct matrix3 { + struct vec3 x; + struct vec3 y; + struct vec3 z; + struct vec3 t; +}; + +static inline void matrix3_copy(struct matrix3 *dst, const struct matrix3 *m) +{ + vec3_copy(&dst->x, &m->x); + vec3_copy(&dst->y, &m->y); + vec3_copy(&dst->z, &m->z); + vec3_copy(&dst->t, &m->t); +} + +static inline void matrix3_identity(struct matrix3 *dst) +{ + vec3_zero(&dst->x); + vec3_zero(&dst->y); + vec3_zero(&dst->z); + vec3_zero(&dst->t); + dst->x.x = dst->y.y = dst->z.z = 1.0f; +} + +EXPORT void matrix3_from_quat(struct matrix3 *dst, const struct quat *q); +EXPORT void matrix3_from_axisang(struct matrix3 *dst, + const struct axisang *aa); +EXPORT void matrix3_from_matrix4(struct matrix3 *dst, const struct matrix4 *m); + +EXPORT void matrix3_mul(struct matrix3 *dst, const struct matrix3 *m1, + const struct matrix3 *m2); +static inline void matrix3_translate(struct matrix3 *dst, + const struct matrix3 *m, const struct vec3 *v) +{ + vec3_sub(&dst->t, &m->t, v); +} + +EXPORT void matrix3_rotate(struct matrix3 *dst, const struct matrix3 *m, + const struct quat *q); +EXPORT void matrix3_rotate_aa(struct matrix3 *dst, const struct matrix3 *m, + const struct axisang *aa); +EXPORT void matrix3_scale(struct matrix3 *dst, const struct matrix3 *m, + const struct vec3 *v); +EXPORT void matrix3_transpose(struct matrix3 *dst, const struct matrix3 *m); +EXPORT void matrix3_inv(struct matrix3 *dst, const struct matrix3 *m); + +EXPORT void matrix3_mirror(struct matrix3 *dst, const struct matrix3 *m, + const struct plane *p); +EXPORT void matrix3_mirrorv(struct matrix3 *dst, const struct matrix3 *m, + const struct vec3 *v); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/matrix4.c b/libobs/graphics/matrix4.c new file mode 100644 index 000000000..3cbd235ce --- /dev/null +++ b/libobs/graphics/matrix4.c @@ -0,0 +1,209 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "math-defs.h" +#include "matrix4.h" +#include "matrix3.h" + +void matrix4_from_matrix3(struct matrix4 *dst, const struct matrix3 *m) +{ + dst->x.m = m->x.m; + dst->y.m = m->y.m; + dst->z.m = m->z.m; + dst->t.m = m->t.m; + dst->t.w = 1.0f; +} + +void matrix4_mul(struct matrix4 *dst, const struct matrix4 *m1, + const struct matrix4 *m2) +{ + const struct vec4 *m1v = (const struct vec4*)m1; + const float *m2f = (const float*)m2; + struct vec4 out[4]; + int i, j; + + for (i = 0; i < 4; i++) { + for (j=0; j<4; j++) { + struct vec4 temp; + vec4_set(&temp, m2f[j], m2f[j+4], m2f[j+8], m2f[j+12]); + out[i].ptr[j] = vec4_dot(&m1v[i], &temp); + } + } + + matrix4_copy(dst, (struct matrix4*)out); +} + +static inline void get_3x3_submatrix(float *dst, const struct matrix4 *m, + int i, int j) +{ + const float *mf = (const float *)m; + int ti, tj, idst, jdst; + + for (ti = 0; ti < 4; ti++) { + if (ti < i) + idst = ti; + else if (ti > i) + idst = ti-1; + else + continue; + + for (tj = 0; tj < 4; tj++) { + if (tj < j) + jdst = tj; + else if (tj > j) + jdst = tj-1; + else + continue; + + dst[(idst*3) + jdst] = mf[(ti*4) + tj]; + } + } +} + +static inline float get_3x3_determinant(const float *m) +{ + return (m[0] * ((m[4]*m[8]) - (m[7]*m[5]))) - + (m[1] * ((m[3]*m[8]) - (m[6]*m[5]))) + + (m[2] * ((m[3]*m[7]) - (m[6]*m[4]))); +} + +float matrix4_determinant(const struct matrix4 *m) +{ + const float *mf = (const float *)m; + float det, result = 0.0f, i = 1.0f; + float m3x3[9]; + int n; + + for (n = 0; n < 4; n++, i *= -1.0f) { + get_3x3_submatrix(m3x3, m, 0, n); + + det = get_3x3_determinant(m3x3); + result += mf[n] * det * i; + } + + return result; +} + +bool matrix4_inv(struct matrix4 *dst, const struct matrix4 *m) +{ + struct vec4 *dstv = (struct vec4 *)dst; + float det = matrix4_determinant(m); + float m3x3[9]; + int i, j, sign; + + if (fabs(det) < 0.0005f) + return false; + + for (i = 0; i < 4; i++) { + for (j = 0; j < 4; j++) { + sign = 1 - ((i+j) % 2) * 2; + get_3x3_submatrix(m3x3, m, i, j); + dstv[j].ptr[i] = get_3x3_determinant(m3x3) * + (float)sign / det; + } + } + + return true; +} + +void matrix4_transpose(struct matrix4 *dst, const struct matrix4 *m) +{ + struct matrix4 temp; + + /* TODO: Use SSE */ + temp.x.x = m->x.x; + temp.x.y = m->y.x; + temp.x.z = m->z.x; + temp.x.w = m->t.x; + temp.y.x = m->x.y; + temp.y.y = m->y.y; + temp.y.z = m->z.y; + temp.y.w = m->t.y; + temp.z.x = m->x.z; + temp.z.y = m->y.z; + temp.z.z = m->z.z; + temp.z.w = m->t.z; + temp.t.x = m->x.w; + temp.t.y = m->y.w; + temp.t.z = m->z.w; + temp.t.w = m->t.w; + + matrix4_copy(dst, &temp); +} + +void matrix4_ortho(struct matrix4 *dst, float left, float right, + float top, float bottom, float near, float far) +{ + float rml = right-left; + float bmt = bottom-top; + float fmn = far-near; + + vec4_zero(&dst->x); + vec4_zero(&dst->y); + vec4_zero(&dst->z); + vec4_zero(&dst->t); + + dst->x.x = 2.0f / rml; + dst->t.x = (left+right) / -rml; + + dst->y.y = 2.0f / -bmt; + dst->t.y = (bottom+top) / bmt; + + dst->z.z = 1.0f / fmn; + dst->t.z = near / -fmn; + + dst->t.w = 1.0f; +} + +void matrix4_frustum(struct matrix4 *dst, float left, float right, + float top, float bottom, float near, float far) +{ + float rml = right-left; + float bmt = bottom-top; + float fmn = far-near; + float nearx2 = 2.0f*near; + + vec4_zero(&dst->x); + vec4_zero(&dst->y); + vec4_zero(&dst->z); + vec4_zero(&dst->t); + + dst->x.x = nearx2 / rml; + dst->z.x = (left+right) / -rml; + + dst->y.y = nearx2 / -bmt; + dst->z.y = (bottom+top) / bmt; + + dst->z.z = far / fmn; + dst->t.z = (near*far) / -fmn; + + dst->z.w = 1.0f; +} + +void matrix4_perspective(struct matrix4 *dst, float angle, + float aspect, float near, float far) +{ + float xmin, xmax, ymin, ymax; + + ymax = near * tanf(RAD(angle)*0.5f); + ymin = -ymax; + + xmin = ymin * aspect; + xmax = ymax * aspect; + + matrix4_frustum(dst, xmin, xmax, ymin, ymax, near, far); +} diff --git a/libobs/graphics/matrix4.h b/libobs/graphics/matrix4.h new file mode 100644 index 000000000..b72f280b7 --- /dev/null +++ b/libobs/graphics/matrix4.h @@ -0,0 +1,76 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef MATRIX4_H +#define MATRIX4_H + +#include "vec4.h" + +/* 4x4 Matrix */ + +#ifdef __cplusplus +extern "C" { +#endif + +struct matrix3; + +struct matrix4 { + struct vec4 x, y, z, t; +}; + +static inline void matrix4_copy(struct matrix4 *dst, const struct matrix4 *m) +{ + dst->x.m = m->x.m; + dst->y.m = m->y.m; + dst->z.m = m->z.m; + dst->t.m = m->t.m; +} + +static inline void matrix4_identity(struct matrix4 *dst) +{ + vec4_zero(&dst->x); + vec4_zero(&dst->y); + vec4_zero(&dst->z); + vec4_zero(&dst->t); + dst->x.x = 1.0f; + dst->y.y = 1.0f; + dst->z.z = 1.0f; + dst->t.w = 1.0f; +} + +EXPORT void matrix4_from_matrix3(struct matrix4 *dst, const struct matrix3 *m); + +EXPORT void matrix4_mul(struct matrix4 *dst, const struct matrix4 *m1, + const struct matrix4 *m2); + +EXPORT float matrix4_determinant(const struct matrix4 *m); + +EXPORT bool matrix4_inv(struct matrix4 *dst, const struct matrix4 *m); +EXPORT void matrix4_transpose(struct matrix4 *dst, const struct matrix4 *m); + +EXPORT void matrix4_ortho(struct matrix4 *dst, float left, float right, + float top, float bottom, float near, float far); +EXPORT void matrix4_frustum(struct matrix4 *dst, float left, float right, + float top, float bottom, float near, float far); +EXPORT void matrix4_perspective(struct matrix4 *dst, float angle, + float aspect, float near, float far); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/plane.c b/libobs/graphics/plane.c new file mode 100644 index 000000000..af4095083 --- /dev/null +++ b/libobs/graphics/plane.c @@ -0,0 +1,148 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "../util/c99defs.h" +#include "matrix3.h" +#include "plane.h" + +void plane_from_tri(struct plane *dst, + const struct vec3 *v1, + const struct vec3 *v2, + const struct vec3 *v3) +{ + struct vec3 temp; + + vec3_sub(&temp, v2, v1); + vec3_sub(&dst->dir, v3, v1); + vec3_cross(&dst->dir, &temp, &dst->dir); + vec3_norm(&dst->dir, &dst->dir); + dst->dist = vec3_dot(v1, &dst->dir); +} + +void plane_transform(struct plane *dst, const struct plane *p, + const struct matrix3 *m) +{ + struct vec3 temp; + + vec3_transform(&dst->dir, &p->dir, m); + vec3_norm(&dst->dir, &dst->dir); + + vec3_transform(&temp, &m->t, m); + dst->dist = p->dist - vec3_dot(&dst->dir, &temp); +} + +bool plane_intersection_ray(const struct plane *p, const struct vec3 *orig, + const struct vec3 *dir, float *t) +{ + float c = vec3_dot(&p->dir, dir); + + if (fabsf(c) < EPSILON) { + *t = 0.0f; + return false; + } else { + *t = (p->dist - vec3_dot(&p->dir, orig)) / c; + return true; + } +} + +bool plane_intersection_line(const struct plane *p, const struct vec3 *v1, + const struct vec3 *v2, float *t) +{ + float p1_dist, p2_dist, p1_abs_dist, dist2; + bool p1_over, p2_over; + + p1_dist = vec3_plane_dist(v1, p); + p2_dist = vec3_plane_dist(v2, p); + + if (close_float(p1_dist, 0.0f, EPSILON)) { + if (close_float(p2_dist, 0.0f, EPSILON)) + return false; + + *t = 0.0f; + return true; + } else if (close_float(p2_dist, 0.0f, EPSILON)) { + *t = 1.0f; + return true; + } + + p1_over = (p1_dist > 0.0f); + p2_over = (p2_dist > 0.0f); + + if (p1_over == p2_over) + return false; + + p1_abs_dist = fabsf(p1_dist); + dist2 = p1_abs_dist + fabsf(p2_dist); + if (dist2 < EPSILON) + return false; + + *t = p1_abs_dist / dist2; + return true; +} + +bool plane_tri_inside(const struct plane *p, + const struct vec3 *v1, + const struct vec3 *v2, + const struct vec3 *v3, + float precision) +{ + /* bit 1: part or all is behind the plane */ + /* bit 2: part or all is in front of the plane */ + int sides = 0; + float d1 = vec3_plane_dist(v1, p); + float d2 = vec3_plane_dist(v2, p); + float d3 = vec3_plane_dist(v3, p); + + if (d1 >= precision) + sides = 2; + else if (d1 <= -precision) + sides = 1; + + if (d2 >= precision) + sides |= 2; + else if (d2 <= -precision) + sides |= 1; + + if (d3 >= precision) + sides |= 2; + else if (d3 <= -precision) + sides |= 1; + + return sides; +} + +bool plane_line_inside(const struct plane *p, const struct vec3 *v1, + const struct vec3 *v2, float precision) +{ + /* bit 1: part or all is behind the plane */ + /* bit 2: part or all is in front of the plane */ + int sides = 0; + float d1 = vec3_plane_dist(v1, p); + float d2 = vec3_plane_dist(v2, p); + + if (d1 >= precision) + sides = 2; + else if (d1 <= -precision) + sides = 1; + + if (d2 >= precision) + sides |= 2; + else if (d2 <= -precision) + sides |= 1; + + return sides; +} diff --git a/libobs/graphics/plane.h b/libobs/graphics/plane.h new file mode 100644 index 000000000..f102f1b64 --- /dev/null +++ b/libobs/graphics/plane.h @@ -0,0 +1,101 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef PLANE_H +#define PLANE_H + +#include "math-defs.h" +#include "vec3.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct matrix3; + +struct plane { + struct vec3 dir; + float dist; +}; + +static inline void plane_copy(struct plane *dst, const struct plane *p) +{ + vec3_copy(&dst->dir, &p->dir); + dst->dist = p->dist; +} + +static inline void plane_set(struct plane *dst, const struct vec3 *dir, + float dist) +{ + vec3_copy(&dst->dir, dir); + dst->dist = dist; +} + +static inline void plane_setf(struct plane *dst, float a, float b, float c, + float d) +{ + vec3_set(&dst->dir, a, b, c); + dst->dist = d; +} + +EXPORT void plane_from_tri(struct plane *dst, + const struct vec3 *v1, + const struct vec3 *v2, + const struct vec3 *v3); + +EXPORT void plane_transform(struct plane *dst, const struct plane *p, + const struct matrix3 *m); + +EXPORT bool plane_intersection_ray(const struct plane *p, + const struct vec3 *orig, const struct vec3 *dir, float *t); +EXPORT bool plane_intersection_line(const struct plane *p, + const struct vec3 *v1, const struct vec3 *v2, float *t); + +EXPORT bool plane_tri_inside(const struct plane *p, + const struct vec3 *v1, + const struct vec3 *v2, + const struct vec3 *v3, + float precision); + +EXPORT bool plane_line_inside(const struct plane *p, const struct vec3 *v1, + const struct vec3 *v2, float precision); + +static inline bool plane_close(const struct plane *p1, const struct plane *p2, + float precision) +{ + return vec3_close(&p1->dir, &p2->dir, precision) && + close_float(p1->dist, p2->dist, precision); +} + +static inline bool plane_coplanar(const struct plane *p1, + const struct plane *p2, float precision) +{ + float cos_angle = vec3_dot(&p1->dir, &p2->dir); + + if (close_float(cos_angle, 1.0f, precision)) + return close_float(p1->dist, p2->dist, precision); + else if (close_float(cos_angle, -1.0f, precision)) + return close_float(-p1->dist, p2->dist, precision); + + return false; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/quat.c b/libobs/graphics/quat.c new file mode 100644 index 000000000..08dfcdecb --- /dev/null +++ b/libobs/graphics/quat.c @@ -0,0 +1,216 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "quat.h" +#include "vec3.h" +#include "matrix3.h" +#include "axisang.h" + +static inline void quat_vec3(struct vec3 *v, const struct quat *q) +{ + v->m = q->m; + v->w = 0.0f; +} + +void quat_mul(struct quat *dst, const struct quat *q1, const struct quat *q2) +{ + struct vec3 q1axis, q2axis; + struct vec3 temp1, temp2; + + quat_vec3(&q1axis, q1); + quat_vec3(&q2axis, q2); + + vec3_mulf(&temp1, &q2axis, q1->w); + vec3_mulf(&temp2, &q1axis, q2->w); + vec3_add(&temp1, &temp1, &temp2); + vec3_cross(&temp2, &q1axis, &q2axis); + vec3_add((struct vec3 *)dst, &temp1, &temp2); + + dst->w = (q1->w * q2->w) - vec3_dot(&q1axis, &q2axis); +} + +void quat_from_axisang(struct quat *dst, const struct axisang *aa) +{ + float halfa = aa->w * 0.5f; + float sine = sinf(halfa); + + dst->x = aa->x * sine; + dst->y = aa->y * sine; + dst->z = aa->z * sine; + dst->w = cosf(halfa); +} + +struct f4x4 { + float ptr[4][4]; +}; + +void quat_from_matrix(struct quat *dst, const struct matrix3 *m) +{ + float tr = (m->x.x + m->y.y + m->z.z); + float inv_half; + float four_d; + int i,j,k; + + if (tr > 0.0f) { + four_d = sqrtf(tr+1.0f); + dst->w = four_d*0.5f; + + inv_half = 0.5f/four_d; + dst->x = (m->y.z - m->z.y)*inv_half; + dst->y = (m->z.x - m->x.z)*inv_half; + dst->z = (m->x.y - m->y.x)*inv_half; + } else { + struct f4x4 *val = (struct f4x4*)m; + + i = (m->x.x > m->y.y) ? 0 : 1; + + if (m->z.z > val->ptr[i][i]) + i = 2; + + j = (i+1)%3; + k = (i+2)%3; + + /* ---------------------------------- */ + + four_d = sqrtf((val->ptr[i][i] - val->ptr[j][j] - + val->ptr[k][k]) + 1.0f); + + dst->ptr[i] = four_d*0.5f; + + inv_half = 0.5f/four_d; + dst->ptr[j] = (val->ptr[i][j] + val->ptr[j][i])*inv_half; + dst->ptr[k] = (val->ptr[i][k] + val->ptr[k][i])*inv_half; + dst->w = (val->ptr[j][k] - val->ptr[k][j])*inv_half; + } +} + +void quat_get_dir(struct vec3 *dst, const struct quat *q) +{ + struct matrix3 m; + matrix3_from_quat(&m, q); + vec3_copy(dst, &m.z); +} + +void quat_set_look_dir(struct quat *dst, const struct vec3 *dir) +{ + struct vec3 new_dir; + struct quat xz_rot, yz_rot; + bool xz_valid; + bool yz_valid; + struct axisang aa; + + vec3_norm(&new_dir, dir); + vec3_neg(&new_dir, &new_dir); + + quat_identity(&xz_rot); + quat_identity(&yz_rot); + + xz_valid = close_float(new_dir.x, 0.0f, EPSILON) || + close_float(new_dir.z, 0.0f, EPSILON); + yz_valid = close_float(new_dir.y, 0.0f, EPSILON); + + if (xz_valid) { + axisang_set(&aa, 0.0f, 1.0f, 0.0f, + atan2f(new_dir.x, new_dir.z)); + + quat_from_axisang(&xz_rot, &aa); + } + if (yz_valid) { + axisang_set(&aa, -1.0f, 0.0f, 0.0f, asinf(new_dir.y)); + quat_from_axisang(&yz_rot, &aa); + } + + if (!xz_valid) + quat_copy(dst, &yz_rot); + else if (!yz_valid) + quat_copy(dst, &xz_rot); + else + quat_mul(dst, &xz_rot, &yz_rot); +} + +void quat_log(struct quat *dst, const struct quat *q) +{ + float angle = acosf(q->w); + float sine = sinf(angle); + float w = q->w; + + quat_copy(dst, q); + dst->w = 0.0f; + + if ((fabsf(w) < 1.0f) && (fabsf(sine) >= EPSILON)) { + sine = angle/sine; + quat_mulf(dst, dst, sine); + } +} + +void quat_exp(struct quat *dst, const struct quat *q) +{ + float length = sqrtf(q->x*q->x + q->y*q->y + q->z*q->z); + float sine = sinf(length); + + quat_copy(dst, q); + sine = (length > EPSILON) ? (sine/length) : 1.0f; + quat_mulf(dst, dst, sine); + dst->w = cosf(length); +} + +void quat_interpolate(struct quat *dst, const struct quat *q1, + const struct quat *q2, float t) +{ + float dot = quat_dot(q1, q2); + float anglef = acosf(dot); + float sine, sinei, sinet, sineti; + struct quat temp; + + if (anglef >= EPSILON) { + sine = sinf(anglef); + sinei = 1/sine; + sinet = sinf(anglef*t)*sinei; + sineti = sinf(anglef*(1.0f-t))*sinei; + + quat_mulf(&temp, q1, sineti); + quat_mulf(dst, q2, sinet); + quat_add(dst, &temp, dst); + } else { + quat_sub(&temp, q2, q1); + quat_mulf(&temp, &temp, t); + quat_add(dst, &temp, q1); + } +} + +void quat_get_tangent(struct quat *dst, const struct quat *prev, + const struct quat *q, const struct quat *next) +{ + struct quat temp; + + quat_sub(&temp, q, prev); + quat_add(&temp, &temp, next); + quat_sub(&temp, &temp, q); + quat_mulf(dst, &temp, 0.5f); +} + +void quat_interpolate_cubic(struct quat *dst, + const struct quat *q1, const struct quat *q2, + const struct quat *m1, const struct quat *m2, + float t) +{ + struct quat temp1, temp2; + + quat_interpolate(&temp1, q1, q2, t); + quat_interpolate(&temp2, m1, m2, t); + quat_interpolate(dst, &temp1, &temp2, 2.0f*(1.0f-t)*t); +} diff --git a/libobs/graphics/quat.h b/libobs/graphics/quat.h new file mode 100644 index 000000000..b98c057e2 --- /dev/null +++ b/libobs/graphics/quat.h @@ -0,0 +1,185 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef QUAT_H +#define QUAT_H + +#include "../util/c99defs.h" +#include "math-defs.h" +#include "vec3.h" +#include + +/* + * Quaternion math + * + * Generally used to represent rotational data more than anything. Allows + * for efficient and correct rotational interpolation without suffering from + * things like gimbal lock. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +struct matrix3; +struct axisang; + +struct quat { + union { + struct {float x, y, z, w;}; + float ptr[4]; + __m128 m; + }; +}; + +static inline void quat_identity(struct quat *q) +{ + q->m = _mm_setzero_ps(); + q->w = 1.0f; +} + +static inline void quat_set(struct quat *dst, float x, float y, float z, + float w) +{ + dst->m = _mm_set_ps(x, y, z, w); +} + +static inline void quat_copy(struct quat *dst, const struct quat *q) +{ + dst->m = q->m; +} + +static inline void quat_add(struct quat *dst, const struct quat *q1, + const struct quat *q2) +{ + dst->m = _mm_add_ps(q1->m, q2->m); +} + +static inline void quat_sub(struct quat *dst, const struct quat *q1, + const struct quat *q2) +{ + dst->m = _mm_sub_ps(q1->m, q2->m); +} + +EXPORT void quat_mul(struct quat *dst, const struct quat *q1, + const struct quat *q2); + +static inline void quat_addf(struct quat *dst, const struct quat *q, + float f) +{ + dst->m = _mm_add_ps(q->m, _mm_set1_ps(f)); +} + +static inline void quat_subf(struct quat *dst, const struct quat *q, + float f) +{ + dst->m = _mm_sub_ps(q->m, _mm_set1_ps(f)); +} + +static inline void quat_mulf(struct quat *dst, const struct quat *q, + float f) +{ + dst->m = _mm_mul_ps(q->m, _mm_set1_ps(f)); +} + +static inline void quat_divf(struct quat *dst, const struct quat *q, + float f) +{ + dst->m = _mm_div_ps(q->m, _mm_set1_ps(f)); +} + +static inline float quat_dot(const struct quat *q1, const struct quat *q2) +{ + struct vec3 add; + __m128 mul = _mm_mul_ps(q1->m, q2->m); + add.m = _mm_add_ps(_mm_movehl_ps(mul, mul), mul); + add.m = _mm_add_ps(_mm_shuffle_ps(add.m, add.m, 0x55), add.m); + return add.x; +} + +static inline void quat_inv(struct quat *dst, const struct quat *q) +{ + dst->x = -q->x; + dst->y = -q->y; + dst->z = -q->z; +} + +static inline void quat_neg(struct quat *dst, const struct quat *q) +{ + dst->x = -q->x; + dst->y = -q->y; + dst->z = -q->z; + dst->w = -q->w; +} + +static inline float quat_len(const struct quat *q) +{ + float dot_val = quat_dot(q, q); + return (dot_val > 0.0f) ? sqrtf(dot_val) : 0.0f; +} + +static inline float quat_dist(const struct quat *q1, const struct quat *q2) +{ + struct quat temp; + float dot_val; + + quat_sub(&temp, q1, q2); + dot_val = quat_dot(&temp, &temp); + return (dot_val > 0.0f) ? sqrtf(dot_val) : 0.0f; +} + +static inline void quat_norm(struct quat *dst, const struct quat *q) +{ + float dot_val = quat_dot(q, q); + dst->m = (dot_val > 0.0f) ? + _mm_mul_ps(q->m, _mm_set1_ps(1.0f/sqrtf(dot_val))) : + _mm_setzero_ps(); +} + +static inline bool quat_close(const struct quat *q1, const struct quat *q2, + float epsilon) +{ + struct quat test; + quat_sub(&test, q1, q2); + return test.x < epsilon && + test.y < epsilon && + test.z < epsilon && + test.w < epsilon; +} + +EXPORT void quat_from_axisang(struct quat *dst, const struct axisang *aa); +EXPORT void quat_from_matrix3(struct quat *dst, const struct matrix3 *m); + +EXPORT void quat_get_dir(struct vec3 *dst, const struct quat *q); +EXPORT void quat_set_look_dir(struct quat *dst, const struct vec3 *dir); + +EXPORT void quat_log(struct quat *dst, const struct quat *q); +EXPORT void quat_exp(struct quat *dst, const struct quat *q); + +EXPORT void quat_interpolate(struct quat *dst, const struct quat *q1, + const struct quat *q2, float t); +EXPORT void quat_get_tangent(struct quat *dst, const struct quat *prev, + const struct quat *q, const struct quat *next); +EXPORT void quat_interpolate_cubic(struct quat *dst, const struct quat *q1, + const struct quat *q2, const struct quat *m1, + const struct quat *m2, float t); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/shader-parser.c b/libobs/graphics/shader-parser.c new file mode 100644 index 000000000..809da93fa --- /dev/null +++ b/libobs/graphics/shader-parser.c @@ -0,0 +1,677 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "shader-parser.h" + +enum shader_param_type get_shader_param_type(const char *type) +{ + if (strcmp(type, "float") == 0) + return SHADER_PARAM_FLOAT; + else if (strcmp(type, "float2") == 0) + return SHADER_PARAM_VEC2; + else if (strcmp(type, "float3") == 0) + return SHADER_PARAM_VEC3; + else if (strcmp(type, "float4") == 0) + return SHADER_PARAM_VEC4; + else if (astrcmp_n(type, "texture", 7) == 0) + return SHADER_PARAM_TEXTURE; + else if (strcmp(type, "float3x3") == 0) + return SHADER_PARAM_MATRIX3X3; + else if (strcmp(type, "float4x4") == 0) + return SHADER_PARAM_MATRIX4X4; + else if (strcmp(type, "bool") == 0) + return SHADER_PARAM_BOOL; + else if (strcmp(type, "int") == 0) + return SHADER_PARAM_INT; + else if (strcmp(type, "string") == 0) + return SHADER_PARAM_STRING; + + return SHADER_PARAM_UNKNOWN; +} + +enum gs_sample_filter get_sample_filter(const char *filter) +{ + if (astrcmpi(filter, "Anisotropy") == 0) + return GS_FILTER_ANISOTROPIC; + + else if (astrcmpi(filter, "Point") == 0 || + strcmp(filter, "MIN_MAG_MIP_POINT") == 0) + return GS_FILTER_POINT; + + else if (astrcmpi(filter, "Linear") == 0 || + strcmp(filter, "MIN_MAG_MIP_LINEAR") == 0) + return GS_FILTER_LINEAR; + + else if (strcmp(filter, "MIN_MAG_POINT_MIP_LINEAR") == 0) + return GS_FILTER_MIN_MAG_POINT_MIP_LINEAR; + + else if (strcmp(filter, "MIN_POINT_MAG_LINEAR_MIP_POINT") == 0) + return GS_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT; + + else if (strcmp(filter, "MIN_POINT_MAG_MIP_LINEAR") == 0) + return GS_FILTER_MIN_POINT_MAG_MIP_LINEAR; + + else if (strcmp(filter, "MIN_LINEAR_MAG_MIP_POINT") == 0) + return GS_FILTER_MIN_LINEAR_MAG_MIP_POINT; + + else if (strcmp(filter, "MIN_LINEAR_MAG_POINT_MIP_LINEAR") == 0) + return GS_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR; + + else if (strcmp(filter, "MIN_MAG_LINEAR_MIP_POINT") == 0) + return GS_FILTER_MIN_MAG_LINEAR_MIP_POINT; + + return GS_FILTER_LINEAR; +} + +extern enum gs_address_mode get_address_mode(const char *mode) +{ + if (astrcmpi(mode, "Wrap") == 0 || astrcmpi(mode, "Repeat") == 0) + return GS_ADDRESS_WRAP; + else if (astrcmpi(mode, "Clamp") == 0 || astrcmpi(mode, "None") == 0) + return GS_ADDRESS_CLAMP; + else if (astrcmpi(mode, "Mirror") == 0) + return GS_ADDRESS_MIRROR; + else if (astrcmpi(mode, "Border") == 0) + return GS_ADDRESS_BORDER; + else if (astrcmpi(mode, "MirrorOnce") == 0) + return GS_ADDRESS_MIRRORONCE; + + return GS_ADDRESS_CLAMP; +} + +void shader_sampler_convert(struct shader_sampler *ss, + struct gs_sampler_info *info) +{ + size_t i; + memset(info, 0, sizeof(struct gs_sampler_info)); + + for (i = 0; i < ss->states.num; i++) { + const char *state = ss->states.array[i]; + const char *value = ss->values.array[i]; + + if (astrcmpi(state, "Filter") == 0) + info->filter = get_sample_filter(value); + else if (astrcmpi(state, "AddressU") == 0) + info->address_u = get_address_mode(value); + else if (astrcmpi(state, "AddressV") == 0) + info->address_v = get_address_mode(value); + else if (astrcmpi(state, "AddressW") == 0) + info->address_w = get_address_mode(value); + else if (astrcmpi(state, "MaxAnisotropy") == 0) + info->max_anisotropy = strtol(value, NULL, 10); + /*else if (astrcmpi(state, "BorderColor") == 0) + // TODO */ + } +} + +/* ------------------------------------------------------------------------- */ + +static int sp_parse_sampler_state_item(struct shader_parser *sp, + struct shader_sampler *ss) +{ + int ret; + char *state = NULL, *value = NULL; + + ret = next_name(&sp->cfp, &state, "state name", ";"); + if (ret != PARSE_SUCCESS) goto fail; + + ret = next_token_should_be(&sp->cfp, "=", ";", NULL); + if (ret != PARSE_SUCCESS) goto fail; + + ret = next_name(&sp->cfp, &value, "value name", ";"); + if (ret != PARSE_SUCCESS) goto fail; + + ret = next_token_should_be(&sp->cfp, ";", ";", NULL); + if (ret != PARSE_SUCCESS) goto fail; + + da_push_back(ss->states, &state); + da_push_back(ss->values, &value); + return ret; + +fail: + bfree(state); + bfree(value); + return ret; +} + +static void sp_parse_sampler_state(struct shader_parser *sp) +{ + struct shader_sampler ss; + struct cf_token peek; + shader_sampler_init(&ss); + + if (next_name(&sp->cfp, &ss.name, "name", ";") != PARSE_SUCCESS) + goto error; + if (next_token_should_be(&sp->cfp, "{", ";", NULL) != PARSE_SUCCESS) + goto error; + + if (!peek_valid_token(&sp->cfp, &peek)) + goto error; + + while (strref_cmp(&peek.str, "}") != 0) { + int ret = sp_parse_sampler_state_item(sp, &ss); + if (ret == PARSE_EOF) + goto error; + + if (!peek_valid_token(&sp->cfp, &peek)) + goto error; + } + + if (next_token_should_be(&sp->cfp, "}", ";", NULL) != PARSE_SUCCESS) + goto error; + if (next_token_should_be(&sp->cfp, ";", NULL, NULL) != PARSE_SUCCESS) + goto error; + + da_push_back(sp->samplers, &ss); + return; + +error: + shader_sampler_free(&ss); +} + +static inline int sp_parse_struct_var(struct shader_parser *sp, + struct shader_var *var) +{ + int errcode; + + /* -------------------------------------- */ + /* variable type */ + + if (!next_valid_token(&sp->cfp)) return PARSE_EOF; + + if (token_is(&sp->cfp, ";")) return PARSE_CONTINUE; + if (token_is(&sp->cfp, "}")) return PARSE_BREAK; + + errcode = token_is_type(&sp->cfp, CFTOKEN_NAME, "type name", ";"); + if (errcode != PARSE_SUCCESS) + return errcode; + + copy_token(&sp->cfp, &var->type); + + /* -------------------------------------- */ + /* variable name */ + + if (!next_valid_token(&sp->cfp)) return PARSE_EOF; + + if (token_is(&sp->cfp, ";")) return PARSE_UNEXPECTED_CONTINUE; + if (token_is(&sp->cfp, "}")) return PARSE_UNEXPECTED_BREAK; + + errcode = token_is_type(&sp->cfp, CFTOKEN_NAME, "variable name", ";"); + if (errcode != PARSE_SUCCESS) + return errcode; + + copy_token(&sp->cfp, &var->name); + + /* -------------------------------------- */ + /* variable mapping if any (POSITION, TEXCOORD, etc) */ + + if (!next_valid_token(&sp->cfp)) return PARSE_EOF; + + if (token_is(&sp->cfp, ":")) { + if (!next_valid_token(&sp->cfp)) return PARSE_EOF; + + if (token_is(&sp->cfp, ";")) return PARSE_UNEXPECTED_CONTINUE; + if (token_is(&sp->cfp, "}")) return PARSE_UNEXPECTED_BREAK; + + errcode = token_is_type(&sp->cfp, CFTOKEN_NAME, + "mapping name", ";"); + if (errcode != PARSE_SUCCESS) + return errcode; + + copy_token(&sp->cfp, &var->mapping); + + if (!next_valid_token(&sp->cfp)) return PARSE_EOF; + } + + /* -------------------------------------- */ + + if (!token_is(&sp->cfp, ";")) { + if (!go_to_valid_token(&sp->cfp, ";", "}")) + return PARSE_EOF; + return PARSE_CONTINUE; + } + + return PARSE_SUCCESS; +} + +static void sp_parse_struct(struct shader_parser *sp) +{ + struct shader_struct ss; + shader_struct_init(&ss); + + if (next_name(&sp->cfp, &ss.name, "name", ";") != PARSE_SUCCESS) + goto error; + if (next_token_should_be(&sp->cfp, "{", ";", NULL) != PARSE_SUCCESS) + goto error; + + /* get structure variables */ + while (true) { + bool do_break = false; + struct shader_var var; + + shader_var_init(&var); + + switch (sp_parse_struct_var(sp, &var)) { + + case PARSE_UNEXPECTED_CONTINUE: + cf_adderror_syntax_error(&sp->cfp); + case PARSE_CONTINUE: + shader_var_free(&var); + continue; + + case PARSE_UNEXPECTED_BREAK: + cf_adderror_syntax_error(&sp->cfp); + case PARSE_BREAK: + shader_var_free(&var); + do_break = true; + break; + + case PARSE_EOF: + shader_var_free(&var); + goto error; + } + + if (do_break) + break; + + da_push_back(ss.vars, &var); + } + + if (next_token_should_be(&sp->cfp, ";", NULL, NULL) != PARSE_SUCCESS) + goto error; + + da_push_back(sp->structs, &ss); + return; + +error: + shader_struct_free(&ss); +} + +static inline int sp_check_for_keyword(struct shader_parser *sp, + const char *keyword, bool *val) +{ + bool new_val; + new_val = token_is(&sp->cfp, keyword); + if (new_val) { + if (!next_valid_token(&sp->cfp)) + return PARSE_EOF; + + if (new_val && *val) + cf_adderror(&sp->cfp, "'$1' keyword already specified", + LEVEL_WARNING, keyword, NULL, NULL); + *val = new_val; + + return PARSE_CONTINUE; + } + + return PARSE_SUCCESS; +} + +static inline int sp_parse_func_param(struct shader_parser *sp, + struct shader_func *func, struct shader_var *var) +{ + int errcode; + bool is_uniform; + + if (!next_valid_token(&sp->cfp)) + return PARSE_EOF; + + errcode = sp_check_for_keyword(sp, "uniform", &is_uniform); + if (errcode == PARSE_EOF) + return PARSE_EOF; + + var->var_type = is_uniform ? SHADER_VAR_UNIFORM : SHADER_VAR_NONE; + + errcode = get_name(&sp->cfp, &var->type, "type", ")"); + if (errcode != PARSE_SUCCESS) + return errcode; + + errcode = next_name(&sp->cfp, &var->name, "name", ")"); + if (errcode != PARSE_SUCCESS) + return errcode; + + if (!next_valid_token(&sp->cfp)) + return PARSE_EOF; + + if (token_is(&sp->cfp, ":")) { + errcode = next_name(&sp->cfp, &var->mapping, + "mapping specifier", ")"); + if (errcode != PARSE_SUCCESS) + return errcode; + + if (!next_valid_token(&sp->cfp)) + return PARSE_EOF; + } + + return PARSE_SUCCESS; +} + +static bool sp_parse_func_params(struct shader_parser *sp, + struct shader_func *func) +{ + struct cf_token peek; + int errcode; + + cf_token_clear(&peek); + + if (!peek_valid_token(&sp->cfp, &peek)) + return false; + + if (*peek.str.array == ')') { + next_token(&sp->cfp); + goto exit; + } + + do { + struct shader_var var; + shader_var_init(&var); + + if (!token_is(&sp->cfp, "(") && !token_is(&sp->cfp, ",")) + cf_adderror_syntax_error(&sp->cfp); + + errcode = sp_parse_func_param(sp, func, &var); + if (errcode != PARSE_SUCCESS) { + shader_var_free(&var); + + if (errcode == PARSE_CONTINUE) + goto exit; + else if (errcode == PARSE_EOF) + return false; + } + + da_push_back(func->params, &var); + } while (!token_is(&sp->cfp, ")")); + +exit: + return true; +} + +static void sp_parse_function(struct shader_parser *sp, + char *type, char *name) +{ + struct shader_func func; + + shader_func_init(&func, type, name); + if (!sp_parse_func_params(sp, &func)) + goto error; + + if (!next_valid_token(&sp->cfp)) + goto error; + + /* if function is mapped to something, for example COLOR */ + if (token_is(&sp->cfp, ":")) { + if (!next_valid_token(&sp->cfp)) + goto error; + if (!next_valid_token(&sp->cfp)) + goto error; + } + + if (!token_is(&sp->cfp, "{")) { + cf_adderror_expecting(&sp->cfp, "{"); + goto error; + } + + func.start = sp->cfp.cur_token; + if (!pass_pair(&sp->cfp, '{', '}')) + goto error; + + /* it is established that the current token is '}' if we reach this */ + next_token(&sp->cfp); + + func.end = sp->cfp.cur_token; + da_push_back(sp->funcs, &func); + return; + +error: + shader_func_free(&func); +} + +/* parses "array[count]" */ +static bool sp_parse_param_array(struct shader_parser *sp, + struct shader_var *param) +{ + if (!next_valid_token(&sp->cfp)) + return false; + + if (sp->cfp.cur_token->type != CFTOKEN_NUM || + !valid_int_str(sp->cfp.cur_token->str.array, + sp->cfp.cur_token->str.len)) + return false; + + param->array_count = strtol(sp->cfp.cur_token->str.array, NULL, 10); + + if (next_token_should_be(&sp->cfp, "]", ";", NULL) == PARSE_EOF) + return false; + + if (!next_valid_token(&sp->cfp)) + return false; + + return true; +} + +static inline int sp_parse_param_assign_intfloat(struct shader_parser *sp, + struct shader_var *param, bool is_float) +{ + int errcode; + + if (!next_valid_token(&sp->cfp)) + return PARSE_EOF; + + errcode = token_is_type(&sp->cfp, CFTOKEN_NUM, "numeric value", ";"); + if (errcode != PARSE_SUCCESS) + return errcode; + + if (is_float) { + float f = (float)strtod(sp->cfp.cur_token->str.array, NULL); + da_push_back_array(param->default_val, &f, sizeof(float)); + } else { + long l = strtol(sp->cfp.cur_token->str.array, NULL, 10); + da_push_back_array(param->default_val, &l, sizeof(long)); + } + + return PARSE_SUCCESS; +} + +/* + * parses assignment for float1, float2, float3, float4, and any combination + * for float3x3, float4x4, etc + */ +static inline int sp_parse_param_assign_float_array(struct shader_parser *sp, + struct shader_var *param) +{ + const char *float_type = param->type+5; + int float_count = 0, errcode, i; + + /* -------------------------------------------- */ + + if (float_type[0] < '1' || float_type[0] > '4') + cf_adderror(&sp->cfp, "Invalid row count", LEVEL_ERROR, + NULL, NULL, NULL); + + float_count = float_type[0]-'0'; + + if (float_type[1] == 'x') { + if (float_type[2] < '1' || float_type[2] > '4') + cf_adderror(&sp->cfp, "Invalid column count", + LEVEL_ERROR, NULL, NULL, NULL); + + float_count *= float_type[2]-'0'; + } + + /* -------------------------------------------- */ + + errcode = next_token_should_be(&sp->cfp, "{", ";", NULL); + if (errcode != PARSE_SUCCESS) return errcode; + + for (i = 0; i < float_count; i++) { + char *next = ((i+1) < float_count) ? "," : "}"; + + errcode = sp_parse_param_assign_intfloat(sp, param, true); + if (errcode != PARSE_SUCCESS) return errcode; + + errcode = next_token_should_be(&sp->cfp, next, ";", NULL); + if (errcode != PARSE_SUCCESS) return errcode; + } + + return PARSE_SUCCESS; +} + +static int sp_parse_param_assignment_val(struct shader_parser *sp, + struct shader_var *param) +{ + if (strcmp(param->type, "int") == 0) + return sp_parse_param_assign_intfloat(sp, param, false); + else if (strcmp(param->type, "float") == 0) + return sp_parse_param_assign_intfloat(sp, param, true); + else if (astrcmp_n(param->type, "float", 5) == 0) + return sp_parse_param_assign_float_array(sp, param); + + cf_adderror(&sp->cfp, "Invalid type '$1' used for assignment", + LEVEL_ERROR, param->type, NULL, NULL); + + return PARSE_CONTINUE; +} + +static inline bool sp_parse_param_assignment(struct shader_parser *sp, + struct shader_var *param) +{ + if (sp_parse_param_assignment_val(sp, param) != PARSE_SUCCESS) + return false; + + if (!next_valid_token(&sp->cfp)) + return false; + + return true; +} + +static void sp_parse_param(struct shader_parser *sp, + char *type, char *name, bool is_const, bool is_uniform) +{ + struct shader_var param; + shader_var_init_param(¶m, type, name, is_uniform, is_const); + + if (token_is(&sp->cfp, ";")) + goto complete; + if (token_is(&sp->cfp, "[") && !sp_parse_param_array(sp, ¶m)) + goto error; + if (token_is(&sp->cfp, "=") && !sp_parse_param_assignment(sp, ¶m)) + goto error; + if (!token_is(&sp->cfp, ";")) + goto error; + +complete: + da_push_back(sp->params, ¶m); + return; + +error: + shader_var_free(¶m); +} + +static bool sp_get_var_specifiers(struct shader_parser *sp, + bool *is_const, bool *is_uniform) +{ + while(true) { + int errcode; + errcode = sp_check_for_keyword(sp, "const", is_const); + if (errcode == PARSE_EOF) + return false; + else if (errcode == PARSE_CONTINUE) + continue; + + errcode = sp_check_for_keyword(sp, "uniform", is_uniform); + if (errcode == PARSE_EOF) + return false; + else if (errcode == PARSE_CONTINUE) + continue; + + break; + } + + return true; +} + +static inline void report_invalid_func_keyword(struct shader_parser *sp, + const char *name, bool val) +{ + if (val) + cf_adderror(&sp->cfp, "'$1' keyword cannot be used with a " + "function", LEVEL_ERROR, + name, NULL, NULL); +} + +static void sp_parse_other(struct shader_parser *sp) +{ + bool is_const = false, is_uniform = false; + char *type = NULL, *name = NULL; + + if (!sp_get_var_specifiers(sp, &is_const, &is_uniform)) + goto error; + + if (get_name(&sp->cfp, &type, "type", ";") != PARSE_SUCCESS) + goto error; + if (next_name(&sp->cfp, &name, "name", ";") != PARSE_SUCCESS) + goto error; + + if (!next_valid_token(&sp->cfp)) + goto error; + + if (token_is(&sp->cfp, "(")) { + report_invalid_func_keyword(sp, "const", is_const); + report_invalid_func_keyword(sp, "uniform", is_uniform); + + sp_parse_function(sp, type, name); + return; + } else { + sp_parse_param(sp, type, name, is_const, is_uniform); + return; + } + +error: + bfree(type); + bfree(name); +} + +bool shader_parse(struct shader_parser *sp, const char *shader, + const char *file) +{ + if (!cf_parser_parse(&sp->cfp, shader, file)) + return false; + + while (sp->cfp.cur_token && sp->cfp.cur_token->type != CFTOKEN_NONE) { + if (token_is(&sp->cfp, ";") || + is_whitespace(*sp->cfp.cur_token->str.array)) { + sp->cfp.cur_token++; + + } else if (token_is(&sp->cfp, "struct")) { + sp_parse_struct(sp); + + } else if (token_is(&sp->cfp, "sampler_state")) { + sp_parse_sampler_state(sp); + + } else if (token_is(&sp->cfp, "{")) { + cf_adderror(&sp->cfp, "Unexpected code segment", + LEVEL_ERROR, NULL, NULL, NULL); + pass_pair(&sp->cfp, '{', '}'); + + } else { + /* parameters and functions */ + sp_parse_other(sp); + } + } + + return !error_data_has_errors(&sp->cfp.error_list); +} diff --git a/libobs/graphics/shader-parser.h b/libobs/graphics/shader-parser.h new file mode 100644 index 000000000..8b1805316 --- /dev/null +++ b/libobs/graphics/shader-parser.h @@ -0,0 +1,246 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef SHADER_PARSER_H +#define SHADER_PARSER_H + +#include "../util/cf-parser.h" +#include "graphics.h" + +#ifdef __cplusplus +extern "C" { +#endif + +EXPORT enum shader_param_type get_shader_param_type(const char *type); +EXPORT enum gs_sample_filter get_sample_filter(const char *filter); +EXPORT enum gs_address_mode get_address_mode(const char *address_mode); + +/* + * Shader Parser + * + * Parses a shader and extracts data such as shader constants, samplers, + * and vertex input information. Also allows the reformatting of shaders for + * different libraries. This is usually used only by graphics libraries, + */ + +enum shader_var_type { + SHADER_VAR_NONE, + SHADER_VAR_UNIFORM, + SHADER_VAR_CONST +}; + +struct shader_var { + char *type; + char *name; + char *mapping; + enum shader_var_type var_type; + int array_count; + + DARRAY(uint8_t) default_val; +}; + +static inline void shader_var_init(struct shader_var *sv) +{ + memset(sv, 0, sizeof(struct shader_var)); +} + +static inline void shader_var_init_param(struct shader_var *sv, + char *type, char *name, bool is_uniform, + bool is_const) +{ + if (is_uniform) + sv->var_type = SHADER_VAR_UNIFORM; + else if (is_const) + sv->var_type = SHADER_VAR_CONST; + else + sv->var_type = SHADER_VAR_NONE; + + sv->type = type; + sv->name = name; + sv->mapping = NULL; + sv->array_count = 0; + da_init(sv->default_val); +} + +static inline void shader_var_free(struct shader_var *sv) +{ + bfree(sv->type); + bfree(sv->name); + bfree(sv->mapping); + da_free(sv->default_val); +} + +/* ------------------------------------------------------------------------- */ + +struct shader_sampler { + char *name; + DARRAY(char*) states; + DARRAY(char*) values; +}; + +static inline void shader_sampler_init(struct shader_sampler *ss) +{ + memset(ss, 0, sizeof(struct shader_sampler)); +} + +static inline void shader_sampler_free(struct shader_sampler *ss) +{ + size_t i; + for (i = 0; i < ss->states.num; i++) + bfree(ss->states.array[i]); + for (i = 0; i < ss->values.num; i++) + bfree(ss->values.array[i]); + + bfree(ss->name); + da_free(ss->states); + da_free(ss->values); +} + +EXPORT void shader_sampler_convert(struct shader_sampler *ss, + struct gs_sampler_info *info); + +/* ------------------------------------------------------------------------- */ + +struct shader_struct { + char *name; + DARRAY(struct shader_var) vars; +}; + +static inline void shader_struct_init(struct shader_struct *ss) +{ + memset(ss, 0, sizeof(struct shader_struct)); +} + +static inline void shader_struct_free(struct shader_struct *ss) +{ + size_t i; + + for (i = 0; i < ss->vars.num; i++) + shader_var_free(ss->vars.array+i); + + bfree(ss->name); + da_free(ss->vars); +} + +/* ------------------------------------------------------------------------- */ + +struct shader_func { + char *name; + char *return_type; + DARRAY(struct shader_var) params; + + const struct cf_token *start, *end; +}; + +static inline void shader_func_init(struct shader_func *sf, + char *return_type, char *name) +{ + da_init(sf->params); + + sf->return_type = return_type; + sf->name = name; + sf->start = NULL; + sf->end = NULL; +} + +static inline void shader_func_free(struct shader_func *sf) +{ + size_t i; + + for (i = 0; i < sf->params.num; i++) + shader_var_free(sf->params.array+i); + + bfree(sf->name); + bfree(sf->return_type); + da_free(sf->params); +} + +/* ------------------------------------------------------------------------- */ + +struct shader_parser { + struct cf_parser cfp; + + DARRAY(struct shader_var) params; + DARRAY(struct shader_struct) structs; + DARRAY(struct shader_sampler) samplers; + DARRAY(struct shader_func) funcs; +}; + +static inline void shader_parser_init(struct shader_parser *sp) +{ + cf_parser_init(&sp->cfp); + + da_init(sp->params); + da_init(sp->structs); + da_init(sp->samplers); + da_init(sp->funcs); +} + +static inline void shader_parser_free(struct shader_parser *sp) +{ + size_t i; + + for (i = 0; i < sp->params.num; i++) + shader_var_free(sp->params.array+i); + for (i = 0; i < sp->structs.num; i++) + shader_struct_free(sp->structs.array+i); + for (i = 0; i < sp->samplers.num; i++) + shader_sampler_free(sp->samplers.array+i); + for (i = 0; i < sp->funcs.num; i++) + shader_func_free(sp->funcs.array+i); + + cf_parser_free(&sp->cfp); + da_free(sp->params); + da_free(sp->structs); + da_free(sp->samplers); + da_free(sp->funcs); +} + +EXPORT bool shader_parse(struct shader_parser *sp, const char *shader, + const char *file); + +static inline struct shader_func *shader_parser_getfunc( + struct shader_parser *sp, const char *func_name) +{ + size_t i; + for (i = 0; i < sp->funcs.num; i++) { + struct shader_func *func = sp->funcs.array+i; + if (strcmp(func->name, func_name) == 0) + return func; + } + + return NULL; +} + +static inline struct shader_struct *shader_parser_getstruct( + struct shader_parser *sp, const char *struct_name) +{ + size_t i; + for (i = 0; i < sp->structs.num; i++) { + struct shader_struct *st = sp->structs.array+i; + if (strcmp(st->name, struct_name) == 0) + return st; + } + + return NULL; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/texture-render.c b/libobs/graphics/texture-render.c new file mode 100644 index 000000000..63450bced --- /dev/null +++ b/libobs/graphics/texture-render.c @@ -0,0 +1,139 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +/* + * This is a set of helper functions to more easily render to textures + * without having to duplicate too much code. + */ + +#include +#include "graphics.h" + +struct gs_texture_render { + texture_t target, prev_target; + zstencil_t zs, prev_zs; + + int cx, cy; + + enum gs_color_format format; + enum gs_zstencil_format zsformat; + + bool rendered; +}; + +texrender_t texrender_create(enum gs_color_format format, + enum gs_zstencil_format zsformat) +{ + struct gs_texture_render *texrender; + texrender = bmalloc(sizeof(struct gs_texture_render)); + memset(texrender, 0, sizeof(struct gs_texture_render)); + + texrender->format = format; + texrender->zsformat = zsformat; + + return texrender; +} + +void texrender_destroy(texrender_t texrender) +{ + if (texrender) { + texture_destroy(texrender->target); + zstencil_destroy(texrender->zs); + bfree(texrender); + } +} + +static bool texrender_resetbuffer(texrender_t texrender, int cx, int cy) +{ + texture_destroy(texrender->target); + zstencil_destroy(texrender->zs); + + texrender->target = NULL; + texrender->zs = NULL; + texrender->cx = cx; + texrender->cy = cy; + + texrender->target = gs_create_texture(cx, cy, texrender->format, + NULL, GS_RENDERTARGET); + if (!texrender->target) + return false; + + if (texrender->zsformat != GS_ZS_NONE) { + texrender->zs = gs_create_zstencil(cx, cy, texrender->zsformat); + if (!texrender->zs) { + texture_destroy(texrender->target); + texrender->target = NULL; + + return false; + } + } + + return true; +} + +bool texrender_begin(texrender_t texrender, int cx, int cy) +{ + if (texrender->rendered) + return false; + + if (cx == -1) + cx = gs_getwidth(); + if (cy == -1) + cy = gs_getheight(); + + assert(cx && cy); + if (!cx || !cy) + return false; + + if (texrender->cx != cx || texrender->cy != cy) + if (!texrender_resetbuffer(texrender, cx, cy)) + return false; + + gs_viewport_push(); + gs_projection_push(); + gs_matrix_push(); + gs_matrix_identity(); + + texrender->prev_target = gs_getrendertarget(); + texrender->prev_zs = gs_getzstenciltarget(); + gs_setrendertarget(texrender->target, texrender->zs); + + gs_setviewport(0, 0, texrender->cx, texrender->cy); + + return true; +} + +void texrender_end(texrender_t texrender) +{ + gs_setrendertarget(texrender->prev_target, texrender->prev_zs); + + gs_matrix_pop(); + gs_projection_pop(); + gs_viewport_pop(); + + texrender->rendered = true; +} + +void texrender_reset(texrender_t texrender) +{ + texrender->rendered = false; +} + +texture_t texrender_gettexture(texrender_t texrender) +{ + return texrender->target; +} diff --git a/libobs/graphics/vec2.c b/libobs/graphics/vec2.c new file mode 100644 index 000000000..d9cfb753d --- /dev/null +++ b/libobs/graphics/vec2.c @@ -0,0 +1,52 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include +#include "math-extra.h" +#include "math-defs.h" +#include "vec2.h" + +void vec2_abs(struct vec2 *dst, const struct vec2 *v) +{ + vec2_set(dst, fabsf(v->x), fabsf(v->y)); +} + +void vec2_floor(struct vec2 *dst, const struct vec2 *v) +{ + vec2_set(dst, floorf(v->x), floorf(v->y)); +} + +void vec2_ceil(struct vec2 *dst, const struct vec2 *v) +{ + vec2_set(dst, ceilf(v->x), ceilf(v->y)); +} + +int vec2_close(const struct vec2 *v1, const struct vec2 *v2, float epsilon) +{ + return close_float(v1->x, v2->x, epsilon) && + close_float(v1->y, v2->y, epsilon); +} + +void vec2_norm(struct vec2 *dst, const struct vec2 *v) +{ + float len = vec2_len(v); + + if (len > 0.0f) { + len = 1.0f / len; + vec2_mulf(dst, v, len); + } +} diff --git a/libobs/graphics/vec2.h b/libobs/graphics/vec2.h new file mode 100644 index 000000000..ce0879513 --- /dev/null +++ b/libobs/graphics/vec2.h @@ -0,0 +1,171 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef VECT2_H +#define VECT2_H + +#include "../util/c99defs.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct vec2 { + union { + struct { + float x, y; + }; + float ptr[2]; + }; +}; + +static inline void vec2_zero(struct vec2 *dst) +{ + dst->x = 0.0f; + dst->y = 0.0f; +} + +static inline void vec2_set(struct vec2 *dst, float x, float y) +{ + dst->x = x; + dst->y = y; +} + +static inline void vec2_copy(struct vec2 *dst, const struct vec2 *v) +{ + dst->x = v->x; + dst->y = v->y; +} + +static inline void vec2_add(struct vec2 *dst, const struct vec2 *v1, + const struct vec2 *v2) +{ + vec2_set(dst, v1->x+v2->x, v1->y+v2->y); +} + +static inline void vec2_sub(struct vec2 *dst, const struct vec2 *v1, + const struct vec2 *v2) +{ + vec2_set(dst, v1->x-v2->x, v1->y-v2->y); +} + +static inline void vec2_mul(struct vec2 *dst, const struct vec2 *v1, + const struct vec2 *v2) +{ + vec2_set(dst, v1->x*v2->x, v1->y*v2->y); +} + +static inline void vec2_div(struct vec2 *dst, const struct vec2 *v1, + const struct vec2 *v2) +{ + vec2_set(dst, v1->x/v2->x, v1->y/v2->y); +} + +static inline void vec2_addf(struct vec2 *dst, const struct vec2 *v, + float f) +{ + vec2_set(dst, v->x+f, v->y+f); +} + +static inline void vec2_subf(struct vec2 *dst, const struct vec2 *v, + float f) +{ + vec2_set(dst, v->x-f, v->y-f); +} + +static inline void vec2_mulf(struct vec2 *dst, const struct vec2 *v, + float f) +{ + vec2_set(dst, v->x*f, v->y*f); +} + +static inline void vec2_divf(struct vec2 *dst, const struct vec2 *v, + float f) +{ + vec2_set(dst, v->x/f, v->y/f); +} + +static inline void vec2_neg(struct vec2 *dst, const struct vec2 *v) +{ + vec2_set(dst, -v->x, -v->y); +} + +static inline float vec2_dot(const struct vec2 *v1, const struct vec2 *v2) +{ + return (v1->x+v2->x) * (v1->y+v2->y); +} + +static inline float vec2_len(const struct vec2 *v) +{ + return sqrtf(v->x*v->x + v->y*v->y); +} + +static inline float vec2_dist(const struct vec2 *v1, const struct vec2 *v2) +{ + struct vec2 temp; + vec2_sub(&temp, v1, v2); + return vec2_len(&temp); +} + +static inline void vec2_minf(struct vec2 *dst, const struct vec2 *v, + float val) +{ + if (v->x < val) + dst->x = val; + if (v->y < val) + dst->y = val; +} + +static inline void vec2_min(struct vec2 *dst, const struct vec2 *v, + const struct vec2 *min_v) +{ + if (v->x < min_v->x) + dst->x = min_v->x; + if (v->y < min_v->y) + dst->y = min_v->y; +} + +static inline void vec2_maxf(struct vec2 *dst, const struct vec2 *v, + float val) +{ + if (v->x > val) + dst->x = val; + if (v->y > val) + dst->y = val; +} + +static inline void vec2_max(struct vec2 *dst, const struct vec2 *v, + const struct vec2 *max_v) +{ + if (v->x > max_v->x) + dst->x = max_v->x; + if (v->y > max_v->y) + dst->y = max_v->y; +} + +EXPORT void vec2_abs(struct vec2 *dst, const struct vec2 *v); +EXPORT void vec2_floor(struct vec2 *dst, const struct vec2 *v); +EXPORT void vec2_ceil(struct vec2 *dst, const struct vec2 *v); +EXPORT int vec2_close(const struct vec2 *v1, const struct vec2 *v2, + float epsilon); +EXPORT void vec2_norm(struct vec2 *dst, const struct vec2 *v); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libobs/graphics/vec3.c b/libobs/graphics/vec3.c new file mode 100644 index 000000000..abe28ca16 --- /dev/null +++ b/libobs/graphics/vec3.c @@ -0,0 +1,73 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "vec3.h" +#include "quat.h" +#include "axisang.h" +#include "plane.h" +#include "matrix3.h" +#include "math-extra.h" + +float vec3_plane_dist(const struct vec3 *v, const struct plane *p) +{ + return vec3_dot(v, &p->dir) - p->dist; +} + +void vec3_rotate(struct vec3 *dst, const struct vec3 *v, + const struct matrix3 *m) +{ + struct vec3 temp; + vec3_copy(&temp, v); + + dst->x = vec3_dot(&temp, &m->x); + dst->y = vec3_dot(&temp, &m->y); + dst->z = vec3_dot(&temp, &m->z); +} + +void vec3_transform(struct vec3 *dst, const struct vec3 *v, + const struct matrix3 *m) +{ + struct vec3 temp; + vec3_sub(&temp, v, &m->t); + + dst->x = vec3_dot(&temp, &m->x); + dst->y = vec3_dot(&temp, &m->y); + dst->z = vec3_dot(&temp, &m->z); +} + +void vec3_mirror(struct vec3 *dst, const struct vec3 *v, const struct plane *p) +{ + struct vec3 temp; + vec3_mulf(&temp, &p->dir, vec3_plane_dist(v, p) * 2.0f); + vec3_sub(dst, v, &temp); +} + +void vec3_mirrorv(struct vec3 *dst, const struct vec3 *v, + const struct vec3 *vec) +{ + struct vec3 temp; + vec3_mulf(&temp, vec, vec3_dot(v, vec) * 2.0f); + vec3_sub(dst, v, &temp); +} + +void vec3_rand(struct vec3 *dst, int positive_only) +{ + dst->x = rand_float(positive_only); + dst->y = rand_float(positive_only); + dst->z = rand_float(positive_only); + dst->w = 0.0f; +} diff --git a/libobs/graphics/vec3.h b/libobs/graphics/vec3.h new file mode 100644 index 000000000..0bf48085a --- /dev/null +++ b/libobs/graphics/vec3.h @@ -0,0 +1,236 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef VECT_H +#define VECT_H + +#include "math-defs.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct plane; +struct matrix3; +struct quat; + +struct vec3 { + union { + struct { + float x, y, z, w; + }; + float ptr[4]; + __m128 m; + }; +}; + +static inline void vec3_zero(struct vec3 *v) +{ + v->m = _mm_setzero_ps(); +} + +static inline void vec3_set(struct vec3 *dst, float x, float y, float z) +{ + dst->m = _mm_set_ps(0.0f, z, y, x); +} + +static inline void vec3_copy(struct vec3 *dst, const struct vec3 *v) +{ + dst->m = v->m; +} + +static inline void vec3_add(struct vec3 *dst, const struct vec3 *v1, + const struct vec3 *v2) +{ + dst->m = _mm_add_ps(v1->m, v2->m); + dst->w = 0.0f; +} + +static inline void vec3_sub(struct vec3 *dst, const struct vec3 *v1, + const struct vec3 *v2) +{ + dst->m = _mm_sub_ps(v1->m, v2->m); + dst->w = 0.0f; +} + +static inline void vec3_mul(struct vec3 *dst, const struct vec3 *v1, + const struct vec3 *v2) +{ + dst->m = _mm_mul_ps(v1->m, v2->m); +} + +static inline void vec3_div(struct vec3 *dst, const struct vec3 *v1, + const struct vec3 *v2) +{ + dst->m = _mm_div_ps(v1->m, v2->m); + dst->w = 0.0f; +} + +static inline void vec3_addf(struct vec3 *dst, const struct vec3 *v, + float f) +{ + dst->m = _mm_add_ps(v->m, _mm_set1_ps(f)); + dst->w = 0.0f; +} + +static inline void vec3_subf(struct vec3 *dst, const struct vec3 *v, + float f) +{ + dst->m = _mm_sub_ps(v->m, _mm_set1_ps(f)); + dst->w = 0.0f; +} + +static inline void vec3_mulf(struct vec3 *dst, const struct vec3 *v, + float f) +{ + dst->m = _mm_mul_ps(v->m, _mm_set1_ps(f)); +} + +static inline void vec3_divf(struct vec3 *dst, const struct vec3 *v, + float f) +{ + dst->m = _mm_div_ps(v->m, _mm_set1_ps(f)); + dst->w = 0.0f; +} + +static inline float vec3_dot(const struct vec3 *v1, const struct vec3 *v2) +{ + struct vec3 add; + __m128 mul = _mm_mul_ps(v1->m, v2->m); + add.m = _mm_add_ps(_mm_movehl_ps(mul, mul), mul); + add.m = _mm_add_ps(_mm_shuffle_ps(add.m, add.m, 0x55), add.m); + return add.x; +} + +static inline void vec3_cross(struct vec3 *dst, const struct vec3 *v1, + const struct vec3 *v2) +{ + __m128 s1v1 = _mm_shuffle_ps(v1->m, v1->m, _MM_SHUFFLE(3, 0, 2, 1)); + __m128 s1v2 = _mm_shuffle_ps(v2->m, v2->m, _MM_SHUFFLE(3, 1, 0, 2)); + __m128 s2v1 = _mm_shuffle_ps(v1->m, v1->m, _MM_SHUFFLE(3, 1, 0, 2)); + __m128 s2v2 = _mm_shuffle_ps(v2->m, v2->m, _MM_SHUFFLE(3, 0, 2, 1)); + dst->m = _mm_sub_ps(_mm_mul_ps(s1v1, s1v2), _mm_mul_ps(s2v1, s2v2)); +} + +static inline void vec3_neg(struct vec3 *dst, const struct vec3 *v) +{ + dst->x = -dst->x; + dst->y = -dst->y; + dst->z = -dst->z; +} + +static inline float vec3_len(const struct vec3 *v) +{ + float dot_val = vec3_dot(v, v); + return (dot_val > 0.0f) ? sqrtf(dot_val) : 0.0f; +} + +static inline float vec3_dist(const struct vec3 *v1, const struct vec3 *v2) +{ + struct vec3 temp; + float dot_val; + + vec3_sub(&temp, v1, v2); + dot_val = vec3_dot(&temp, &temp); + return (dot_val > 0.0f) ? sqrtf(dot_val) : 0.0f; +} + +static inline void vec3_norm(struct vec3 *dst, const struct vec3 *v) +{ + float dot_val = vec3_dot(v, v); + dst->m = (dot_val > 0.0f) ? + _mm_mul_ps(v->m, _mm_set1_ps(1.0f/sqrtf(dot_val))) : + _mm_setzero_ps(); +} + +static inline bool vec3_close(const struct vec3 *v1, const struct vec3 *v2, + float epsilon) +{ + struct vec3 test; + vec3_sub(&test, v1, v2); + return test.x < epsilon && test.y < epsilon && test.z < epsilon; +} + +static inline void vec3_min(struct vec3 *dst, const struct vec3 *v1, + const struct vec3 *v2) +{ + dst->m = _mm_min_ps(v1->m, v2->m); + dst->w = 0.0f; +} + +static inline void vec3_minf(struct vec3 *dst, const struct vec3 *v, + float f) +{ + dst->m = _mm_min_ps(v->m, _mm_set1_ps(f)); + dst->w = 0.0f; +} + +static inline void vec3_max(struct vec3 *dst, const struct vec3 *v1, + const struct vec3 *v2) +{ + dst->m = _mm_max_ps(v1->m, v2->m); + dst->w = 0.0f; +} + +static inline void vec3_maxf(struct vec3 *dst, const struct vec3 *v, + float f) +{ + dst->m = _mm_max_ps(v->m, _mm_set1_ps(f)); + dst->w = 0.0f; +} + +static inline void vec3_abs(struct vec3 *dst, const struct vec3 *v) +{ + dst->x = fabsf(v->x); + dst->y = fabsf(v->y); + dst->z = fabsf(v->z); +} + +static inline void vec3_floor(struct vec3 *dst, const struct vec3 *v) +{ + dst->x = floorf(v->x); + dst->y = floorf(v->y); + dst->z = floorf(v->z); +} + +static inline void vec3_ceil(struct vec3 *dst, const struct vec3 *v) +{ + dst->x = ceilf(v->x); + dst->y = ceilf(v->y); + dst->z = ceilf(v->z); +} + +EXPORT float vec3_plane_dist(const struct vec3 *v, const struct plane *p); + +EXPORT void vec3_rotate(struct vec3 *dst, const struct vec3 *v, + const struct matrix3 *m); +EXPORT void vec3_transform(struct vec3 *dst, const struct vec3 *v, + const struct matrix3 *m); + +EXPORT void vec3_mirror(struct vec3 *dst, const struct vec3 *v, + const struct plane *p); +EXPORT void vec3_mirrorv(struct vec3 *dst, const struct vec3 *v, + const struct vec3 *vec); + +EXPORT void vec3_rand(struct vec3 *dst, int positive_only); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/graphics/vec4.c b/libobs/graphics/vec4.c new file mode 100644 index 000000000..0f3fbe793 --- /dev/null +++ b/libobs/graphics/vec4.c @@ -0,0 +1,32 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "vec4.h" +#include "matrix4.h" + +void vec4_transform(struct vec4 *dst, const struct vec4 *v, + const struct matrix4 *m) +{ + struct vec4 temp; + + temp.x = vec4_dot(&m->x, v); + temp.y = vec4_dot(&m->y, v); + temp.z = vec4_dot(&m->z, v); + temp.w = vec4_dot(&m->t, v); + + vec4_copy(dst, &temp); +} diff --git a/libobs/graphics/vec4.h b/libobs/graphics/vec4.h new file mode 100644 index 000000000..2da744a48 --- /dev/null +++ b/libobs/graphics/vec4.h @@ -0,0 +1,253 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef VECT4_H +#define VECT4_H + +#include "math-defs.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct matrix4; + +struct vec4 { + union { + struct { + float x, y, z, w; + }; + float ptr[4]; + __m128 m; + }; +}; + +static inline void vec4_zero(struct vec4 *v) +{ + v->m = _mm_setzero_ps(); +} + +static inline void vec4_set(struct vec4 *dst, float x, float y, float z, + float w) +{ + dst->m = _mm_set_ps(w, z, y, x); +} + +static inline void vec4_copy(struct vec4 *dst, const struct vec4 *v) +{ + dst->m = v->m; +} + +static inline void vec4_add(struct vec4 *dst, const struct vec4 *v1, + const struct vec4 *v2) +{ + dst->m = _mm_add_ps(v1->m, v2->m); +} + +static inline void vec4_sub(struct vec4 *dst, const struct vec4 *v1, + const struct vec4 *v2) +{ + dst->m = _mm_sub_ps(v1->m, v2->m); +} + +static inline void vec4_mul(struct vec4 *dst, const struct vec4 *v1, + const struct vec4 *v2) +{ + dst->m = _mm_mul_ps(v1->m, v2->m); +} + +static inline void vec4_div(struct vec4 *dst, const struct vec4 *v1, + const struct vec4 *v2) +{ + dst->m = _mm_div_ps(v1->m, v2->m); +} + +static inline void vec4_addf(struct vec4 *dst, const struct vec4 *v, + float f) +{ + dst->m = _mm_add_ps(v->m, _mm_set1_ps(f)); +} + +static inline void vec4_subf(struct vec4 *dst, const struct vec4 *v, + float f) +{ + dst->m = _mm_sub_ps(v->m, _mm_set1_ps(f)); +} + +static inline void vec4_mulf(struct vec4 *dst, const struct vec4 *v, + float f) +{ + dst->m = _mm_mul_ps(v->m, _mm_set1_ps(f)); +} + +static inline void vec4_divf(struct vec4 *dst, const struct vec4 *v, + float f) +{ + dst->m = _mm_div_ps(v->m, _mm_set1_ps(f)); +} + +static inline float vec4_dot(const struct vec4 *v1, const struct vec4 *v2) +{ + struct vec4 add; + __m128 mul = _mm_mul_ps(v1->m, v2->m); + add.m = _mm_add_ps(_mm_movehl_ps(mul, mul), mul); + add.m = _mm_add_ps(_mm_shuffle_ps(add.m, add.m, 0x55), add.m); + return add.x; +} + +static inline void vec4_neg(struct vec4 *dst, const struct vec4 *v) +{ + dst->x = -dst->x; + dst->y = -dst->y; + dst->z = -dst->z; + dst->w = -dst->w; +} + +static inline float vec4_len(const struct vec4 *v) +{ + float dot_val = vec4_dot(v, v); + return (dot_val > 0.0f) ? sqrtf(dot_val) : 0.0f; +} + +static inline float vec4_dist(const struct vec4 *v1, const struct vec4 *v2) +{ + struct vec4 temp; + float dot_val; + + vec4_sub(&temp, v1, v2); + dot_val = vec4_dot(&temp, &temp); + return (dot_val > 0.0f) ? sqrtf(dot_val) : 0.0f; +} + +static inline void vec4_norm(struct vec4 *dst, const struct vec4 *v) +{ + float dot_val = vec4_dot(v, v); + dst->m = (dot_val > 0.0f) ? + _mm_mul_ps(v->m, _mm_set1_ps(1.0f/sqrtf(dot_val))) : + _mm_setzero_ps(); +} + +static inline int vec4_close(const struct vec4 *v1, const struct vec4 *v2, + float epsilon) +{ + struct vec4 test; + vec4_sub(&test, v1, v2); + return test.x < epsilon && + test.y < epsilon && + test.z < epsilon && + test.w < epsilon; +} + +static inline void vec4_min(struct vec4 *dst, const struct vec4 *v1, + const struct vec4 *v2) +{ + dst->m = _mm_min_ps(v1->m, v2->m); +} + +static inline void vec4_minf(struct vec4 *dst, const struct vec4 *v, + float f) +{ + dst->m = _mm_min_ps(v->m, _mm_set1_ps(f)); +} + +static inline void vec4_max(struct vec4 *dst, const struct vec4 *v1, + const struct vec4 *v2) +{ + dst->m = _mm_max_ps(v1->m, v2->m); +} + +static inline void vec4_maxf(struct vec4 *dst, const struct vec4 *v, + float f) +{ + dst->m = _mm_max_ps(v->m, _mm_set1_ps(f)); +} + +static inline void vec4_abs(struct vec4 *dst, const struct vec4 *v) +{ + dst->x = fabsf(v->x); + dst->y = fabsf(v->y); + dst->z = fabsf(v->z); + dst->w = fabsf(v->w); +} + +static inline void vec4_floor(struct vec4 *dst, const struct vec4 *v) +{ + dst->x = floorf(v->x); + dst->y = floorf(v->y); + dst->z = floorf(v->z); + dst->w = floorf(v->w); +} + +static inline void vec4_ceil(struct vec4 *dst, const struct vec4 *v) +{ + dst->x = ceilf(v->x); + dst->y = ceilf(v->y); + dst->z = ceilf(v->z); + dst->w = ceilf(v->w); +} + +static inline uint32_t vec4_to_rgba(const struct vec4 *src) +{ + uint32_t val; + val = (uint32_t)((double)src->x * 255.0); + val |= (uint32_t)((double)src->y * 255.0); + val |= (uint32_t)((double)src->z * 255.0); + val |= (uint32_t)((double)src->w * 255.0); + return val; +} + +static inline uint32_t vec4_to_bgra(const struct vec4 *src) +{ + uint32_t val; + val = (uint32_t)((double)src->z * 255.0); + val |= (uint32_t)((double)src->y * 255.0); + val |= (uint32_t)((double)src->x * 255.0); + val |= (uint32_t)((double)src->w * 255.0); + return val; +} + +static inline void vec4_from_rgba(struct vec4 *dst, uint32_t rgba) +{ + dst->x = (float)((double)(rgba&0xFF) * (1.0/255.0)); + rgba >>= 8; + dst->y = (float)((double)(rgba&0xFF) * (1.0/255.0)); + rgba >>= 8; + dst->z = (float)((double)(rgba&0xFF) * (1.0/255.0)); + rgba >>= 8; + dst->w = (float)((double)(rgba&0xFF) * (1.0/255.0)); +} + +static inline void vec4_from_bgra(struct vec4 *dst, uint32_t bgra) +{ + dst->z = (float)((double)(bgra&0xFF) * (1.0/255.0)); + bgra >>= 8; + dst->y = (float)((double)(bgra&0xFF) * (1.0/255.0)); + bgra >>= 8; + dst->x = (float)((double)(bgra&0xFF) * (1.0/255.0)); + bgra >>= 8; + dst->w = (float)((double)(bgra&0xFF) * (1.0/255.0)); +} + +EXPORT void vec4_transform(struct vec4 *dst, const struct vec4 *v, + const struct matrix4 *m); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/makefile b/libobs/makefile new file mode 100644 index 000000000..211bef54a --- /dev/null +++ b/libobs/makefile @@ -0,0 +1,67 @@ +include ../config.mak + +.PHONY: all default clean + +all: default + +SRCFILES=util/bmem.c \ + util/base.c \ + util/dstr.c \ + util/lexer.c \ + util/utf8.c \ + util/text-lookup.c \ + util/platform.c \ + util/platform-windows.c \ + util/config-file.c \ + util/cf-lexer.c \ + util/cf-parser.c \ + graphics/axisang.c \ + graphics/bounds.c \ + graphics/effect.c \ + graphics/effect-parser.c \ + graphics/graphics.c \ + graphics/graphics-imports.c \ + graphics/math-extra.c \ + graphics/matrix3.c \ + graphics/matrix4.c \ + graphics/plane.c \ + graphics/quat.c \ + graphics/shader-parser.c \ + graphics/texture-render.c \ + graphics/vec2.c \ + graphics/vec3.c \ + graphics/vec4.c \ + media-io/video-io.c \ + media-io/audio-io.c \ + media-io/media-io.c \ + obs-module.c \ + obs-output.c \ + obs-source.c \ + obs-scene.c \ + obs-display.c \ + obs-video.c \ + obs.c + +SONAME=../build/libobs.$(SOEXT) + +OBJS += $(SRCFILES:%.c=%.$(OBJ)) +LDFLAGS += -lpthread + +default: $(SONAME) + +.depend: + @rm -f .depend + @$(foreach SRC, $(addprefix $(SRCPATH)/, $(SRCFILES)), $(CCDEP) \ + $(CPPFLAGS) $(SRC) \ + -MT $(SRC:$(SRCPATH)/%.c=%.$(OBJ)) -MM 1>> .depend;) + +$(SONAME): .depend $(OBJS) + $(LD)$@ $(LDFLAGS) $(OBJS) + +depend: .depend +ifneq ($(wildcard .depend),) +include .depend +endif + +clean: + rm -f $(OBJS) $(SONAME) *.a *.lib *.exp *.pdb .depend diff --git a/libobs/media-io/audio-io.c b/libobs/media-io/audio-io.c new file mode 100644 index 000000000..8acc0075c --- /dev/null +++ b/libobs/media-io/audio-io.c @@ -0,0 +1,134 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "../util/threading.h" +#include "../util/darray.h" +#include "../util/platform.h" + +#include "audio-io.h" + +/* TODO: Incomplete */ + +struct audio_output { + struct audio_info info; + media_t media; + media_output_t output; + + pthread_t thread; + pthread_mutex_t data_mutex; + event_t stop_event; + + struct darray pending_frames; + + bool initialized; +}; + +/* ------------------------------------------------------------------------- */ + +static void *audio_thread(void *param) +{ + struct audio_output *audio = param; + + while (event_try(&audio->stop_event) == EAGAIN) { + os_sleep_ms(5); + /* TODO */ + } + + return NULL; +} + +/* ------------------------------------------------------------------------- */ + +static inline bool valid_audio_params(struct audio_info *info) +{ + return info->channels > 0 && info->format && info->name && + info->samples_per_sec > 0 && info->speakers > 0; +} + +static inline bool ao_add_to_media(audio_t audio) +{ + struct media_output_info oi; + oi.format = audio->info.format; + oi.obj = audio; + oi.connect = NULL; + + audio->output = media_output_create(&oi); + if (!audio->output) + return false; + + media_add_output(audio->media, audio->output); + return true; +} + +int audio_output_open(audio_t *audio, media_t media, struct audio_info *info) +{ + struct audio_output *out; + + if (!valid_audio_params(info)) + return AUDIO_OUTPUT_INVALIDPARAM; + + out = bmalloc(sizeof(struct audio_output)); + memset(out, 0, sizeof(struct audio_output)); + + memcpy(&out->info, info, sizeof(struct audio_info)); + out->media = media; + + if (pthread_mutex_init(&out->data_mutex, NULL) != 0) + goto fail; + + if (event_init(&out->stop_event, true) != 0) + goto fail; + + if (!ao_add_to_media(out)) + goto fail; + + if (pthread_create(&out->thread, NULL, audio_thread, out) != 0) + goto fail; + + out->initialized = true; + *audio = out; + return AUDIO_OUTPUT_SUCCESS; + +fail: + audio_output_close(out); + return AUDIO_OUTPUT_FAIL; +} + +void audio_output_data(audio_t audio, struct audio_data *data) +{ + pthread_mutex_lock(&audio->data_mutex); + /* TODO */ + pthread_mutex_unlock(&audio->data_mutex); +} + +void audio_output_close(audio_t audio) +{ + void *thread_ret; + + if (!audio) + return; + + if (audio->initialized) { + event_signal(&audio->stop_event); + pthread_join(audio->thread, &thread_ret); + } + + media_remove_output(audio->media, audio->output); + event_destroy(&audio->stop_event); + pthread_mutex_destroy(&audio->data_mutex); + bfree(audio); +} diff --git a/libobs/media-io/audio-io.h b/libobs/media-io/audio-io.h new file mode 100644 index 000000000..527f5b870 --- /dev/null +++ b/libobs/media-io/audio-io.h @@ -0,0 +1,91 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef AUDIO_IO_H +#define AUDIO_IO_H + +#include "../util/c99defs.h" +#include "media-io.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Base audio output component. Use this to create an audio output track + * for the media. + */ + +struct audio_output; +typedef struct audio_output *audio_t; + +enum audio_type { + AUDIO_FORMAT_UNKNOWN, + AUDIO_FORMAT_8BIT, + AUDIO_FORMAT_16BIT, + AUDIO_FORMAT_24BIT, + AUDIO_FORMAT_32BIT, + AUDIO_FORMAT_FLOAT, +}; + +enum speaker_setup { + SPEAKERS_UNKNOWN, + SPEAKERS_MONO, + SPEAKERS_STEREO, + SPEAKERS_2POINT1, + SPEAKERS_QUAD, + SPEAKERS_4POINT1, + SPEAKERS_5POINT1, + SPEAKERS_5POINT1_SURROUND, + SPEAKERS_7POINT1, + SPEAKERS_7POINT1_SURROUND, + SPEAKERS_SURROUND, +}; + +struct audio_data { + void *data; + uint32_t frames; + uint32_t speakers; + uint32_t samples_per_sec; + enum audio_type type; + uint64_t timestamp; +}; + +struct audio_info { + const char *name; + const char *format; + + uint32_t channels; + uint32_t samples_per_sec; + enum audio_type type; + enum speaker_setup speakers; +}; + +#define AUDIO_OUTPUT_SUCCESS 0 +#define AUDIO_OUTPUT_INVALIDPARAM -1 +#define AUDIO_OUTPUT_FAIL -2 + +EXPORT int audio_output_open(audio_t *audio, media_t media, + struct audio_info *info); +EXPORT void audio_output_data(audio_t audio, struct audio_data *data); +EXPORT void audio_output_close(audio_t audio); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/media-io/audio-mixer.h b/libobs/media-io/audio-mixer.h new file mode 100644 index 000000000..e69de29bb diff --git a/libobs/media-io/media-io.c b/libobs/media-io/media-io.c new file mode 100644 index 000000000..cca5ad0f5 --- /dev/null +++ b/libobs/media-io/media-io.c @@ -0,0 +1,158 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "../util/threading.h" +#include "../util/darray.h" +#include "../util/bmem.h" + +#include "media-io.h" + +/* TODO: Incomplete */ + +struct media_input { + struct media_input_info info; + struct media_output *connection; +}; + +struct media_output { + struct media_output_info info; + DARRAY(media_input_t) connections; + pthread_mutex_t mutex; +}; + +struct media_data { + DARRAY(media_output_t) outputs; +}; + +/* ------------------------------------------------------------------------- */ + +media_input_t media_input_create(struct media_input_info *info) +{ + struct media_input *input; + + if (!info || !info->format || !info->on_input) + return NULL; + + input = bmalloc(sizeof(struct media_input)); + input->connection = NULL; + memcpy(&input->info, info, sizeof(struct media_input_info)); + + return input; +} + +void media_input_destroy(media_input_t input) +{ + if (input) + bfree(input); +} + +/* ------------------------------------------------------------------------- */ + +media_output_t media_output_create(struct media_output_info *info) +{ + struct media_output *output; + + if (!info || !info->format) + return NULL; + + output = bmalloc(sizeof(struct media_output)); + da_init(output->connections); + memcpy(&output->info, info, sizeof(struct media_output_info)); + + if (pthread_mutex_init(&output->mutex, NULL) != 0) { + bfree(output); + return NULL; + } + + return output; +} + +void media_output_data(media_output_t output, const void *data) +{ + size_t i; + + pthread_mutex_lock(&output->mutex); + + for (i = 0; i < output->connections.num; i++) { + media_input_t input = output->connections.array[i]; + input->info.on_input(input->info.obj, data); + } + + pthread_mutex_unlock(&output->mutex); +} + +void media_output_destroy(media_output_t output) +{ + if (output) { + da_free(output->connections); + pthread_mutex_destroy(&output->mutex); + bfree(output); + } +} + +/* ------------------------------------------------------------------------- */ + +media_t media_open(void) +{ + struct media_data *media = bmalloc(sizeof(struct media_data)); + da_init(media->outputs); + + return media; +} + +bool media_add_input(media_t media, media_input_t input) +{ + media_output_t *outputs = media->outputs.array; + size_t i; + + for (i = 0; i < media->outputs.num; i++) { + media_output_t output = outputs[i]; + + if (strcmp(output->info.format, input->info.format) == 0) { + da_push_back(output->connections, input); + return true; + } + } + + return false; +} + +void media_add_output(media_t media, media_output_t output) +{ + da_push_back(media->outputs, output); +} + +void media_remove_input(media_t media, media_input_t input) +{ + if (!input->connection) + return; + + da_erase_item(input->connection->connections, input); +} + +void media_remove_output(media_t media, media_output_t output) +{ + da_erase_item(media->outputs, output); +} + +void media_close(media_t media) +{ + if (media) { + da_free(media->outputs); + bfree(media); + } +} diff --git a/libobs/media-io/media-io.h b/libobs/media-io/media-io.h new file mode 100644 index 000000000..8e8fd2ec8 --- /dev/null +++ b/libobs/media-io/media-io.h @@ -0,0 +1,77 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef MEDIA_IO_H +#define MEDIA_IO_H + +/* + * Media input/output components used for connecting media outputs/inputs + * together. An input requests a connection to an output and the output + * sends frames to it through the callbacks in media_data_in structure. + * + * The id member should indicate the format/parameters used in text form. + */ + +/* opaque data types */ +struct media_input; +struct media_output; +struct media_data; +typedef struct media_input *media_input_t; +typedef struct media_output *media_output_t; +typedef struct media_data *media_t; + +#include "../util/c99defs.h" +#include "video-io.h" +#include "audio-io.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct media_input_info { + const char *format; + + void *obj; + void (*on_input)(void *obj, const void *data); +}; + +struct media_output_info { + const char *format; + + void *obj; + bool (*connect)(void *obj, media_input_t input); +}; + +EXPORT media_input_t media_input_create(struct media_input_info *info); +EXPORT void media_input_destroy(media_input_t input); + +EXPORT media_output_t media_output_create(struct media_output_info *info); +EXPORT void media_output_data(media_output_t out, const void *data); +EXPORT void media_output_destroy(media_output_t output); + +EXPORT media_t media_open(void); +EXPORT bool media_add_input(media_t media, media_input_t input); +EXPORT void media_add_output(media_t media, media_output_t output); +EXPORT void media_remove_input(media_t media, media_input_t input); +EXPORT void media_remove_output(media_t media, media_output_t output); +EXPORT void media_close(media_t media); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/media-io/video-io.c b/libobs/media-io/video-io.c new file mode 100644 index 000000000..ea006af71 --- /dev/null +++ b/libobs/media-io/video-io.c @@ -0,0 +1,194 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include +#include "../util/bmem.h" +#include "../util/platform.h" +#include "../util/threading.h" + +#include "video-io.h" + +struct video_output { + struct video_info info; + media_t media; + media_output_t output; + + pthread_t thread; + pthread_mutex_t data_mutex; + event_t stop_event; + + struct video_frame *cur_frame; + struct video_frame *next_frame; + event_t update_event; + uint64_t frame_time; + volatile uint64_t cur_video_time; + + bool initialized; +}; + +/* ------------------------------------------------------------------------- */ + +static inline void video_swapframes(struct video_output *video) +{ + pthread_mutex_lock(&video->data_mutex); + + if (video->next_frame) { + video->cur_frame = video->next_frame; + video->next_frame = NULL; + } + + pthread_mutex_unlock(&video->data_mutex); +} + +static void *video_thread(void *param) +{ + struct video_output *video = param; + uint64_t cur_time = os_gettime_ns(); + + while (event_try(&video->stop_event) == EAGAIN) { + /* wait half a frame, update frame */ + os_sleepto_ns(cur_time += (video->frame_time/2)); + video->cur_video_time = cur_time; + event_signal(&video->update_event); + + /* wait another half a frame, swap and output frames */ + os_sleepto_ns(cur_time += (video->frame_time/2)); + video_swapframes(video); + if (video->cur_frame) + media_output_data(video->output, video->cur_frame); + } + + return NULL; +} + +/* ------------------------------------------------------------------------- */ + +static inline bool valid_video_params(struct video_info *info) +{ + return info->height != 0 && info->width != 0 && info->fps_den != 0 && + info->fps_num != 0 && info->format != NULL; +} + +static inline bool vo_add_to_media(video_t video) +{ + struct media_output_info oi; + oi.format = video->info.format; + oi.obj = video; + oi.connect = NULL; + + video->output = media_output_create(&oi); + if (!video->output) + return false; + + media_add_output(video->media, video->output); + return true; +} + +int video_output_open(video_t *video, media_t media, struct video_info *info) +{ + struct video_output *out; + + if (!valid_video_params(info)) + return VIDEO_OUTPUT_INVALIDPARAM; + + out = bmalloc(sizeof(struct video_output)); + memset(out, 0, sizeof(struct video_output)); + + memcpy(&out->info, info, sizeof(struct video_info)); + out->frame_time = (uint64_t)(1000000000.0 * (double)info->fps_den / + (double)info->fps_num); + out->media = media; + out->initialized = false; + + if (pthread_mutex_init(&out->data_mutex, NULL) != 0) + goto fail; + + if (event_init(&out->stop_event, true) != 0) + goto fail; + + if (event_init(&out->update_event, false) != 0) + goto fail; + + if (!vo_add_to_media(out)) + goto fail; + + if (pthread_create(&out->thread, NULL, video_thread, out) != 0) + goto fail; + + out->initialized = true; + *video = out; + return VIDEO_OUTPUT_SUCCESS; + +fail: + video_output_close(out); + return VIDEO_OUTPUT_FAIL; +} + +void video_output_frame(video_t video, struct video_frame *frame) +{ + pthread_mutex_lock(&video->data_mutex); + video->next_frame = frame; + pthread_mutex_unlock(&video->data_mutex); +} + +bool video_output_wait(video_t video) +{ + event_wait(&video->update_event); + return event_try(&video->stop_event) == EAGAIN; +} + +uint64_t video_getframetime(video_t video) +{ + return video->frame_time; +} + +uint64_t video_gettime(video_t video) +{ + return video->cur_video_time; +} + +void video_output_stop(video_t video) +{ + void *thread_ret; + + if (!video) + return; + + if (video->initialized) { + event_signal(&video->stop_event); + pthread_join(video->thread, &thread_ret); + event_signal(&video->update_event); + } +} + +void video_output_close(video_t video) +{ + if (!video) + return; + + video_output_stop(video); + + if (video->output) { + media_remove_output(video->media, video->output); + media_output_destroy(video->output); + } + + event_destroy(&video->update_event); + event_destroy(&video->stop_event); + pthread_mutex_destroy(&video->data_mutex); + bfree(video); +} diff --git a/libobs/media-io/video-io.h b/libobs/media-io/video-io.h new file mode 100644 index 000000000..ec6f09d6b --- /dev/null +++ b/libobs/media-io/video-io.h @@ -0,0 +1,69 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef VIDEO_IO_H +#define VIDEO_IO_H + +#include "../util/c99defs.h" +#include "media-io.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Base video output component. Use this to create an video output track + * for the media. + */ + +struct video_output; +typedef struct video_output *video_t; + +struct video_frame { + const void *data; + uint32_t row_size; + uint64_t timestamp; +}; + +struct video_info { + const char *name; + const char *format; + + uint32_t fps_num; /* numerator */ + uint32_t fps_den; /* denominator */ + uint32_t width; + uint32_t height; +}; + +#define VIDEO_OUTPUT_SUCCESS 0 +#define VIDEO_OUTPUT_INVALIDPARAM -1 +#define VIDEO_OUTPUT_FAIL -2 + +EXPORT int video_output_open(video_t *video, media_t media, + struct video_info *info); +EXPORT void video_output_frame(video_t video, struct video_frame *frame); +EXPORT bool video_output_wait(video_t video); +EXPORT uint64_t video_getframetime(video_t video); +EXPORT uint64_t video_gettime(video_t video); +EXPORT void video_output_stop(video_t video); +EXPORT void video_output_close(video_t video); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/obs-data.h b/libobs/obs-data.h new file mode 100644 index 000000000..c22f0fb69 --- /dev/null +++ b/libobs/obs-data.h @@ -0,0 +1,83 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef OBS_DATA_H +#define OBS_DATA_H + +#include "util/darray.h" +#include "util/threading.h" + +#include "graphics/graphics.h" + +#include "media-io/media-io.h" +#include "media-io/video-io.h" +#include "media-io/audio-io.h" + +#include "obs.h" +#include "obs-module.h" +#include "obs-source.h" +#include "obs-output.h" +/*#include "obs-service.h"*/ + +#define NUM_TEXTURES 2 + +struct obs_display { + swapchain_t swap; /* can be NULL if just sound */ + source_t source; + /* TODO: sound output target */ +}; + +struct obs_data { + DARRAY(struct obs_module) modules; + + DARRAY(struct source_info) input_types; + DARRAY(struct source_info) filter_types; + DARRAY(struct source_info) transition_types; + DARRAY(struct output_info) output_types; + /*DARRAY(struct service_info) service_types;*/ + + DARRAY(struct obs_display*) displays; + DARRAY(struct obs_source*) sources; + + /* graphics */ + graphics_t graphics; + stagesurf_t copy_surfaces[NUM_TEXTURES]; + bool textures_copied[NUM_TEXTURES]; + bool copy_mapped; + int cur_texture; + + /* TODO: sound output stuff */ + + /* media */ + media_t media; + video_t video; + audio_t audio; + + uint32_t output_width; + uint32_t output_height; + + /* threading */ + pthread_t video_thread; + pthread_mutex_t source_mutex; + bool thread_initialized; + + source_t primary_source; +}; + +extern void *obs_video_thread(void *param); + +#endif diff --git a/libobs/obs-defs.h b/libobs/obs-defs.h new file mode 100644 index 000000000..b857fea8f --- /dev/null +++ b/libobs/obs-defs.h @@ -0,0 +1,30 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef OBS_DEFS_H +#define OBS_DEFS_H + +#define MODULE_SUCCESS 0 +#define MODULE_ERROR -1 +#define MODULE_FILENOTFOUND -2 +#define MODULE_FUNCTIONNOTFOUND -3 + +#define SOURCE_VIDEO (1<<0) +#define SOURCE_AUDIO (1<<1) +#define SOURCE_ASYNC (1<<2) + +#endif diff --git a/libobs/obs-display.c b/libobs/obs-display.c new file mode 100644 index 000000000..6acac2608 --- /dev/null +++ b/libobs/obs-display.c @@ -0,0 +1,53 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "obs.h" +#include "obs-data.h" + +display_t display_create(obs_t obs, struct gs_init_data *graphics_data) +{ + struct obs_display *display = bmalloc(sizeof(struct obs_display)); + memset(display, 0, sizeof(struct obs_display)); + + if (graphics_data) { + display->swap = gs_create_swapchain(graphics_data); + if (!display->swap) { + display_destroy(display); + return NULL; + } + } + + return display; +} + +void display_destroy(display_t display) +{ + if (display) { + swapchain_destroy(display->swap); + bfree(display); + } +} + +source_t display_getsource(display_t display) +{ + return display->source; +} + +void display_setsource(display_t display, source_t source) +{ + display->source = source; +} diff --git a/libobs/obs-module.c b/libobs/obs-module.c new file mode 100644 index 000000000..231826bda --- /dev/null +++ b/libobs/obs-module.c @@ -0,0 +1,127 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "util/platform.h" +#include "util/dstr.h" + +#include "obs-defs.h" +#include "obs-data.h" +#include "obs-module.h" + +void *load_module_subfunc(void *module, const char *module_name, + const char *name, const char *func, bool required) +{ + struct dstr func_name; + void *func_addr = NULL; + + dstr_init_copy(&func_name, name); + dstr_cat(&func_name, "_"); + dstr_cat(&func_name, func); + + func_addr = os_dlsym(module, func_name.array); + if (required && !func_addr) + blog(LOG_ERROR, "Could not load function '%s' from module '%s'", + func_name.array, module_name); + + dstr_free(&func_name); + return func_addr; +} + +static void module_load_exports(struct obs_data *obs, struct obs_module *mod, + struct darray *output_array, const char *type, + const size_t data_size, void *callback_ptr) +{ + bool (*enum_func)(size_t idx, const char **name); + bool (*callback)(void*, const char*, const char*, void*); + struct dstr enum_name; + const char *name; + size_t i = 0; + + callback = callback_ptr; + + dstr_init_copy(&enum_name, "enum_"); + dstr_cat(&enum_name, type); + + enum_func = os_dlsym(mod->module, enum_name.array); + if (!enum_func) + goto complete; + + while (enum_func(i++, &name)) { + void *info = bmalloc(data_size); + if (!callback(mod->module, mod->name, name, info)) + blog(LOG_ERROR, "Couldn't load '%s' because it " + "was missing required functions", + name); + else + darray_push_back(data_size, output_array, info); + + bfree(info); + } + +complete: + dstr_free(&enum_name); +} + +int obs_load_module(struct obs_data *obs, const char *path) +{ + struct obs_module mod; + bool (*module_load)(void) = NULL; + + mod.module = os_dlopen(path); + if (!mod.module) + return MODULE_FILENOTFOUND; + + module_load = os_dlsym(mod.module, "module_load"); + if (module_load) { + if (!module_load()) { + os_dlclose(mod.module); + return MODULE_ERROR; + } + } + + mod.name = bstrdup(path); + module_load_exports(obs, &mod, &obs->input_types.da, "inputs", + sizeof(struct source_info), get_source_info); + module_load_exports(obs, &mod, &obs->filter_types.da, "filters", + sizeof(struct source_info), get_source_info); + module_load_exports(obs, &mod, &obs->transition_types.da, "transitions", + sizeof(struct source_info), get_source_info); + module_load_exports(obs, &mod, &obs->output_types.da, "outputs", + sizeof(struct output_info), get_output_info); + + da_push_back(obs->modules, &mod); + return MODULE_SUCCESS; +} + +void free_module(struct obs_module *mod) +{ + if (!mod) + return; + + if (mod->module) { + void (*module_unload)(void); + + module_unload = os_dlsym(mod->module, + "module_unload"); + if (module_unload) + module_unload(); + + os_dlclose(mod->module); + } + + bfree(mod->name); +} diff --git a/libobs/obs-module.h b/libobs/obs-module.h new file mode 100644 index 000000000..62182a0b1 --- /dev/null +++ b/libobs/obs-module.h @@ -0,0 +1,32 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef OBS_MODULE_H +#define OBS_MODULE_H + +#include "util/darray.h" + +struct obs_module { + char *name; + void *module; +}; + +extern void *load_module_subfunc(void *module, const char *module_name, + const char *name, const char *func, bool required); +extern void free_module(struct obs_module *mod); + +#endif diff --git a/libobs/obs-output.c b/libobs/obs-output.c new file mode 100644 index 000000000..9e0a82846 --- /dev/null +++ b/libobs/obs-output.c @@ -0,0 +1,121 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "obs.h" +#include "obs-data.h" + +bool get_output_info(void *module, const char *module_name, + const char *output_name, struct output_info *info) +{ + info->create = load_module_subfunc(module, module_name, + output_name, "create", true); + info->destroy = load_module_subfunc(module, module_name, + output_name, "destroy", true); + info->start = load_module_subfunc(module, module_name, + output_name, "start", true); + info->stop = load_module_subfunc(module, module_name, + output_name, "stop", true); + + if (!info->create || !info->destroy || !info->start || !info->stop) + return false; + + info->config = load_module_subfunc(module, module_name, + output_name, "config", false); + info->pause = load_module_subfunc(module, module_name, + output_name, "pause", false); + + info->name = output_name; + return true; +} + +static inline const struct output_info *find_output(obs_t obs, const char *type) +{ + size_t i; + for (i = 0; i < obs->output_types.num; i++) + if (strcmp(obs->output_types.array[i].name, type) == 0) + return obs->output_types.array+i; + + return NULL; +} + +output_t output_create(obs_t obs, const char *type, const char *settings) +{ + const struct output_info *info = find_output(obs, type); + struct obs_output *output; + + if (!info) { + blog(LOG_WARNING, "Output type '%s' not found", type); + return NULL; + } + + output = bmalloc(sizeof(struct obs_output)); + output->data = info->create(settings, output); + if (!output->data) { + bfree(output); + return NULL; + } + + dstr_init_copy(&output->settings, settings); + memcpy(&output->callbacks, info, sizeof(struct output_info)); + return output; +} + +void output_destroy(output_t output) +{ + if (output) { + output->callbacks.destroy(output->data); + dstr_free(&output->settings); + bfree(output); + } +} + +void output_start(output_t output) +{ + output->callbacks.start(output->data); +} + +void output_stop(output_t output) +{ + output->callbacks.stop(output->data); +} + +bool output_canconfig(output_t output) +{ + return output->callbacks.config != NULL; +} + +void output_config(output_t output, void *parent) +{ + if (output->callbacks.config) + output->callbacks.config(output->data, parent); +} + +bool output_canpause(output_t output) +{ + return output->callbacks.pause != NULL; +} + +void output_pause(output_t output) +{ + if (output->callbacks.pause) + output->callbacks.pause(output->data); +} + +void output_save_settings(output_t output, const char *settings) +{ + dstr_copy(&output->settings, settings); +} diff --git a/libobs/obs-output.h b/libobs/obs-output.h new file mode 100644 index 000000000..8ffc41315 --- /dev/null +++ b/libobs/obs-output.h @@ -0,0 +1,119 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef OBS_OUTPUT_H +#define OBS_OUTPUT_H + +#include "util/c99defs.h" +#include "util/dstr.h" + +/* + * =========================================== + * Outputs + * =========================================== + * + * An output takes raw audio and/or video and processes and/or outputs it + * to a destination, whether that destination be a file, network, or other. + * + * A module with outputs needs to export these functions: + * + enum_outputss + * + * Each individual output is then exported by it's name. For example, an + * output named "myoutput" would have the following exports: + * + myoutput_create + * + myoutput_destroy + * + myoutput_start + * + myoutput_stop + * + * [and optionally] + * + myoutput_config + * + myoutput_pause + * + * =========================================== + * Primary Exports + * =========================================== + * const char *enum_outputs(size_t idx); + * idx: index of the output. + * Return value: Output identifier name. NULL when no more available. + * + * =========================================== + * Output Exports + * =========================================== + * void *[name]_create(const char *settings, output_t output); + * Creates an output. + * + * settings: Settings of the output. + * output: pointer to main output + * Return value: Internal output pointer, or NULL if failed. + * + * --------------------------------------------------------- + * void [name]_destroy(void *data); + * Destroys the output. + * + * --------------------------------------------------------- + * void [name]_update(void *data, const char *settings) + * Updates the output's settings + * + * settings: New settings of the output + * + * --------------------------------------------------------- + * void [name]_start(void *data) + * Starts output + * + * --------------------------------------------------------- + * void [name]_stop(void *data) + * Stops output + * + * =========================================== + * Optional Output Exports + * =========================================== + * void [name]_config(void *data, void *parent); + * Called to configure the output. + * + * parent: Parent window pointer + * + * --------------------------------------------------------- + * void [name]_pause(void *data) + * Pauses output. Typically only usable for local recordings. + */ + +struct obs_output; + +struct output_info { + const char *name; + + void *(*create)(const char *settings, struct obs_output *output); + void (*destroy)(void *data); + + void (*start)(void *data); + void (*stop)(void *data); + + /* optional */ + void (*config)(void *data, void *parent); + void (*pause)(void *data); +}; + +struct obs_output { + void *data; + struct output_info callbacks; + struct dstr settings; +}; + +extern bool get_output_info(void *module, const char *module_name, + const char *output_name, struct output_info *info); + +#endif diff --git a/libobs/obs-scene.c b/libobs/obs-scene.c new file mode 100644 index 000000000..224f5233e --- /dev/null +++ b/libobs/obs-scene.c @@ -0,0 +1,222 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "graphics/math-defs.h" +#include "obs-scene.h" + +static void *obs_scene_create(const char *settings, struct obs_source *source) +{ + struct obs_scene *scene = bmalloc(sizeof(struct obs_scene)); + scene->source = source; + da_init(scene->items); + + return scene; +} + +static void obs_scene_destroy(void *data) +{ + struct obs_scene *scene = data; + size_t i; + + for (i = 0; i < scene->items.num; i++) + bfree(scene->items.array[i]); + + da_free(scene->items); + bfree(scene); +} + +static uint32_t obs_scene_get_output_flags(void *data) +{ + return SOURCE_VIDEO | SOURCE_AUDIO; +} + +static void obs_scene_video_render(void *data) +{ + struct obs_scene *scene = data; + size_t i; + + for (i = scene->items.num; i > 0; i--) { + struct obs_scene_item *item = scene->items.array[i-1]; + + gs_matrix_push(); + gs_matrix_translate3f(item->origin.x, item->origin.y, 0.0f); + gs_matrix_scale3f(item->scale.x, item->scale.y, 1.0f); + gs_matrix_rotaa4f(0.0f, 0.0f, 1.0f, RAD(-item->rot)); + gs_matrix_translate3f(-item->pos.x, -item->pos.y, 0.0f); + + source_video_render(item->source); + + gs_matrix_pop(); + } +} + +static int obs_scene_getsize(void *data) +{ + return -1; +} + +static bool obs_scene_enum_children(void *data, size_t idx, source_t *child) +{ + struct obs_scene *scene = data; + if (idx >= scene->items.num) + return false; + + *child = scene->items.array[idx]->source; + return true; +} + +/* thanks for being completely worthless, microsoft. */ +#if 1 +static const struct source_info scene_info = +{ + "scene", + obs_scene_create, + obs_scene_destroy, + obs_scene_get_output_flags, NULL, NULL, NULL, NULL, + obs_scene_video_render, + obs_scene_getsize, + obs_scene_getsize, NULL, NULL, + obs_scene_enum_children, NULL, NULL +}; +#else +static const struct source_info scene_info = +{ + .name = "scene", + .create = obs_scene_create, + .destroy = obs_scene_destroy, + .get_output_flags = obs_scene_get_output_flags, + .video_render = obs_scene_video_render, + .getwidth = obs_scene_getsize, + .getheight = obs_scene_getsize, + .enum_children = obs_scene_enum_children +}; +#endif + +scene_t scene_create(obs_t obs) +{ + struct obs_source *source = bmalloc(sizeof(struct obs_source)); + struct obs_scene *scene = obs_scene_create(NULL, source); + + source->data = scene; + if (!source->data) { + bfree(source); + return NULL; + } + + scene->source = source; + source_init(obs, source); + memcpy(&source->callbacks, &scene_info, sizeof(struct source_info)); + return scene; +} + +void scene_destroy(scene_t scene) +{ + if (scene) + source_destroy(scene->source); +} + +source_t scene_source(scene_t scene) +{ + return scene->source; +} + +sceneitem_t scene_add(scene_t scene, source_t source) +{ + struct obs_scene_item *item = bmalloc(sizeof(struct obs_scene_item)); + memset(item, 0, sizeof(struct obs_scene_item)); + item->source = source; + item->visible = true; + item->parent = scene; + vec2_set(&item->scale, 1.0f, 1.0f); + + da_push_back(scene->items, &item); + return item; +} + +void sceneitem_remove(sceneitem_t item) +{ + if (item) { + da_erase_item(item->parent->items, item); + bfree(item); + } +} + +void sceneitem_setpos(sceneitem_t item, const struct vec2 *pos) +{ + vec2_copy(&item->pos, pos); +} + +void sceneitem_setrot(sceneitem_t item, float rot) +{ + item->rot = rot; +} + +void sceneitem_setorigin(sceneitem_t item, const struct vec2 *origin) +{ + vec2_copy(&item->origin, origin); +} + +void sceneitem_setscale(sceneitem_t item, const struct vec2 *scale) +{ + vec2_copy(&item->scale, scale); +} + +void sceneitem_setorder(sceneitem_t item, enum order_movement movement) +{ + struct obs_scene *scene = item->parent; + + if (movement == ORDER_MOVE_UP) { + size_t idx = da_find(scene->items, &item, 0); + if (idx > 0) + da_move_item(scene->items, idx, idx-1); + + } else if (movement == ORDER_MOVE_DOWN) { + size_t idx = da_find(scene->items, &item, 0); + if (idx < (scene->items.num-1)) + da_move_item(scene->items, idx, idx+1); + + } else if (movement == ORDER_MOVE_TOP) { + size_t idx = da_find(scene->items, &item, 0); + if (idx > 0) + da_move_item(scene->items, idx, 0); + + } else if (movement == ORDER_MOVE_TOP) { + size_t idx = da_find(scene->items, &item, 0); + if (idx < (scene->items.num-1)) + da_move_item(scene->items, idx, scene->items.num-1); + } +} + +void sceneitem_getpos(sceneitem_t item, struct vec2 *pos) +{ + vec2_copy(pos, &item->pos); +} + +float sceneitem_getrot(sceneitem_t item) +{ + return item->rot; +} + +void sceneitem_getorigin(sceneitem_t item, struct vec2 *origin) +{ + vec2_copy(origin, &item->origin); +} + +void sceneitem_getscale(sceneitem_t item, struct vec2 *scale) +{ + vec2_copy(scale, &item->scale); +} diff --git a/libobs/obs-scene.h b/libobs/obs-scene.h new file mode 100644 index 000000000..e8eeca699 --- /dev/null +++ b/libobs/obs-scene.h @@ -0,0 +1,42 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef OBS_SCENE_H +#define OBS_SCENE_H + +#include "obs.h" +#include "obs-source.h" + +/* how obs scene! */ + +struct obs_scene_item { + scene_t parent; + source_t source; + bool visible; + + struct vec2 origin; + struct vec2 pos; + struct vec2 scale; + float rot; +}; + +struct obs_scene { + source_t source; + DARRAY(struct obs_scene_item*) items; +}; + +#endif diff --git a/libobs/obs-service.h b/libobs/obs-service.h new file mode 100644 index 000000000..b48b86171 --- /dev/null +++ b/libobs/obs-service.h @@ -0,0 +1,33 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef OBS_SERVICE_H +#define OBS_SERVICE_H + +struct service_data; + +struct service_info { + void *(*create)(const char *settings, struct service_data *service); + void (*destroy)(void *data); + void (*config)(void *data, const char *settings); + + /* get stream url/key */ + /* get (viewers/etc) */ + /* send (current game/title/activate commercial/etc) */ +}; + +#endif diff --git a/libobs/obs-source.c b/libobs/obs-source.c new file mode 100644 index 000000000..6c330131b --- /dev/null +++ b/libobs/obs-source.c @@ -0,0 +1,313 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "obs.h" +#include "obs-data.h" + +bool get_source_info(void *module, const char *module_name, + const char *source_name, struct source_info *info) +{ + info->create = load_module_subfunc(module, module_name, + source_name,"create", true); + info->destroy = load_module_subfunc(module, module_name, + source_name, "destroy", true); + info->get_output_flags = load_module_subfunc(module, module_name, + source_name, "get_output_flags", true); + + if (!info->create || !info->destroy || !info->get_output_flags) + return false; + + info->config = load_module_subfunc(module, module_name, + source_name, "config", false); + info->activate = load_module_subfunc(module, module_name, + source_name, "activate", false); + info->deactivate = load_module_subfunc(module, module_name, + source_name, "deactivate", false); + info->video_tick = load_module_subfunc(module, module_name, + source_name, "video_tick", false); + info->video_render = load_module_subfunc(module, module_name, + source_name, "video_render", false); + info->getwidth = load_module_subfunc(module, module_name, + source_name, "getwidth", false); + info->getheight = load_module_subfunc(module, module_name, + source_name, "getheight", false); + + info->getparam = load_module_subfunc(module, module_name, + source_name, "getparam", false); + info->setparam = load_module_subfunc(module, module_name, + source_name, "setparam", false); + info->enum_children = load_module_subfunc(module, module_name, + source_name, "enum_children", false); + + info->filter_video = load_module_subfunc(module, module_name, + source_name, "filter_video", false); + info->filter_audio = load_module_subfunc(module, module_name, + source_name, "filter_audio", false); + + info->name = source_name; + return true; +} + +static inline const struct source_info *find_source(obs_t obs, + struct darray *list, const char *name) +{ + size_t i; + struct source_info *array = list->array; + + for (i = 0; i < list->num; i++) { + struct source_info *info = array+i; + if (strcmp(info->name, name) == 0) + return info; + } + + return NULL; +} + +void source_init(obs_t obs, struct obs_source *source) +{ + source->obs = obs; + source->filter_target = NULL; + source->rendering_filter = false; + + dstr_init(&source->settings); + da_init(source->filters); + da_push_back(obs->sources, &source); +} + +source_t source_create(obs_t obs, enum source_type type, const char *name, + const char *settings) +{ + const struct source_info *info = NULL; + struct darray *list = NULL; + struct obs_source *source; + + switch (type) { + case SOURCE_INPUT: list = &obs->input_types.da; break; + case SOURCE_FILTER: list = &obs->filter_types.da; break; + case SOURCE_TRANSITION: list = &obs->transition_types.da; break; + default: + return NULL; + } + + info = find_source(obs, list, name); + if (!info) { + blog(LOG_WARNING, "Source '%s' not found", type); + return NULL; + } + + source = bmalloc(sizeof(struct obs_source)); + source->data = info->create(settings, source); + if (!source->data) { + bfree(source); + return NULL; + } + + source_init(obs, source); + dstr_copy(&source->settings, settings); + memcpy(&source->callbacks, info, sizeof(struct source_info)); + return source; +} + +void source_destroy(source_t source) +{ + if (source) { + da_free(source->filters); + da_erase_item(source->obs->sources, &source); + + source->callbacks.destroy(source->data); + dstr_free(&source->settings); + bfree(source); + } +} + +uint32_t source_get_output_flags(source_t source) +{ + return source->callbacks.get_output_flags(source->data); +} + +bool source_hasconfig(source_t source) +{ + return source->callbacks.config != NULL; +} + +void source_config(source_t source, void *parent) +{ + if (source->callbacks.config) + source->callbacks.config(source->data, parent); +} + +void source_activate(source_t source) +{ + if (source->callbacks.activate) + source->callbacks.activate(source->data); +} + +void source_deactivate(source_t source) +{ + if (source->callbacks.deactivate) + source->callbacks.deactivate(source->data); +} + +void source_video_tick(source_t source, float seconds) +{ + if (source->callbacks.video_tick) + source->callbacks.video_tick(source->data, seconds); +} + +void source_video_render(source_t source) +{ + if (source->callbacks.video_render) { + if (source->filters.num && !source->rendering_filter) { + source->rendering_filter = true; + source_video_render(source->filters.array[0]); + source->rendering_filter = false; + } else { + source->callbacks.video_render(source->data); + } + } +} + +int source_getwidth(source_t source) +{ + if (source->callbacks.getwidth) + return source->callbacks.getwidth(source->data); + return 0; +} + +int source_getheight(source_t source) +{ + if (source->callbacks.getheight) + return source->callbacks.getheight(source->data); + return 0; +} + +size_t source_getparam(source_t source, const char *param, void *buf, + size_t buf_size) +{ + if (source->callbacks.getparam) + return source->callbacks.getparam(source->data, param, buf, + buf_size); + return 0; +} + +void source_setparam(source_t source, const char *param, const void *data, + size_t size) +{ + if (source->callbacks.setparam) + source->callbacks.setparam(source->data, param, data, size); +} + +bool source_enum_children(source_t source, size_t idx, source_t *child) +{ + if (source->callbacks.enum_children) + return source->callbacks.enum_children(source, idx, child); + return false; +} + +source_t filter_gettarget(source_t filter) +{ + return filter->filter_target; +} + +void source_filter_add(source_t source, source_t filter) +{ + if (da_find(source->filters, &filter, 0) != -1) { + blog(LOG_WARNING, "Tried to add a filter that was already " + "present on the source"); + return; + } + + if (source->filters.num) { + source_t *back = da_end(source->filters); + (*back)->filter_target = filter; + } + + da_push_back(source->filters, &filter); + filter->filter_target = source; +} + +void source_filter_remove(source_t source, source_t filter) +{ + size_t idx = da_find(source->filters, &filter, 0); + if (idx == -1) + return; + + if (idx > 0) { + source_t prev = source->filters.array[idx-1]; + prev->filter_target = filter->filter_target; + } + + da_erase(source->filters, idx); + filter->filter_target = NULL; +} + +void source_filter_setorder(source_t source, source_t filter, + enum order_movement movement) +{ + size_t idx = da_find(source->filters, &filter, 0); + size_t i; + if (idx == -1) + return; + + if (movement == ORDER_MOVE_UP) { + if (idx == source->filters.num-1) + return; + da_move_item(source->filters, idx, idx+1); + + } else if (movement == ORDER_MOVE_DOWN) { + if (idx == 0) + return; + da_move_item(source->filters, idx, idx-1); + + } else if (movement == ORDER_MOVE_TOP) { + if (idx == source->filters.num-1) + return; + da_move_item(source->filters, idx, source->filters.num-1); + + } else if (movement == ORDER_MOVE_BOTTOM) { + if (idx == 0) + return; + da_move_item(source->filters, idx, 0); + } + + /* reorder filter targets */ + for (i = 0; i < source->filters.num; i++) { + source_t next_filter = (i == source->filters.num-1) ? + source : source->filters.array[idx+1]; + source->filters.array[i]->filter_target = next_filter; + } +} + +const char *source_get_settings(source_t source) +{ + return source->settings.array; +} + +void source_save_settings(source_t source, const char *settings) +{ + dstr_copy(&source->settings, settings); +} + +void source_output_video(source_t source, struct video_frame *frame) +{ + /* TODO */ +} + +void source_output_audio(source_t source, struct audio_data *audio) +{ + /* TODO */ +} diff --git a/libobs/obs-source.h b/libobs/obs-source.h new file mode 100644 index 000000000..2334d2568 --- /dev/null +++ b/libobs/obs-source.h @@ -0,0 +1,214 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef SOURCE_H +#define SOURCE_H + +#include "util/c99defs.h" +#include "util/darray.h" +#include "util/dstr.h" +#include "media-io/media-io.h" + +/* + * =========================================== + * Sources + * =========================================== + * + * A source is literally a "source" of audio and/or video. + * + * A module with sources needs to export these functions: + * + enum_[type] + * + * Each individual source is then exported by it's name. For example, a + * source named "mysource" would have the following exports: + * + mysource_create + * + mysource_destroy + * + mysource_getflags + * + * [and optionally] + * + mysource_update + * + mysource_config + * + mysource_video_tick + * + mysource_video_render + * + mysource_getparam + * + mysource_setparam + * + * =========================================== + * Primary Exports + * =========================================== + * const bool enum_[type](size_t idx, const char **name); + * idx: index of the source. + * type: pointer to variable that receives the type of the source + * Return value: false when no more available. + * + * =========================================== + * Source Exports + * =========================================== + * void *[name]_create(const char *settings, source_t source); + * Creates a source. + * + * settings: Settings of the source. + * source: pointer to main source + * Return value: Internal source pointer, or NULL if failed. + * + * --------------------------------------------------------- + * void [name]_destroy(void *data); + * Destroys the source. + * + * --------------------------------------------------------- + * uint32_t [name]_getflags(void *data); + * Returns a combination of one of the following values: + * + SOURCE_VIDEO: source has video + * + SOURCE_AUDIO: source has audio + * + SOURCE_ASYNC: video is sent asynchronously via RAM + * + * --------------------------------------------------------- + * int [name]_getwidth(void *data); + * Returns the width of a source, or -1 for maximum width. If you render + * video, this is required. + * + * --------------------------------------------------------- + * int [name]_getheight(void *data); + * Returns the height of a source, or -1 for maximum height. If you + * render video, this is required. + * + * =========================================== + * Optional Source Exports + * =========================================== + * void [name]_update(void *data, const char *settings) + * Updates the source's settings + * + * settings: New settings of the source + * + * --------------------------------------------------------- + * void [name]_config(void *data, void *parent); + * Called to configure the source. + * + * parent: Parent window pointer + * + * --------------------------------------------------------- + * void [name]_video_activate(void *data); + * Called when the source is being displayed. + * + * --------------------------------------------------------- + * void [name]_video_deactivate(void *data); + * Called when the source is no longer being displayed. + * + * --------------------------------------------------------- + * void [name]_video_tick(void *data, float seconds); + * Called each video frame with the time taken between the last and + * current frame, in seconds. + * + * --------------------------------------------------------- + * void [name]_video_render(void *data); + * Called to render the source. + * + * --------------------------------------------------------- + * void [name]_getparam(void *data, const char *param, void *buf, + * size_t buf_size); + * Gets a source parameter value. + * + * param: Name of parameter. + * Return value: Value of parameter. + * + * --------------------------------------------------------- + * void [name]_setparam(void *data, const char *param, const void *buf, + * size_t size); + * Sets a source parameter value. + * + * param: Name of parameter. + * val: Value of parameter to set. + * + * --------------------------------------------------------- + * bool [name]_enum_children(void *data, size_t idx, source_t *child); + * Enumerates child sources, if any. + * + * idx: Child source index. + * child: Pointer to variable that receives child source. + * Return value: true if sources remaining, otherwise false. + * + * --------------------------------------------------------- + * void [name]_filter_video(void *data, struct video_frame *frame); + * Filters audio data. Used with audio filters. + * + * frame: Video frame data. + * + * --------------------------------------------------------- + * void [name]_filter_audio(void *data, struct audio_data *audio); + * Filters video data. Used with async video data. + * + * audio: Audio data. + */ + +struct obs_source; + +struct source_info { + const char *name; + + /* ----------------------------------------------------------------- */ + /* required implementations */ + + void *(*create)(const char *settings, struct obs_source *source); + void (*destroy)(void *data); + + uint32_t (*get_output_flags)(void *data); + + /* ----------------------------------------------------------------- */ + /* optional implementations */ + + bool (*config)(void *data, void *parent); + + void (*activate)(void *data); + void (*deactivate)(void *data); + + void (*video_tick)(void *data, float seconds); + void (*video_render)(void *data); + int (*getwidth)(void *data); + int (*getheight)(void *data); + + size_t (*getparam)(void *data, const char *param, void *data_out, + size_t buf_size); + void (*setparam)(void *data, const char *param, const void *data_in, + size_t size); + + bool (*enum_children)(void *data, size_t idx, source_t *child); + + void (*filter_video)(void *data, struct video_frame *frame); + void (*filter_audio)(void *data, struct audio_data *audio); +}; + +struct obs_source { + struct obs_data *obs; + void *data; + struct source_info callbacks; + struct dstr settings; + bool rendering_filter; + + struct obs_source *filter_target; + DARRAY(struct obs_source*) filters; +}; + +extern bool get_source_info(void *module, const char *module_name, + const char *source_name, struct source_info *info); + +extern void source_init(obs_t obs, struct obs_source *source); + +EXPORT void source_activate(source_t source); +EXPORT void source_deactivate(source_t source); +EXPORT void source_video_tick(source_t source, float seconds); + +#endif diff --git a/libobs/obs-video.c b/libobs/obs-video.c new file mode 100644 index 000000000..e92c5c69e --- /dev/null +++ b/libobs/obs-video.c @@ -0,0 +1,126 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "obs.h" +#include "obs-data.h" +#include "graphics/vec4.h" + +static void tick_sources(obs_t obs, uint64_t cur_time, uint64_t *last_time) +{ + size_t i; + uint64_t delta_time; + float seconds; + + if (!last_time) + *last_time = cur_time - video_getframetime(obs->video); + delta_time = cur_time - *last_time; + seconds = (float)((double)delta_time / 1000000000.0); + + for (i = 0; i < obs->sources.num; i++) + source_video_tick(obs->sources.array[i], seconds); + + *last_time = cur_time; +} + +static inline void render_displays(obs_t obs) +{ + size_t i; + struct vec4 clear_color; + vec4_set(&clear_color, 0.3f, 0.0f, 0.0f, 1.0f); + + //gs_enable_depthtest(false); + + gs_ortho(0.0f, (float)obs->output_width, + 0.0f, (float)obs->output_height, + -100.0f, 100.0f); + + for (i = 0; i < obs->displays.num; i++) { + display_t display = obs->displays.array[i]; + + gs_load_swapchain(display->swap); + + gs_beginscene(); + gs_setviewport(0, 0, gs_getwidth(), gs_getheight()); + + if (display->source) + source_video_render(display->source); + + gs_endscene(); + gs_present(); + } + + gs_load_swapchain(NULL); + + gs_beginscene(); + gs_clear(GS_CLEAR_COLOR|GS_CLEAR_DEPTH|GS_CLEAR_STENCIL, + &clear_color, 1.0f, 0); + + gs_setviewport(0, 0, gs_getwidth(), gs_getheight()); + + if (obs->primary_source) + source_video_render(obs->primary_source); + + gs_endscene(); + gs_present(); +} + +static bool swap_frame(obs_t obs, uint64_t timestamp) +{ + stagesurf_t last_surface = obs->copy_surfaces[obs->cur_texture]; + stagesurf_t surface; + struct video_frame frame; + + if (obs->copy_mapped) { + stagesurface_unmap(last_surface); + obs->copy_mapped = false; + } + + obs->textures_copied[obs->cur_texture] = true; + gs_stage_texture(last_surface, NULL); + + if (++obs->cur_texture == NUM_TEXTURES) + obs->cur_texture = 0; + + if (obs->textures_copied[obs->cur_texture]) { + surface = obs->copy_surfaces[obs->cur_texture]; + obs->copy_mapped = stagesurface_map(surface, &frame.data, + &frame.row_size); + + if (obs->copy_mapped) { + frame.timestamp = timestamp; + video_output_frame(obs->video, &frame); + } + } + + return obs->copy_mapped; +} + +void *obs_video_thread(void *param) +{ + struct obs_data *obs = param; + uint64_t last_time = 0; + + while (video_output_wait(obs->video)) { + uint64_t cur_time = video_gettime(obs->video); + + tick_sources(obs, cur_time, &last_time); + render_displays(obs); + swap_frame(obs, cur_time); + } + + return NULL; +} diff --git a/libobs/obs.c b/libobs/obs.c new file mode 100644 index 000000000..49140ca9f --- /dev/null +++ b/libobs/obs.c @@ -0,0 +1,242 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +******************************************************************************/ + +#include "obs.h" +#include "obs-data.h" +#include "obs-module.h" + +static bool obs_init_graphics(struct obs_data *obs, const char *graphics_module, + struct gs_init_data *graphics_data, struct video_info *vi) +{ + int errorcode; + size_t i; + + errorcode = gs_create(&obs->graphics, graphics_module, graphics_data); + if (errorcode != GS_SUCCESS) { + if (errorcode == GS_ERROR_MODULENOTFOUND) + blog(LOG_ERROR, "Could not find graphics module '%s'", + graphics_module); + return false; + } + + gs_setcontext(obs->graphics); + + for (i = 0; i < NUM_TEXTURES; i++) { + obs->copy_surfaces[i] = gs_create_stagesurface(vi->width, + vi->height, graphics_data->format); + if (!obs->copy_surfaces[i]) + return false; + } + + return true; +} + +static bool obs_init_media(struct obs_data *obs, + struct video_info *vi, struct audio_info *ai) +{ + obs->media = media_open(); + if (!obs->media) + return false; + + if (!obs_reset_video(obs, vi)) + return false; + if (!obs_reset_audio(obs, ai)) + return false; + + return true; +} + +static bool obs_init_threading(struct obs_data *obs) +{ + if (pthread_mutex_init(&obs->source_mutex, NULL) != 0) + return false; + if (pthread_create(&obs->video_thread, NULL, obs_video_thread, + obs) != 0) + return false; + + obs->thread_initialized = true; + return true; +} + +static pthread_mutex_t pthread_init_val = PTHREAD_MUTEX_INITIALIZER; + +obs_t obs_create(const char *graphics_module, + struct gs_init_data *graphics_data, + struct video_info *vi, struct audio_info *ai) +{ + struct obs_data *obs = bmalloc(sizeof(struct obs_data)); + + memset(obs, 0, sizeof(struct obs_data)); + obs->source_mutex = pthread_init_val; + + if (!obs_init_graphics(obs, graphics_module, graphics_data, vi)) + goto error; + if (!obs_init_media(obs, vi, ai)) + goto error; + if (!obs_init_threading(obs)) + goto error; + + return obs; + +error: + obs_destroy(obs); + return NULL; +} + +static inline void obs_free_graphics(obs_t obs) +{ + size_t i; + if (!obs->graphics) + return; + + if (obs->copy_mapped) + stagesurface_unmap(obs->copy_surfaces[obs->cur_texture]); + + for (i = 0; i < NUM_TEXTURES; i++) + stagesurface_destroy(obs->copy_surfaces[i]); + + gs_setcontext(NULL); + gs_destroy(obs->graphics); +} + +static inline void obs_free_media(obs_t obs) +{ + video_output_close(obs->video); + audio_output_close(obs->audio); + media_close(obs->media); +} + +static inline void obs_free_threading(obs_t obs) +{ + void *thread_ret; + video_output_stop(obs->video); + if (obs->thread_initialized) + pthread_join(obs->video_thread, &thread_ret); + pthread_mutex_destroy(&obs->source_mutex); +} + +void obs_destroy(obs_t obs) +{ + size_t i; + + if (!obs) + return; + + for (i = 0; i < obs->displays.num; i++) + display_destroy(obs->displays.array[i]); + + da_free(obs->input_types); + da_free(obs->filter_types); + da_free(obs->transition_types); + da_free(obs->output_types); + /*da_free(obs->services);*/ + + da_free(obs->displays); + da_free(obs->sources); + + obs_free_threading(obs); + obs_free_media(obs); + obs_free_graphics(obs); + + for (i = 0; i < obs->modules.num; i++) + free_module(obs->modules.array+i); + da_free(obs->modules); + + bfree(obs); +} + +bool obs_reset_video(obs_t obs, struct video_info *vi) +{ + int errorcode; + + if (obs->video) { + video_output_close(obs->video); + obs->video = NULL; + } + + obs->output_width = vi->width; + obs->output_height = vi->height; + + errorcode = video_output_open(&obs->video, obs->media, vi); + if (errorcode == VIDEO_OUTPUT_SUCCESS) + return true; + else if (errorcode == VIDEO_OUTPUT_INVALIDPARAM) + blog(LOG_ERROR, "Invalid video parameters specified"); + else + blog(LOG_ERROR, "Could not open video output"); + + return false; +} + +bool obs_reset_audio(obs_t obs, struct audio_info *ai) +{ + return true; +} + + +bool obs_enum_inputs(obs_t obs, size_t idx, const char **name) +{ + if (idx >= obs->input_types.num) + return false; + *name = obs->input_types.array[idx].name; + return true; +} + +bool obs_enum_filters(obs_t obs, size_t idx, const char **name) +{ + if (idx >= obs->filter_types.num) + return false; + *name = obs->filter_types.array[idx].name; + return true; +} + +bool obs_enum_transitions(obs_t obs, size_t idx, const char **name) +{ + if (idx >= obs->transition_types.num) + return false; + *name = obs->transition_types.array[idx].name; + return true; +} + +bool obs_enum_outputs(obs_t obs, size_t idx, const char **name) +{ + if (idx >= obs->output_types.num) + return false; + *name = obs->output_types.array[idx].name; + return true; +} + + +graphics_t obs_graphics(obs_t obs) +{ + return obs->graphics; +} + +media_t obs_media(obs_t obs) +{ + return obs->media; +} + +source_t obs_get_primary_source(obs_t obs) +{ + return obs->primary_source; +} + +void obs_set_primary_source(obs_t obs, source_t source) +{ + obs->primary_source = source; +} diff --git a/libobs/obs.h b/libobs/obs.h new file mode 100644 index 000000000..7e76b148a --- /dev/null +++ b/libobs/obs.h @@ -0,0 +1,304 @@ +/****************************************************************************** + Copyright (C) 2013 by Hugh Bailey + + 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 . +******************************************************************************/ + +#ifndef LIBOBS_H +#define LIBOBS_H + +#include "util/c99defs.h" +#include "graphics/graphics.h" +#include "graphics/vec2.h" +#include "media-io/media-io.h" + +#include "obs-defs.h" + +/* + * Main libobs header used by applications. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +enum source_type { + SOURCE_INPUT, + SOURCE_FILTER, + SOURCE_TRANSITION, + SOURCE_SCENE +}; + +enum order_movement { + ORDER_MOVE_UP, + ORDER_MOVE_DOWN, + ORDER_MOVE_TOP, + ORDER_MOVE_BOTTOM +}; + +/* opaque types */ +struct obs_data; +struct obs_display; +struct obs_source; +struct obs_scene; +struct obs_scene_item; +struct obs_output; + +typedef struct obs_data *obs_t; +typedef struct obs_display *display_t; +typedef struct obs_source *source_t; +typedef struct obs_scene *scene_t; +typedef struct obs_scene_item *sceneitem_t; +typedef struct obs_output *output_t; + +/* ------------------------------------------------------------------------- */ +/* OBS context */ + +/** + * Creates the OBS context. + * + * Using the graphics module specified, creates an OBS context and sets the + * primary video/audio output information. + */ +EXPORT obs_t obs_create(const char *graphics_module, + struct gs_init_data *graphics_data, + struct video_info *vi, struct audio_info *ai); +EXPORT void obs_destroy(obs_t obs); + +/** + * Sets base video ouput base resolution/fps/format + * + * NOTE: Cannot reset base video if currently streaming/recording. + */ +EXPORT bool obs_reset_video(obs_t obs, struct video_info *vi); +/** + * Sets base audio output format/channels/samples/etc + * + * NOTE: Cannot reset base audio if currently streaming/recording. + */ +EXPORT bool obs_reset_audio(obs_t obs, struct audio_info *ai); + +/** + * Loads a plugin module + * + * A plugin module contains exports for inputs/fitlers/transitions/outputs. + * See obs-source.h and obs-output.h for more information on the exports to + * use. + */ +EXPORT int obs_load_module(obs_t obs, const char *path); + +/** + * Enumerates all available inputs. + * + * Inputs are general source inputs (such as capture sources, device sources, + * etc). + */ +EXPORT bool obs_enum_inputs(obs_t obs, size_t idx, const char **name); +/** + * Enumerates all available filters. + * + * Filters are sources that are used to modify the video/audio output of + * other sources. + */ +EXPORT bool obs_enum_filters(obs_t obs, size_t idx, const char **name); +/** + * Enumerates all available transitions. + * + * Transitions are sources used to transition between two or more other + * sources. + */ +EXPORT bool obs_enum_transitions(obs_t obs, size_t idx, + const char **name); +/** + * Enumerates all available ouputs. + * + * Outputs handle color space conversion, encoding, and output to file or + * streams. + */ +EXPORT bool obs_enum_outputs(obs_t obs, size_t idx, const char **name); + +/** Gets the graphics context for this OBS context */ +EXPORT graphics_t obs_graphics(obs_t obs); +/** Get the media context for this OBS context (used for outputs) */ +EXPORT media_t obs_media(obs_t obs); + +/** + * Sets/gets the primary output source. + * + * The primary source is the source that's broadcasted/saved. + */ +EXPORT void obs_set_primary_source(obs_t obs, source_t source); +EXPORT source_t obs_get_primary_source(obs_t obs); + + +/* ------------------------------------------------------------------------- */ +/* Display context */ + +/** + * Creates an extra display context. + * + * An extra display can be used for things like separate previews, + * viewing sources independently, and other things. Creates a new swap chain + * linked to a specific window to display a source. + */ +EXPORT display_t display_create(obs_t obs, struct gs_init_data *graphics_data); +EXPORT void display_destroy(display_t display); +/** Sets the source to be used for a display context. */ +EXPORT void display_setsource(display_t display, source_t source); +EXPORT source_t display_getsource(display_t display); + + +/* ------------------------------------------------------------------------- */ +/* Sources */ + +/** + * Creates a source of the specified type with the specified settings. + * + * The "source" context is used for anything related to presenting + * or modifying video/audio. + */ +EXPORT source_t source_create(obs_t obs, enum source_type type, + const char *name, const char *settings); +EXPORT void source_destroy(source_t source); +/** + * Retrieves flags that specify what type of data the source presents/modifies. + * + * SOURCE_VIDEO if it presents/modifies video_frame + * SOURCE_ASYNC if the video is asynchronous. + * SOURCE_AUDIO if it presents/modifies audio (always async) + */ +EXPORT uint32_t source_get_output_flags(source_t source); +/** Specifies whether the source can be configured */ +EXPORT bool source_hasconfig(source_t source); +/** Opens a configuration panel and attaches it to the parent window */ +EXPORT void source_config(source_t source, void *parent); +/** Renders a video source. */ +EXPORT void source_video_render(source_t source); +/** Gets the width of a source (if it has video) */ +EXPORT int source_getwidth(source_t source); +/** Gets the height of a source (if it has video) */ +EXPORT int source_getheight(source_t source); +/** + * Gets a custom parameter from the source. + * + * Used for efficiently modifying source properties in real time. + */ +EXPORT size_t source_getparam(source_t source, const char *param, void *buf, + size_t buf_size); +/** + * Sets a custom parameter for the source. + * + * Used for efficiently modifying source properties in real time. + */ +EXPORT void source_setparam(source_t source, const char *param, + const void *data, size_t size); +/** + * Enumerates child sources this source has + */ +EXPORT bool source_enum_children(source_t source, size_t idx, + source_t *child); + +/** If the source is a filter, returns the target source of the filter */ +EXPORT source_t filter_gettarget(source_t filter); +/** Adds a filter to the source (which is used whenever the source is used) */ +EXPORT void source_filter_add(source_t source, source_t filter); +/** Removes a filter from the source */ +EXPORT void source_filter_remove(source_t source, source_t filter); +/** Modifies the order of a specific filter */ +EXPORT void source_filter_setorder(source_t source, source_t filter, + enum order_movement movement); + +/** Gets the settings string for a source */ +EXPORT const char *source_get_settings(source_t source); + +/* ------------------------------------------------------------------------- */ +/* Functions used by sources */ + +/** Saves the settings string for a source */ +EXPORT void source_save_settings(source_t source, const char *settings); +/** Outputs asynchronous video data */ +EXPORT void source_output_video(source_t source, struct video_frame *frame); +/** Outputs audio data (always asynchronous) */ +EXPORT void source_output_audio(source_t source, struct audio_data *audio); + + +/* ------------------------------------------------------------------------- */ +/* Scenes */ + +/** + * Creates a scene. + * + * A scene is a source which is a container of other sources with specific + * display oriantations. Scenes can also be used like any other source. + */ +EXPORT scene_t scene_create(obs_t obs); +EXPORT void scene_destroy(scene_t scene); +/** Gets the scene's source context */ +EXPORT source_t scene_source(scene_t scene); + +/** Adds/creates a new scene item for a source */ +EXPORT sceneitem_t scene_add(scene_t scene, source_t source); + +/** Removes/destroys a scene item */ +EXPORT void sceneitem_destroy(sceneitem_t item); + +/* Functions for gettings/setting specific oriantation of a scene item */ +EXPORT void sceneitem_setpos(sceneitem_t item, const struct vec2 *pos); +EXPORT void sceneitem_setrot(sceneitem_t item, float rot); +EXPORT void sceneitem_setorigin(sceneitem_t item, const struct vec2 *origin); +EXPORT void sceneitem_setscale(sceneitem_t item, const struct vec2 *scale); +EXPORT void sceneitem_setorder(sceneitem_t item, enum order_movement movement); + +EXPORT void sceneitem_getpos(sceneitem_t item, struct vec2 *pos); +EXPORT float sceneitem_getrot(sceneitem_t item); +EXPORT void sceneitem_getorigin(sceneitem_t item, struct vec2 *center); +EXPORT void sceneitem_getscale(sceneitem_t item, struct vec2 *scale); + + +/* ------------------------------------------------------------------------- */ +/* Outputs */ + +/** + * Creates an output. + * + * Outputs allow outputting to file, outputting to network, outputting to + * directshow, or other custom outputs. + */ +EXPORT output_t output_create(obs_t obs, const char *name, + const char *settings); +EXPORT void output_destroy(output_t output); +/** Starts the output. */ +EXPORT void output_start(output_t output); +/** Stops the output. */ +EXPORT void output_stop(output_t output); +/** Specifies whether the output can be configured */ +EXPORT bool output_canconfig(output_t output); +/** Opens a configuration panel with the specified parent window */ +EXPORT void output_config(output_t output, void *parent); +/** Specifies whether the output can be paused */ +EXPORT bool output_canpause(output_t output); +/** Pauses the output (if the functionality is allowed by the output */ +EXPORT void output_pause(output_t output); + +/* Gets the current output settings string */ +EXPORT const char *output_get_settings(output_t output); + +/* Saves the output settings string, typically used only by outputs */ +EXPORT void output_save_settings(output_t output, const char *settings); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/util/base.c b/libobs/util/base.c new file mode 100644 index 000000000..a6bd68551 --- /dev/null +++ b/libobs/util/base.c @@ -0,0 +1,104 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#include +#include +#include +#include + +#include "c99defs.h" +#include "base.h" + +static enum log_type log_output_level = LOG_WARNING; +static int crashing = 0; + +static void def_log_handler(enum log_type type, const char *format, + va_list args) +{ + char out[4096]; + vsnprintf(out, sizeof(out), format, args); + + if (type >= log_output_level) { + switch (type) { + case LOG_DEBUG: + printf("debug: %s\n", out); + break; + + case LOG_INFO: + printf("info: %s\n", out); + break; + + case LOG_WARNING: + fprintf(stderr, "warning: %s\n", out); + break; + + case LOG_ERROR: + fprintf(stderr, "error: %s\n", out); + } + } +} + +static void def_crash_handler(const char *format, va_list args) +{ + vfprintf(stderr, format, args); + exit(0); +} + +static void (*log_handler)(enum log_type, const char *, va_list) = + def_log_handler; +static void (*crash_handler)(const char *, va_list) = def_crash_handler; + +void base_set_log_handler( + void (*handler)(enum log_type, const char *, va_list)) +{ + log_handler = handler; +} + +void base_set_crash_handler(void (*handler)(const char *, va_list)) +{ + crash_handler = handler; +} + +void bcrash(const char *format, ...) +{ + va_list args; + + if (crashing) { + fputs("Crashed in the crash handler", stderr); + exit(2); + } + + crashing = 1; + va_start(args, format); + crash_handler(format, args); + va_end(args); +} + +void blog(enum log_type type, const char *format, ...) +{ + va_list args; + + va_start(args, format); + log_handler(type, format, args); + va_end(args); +} diff --git a/libobs/util/base.h b/libobs/util/base.h new file mode 100644 index 000000000..5640d4182 --- /dev/null +++ b/libobs/util/base.h @@ -0,0 +1,58 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifndef BASE_H +#define BASE_H + +#include +#include + +#include "c99defs.h" + +/* + * Just contains logging/crash related stuff + */ + +#ifdef __cplusplus +extern "C" { +#endif + +enum log_type { + LOG_DEBUG, + LOG_INFO, + LOG_WARNING, + LOG_ERROR +}; + +EXPORT void base_set_log_handler( + void (*handler)(enum log_type, const char *, va_list)); +EXPORT void base_set_crash_handler(void (*handler)(const char *, va_list)); + +EXPORT void blog(enum log_type type, const char *format, ...); +EXPORT void bcrash(const char *format, ...); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/util/bmem.c b/libobs/util/bmem.c new file mode 100644 index 000000000..090356564 --- /dev/null +++ b/libobs/util/bmem.c @@ -0,0 +1,131 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#include +#include +#include +#include "base.h" +#include "bmem.h" + +static void *a_malloc(size_t size, size_t align) +{ +#if defined(_WIN32) + return _aligned_malloc(size, align); +#elif defined (__posix__) + void *ptr; + if (posix_memalign(&ptr, align, size) != 0) + return NULL; + + return ptr; +#else +#error unknown OS +#endif +} + +static void a_free(void *ptr) +{ +#if defined(_WIN32) + _aligned_free(ptr); +#elif defined (__posix__) + free(ptr); +#else +#error unknown OS +#endif +} + +static struct base_allocator alloc = {malloc, realloc, free, a_malloc, a_free}; +static size_t num_allocs = 0; + +void base_set_allocator(struct base_allocator *defs) +{ + memcpy(&alloc, defs, sizeof(struct base_allocator)); +} + +void *bmalloc(size_t size) +{ + void *ptr = alloc.malloc(size); + if (!ptr && !size) + ptr = alloc.malloc(1); + if (!ptr) + bcrash("Out of memory while trying to allocate %lu bytes", + (unsigned long)size); + + num_allocs++; + return ptr; +} + +void *brealloc(void *ptr, size_t size) +{ + if (!ptr) + num_allocs++; + + ptr = alloc.realloc(ptr, size); + if (!ptr && !size) + ptr = alloc.realloc(ptr, 1); + if (!ptr) + bcrash("Out of memory while trying to allocate %lu bytes", + (unsigned long)size); + + return ptr; +} + +void bfree(void *ptr) +{ + if (ptr) + num_allocs--; + alloc.free(ptr); +} + +void *baligned_malloc(size_t size, size_t align) +{ + void *ptr = alloc.aligned_malloc(size, align); + if (!ptr && !size) + ptr = alloc.aligned_malloc(1, align); + if (!ptr) + bcrash("Out of memory while trying to allocate %lu bytes", + (unsigned long)size); + + num_allocs++; + return ptr; +} + +void baligned_free(void *ptr) +{ + if (ptr) + num_allocs--; + alloc.aligned_free(ptr); +} + +size_t bnum_allocs(void) +{ + return num_allocs; +} + +void *bmemdup(const void *ptr, size_t size) +{ + void *out = bmalloc(size); + if (size) + memcpy(out, ptr, size); + + return out; +} diff --git a/libobs/util/bmem.h b/libobs/util/bmem.h new file mode 100644 index 000000000..f686c68be --- /dev/null +++ b/libobs/util/bmem.h @@ -0,0 +1,102 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifndef BALLOC_H +#define BALLOC_H + +#include "c99defs.h" +#include "base.h" +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct base_allocator { + void *(*malloc)(size_t); + void *(*realloc)(void *, size_t); + void (*free)(void *); + + void *(*aligned_malloc)(size_t, size_t); + void (*aligned_free)(void *); +}; + +EXPORT void base_set_allocator(struct base_allocator *defs); + +EXPORT void *bmalloc(size_t size); +EXPORT void *brealloc(void *ptr, size_t size); +EXPORT void bfree(void *ptr); + +EXPORT void *baligned_malloc(size_t size, size_t align); +EXPORT void baligned_free(void *ptr); + +EXPORT size_t bnum_allocs(void); + +EXPORT void *bmemdup(const void *ptr, size_t size); + +static inline char *bstrdup_n(const char *str, size_t n) +{ + char *dup; + if (!str || !*str) + return NULL; + + dup = (char*)bmemdup(str, n+1); + dup[n] = 0; + + return dup; +} + +static inline wchar_t *bwstrdup_n(const wchar_t *str, size_t n) +{ + wchar_t *dup; + if (!str || !*str) + return NULL; + + dup = (wchar_t*)bmemdup(str, (n+1) * sizeof(wchar_t)); + dup[n] = 0; + + return dup; +} + +static inline char *bstrdup(const char *str) +{ + if (!str) + return NULL; + + return bstrdup_n(str, strlen(str)); +} + +static inline wchar_t *bwstrdup(const wchar_t *str) +{ + if (!str) + return NULL; + + return bwstrdup_n(str, wcslen(str)); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/util/c99defs.h b/libobs/util/c99defs.h new file mode 100644 index 000000000..e1508df0a --- /dev/null +++ b/libobs/util/c99defs.h @@ -0,0 +1,75 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifndef C99DEFS_H +#define C99DEFS_H + +/* + * Contains hacks for getting some C99 stuff working in VC, things like + * bool, inline, stdint + * + * TODO: Check for VC2013, because it actually supports this C99 stuff. + */ + +#ifdef _MSC_VER +#define EXPORT extern __declspec(dllexport) +#else +#define EXPORT extern +#endif + +#ifdef _MSC_VER + +#pragma warning (disable : 4996) + +#ifndef __cplusplus +#define inline __inline +#endif + +#include "vc/stdint.h" +#include "vc/stdbool.h" + +#ifndef __off_t_defined +#define __off_t_defined +#if _FILE_OFFSET_BITS == 64 +typedef long long off_t; +#else +typedef long off_t; +#endif +typedef int64_t off64_t; +#endif /* __off_t_defined */ + +#ifdef _WIN64 +typedef long long ssize_t; +#else +typedef long ssize_t; +#endif + +#else + +#include +#include +#include + +#endif /* _MSC_VER */ + +#endif diff --git a/libobs/util/cf-lexer.c b/libobs/util/cf-lexer.c new file mode 100644 index 000000000..815151b49 --- /dev/null +++ b/libobs/util/cf-lexer.c @@ -0,0 +1,1311 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#include +#include +#include "platform.h" +#include "cf-lexer.h" + +static inline void cf_convert_from_escape_literal(char **p_dst, + const char **p_src) +{ + char *dst = *p_dst; + const char *src = *p_src; + + switch (*(src++)) { + case '\'': *(dst++) = '\''; break; + case '\"': *(dst++) = '\"'; break; + case '\?': *(dst++) = '\?'; break; + case '\\': *(dst++) = '\\'; break; + case '0': *(dst++) = '\0'; break; + case 'a': *(dst++) = '\a'; break; + case 'b': *(dst++) = '\b'; break; + case 'f': *(dst++) = '\f'; break; + case 'n': *(dst++) = '\n'; break; + case 'r': *(dst++) = '\r'; break; + case 't': *(dst++) = '\t'; break; + case 'v': *(dst++) = '\v'; break; + + /* hex */ + case 'X': + case 'x': + *(dst++) = (char)strtoul(src, NULL, 16); + src += 2; + break; + + /* oct */ + default: + if (isdigit(*src)) { + *(dst++) = (char)strtoul(src, NULL, 8); + src += 3; + } + + /* case 'u': + case 'U': */ + } + + *p_dst = dst; + *p_src = src; +} + +char *cf_literal_to_str(const char *literal, size_t count) +{ + const char *temp_src; + char *str, *temp_dst; + + if (!count) + count = strlen(literal); + + if (count < 2) + return NULL; + if (literal[0] != literal[count-1]) + return NULL; + if (literal[0] != '\"' && literal[0] != '\'') + return NULL; + + str = bmalloc(count - 1); + temp_src = literal; + temp_dst = str; + + while (*temp_src) { + if (*temp_src == '\\') { + temp_src++; + cf_convert_from_escape_literal(&temp_dst, &temp_src); + } else { + *(temp_dst++) = *(temp_src++); + } + } + + *temp_dst = 0; + return str; +} + +static bool cf_is_token_break(struct base_token *start_token, + const struct base_token *token) +{ + switch (start_token->type) { + case BASETOKEN_ALPHA: + if (token->type == BASETOKEN_OTHER || + token->type == BASETOKEN_WHITESPACE) + return true; + break; + + case BASETOKEN_DIGIT: + if (token->type == BASETOKEN_WHITESPACE + || (token->type == BASETOKEN_OTHER + && *token->text.array != '.')) + return true; + break; + + case BASETOKEN_WHITESPACE: + /* lump all non-newline whitespace together when possible */ + if (is_space_or_tab(*start_token->text.array) && + is_space_or_tab(*token->text.array)) + break; + return true; + + case BASETOKEN_OTHER: + if (*start_token->text.array == '.' && + token->type == BASETOKEN_DIGIT) { + start_token->type = BASETOKEN_DIGIT; + break; + } + + default: + return true; + } + + return false; +} + +static inline bool cf_is_splice(const char *array) +{ + return (*array == '\\' && is_newline(array[1])); +} + +static inline void cf_pass_any_splices(const char **parray) +{ + while (cf_is_splice(*parray)) + *parray += 1 + newline_size((*parray)+1); +} + +static inline bool cf_is_comment(const char *array) +{ + const char *offset = array; + + if (*offset++ == '/') { + cf_pass_any_splices(&offset); + return (*offset == '*' || *offset == '/'); + } + + return false; +} + +static bool cf_lexer_process_comment(struct cf_lexer *lex, + struct cf_token *out_token) +{ + const char *offset; + + if (!cf_is_comment(out_token->unmerged_str.array)) + return false; + + offset = lex->base_lexer.offset; + cf_pass_any_splices(&offset); + + strcpy(lex->write_offset++, " "); + out_token->str.len = 1; + + if (*offset == '/') { + while (*++offset && !is_newline(*offset)) + cf_pass_any_splices(&offset); + + } else if (*offset == '*') { + bool was_star = false; + lex->unexpected_eof = true; + + while (*++offset) { + cf_pass_any_splices(&offset); + + if (was_star && *offset == '/') { + offset++; + lex->unexpected_eof = false; + break; + } else { + was_star = (*offset == '*'); + } + } + } + + out_token->unmerged_str.len += offset - out_token->unmerged_str.array; + out_token->type = CFTOKEN_SPACETAB; + lex->base_lexer.offset = offset; + + return true; +} + +static inline void cf_lexer_write_strref(struct cf_lexer *lex, + const struct strref *ref) +{ + strncpy(lex->write_offset, ref->array, ref->len); + lex->write_offset[ref->len] = 0; + lex->write_offset += ref->len; +} + +static bool cf_lexer_is_include(struct cf_lexer *lex) +{ + bool found_include_import = false; + bool found_preprocessor = false; + size_t i; + + for (i = lex->tokens.num; i > 0; i--) { + struct cf_token *token = lex->tokens.array+(i-1); + + if (is_space_or_tab(*token->str.array)) + continue; + + if (!found_include_import) { + if (strref_cmp(&token->str, "include") != 0 && + strref_cmp(&token->str, "import") != 0) + break; + + found_include_import = true; + + } else if (!found_preprocessor) { + if (*token->str.array != '#') + break; + + found_preprocessor = true; + + } else { + return is_newline(*token->str.array); + } + } + + /* if starting line */ + return found_preprocessor && found_include_import; +} + +static void cf_lexer_getstrtoken(struct cf_lexer *lex, + struct cf_token *out_token, char delimiter, + bool allow_escaped_delimiters) +{ + const char *offset = lex->base_lexer.offset; + bool escaped = false; + + out_token->unmerged_str.len++; + out_token->str.len++; + cf_lexer_write_strref(lex, &out_token->unmerged_str); + + while (*offset) { + cf_pass_any_splices(&offset); + if (*offset == delimiter) { + if (!escaped) { + *lex->write_offset++ = *offset; + out_token->str.len++; + offset++; + break; + } + } else if (is_newline(*offset)) { + break; + } + + *lex->write_offset++ = *offset; + out_token->str.len++; + + escaped = (allow_escaped_delimiters && *offset == '\\'); + offset++; + } + + *lex->write_offset = 0; + out_token->unmerged_str.len += offset - out_token->unmerged_str.array; + out_token->type = CFTOKEN_STRING; + lex->base_lexer.offset = offset; +} + +static bool cf_lexer_process_string(struct cf_lexer *lex, + struct cf_token *out_token) +{ + char ch = *out_token->unmerged_str.array; + + if (ch == '<' && cf_lexer_is_include(lex)) { + cf_lexer_getstrtoken(lex, out_token, '>', false); + return true; + + } else if (ch == '"' || ch == '\'') { + cf_lexer_getstrtoken(lex, out_token, ch, + !cf_lexer_is_include(lex)); + return true; + } + + return false; +} + +static inline enum cf_token_type cf_get_token_type(const struct cf_token *token, + const struct base_token *start_token) +{ + switch (start_token->type) { + case BASETOKEN_ALPHA: + return CFTOKEN_NAME; + + case BASETOKEN_DIGIT: + return CFTOKEN_NUM; + + case BASETOKEN_WHITESPACE: + if (is_newline(*token->str.array)) + return CFTOKEN_NEWLINE; + else + return CFTOKEN_SPACETAB; + + default: + break; + } + + return CFTOKEN_OTHER; +} + +static bool cf_lexer_nexttoken(struct cf_lexer *lex, struct cf_token *out_token) +{ + struct base_token token, start_token; + bool wrote_data = false; + + base_token_clear(&token); + base_token_clear(&start_token); + cf_token_clear(out_token); + + while (lexer_getbasetoken(&lex->base_lexer, &token, false)) { + /* reclassify underscore as alpha for alnum tokens */ + if (*token.text.array == '_') + token.type = BASETOKEN_ALPHA; + + /* ignore escaped newlines to merge spliced lines */ + if (cf_is_splice(token.text.array)) { + lex->base_lexer.offset += + newline_size(token.text.array+1); + continue; + } + + if (!wrote_data) { + out_token->unmerged_str.array = token.text.array; + out_token->str.array = lex->write_offset; + + /* if comment then output a space */ + if (cf_lexer_process_comment(lex, out_token)) + return true; + + /* process string tokens if any */ + if (cf_lexer_process_string(lex, out_token)) + return true; + + base_token_copy(&start_token, &token); + wrote_data = true; + + } else if (cf_is_token_break(&start_token, &token)) { + lex->base_lexer.offset -= token.text.len; + break; + } + + /* write token to CF lexer to account for splicing/comments */ + cf_lexer_write_strref(lex, &token.text); + out_token->str.len += token.text.len; + } + + if (wrote_data) { + out_token->unmerged_str.len = lex->base_lexer.offset - + out_token->unmerged_str.array; + out_token->type = cf_get_token_type(out_token, &start_token); + } + + return wrote_data; +} + +void cf_lexer_init(struct cf_lexer *lex) +{ + lexer_init(&lex->base_lexer); + da_init(lex->tokens); + + lex->file = NULL; + lex->reformatted = NULL; + lex->write_offset = NULL; + lex->unexpected_eof = false; +} + +void cf_lexer_free(struct cf_lexer *lex) +{ + bfree(lex->file); + bfree(lex->reformatted); + lexer_free(&lex->base_lexer); + da_free(lex->tokens); + + lex->file = NULL; + lex->reformatted = NULL; + lex->write_offset = NULL; + lex->unexpected_eof = false; +} + +bool cf_lexer_lex(struct cf_lexer *lex, const char *str, const char *file) +{ + struct cf_token token; + struct cf_token *last_token = NULL; + + cf_lexer_free(lex); + if (!str || !*str) + return false; + + if (file) + lex->file = bstrdup(file); + + lexer_start(&lex->base_lexer, str); + cf_token_clear(&token); + + lex->reformatted = bmalloc(strlen(str) + 1); + lex->reformatted[0] = 0; + lex->write_offset = lex->reformatted; + + while (cf_lexer_nexttoken(lex, &token)) { + if (last_token && + is_space_or_tab(*last_token->str.array) && + is_space_or_tab(*token.str.array)) { + cf_token_add(last_token, &token); + continue; + } + + token.lex = lex; + last_token = da_push_back_new(lex->tokens); + memcpy(last_token, &token, sizeof(struct cf_token)); + } + + cf_token_clear(&token); + + token.str.array = lex->write_offset; + token.unmerged_str.array = lex->base_lexer.offset; + token.lex = lex; + da_push_back(lex->tokens, &token); + + return !lex->unexpected_eof; +} + +/* ------------------------------------------------------------------------- */ + +struct macro_param { + struct cf_token name; + DARRAY(struct cf_token) tokens; +}; + +static inline void macro_param_init(struct macro_param *param) +{ + cf_token_clear(¶m->name); + da_init(param->tokens); +} + +static inline void macro_param_free(struct macro_param *param) +{ + cf_token_clear(¶m->name); + da_free(param->tokens); +} + +/* ------------------------------------------------------------------------- */ + +struct macro_params { + DARRAY(struct macro_param) params; +}; + +static inline void macro_params_init(struct macro_params *params) +{ + da_init(params->params); +} + +static inline void macro_params_free(struct macro_params *params) +{ + size_t i; + for (i = 0; i < params->params.num; i++) + macro_param_free(params->params.array+i); + da_free(params->params); +} + +static inline struct macro_param *get_macro_param( + const struct macro_params *params, + const struct strref *name) +{ + size_t i; + if (!params) + return NULL; + + for (i = 0; i < params->params.num; i++) { + struct macro_param *param = params->params.array+i; + if (strref_cmp_strref(¶m->name.str, name) == 0) + return param; + } + + return NULL; +} + +/* ------------------------------------------------------------------------- */ + +static bool cf_preprocessor(struct cf_preprocessor *pp, + bool if_block, struct cf_token **p_cur_token); +static void cf_preprocess_tokens(struct cf_preprocessor *pp, + bool if_block, struct cf_token **p_cur_token); + +static inline bool go_to_newline(struct cf_token **p_cur_token) +{ + struct cf_token *cur_token = *p_cur_token; + while (cur_token->type != CFTOKEN_NEWLINE && + cur_token->type != CFTOKEN_NONE) + cur_token++; + + *p_cur_token = cur_token; + + return cur_token->type != CFTOKEN_NONE; +} + +static inline bool next_token(struct cf_token **p_cur_token, bool preprocessor) +{ + struct cf_token *cur_token = *p_cur_token; + + if (cur_token->type != CFTOKEN_NONE) + cur_token++; + + /* if preprocessor, stop at newline */ + while (cur_token->type == CFTOKEN_SPACETAB && + (preprocessor || cur_token->type == CFTOKEN_NEWLINE)) + cur_token++; + + *p_cur_token = cur_token; + return cur_token->type != CFTOKEN_NONE; +} + +static inline void cf_gettokenoffset(struct cf_preprocessor *pp, + const struct cf_token *token, uint32_t *row, uint32_t *col) +{ + lexer_getstroffset(&pp->lex->base_lexer, + token->unmerged_str.array, row, col); +} + +static void cf_addew(struct cf_preprocessor *pp, const struct cf_token *token, + const char *message, int error_level, + const char *val1, const char *val2, const char *val3) +{ + uint32_t row, col; + cf_gettokenoffset(pp, token, &row, &col); + + if (!val1 && !val2 && !val3) { + error_data_add(pp->ed, token->lex->file, row, col, + message, error_level); + } else { + struct dstr formatted; + dstr_init(&formatted); + dstr_safe_printf(&formatted, message, val1, val2, val3, NULL); + + error_data_add(pp->ed, token->lex->file, row, col, + formatted.array, error_level); + dstr_free(&formatted); + } +} + +static inline void cf_adderror(struct cf_preprocessor *pp, + const struct cf_token *token, const char *error, + const char *val1, const char *val2, const char *val3) +{ + cf_addew(pp, token, error, LEVEL_ERROR, val1, val2, val3); +} + +static inline void cf_addwarning(struct cf_preprocessor *pp, + const struct cf_token *token, const char *warning, + const char *val1, const char *val2, const char *val3) +{ + cf_addew(pp, token, warning, LEVEL_WARNING, val1, val2, val3); +} + +static inline void cf_adderror_expecting(struct cf_preprocessor *pp, + const struct cf_token *token, const char *expecting) +{ + cf_adderror(pp, token, "Expected $1", expecting, + NULL, NULL); +} + +static inline void cf_adderror_expected_newline(struct cf_preprocessor *pp, + const struct cf_token *token) +{ + cf_adderror(pp, token, + "Unexpected token after preprocessor, expected " + "newline", + NULL, NULL, NULL); +} + +static inline void cf_adderror_unexpected_endif_eof(struct cf_preprocessor *pp, + const struct cf_token *token) +{ + cf_adderror(pp, token, "Unexpected end of file before #endif", + NULL, NULL, NULL); +} + +static inline void cf_adderror_unexpected_eof(struct cf_preprocessor *pp, + const struct cf_token *token) +{ + cf_adderror(pp, token, "Unexpected end of file", + NULL, NULL, NULL); +} + +static void cf_include_file(struct cf_preprocessor *pp, + const struct cf_token *file_token) +{ + struct cf_lexer new_lex; + struct dstr str_file; + FILE *file; + char *file_data; + struct cf_token *tokens; + size_t i; + + dstr_init(&str_file); + dstr_copy_strref(&str_file, &file_token->str); + dstr_mid(&str_file, &str_file, 1, str_file.len-2); + + /* if dependency already exists, run preprocessor on it */ + for (i = 0; i < pp->dependencies.num; i++) { + struct cf_lexer *dep = pp->dependencies.array+i; + + if (strcmp(dep->file, str_file.array) == 0) { + tokens = cf_lexer_gettokens(dep); + cf_preprocess_tokens(pp, false, &tokens); + goto exit; + } + } + + file = os_fopen(str_file.array, "rb"); + if (!file) { + cf_adderror(pp, file_token, "Could not open file '$1'", + file_token->str.array, NULL, NULL); + goto exit; + } + + os_fread_utf8(file, &file_data); + fclose(file); + + cf_lexer_init(&new_lex); + cf_lexer_lex(&new_lex, file_data, str_file.array); + tokens = cf_lexer_gettokens(&new_lex); + cf_preprocess_tokens(pp, false, &tokens); + bfree(file_data); + + da_push_back(pp->dependencies, &new_lex); + +exit: + dstr_free(&str_file); +} + +static inline bool is_sys_include(struct strref *ref) +{ + return ref->len >= 2 && + ref->array[0] == '<' && ref->array[ref->len-1] == '>'; +} + +static inline bool is_loc_include(struct strref *ref) +{ + return ref->len >= 2 && + ref->array[0] == '"' && ref->array[ref->len-1] == '"'; +} + +static void cf_preprocess_include(struct cf_preprocessor *pp, + struct cf_token **p_cur_token) +{ + struct cf_token *cur_token = *p_cur_token; + + if (pp->ignore_state) { + go_to_newline(p_cur_token); + return; + } + + next_token(&cur_token, true); + + if (cur_token->type != CFTOKEN_STRING) { + cf_adderror_expecting(pp, cur_token, "string"); + go_to_newline(&cur_token); + goto exit; + } + + if (is_sys_include(&cur_token->str)) { + /* TODO */ + } else if (is_loc_include(&cur_token->str)) { + if (!pp->ignore_state) + cf_include_file(pp, cur_token); + } else { + cf_adderror(pp, cur_token, "Invalid or incomplete string", + NULL, NULL, NULL); + go_to_newline(&cur_token); + goto exit; + } + + cur_token++; + +exit: + *p_cur_token = cur_token; +} + +static bool cf_preprocess_macro_params(struct cf_preprocessor *pp, + struct cf_def *def, struct cf_token **p_cur_token) +{ + struct cf_token *cur_token = *p_cur_token; + bool success = false; + def->macro = true; + + do { + next_token(&cur_token, true); + if (cur_token->type != CFTOKEN_NAME) { + cf_adderror_expecting(pp, cur_token, "identifier"); + go_to_newline(&cur_token); + goto exit; + } + + cf_def_addparam(def, cur_token); + + next_token(&cur_token, true); + if (cur_token->type != CFTOKEN_OTHER + || (*cur_token->str.array != ',' + && *cur_token->str.array != ')')) { + + cf_adderror_expecting(pp, cur_token, "',' or ')'"); + go_to_newline(&cur_token); + goto exit; + } + } while (*cur_token->str.array != ')'); + + /* ended properly, now go to first define token (or newline) */ + next_token(&cur_token, true); + success = true; + +exit: + *p_cur_token = cur_token; + return success; +} + +static inline size_t cf_preprocess_get_def_idx(struct cf_preprocessor *pp, + const struct strref *def_name) +{ + struct cf_def *array = pp->defines.array; + size_t i; + + for (i = 0; i < pp->defines.num; i++) { + struct cf_def *cur_def = array+i; + + if (strref_cmp_strref(&cur_def->name.str, def_name) == 0) + return i; + } + + return -1; +} + +static inline struct cf_def *cf_preprocess_get_def(struct cf_preprocessor *pp, + const struct strref *def_name) +{ + size_t idx = cf_preprocess_get_def_idx(pp, def_name); + if (idx == -1) + return NULL; + + return pp->defines.array+idx; +} + +static char space_filler[2] = " "; + +static inline void append_space(struct cf_preprocessor *pp, + struct darray *tokens, const struct cf_token *base) +{ + struct cf_token token; + + strref_set(&token.str, space_filler, 1); + token.type = CFTOKEN_SPACETAB; + if (base) { + token.lex = base->lex; + strref_copy(&token.unmerged_str, &base->unmerged_str); + } else { + token.lex = pp->lex; + strref_copy(&token.unmerged_str, &token.str); + } + + darray_push_back(sizeof(struct cf_token), tokens, &token); +} + +static inline void append_end_token(struct darray *tokens) +{ + struct cf_token end; + cf_token_clear(&end); + darray_push_back(sizeof(struct cf_token), tokens, &end); +} + +static void cf_preprocess_define(struct cf_preprocessor *pp, + struct cf_token **p_cur_token) +{ + struct cf_token *cur_token = *p_cur_token; + struct cf_def def; + + if (pp->ignore_state) { + go_to_newline(p_cur_token); + return; + } + + cf_def_init(&def); + + next_token(&cur_token, true); + if (cur_token->type != CFTOKEN_NAME) { + cf_adderror_expecting(pp, cur_token, "identifier"); + go_to_newline(&cur_token); + goto exit; + } + + append_space(pp, &def.tokens.da, NULL); + cf_token_copy(&def.name, cur_token); + + if (!next_token(&cur_token, true)) + goto complete; + + /* process macro */ + if (*cur_token->str.array == '(') { + if (!cf_preprocess_macro_params(pp, &def, &cur_token)) + goto error; + } + + while (cur_token->type != CFTOKEN_NEWLINE && + cur_token->type != CFTOKEN_NONE) + cf_def_addtoken(&def, cur_token++); + +complete: + append_end_token(&def.tokens.da); + append_space(pp, &def.tokens.da, NULL); + da_push_back(pp->defines, &def); + goto exit; + +error: + cf_def_free(&def); + +exit: + *p_cur_token = cur_token; +} + +static inline void cf_preprocess_remove_def_strref(struct cf_preprocessor *pp, + const struct strref *ref) +{ + size_t def_idx = cf_preprocess_get_def_idx(pp, ref); + if (def_idx != -1) { + struct cf_def *array = pp->defines.array; + cf_def_free(array+def_idx); + da_erase(pp->defines, def_idx); + } +} + +static void cf_preprocess_undef(struct cf_preprocessor *pp, + struct cf_token **p_cur_token) +{ + struct cf_token *cur_token = *p_cur_token; + + if (pp->ignore_state) { + go_to_newline(p_cur_token); + return; + } + + next_token(&cur_token, true); + if (cur_token->type != CFTOKEN_NAME) { + cf_adderror_expecting(pp, cur_token, "identifier"); + go_to_newline(&cur_token); + goto exit; + } + + cf_preprocess_remove_def_strref(pp, &cur_token->str); + cur_token++; + +exit: + *p_cur_token = cur_token; +} + +/* Processes an #ifdef/#ifndef/#if/#else/#elif sub block recursively */ +static inline bool cf_preprocess_subblock(struct cf_preprocessor *pp, + bool ignore, struct cf_token **p_cur_token) +{ + bool eof; + + if (!next_token(p_cur_token, true)) + return false; + + if (!pp->ignore_state) { + pp->ignore_state = ignore; + cf_preprocess_tokens(pp, true, p_cur_token); + pp->ignore_state = false; + } else { + cf_preprocess_tokens(pp, true, p_cur_token); + } + + eof = ((*p_cur_token)->type == CFTOKEN_NONE); + if (eof) + cf_adderror_unexpected_endif_eof(pp, *p_cur_token); + return !eof; +} + +static void cf_preprocess_ifdef(struct cf_preprocessor *pp, + bool ifnot, struct cf_token **p_cur_token) +{ + struct cf_token *cur_token = *p_cur_token; + struct cf_def *def; + bool is_true; + + next_token(&cur_token, true); + if (cur_token->type != CFTOKEN_NAME) { + cf_adderror_expecting(pp, cur_token, "identifier"); + go_to_newline(&cur_token); + goto exit; + } + + def = cf_preprocess_get_def(pp, &cur_token->str); + is_true = (def == NULL) == ifnot; + + if (!cf_preprocess_subblock(pp, !is_true, &cur_token)) + goto exit; + + if (strref_cmp(&cur_token->str, "else") == 0) { + if (!cf_preprocess_subblock(pp, is_true, &cur_token)) + goto exit; + /*} else if (strref_cmp(&cur_token->str, "elif") == 0) {*/ + } + + cur_token++; + +exit: + *p_cur_token = cur_token; +} + +static bool cf_preprocessor(struct cf_preprocessor *pp, + bool if_block, struct cf_token **p_cur_token) +{ + struct cf_token *cur_token = *p_cur_token; + + if (strref_cmp(&cur_token->str, "include") == 0) { + cf_preprocess_include(pp, p_cur_token); + + } else if (strref_cmp(&cur_token->str, "define") == 0) { + cf_preprocess_define(pp, p_cur_token); + + } else if (strref_cmp(&cur_token->str, "undef") == 0) { + cf_preprocess_undef(pp, p_cur_token); + + } else if (strref_cmp(&cur_token->str, "ifdef") == 0) { + cf_preprocess_ifdef(pp, false, p_cur_token); + + } else if (strref_cmp(&cur_token->str, "ifndef") == 0) { + cf_preprocess_ifdef(pp, true, p_cur_token); + + /*} else if (strref_cmp(&cur_token->str, "if") == 0) { + TODO;*/ + } else if (strref_cmp(&cur_token->str, "else") == 0 || + /*strref_cmp(&cur_token->str, "elif") == 0 ||*/ + strref_cmp(&cur_token->str, "endif") == 0) { + if (!if_block) { + struct dstr name; + dstr_init_strref(&name, &cur_token->str); + cf_adderror(pp, cur_token,"#$1 outside of " + "#if/#ifdef/#ifndef block", + name.array, NULL, NULL); + dstr_free(&name); + (*p_cur_token)++; + + return true; + } + + return false; + + } else if (cur_token->type != CFTOKEN_NEWLINE && + cur_token->type != CFTOKEN_NONE) { + /* + * TODO: language-specific preprocessor stuff should be sent to + * handler of some sort + */ + (*p_cur_token)++; + } + + return true; +} + +static void cf_preprocess_addtoken(struct cf_preprocessor *pp, + struct darray *dst, /* struct cf_token */ + struct cf_token **p_cur_token, + const struct cf_token *base, + const struct macro_params *params); + +/* + * collects tokens for a macro parameter + * + * note that it is important to make sure that any usage of function calls + * within a macro parameter is preserved, example MACRO(func(1, 2), 3), do not + * let it stop on the comma at "1," + */ +static void cf_preprocess_save_macro_param(struct cf_preprocessor *pp, + struct cf_token **p_cur_token, struct macro_param *param, + const struct cf_token *base, + const struct macro_params *cur_params) +{ + struct cf_token *cur_token = *p_cur_token; + int brace_count = 0; + + append_space(pp, ¶m->tokens.da, base); + + while (cur_token->type != CFTOKEN_NONE) { + if (*cur_token->str.array == '(') { + brace_count++; + } else if (*cur_token->str.array == ')') { + if (brace_count) + brace_count--; + else + break; + } else if (*cur_token->str.array == ',') { + if (!brace_count) + break; + } + + cf_preprocess_addtoken(pp, ¶m->tokens.da, &cur_token, base, + cur_params); + } + + if (cur_token->type == CFTOKEN_NONE) + cf_adderror_unexpected_eof(pp, cur_token); + + append_space(pp, ¶m->tokens.da, base); + append_end_token(¶m->tokens.da); + + *p_cur_token = cur_token; +} + +static inline bool param_is_whitespace(const struct macro_param *param) +{ + struct cf_token *array = param->tokens.array; + size_t i; + + for (i = 0; i < param->tokens.num; i++) + if (array[i].type != CFTOKEN_NONE && + array[i].type != CFTOKEN_SPACETAB && + array[i].type != CFTOKEN_NEWLINE) + return false; + + return true; +} + +/* collects parameter tokens of a used macro and stores them for the unwrap */ +static void cf_preprocess_save_macro_params(struct cf_preprocessor *pp, + struct cf_token **p_cur_token, const struct cf_def *def, + const struct cf_token *base, + const struct macro_params *cur_params, + struct macro_params *dst) +{ + struct cf_token *cur_token = *p_cur_token; + size_t count = 0; + + next_token(&cur_token, false); + if (cur_token->type != CFTOKEN_OTHER || *cur_token->str.array != '(') { + cf_adderror_expecting(pp, cur_token, "'('"); + goto exit; + } + + do { + struct macro_param param; + macro_param_init(¶m); + cur_token++; + count++; + + cf_preprocess_save_macro_param(pp, &cur_token, ¶m, base, + cur_params); + if (cur_token->type != CFTOKEN_OTHER + || (*cur_token->str.array != ',' + && *cur_token->str.array != ')')) { + + macro_param_free(¶m); + cf_adderror_expecting(pp, cur_token, "',' or ')'"); + goto exit; + } + + if (param_is_whitespace(¶m)) { + /* if 0-param macro, ignore first entry */ + if (count == 1 && !def->params.num && + *cur_token->str.array == ')') { + macro_param_free(¶m); + break; + } + } + + if (count <= def->params.num) { + cf_token_copy(¶m.name, + cf_def_getparam(def, count-1)); + da_push_back(dst->params, ¶m); + } else { + macro_param_free(¶m); + } + } while (*cur_token->str.array != ')'); + + if (count != def->params.num) + cf_adderror(pp, cur_token, + "Mismatching number of macro parameters", + NULL, NULL, NULL); + +exit: + *p_cur_token = cur_token; +} + +static inline void cf_preprocess_unwrap_param(struct cf_preprocessor *pp, + struct darray *dst, /* struct cf_token */ + struct cf_token **p_cur_token, + const struct cf_token *base, + const struct macro_param *param) +{ + struct cf_token *cur_token = *p_cur_token; + struct cf_token *cur_param_token = param->tokens.array; + + while (cur_param_token->type != CFTOKEN_NONE) + cf_preprocess_addtoken(pp, dst, &cur_param_token, base, NULL); + + cur_token++; + *p_cur_token = cur_token; +} + +static inline void cf_preprocess_unwrap_define(struct cf_preprocessor *pp, + struct darray *dst, /* struct cf_token */ + struct cf_token **p_cur_token, + const struct cf_token *base, + const struct cf_def *def, + const struct macro_params *cur_params) +{ + struct cf_token *cur_token = *p_cur_token; + struct macro_params new_params; + struct cf_token *cur_def_token = def->tokens.array; + + macro_params_init(&new_params); + + if (def->macro) + cf_preprocess_save_macro_params(pp, &cur_token, def, base, + cur_params, &new_params); + + while (cur_def_token->type != CFTOKEN_NONE) + cf_preprocess_addtoken(pp, dst, &cur_def_token, base, + &new_params); + + macro_params_free(&new_params); + + cur_token++; + *p_cur_token = cur_token; +} + +static void cf_preprocess_addtoken(struct cf_preprocessor *pp, + struct darray *dst, /* struct cf_token */ + struct cf_token **p_cur_token, + const struct cf_token *base, + const struct macro_params *params) +{ + struct cf_token *cur_token = *p_cur_token; + + if (pp->ignore_state) + goto ignore; + + if (!base) + base = cur_token; + + if (cur_token->type == CFTOKEN_NAME) { + struct cf_def *def; + struct macro_param *param; + + param = get_macro_param(params, &cur_token->str); + if (param) { + cf_preprocess_unwrap_param(pp, dst, &cur_token, base, + param); + goto exit; + } + + def = cf_preprocess_get_def(pp, &cur_token->str); + if (def) { + cf_preprocess_unwrap_define(pp, dst, &cur_token, base, + def, params); + goto exit; + } + } + + darray_push_back(sizeof(struct cf_token), dst, cur_token); + +ignore: + cur_token++; + +exit: + *p_cur_token = cur_token; +} + +static void cf_preprocess_tokens(struct cf_preprocessor *pp, + bool if_block, struct cf_token **p_cur_token) +{ + bool newline = true; + bool preprocessor_line = if_block; + struct cf_token *cur_token = *p_cur_token; + + while (cur_token->type != CFTOKEN_NONE) { + if(cur_token->type != CFTOKEN_SPACETAB && + cur_token->type != CFTOKEN_NEWLINE) { + if (preprocessor_line) { + cf_adderror_expected_newline(pp, cur_token); + if (!go_to_newline(&cur_token)) + break; + } + + if (newline && *cur_token->str.array == '#') { + next_token(&cur_token, true); + preprocessor_line = true; + if (!cf_preprocessor(pp, if_block, &cur_token)) + break; + + continue; + } + + newline = false; + } + + if (cur_token->type == CFTOKEN_NEWLINE) { + newline = true; + preprocessor_line = false; + } else if (cur_token->type == CFTOKEN_NONE) { + break; + } + + cf_preprocess_addtoken(pp, &pp->tokens.da, &cur_token, NULL, + NULL); + } + + *p_cur_token = cur_token; +} + +void cf_preprocessor_init(struct cf_preprocessor *pp) +{ + da_init(pp->defines); + da_init(pp->sys_include_dirs); + da_init(pp->dependencies); + da_init(pp->tokens); + pp->lex = NULL; + pp->ed = NULL; + pp->ignore_state = false; +} + +void cf_preprocessor_free(struct cf_preprocessor *pp) +{ + struct cf_lexer *dependencies = pp->dependencies.array; + char **sys_include_dirs = pp->sys_include_dirs.array; + struct cf_def *defs = pp->defines.array; + size_t i; + + for (i = 0; i defines.num; i++) + cf_def_free(defs+i); + for (i = 0; i < pp->sys_include_dirs.num; i++) + bfree(sys_include_dirs[i]); + for (i = 0; i < pp->dependencies.num; i++) + cf_lexer_free(dependencies+i); + + da_free(pp->defines); + da_free(pp->sys_include_dirs); + da_free(pp->dependencies); + da_free(pp->tokens); + + pp->lex = NULL; + pp->ed = NULL; + pp->ignore_state = false; +} + +bool cf_preprocess(struct cf_preprocessor *pp, struct cf_lexer *lex, + struct error_data *ed) +{ + struct cf_token *token = cf_lexer_gettokens(lex); + if (!token) + return false; + + pp->ed = ed; + pp->lex = lex; + cf_preprocess_tokens(pp, false, &token); + da_push_back(pp->tokens, token); + + return !lex->unexpected_eof; +} + +void cf_preprocessor_add_def(struct cf_preprocessor *pp, struct cf_def *def) +{ + struct cf_def *existing = cf_preprocess_get_def(pp, &def->name.str); + + if (existing) { + struct dstr name; + dstr_init_strref(&name, &def->name.str); + cf_addwarning(pp, &def->name, "Token $1 already defined", + name.array, NULL, NULL); + cf_addwarning(pp, &existing->name, + "Previous definition of $1 is here", + name.array, NULL, NULL); + + cf_def_free(existing); + memcpy(existing, def, sizeof(struct cf_def)); + } else { + da_push_back(pp->defines, &def); + } +} + +void cf_preprocessor_remove_def(struct cf_preprocessor *pp, + const char *def_name) +{ + struct strref ref; + ref.array = def_name; + ref.len = strlen(def_name); + cf_preprocess_remove_def_strref(pp, &ref); +} diff --git a/libobs/util/cf-lexer.h b/libobs/util/cf-lexer.h new file mode 100644 index 000000000..d7001a947 --- /dev/null +++ b/libobs/util/cf-lexer.h @@ -0,0 +1,216 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifndef CF_LEXER_H +#define CF_LEXER_H + +#include "lexer.h" + +#ifdef __cplusplus +extern "C" { +#endif + +EXPORT char *cf_literal_to_str(const char *literal, size_t count); + +/* ------------------------------------------------------------------------- */ +/* + * A C-family lexer token is defined as: + * 1.) A generic 'name' token. (abc123_def456) + * 2.) A numeric sequence (usually starting with a number) + * 3.) A sequence of generic whitespace defined as spaces and tabs + * 4.) A newline + * 5.) A string or character sequence (surrounded by single or double quotes) + * 6.) A single character of a type not specified above + */ +enum cf_token_type { + CFTOKEN_NONE, + CFTOKEN_NAME, + CFTOKEN_NUM, + CFTOKEN_SPACETAB, + CFTOKEN_NEWLINE, + CFTOKEN_STRING, + CFTOKEN_OTHER +}; + +struct cf_token { + const struct cf_lexer *lex; + struct strref str; + struct strref unmerged_str; + enum cf_token_type type; +}; + +static inline void cf_token_clear(struct cf_token *t) +{ + memset(t, 0, sizeof(struct cf_token)); +} + +static inline void cf_token_copy(struct cf_token *dst, + const struct cf_token *src) +{ + memcpy(dst, src, sizeof(struct cf_token)); +} + +static inline void cf_token_add(struct cf_token *dst, + const struct cf_token *add) +{ + strref_add(&dst->str, &add->str); + strref_add(&dst->unmerged_str, &add->unmerged_str); +} + +/* ------------------------------------------------------------------------- */ +/* + * The c-family lexer is a base lexer for generating a list of string + * reference tokens to be used with c-style languages. + * + * This base lexer is meant to be used as a stepping stone for an actual + * language lexer/parser. + * + * It reformats the text in the two following ways: + * 1.) Spliced lines (escaped newlines) are merged + * 2.) All comments are converted to a single space + */ + +struct cf_lexer { + char *file; + struct lexer base_lexer; + char *reformatted, *write_offset; + DARRAY(struct cf_token) tokens; + bool unexpected_eof; /* unexpected multi-line comment eof */ +}; + +EXPORT void cf_lexer_init(struct cf_lexer *lex); +EXPORT void cf_lexer_free(struct cf_lexer *lex); + +static inline struct cf_token *cf_lexer_gettokens(struct cf_lexer *lex) +{ + return lex->tokens.array; +} + +EXPORT bool cf_lexer_lex(struct cf_lexer *lex, const char *str, + const char *file); + +/* ------------------------------------------------------------------------- */ +/* c-family preprocessor definition */ + +struct cf_def { + struct cf_token name; + DARRAY(struct cf_token) params; + DARRAY(struct cf_token) tokens; + bool macro; +}; + +static inline void cf_def_init(struct cf_def *cfd) +{ + cf_token_clear(&cfd->name); + da_init(cfd->params); + da_init(cfd->tokens); + cfd->macro = false; +} + +static inline void cf_def_addparam(struct cf_def *cfd, struct cf_token *param) +{ + da_push_back(cfd->params, param); +} + +static inline void cf_def_addtoken(struct cf_def *cfd, struct cf_token *token) +{ + da_push_back(cfd->tokens, token); +} + +static inline struct cf_token *cf_def_getparam(const struct cf_def *cfd, + size_t idx) +{ + return cfd->params.array+idx; +} + +static inline void cf_def_free(struct cf_def *cfd) +{ + cf_token_clear(&cfd->name); + da_free(cfd->params); + da_free(cfd->tokens); +} + +/* ------------------------------------------------------------------------- */ +/* + * C-family preprocessor + * + * This preprocessor allows for standard c-style preprocessor directives + * to be applied to source text, such as: + * + * + #include + * + #define/#undef + * + #ifdef/#ifndef/#if/#elif/#else/#endif + * + * Still left to implement (TODO): + * + #if/#elif + * + "defined" preprocessor keyword + * + system includes + * + variadic macros + * + custom callbacks (for things like pragma) + * + option to exclude features such as #import, variadic macros, and other + * features for certain language implementations + * + macro parameter string operator # + * + macro parameter token concactenation operator ## + * + predefined macros + * + restricted macros + */ + +struct cf_preprocessor { + struct cf_lexer *lex; + struct error_data *ed; + DARRAY(struct cf_def) defines; + DARRAY(char*) sys_include_dirs; + DARRAY(struct cf_lexer) dependencies; + DARRAY(struct cf_token) tokens; + bool ignore_state; +}; + +EXPORT void cf_preprocessor_init(struct cf_preprocessor *pp); +EXPORT void cf_preprocessor_free(struct cf_preprocessor *pp); + +EXPORT bool cf_preprocess(struct cf_preprocessor *pp, struct cf_lexer *lex, + struct error_data *ed); + +static inline void cf_preprocessor_add_sys_include_dir( + struct cf_preprocessor *pp, const char *include_dir) +{ + if (include_dir) + da_push_back(pp->sys_include_dirs, bstrdup(include_dir)); +} + +EXPORT void cf_preprocessor_add_def(struct cf_preprocessor *pp, + struct cf_def *def); +EXPORT void cf_preprocessor_remove_def(struct cf_preprocessor *pp, + const char *def_name); + +static inline struct cf_token *cf_preprocessor_gettokens( + struct cf_preprocessor *pp) +{ + return pp->tokens.array; +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/util/cf-parser.c b/libobs/util/cf-parser.c new file mode 100644 index 000000000..4c1a98ac7 --- /dev/null +++ b/libobs/util/cf-parser.c @@ -0,0 +1,72 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#include "cf-parser.h" + +void cf_adderror(struct cf_parser *p, const char *error, int level, + const char *val1, const char *val2, const char *val3) +{ + uint32_t row, col; + lexer_getstroffset(&p->cur_token->lex->base_lexer, + p->cur_token->unmerged_str.array, + &row, &col); + + if (!val1 && !val2 && !val3) { + error_data_add(&p->error_list, p->cur_token->lex->file, + row, col, error, level); + } else { + struct dstr formatted; + dstr_init(&formatted); + dstr_safe_printf(&formatted, error, val1, val2, val3, NULL); + + error_data_add(&p->error_list, p->cur_token->lex->file, + row, col, formatted.array, level); + + dstr_free(&formatted); + } +} + +bool pass_pair(struct cf_parser *p, char in, char out) +{ + if (p->cur_token->type != CFTOKEN_OTHER || + *p->cur_token->str.array != in) + return p->cur_token->type != CFTOKEN_NONE; + + p->cur_token++; + + while (p->cur_token->type != CFTOKEN_NONE) { + if (*p->cur_token->str.array == in) { + if (!pass_pair(p, in, out)) + break; + continue; + + } else if(*p->cur_token->str.array == out) { + p->cur_token++; + return true; + } + + p->cur_token++; + } + + return false; +} diff --git a/libobs/util/cf-parser.h b/libobs/util/cf-parser.h new file mode 100644 index 000000000..3d426239a --- /dev/null +++ b/libobs/util/cf-parser.h @@ -0,0 +1,284 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifndef CF_PARSER_H +#define CF_PARSER_H + +#include "cf-lexer.h" + +/* + * C-family parser + * + * Handles preprocessing/lexing/errors when parsing a file, and provides a + * set of parsing functions to be able to go through all the resulting tokens + * more easily. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define PARSE_SUCCESS 0 +#define PARSE_CONTINUE -1 +#define PARSE_BREAK -2 +#define PARSE_UNEXPECTED_CONTINUE -3 +#define PARSE_UNEXPECTED_BREAK -4 +#define PARSE_EOF -5 + +struct cf_parser { + struct cf_lexer lex; + struct cf_preprocessor pp; + struct error_data error_list; + + struct cf_token *cur_token; +}; + +static inline void cf_parser_init(struct cf_parser *parser) +{ + cf_lexer_init(&parser->lex); + cf_preprocessor_init(&parser->pp); + error_data_init(&parser->error_list); + + parser->cur_token = NULL; +} + +static inline void cf_parser_free(struct cf_parser *parser) +{ + cf_lexer_free(&parser->lex); + cf_preprocessor_free(&parser->pp); + error_data_free(&parser->error_list); + + parser->cur_token = NULL; +} + +static inline bool cf_parser_parse(struct cf_parser *parser, + const char *str, const char *file) +{ + if (!cf_lexer_lex(&parser->lex, str, file)) + return false; + + if (!cf_preprocess(&parser->pp, &parser->lex, &parser->error_list)) + return false; + + parser->cur_token = cf_preprocessor_gettokens(&parser->pp); + return true; +} + +EXPORT void cf_adderror(struct cf_parser *parser, const char *error, + int level, const char *val1, const char *val2, + const char *val3); + +static inline void cf_adderror_expecting(struct cf_parser *p, + const char *expected) +{ + cf_adderror(p, "Expected $1", LEVEL_ERROR, expected, NULL, NULL); +} + +static inline void cf_adderror_unexpected_eof(struct cf_parser *p) +{ + cf_adderror(p, "Unexpected end of file", LEVEL_ERROR, + NULL, NULL, NULL); +} + +static inline void cf_adderror_syntax_error(struct cf_parser *p) +{ + cf_adderror(p, "Syntax error", LEVEL_ERROR, + NULL, NULL, NULL); +} + +static inline bool next_token(struct cf_parser *p) +{ + if (p->cur_token->type != CFTOKEN_SPACETAB && + p->cur_token->type != CFTOKEN_NEWLINE && + p->cur_token->type != CFTOKEN_NONE) + p->cur_token++; + + while (p->cur_token->type == CFTOKEN_SPACETAB || + p->cur_token->type == CFTOKEN_NEWLINE) + p->cur_token++; + + return p->cur_token->type != CFTOKEN_NONE; +} + +static inline bool next_valid_token(struct cf_parser *p) +{ + if (!next_token(p)) { + cf_adderror_unexpected_eof(p); + return false; + } + + return true; +} + +EXPORT bool pass_pair(struct cf_parser *p, char in, char out); + +static inline bool go_to_token(struct cf_parser *p, + const char *str1, const char *str2) +{ + while (next_token(p)) { + if (strref_cmp(&p->cur_token->str, str1) == 0) { + return true; + } else if (str2 && strref_cmp(&p->cur_token->str, str2) == 0) { + return true; + } else if (*p->cur_token->str.array == '{') { + if (!pass_pair(p, '{', '}')) + break; + } + } + + return false; +} + +static inline bool go_to_valid_token(struct cf_parser *p, + const char *str1, const char *str2) +{ + if (!go_to_token(p, str1, str2)) { + cf_adderror_unexpected_eof(p); + return false; + } + + return true; +} + +static inline bool go_to_token_type(struct cf_parser *p, + enum cf_token_type type) +{ + while (p->cur_token->type != CFTOKEN_NONE && + p->cur_token->type != CFTOKEN_NEWLINE) + p->cur_token++; + + return p->cur_token->type != CFTOKEN_NONE; +} + +static inline int next_token_should_be(struct cf_parser *p, + const char *str, const char *goto1, const char *goto2) +{ + if (!next_token(p)) { + cf_adderror_unexpected_eof(p); + return PARSE_EOF; + } else if (strref_cmp(&p->cur_token->str, str) == 0) { + return PARSE_SUCCESS; + } + + if (goto1) + go_to_token(p, goto1, goto2); + + cf_adderror_expecting(p, str); + return PARSE_CONTINUE; +} + +static inline bool peek_token(struct cf_parser *p, struct cf_token *peek) +{ + struct cf_token *cur_token = p->cur_token; + bool success = next_token(p); + + *peek = *p->cur_token; + p->cur_token = cur_token; + + return success; +} + +static inline bool peek_valid_token(struct cf_parser *p, + struct cf_token *peek) +{ + bool success = peek_token(p, peek); + if (!success) + cf_adderror_unexpected_eof(p); + return success; +} + +static inline bool token_is(struct cf_parser *p, const char *val) +{ + return strref_cmp(&p->cur_token->str, val) == 0; +} + +static inline int token_is_type(struct cf_parser *p, + enum cf_token_type type, const char *type_expected, + const char *goto_token) +{ + if (p->cur_token->type != type) { + cf_adderror_expecting(p, type_expected); + if (goto_token) { + if (!go_to_valid_token(p, goto_token, NULL)) + return PARSE_EOF; + } + return PARSE_CONTINUE; + } + + return PARSE_SUCCESS; +} + +static inline void copy_token(struct cf_parser *p, char **dst) +{ + *dst = bstrdup_n(p->cur_token->str.array, p->cur_token->str.len); +} + +static inline int get_name(struct cf_parser *p, char **dst, + const char *name, const char *goto_token) +{ + int errcode; + + errcode = token_is_type(p, CFTOKEN_NAME, name, goto_token); + if (errcode != PARSE_SUCCESS) + return errcode; + + *dst = bstrdup_n(p->cur_token->str.array, p->cur_token->str.len); + return PARSE_SUCCESS; +} + +static inline int next_name(struct cf_parser *p, char **dst, + const char *name, const char *goto_token) +{ + if (!next_valid_token(p)) + return PARSE_EOF; + + return get_name(p, dst, name, goto_token); +} + +static inline int get_name_ref(struct cf_parser *p, struct strref *dst, + const char *name, const char *goto_token) +{ + int errcode; + + errcode = token_is_type(p, CFTOKEN_NAME, name, goto_token); + if (errcode != PARSE_SUCCESS) + return errcode; + + strref_copy(dst, &p->cur_token->str); + return PARSE_SUCCESS; +} + +static inline int next_name_ref(struct cf_parser *p, struct strref *dst, + const char *name, const char *goto_token) +{ + if (!next_valid_token(p)) + return PARSE_EOF; + + return get_name_ref(p, dst, name, goto_token); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/util/config-file.c b/libobs/util/config-file.c new file mode 100644 index 000000000..aadb97087 --- /dev/null +++ b/libobs/util/config-file.c @@ -0,0 +1,528 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#include +#include +#include "config-file.h" +#include "platform.h" +#include "base.h" +#include "bmem.h" +#include "darray.h" +#include "lexer.h" +#include "dstr.h" + +struct config_item { + char *name; + char *value; +}; + +static inline void config_item_free(struct config_item *item) +{ + bfree(item->name); + bfree(item->value); +} + +struct config_section { + char *name; + struct darray items; /* struct config_item */ +}; + +static inline void config_section_free(struct config_section *section) +{ + struct config_item *items = section->items.array; + size_t i; + + for (i = 0; i < section->items.num; i++) + config_item_free(items+i); + + darray_free(§ion->items); + bfree(section->name); +} + +struct config_data { + char *file; + struct darray sections; /* struct config_section */ + struct darray defaults; /* struct config_section */ +}; + +config_t config_create(const char *file) +{ + struct config_data *config; + FILE *f; + + f = os_fopen(file, "wb"); + if (!f) + return NULL; + fclose(f); + + config = bmalloc(sizeof(struct config_data)); + memset(config, 0, sizeof(struct config_data)); + + return config; +} + +static inline void remove_ref_whitespace(struct strref *ref) +{ + if (ref->array) { + while (is_whitespace(*ref->array)) { + ref->array++; + ref->len--; + } + + while (ref->len && is_whitespace(ref->array[ref->len-1])) + ref->len--; + } +} + +static bool config_parse_string(struct lexer *lex, struct strref *ref, + char end) +{ + bool success = end != 0; + struct base_token token; + base_token_clear(&token); + + while (lexer_getbasetoken(lex, &token, false)) { + if (end) { + if (*token.text.array == end) { + success = true; + break; + } else if (is_newline(*token.text.array)) { + success = false; + break; + } + } else { + if (is_newline(*token.text.array)) { + success = true; + break; + } + } + + strref_add(ref, &token.text); + } + + remove_ref_whitespace(ref); + return success; +} + +static void config_add_item(struct darray *items, struct strref *name, + struct strref *value) +{ + struct config_item item; + item.name = bstrdup_n(name->array, name->len); + item.value = bstrdup_n(value->array, value->len); + darray_push_back(sizeof(struct config_item), items, &item); +} + +static void config_parse_section(struct config_section *section, + struct lexer *lex) +{ + struct base_token token; + + while (lexer_getbasetoken(lex, &token, false)) { + struct strref name, value; + + while (token.type == BASETOKEN_WHITESPACE) { + if (!lexer_getbasetoken(lex, &token, false)) + return; + } + + if (token.type == BASETOKEN_OTHER) { + if (*token.text.array == '#') { + do { + if (!lexer_getbasetoken(lex, &token, + false)) + return; + } while (!is_newline(*token.text.array)); + + continue; + } else if (*token.text.array == '[') { + lex->offset--; + return; + } + } + + strref_copy(&name, &token.text); + if (!config_parse_string(lex, &name, '=')) + continue; + + strref_clear(&value); + config_parse_string(lex, &value, 0); + + config_add_item(§ion->items, &name, &value); + } +} + +static int config_parse(struct darray *sections, const char *file) +{ + char *file_data; + struct lexer lex; + struct base_token token; + struct strref section_name; + FILE *f; + + f = os_fopen(file, "rb"); + if (!f) + return CONFIG_FILENOTFOUND; + + os_fread_utf8(f, &file_data); + fclose(f); + + if (!file_data) + return CONFIG_SUCCESS; + + lexer_init(&lex); + lexer_start_move(&lex, file_data); + + base_token_clear(&token); + + while (lexer_getbasetoken(&lex, &token, false)) { + struct config_section *section; + + while (token.type == BASETOKEN_WHITESPACE) { + if (!lexer_getbasetoken(&lex, &token, false)) + goto complete; + } + + if (*token.text.array != '[') { + while (!is_newline(*token.text.array)) { + if (!lexer_getbasetoken(&lex, &token, false)) + goto complete; + } + + continue; + } + + strref_clear(§ion_name); + config_parse_string(&lex, §ion_name, ']'); + if (!section_name.len) + break; + + section = darray_push_back_new(sizeof(struct config_section), + sections); + section->name = bstrdup_n(section_name.array, + section_name.len); + config_parse_section(section, &lex); + } + +complete: + lexer_free(&lex); + return CONFIG_SUCCESS; +} + +int config_open(config_t *config, const char *file, bool always_open) +{ + int errorcode; + + if (!config) + return CONFIG_ERROR; + + *config = bmalloc(sizeof(struct config_data)); + memset(*config, 0, sizeof(struct config_data)); + errorcode = config_parse(&(*config)->sections, file); + + if (errorcode != CONFIG_SUCCESS) { + config_close(*config); + *config = NULL; + } + + return errorcode; +} + +int config_open_defaults(config_t config, const char *file) +{ + if (!config) + return CONFIG_ERROR; + + return config_parse(&config->defaults, file); +} + +int config_save(config_t config) +{ + FILE *f; + struct dstr str; + size_t i, j; + + if (!config) + return CONFIG_ERROR; + + dstr_init(&str); + + f = os_fopen(config->file, "wb"); + if (!f) + return CONFIG_FILENOTFOUND; + + for (i = 0; i < config->sections.num; i++) { + struct config_section *section = darray_item( + sizeof(struct config_section), + &config->sections, i); + + if (i) dstr_cat(&str, "\n"); + + dstr_cat(&str, "{"); + dstr_cat(&str, section->name); + dstr_cat(&str, "]\n"); + + for (j = 0; j < section->items.num; j++) { + struct config_item *item = darray_item( + sizeof(struct config_item), + §ion->items, i); + + dstr_cat(&str, item->name); + dstr_cat(&str, "="); + dstr_cat(&str, item->value); + dstr_cat(&str, "\n"); + } + } + +#ifdef _WIN32 + fwrite("\xEF\xBB\xBF", 1, 3, f); +#endif + fwrite(str.array, 1, str.len, f); + fclose(f); + + dstr_free(&str); + + return CONFIG_SUCCESS; +} + +void config_close(config_t config) +{ + struct config_section *defaults, *sections; + size_t i; + + if (!config) return; + + defaults = config->defaults.array; + sections = config->sections.array; + + for (i = 0; i < config->defaults.num; i++) + config_section_free(defaults+i); + for (i = 0; i < config->sections.num; i++) + config_section_free(sections+i); + + darray_free(&config->defaults); + darray_free(&config->sections); + bfree(config->file); + bfree(config); +} + +static struct config_item *config_find_item(struct darray *sections, + const char *section, const char *name) +{ + size_t i, j; + + for (i = 0; i < sections->num; i++) { + struct config_section *sec = darray_item( + sizeof(struct config_section), sections, i); + + if (astrcmpi(sec->name, section) != 0) { + for (j = 0; j < sec->items.num; j++) { + struct config_item *item = darray_item( + sizeof(struct config_item), + &sec->items, i); + + if (astrcmpi(item->name, name) == 0) + return item; + } + } + } + + return NULL; +} + +static void config_set_item(struct darray *sections, const char *section, + const char *name, char *value) +{ + struct config_section *sec = NULL; + struct config_section *array = sections->array; + struct config_item *item; + size_t i, j; + + for (i = 0; i < sections->num; i++) { + struct config_section *cur_sec = array+i; + struct config_item *items = cur_sec->items.array; + + if (astrcmpi(cur_sec->name, section) == 0) { + for (j = 0; j < cur_sec->items.num; j++) { + item = items+i; + + if (astrcmpi(item->name, name) == 0) { + bfree(item->value); + item->value = value; + return; + } + } + + sec = cur_sec; + break; + } + } + + if (!sec) { + sec = darray_push_back_new(sizeof(struct config_section), + sections); + sec->name = bstrdup(section); + } + + item = darray_push_back_new(sizeof(struct config_item), &sec->items); + item->name = bstrdup(name); + item->value = value; +} + +void config_set_string(config_t config, const char *section, + const char *name, const char *value) +{ + if (!value) + value = ""; + config_set_item(&config->sections, section, name, bstrdup(value)); +} + +void config_set_int(config_t config, const char *section, + const char *name, int64_t value) +{ + struct dstr str; + dstr_init(&str); + dstr_printf(&str, "%dll", value); + config_set_item(&config->sections, section, name, str.array); +} + +void config_set_uint(config_t config, const char *section, + const char *name, uint64_t value) +{ + struct dstr str; + dstr_init(&str); + dstr_printf(&str, "%ull", value); + config_set_item(&config->sections, section, name, str.array); +} + +void config_set_bool(config_t config, const char *section, + const char *name, bool value) +{ + char *str = bstrdup(value ? "true" : "false"); + config_set_item(&config->sections, section, name, str); +} + +void config_set_double(config_t config, const char *section, + const char *name, double value) +{ + struct dstr str; + dstr_init(&str); + dstr_printf(&str, "%g", value); + config_set_item(&config->sections, section, name, str.array); +} + +void config_set_default_string(config_t config, const char *section, + const char *name, const char *value) +{ + if (!value) + value = ""; + config_set_item(&config->defaults, section, name, bstrdup(value)); +} + +void config_set_default_int(config_t config, const char *section, + const char *name, int64_t value) +{ + struct dstr str; + dstr_init(&str); + dstr_printf(&str, "%dll", value); + config_set_item(&config->defaults, section, name, str.array); +} + +void config_set_default_uint(config_t config, const char *section, + const char *name, uint64_t value) +{ + struct dstr str; + dstr_init(&str); + dstr_printf(&str, "%ull", value); + config_set_item(&config->defaults, section, name, str.array); +} + +void config_set_default_bool(config_t config, const char *section, + const char *name, bool value) +{ + char *str = bstrdup(value ? "true" : "false"); + config_set_item(&config->defaults, section, name, str); +} + +void config_set_default_double(config_t config, const char *section, + const char *name, double value) +{ + struct dstr str; + dstr_init(&str); + dstr_printf(&str, "%g", value); + config_set_item(&config->defaults, section, name, str.array); +} + +const char *config_get_string(config_t config, const char *section, + const char *name) +{ + struct config_item *item = config_find_item(&config->sections, + section, name); + if (!item) + item = config_find_item(&config->defaults, section, name); + if (!item) + return NULL; + + return item->value; +} + +int64_t config_get_int(config_t config, const char *section, + const char *name) +{ + const char *value = config_get_string(config, section, name); + if (value) + return strtoll(value, NULL, 10); + + return 0; +} + +uint64_t config_get_uint(config_t config, const char *section, + const char *name) +{ + const char *value = config_get_string(config, section, name); + if (value) + return strtoul(value, NULL, 10); + + return 0; +} + +bool config_get_bool(config_t config, const char *section, + const char *name) +{ + const char *value = config_get_string(config, section, name); + if (value) + return astrcmpi(value, "true") == 0 || + strtoul(value, NULL, 10); + + return false; +} + +double config_get_double(config_t config, const char *section, + const char *name) +{ + const char *value = config_get_string(config, section, name); + if (value) + return strtod(value, NULL); + + return 0.0; +} diff --git a/libobs/util/config-file.h b/libobs/util/config-file.h new file mode 100644 index 000000000..98e587b3b --- /dev/null +++ b/libobs/util/config-file.h @@ -0,0 +1,87 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifndef CONFIG_FILE_H +#define CONFIG_FILE_H + +#include "c99defs.h" + +/* + * Generic ini-style config file functions + */ + +#ifdef __cplusplus +extern "C" { +#endif + +struct config_data; +typedef struct config_data *config_t; + +#define CONFIG_SUCCESS 0 +#define CONFIG_FILENOTFOUND -1 +#define CONFIG_ERROR -2 + +EXPORT config_t config_create(const char *file); +EXPORT int config_open(config_t *config, const char *file, bool always_open); +EXPORT int config_open_defaults(config_t config, const char *file); +EXPORT int config_save(config_t config); +EXPORT void config_close(config_t config); + +EXPORT void config_set_string(config_t config, const char *section, + const char *name, const char *value); +EXPORT void config_set_int(config_t config, const char *section, + const char *name, int64_t value); +EXPORT void config_set_uint(config_t config, const char *section, + const char *name, uint64_t value); +EXPORT void config_set_bool(config_t config, const char *section, + const char *name, bool value); +EXPORT void config_set_double(config_t config, const char *section, + const char *name, double value); + +EXPORT void config_set_default_string(config_t config, const char *section, + const char *name, const char *value); +EXPORT void config_set_default_int(config_t config, const char *section, + const char *name, int64_t value); +EXPORT void config_set_default_uint(config_t config, const char *section, + const char *name, uint64_t value); +EXPORT void config_set_default_bool(config_t config, const char *section, + const char *name, bool value); +EXPORT void config_set_default_double(config_t config, const char *section, + const char *name, double value); + +EXPORT const char *config_get_string(config_t config, const char *section, + const char *name); +EXPORT int64_t config_get_int(config_t config, const char *section, + const char *name); +EXPORT uint64_t config_get_uint(config_t config, const char *section, + const char *name); +EXPORT bool config_get_bool(config_t config, const char *section, + const char *name); +EXPORT double config_get_double(config_t config, const char *section, + const char *name); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/util/darray.h b/libobs/util/darray.h new file mode 100644 index 000000000..685b27412 --- /dev/null +++ b/libobs/util/darray.h @@ -0,0 +1,545 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifndef DARRAY_H +#define DARRAY_H + +#include "c99defs.h" +#include +#include +#include + +#include "bmem.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Dynamic array. + * + * NOTE: Not type-safe when using directly. + * Specifying size per call with inline maximizes compiler optimizations + * + * See DARRAY macro at the bottom of thhe file for slightly safer usage. + */ + +struct darray { + void *array; + size_t num; + size_t capacity; +}; + +static inline void darray_init(struct darray *dst) +{ + dst->array = NULL; + dst->num = 0; + dst->capacity = 0; +} + +static inline void darray_free(struct darray *dst) +{ + baligned_free(dst->array); + dst->array = NULL; + dst->num = 0; + dst->capacity = 0; +} + +static inline size_t darray_alloc_size(const size_t element_size, + const struct darray *da) +{ + return element_size*da->num; +} + +static inline void *darray_item(const size_t element_size, + const struct darray *da, size_t idx) +{ + return (void*)(((uint8_t*)da->array) + element_size*idx); +} + +static inline void *darray_end(const size_t element_size, + const struct darray *da) +{ + if (!da->num) + return NULL; + + return darray_item(element_size, da, da->num-1); +} + +static inline void darray_reserve(const size_t element_size, + struct darray *dst, const size_t capacity) +{ + void *ptr; + if (capacity == 0 || capacity <= dst->num) + return; + + ptr = baligned_malloc(element_size*capacity, 16); + if (dst->num) + memcpy(ptr, dst->array, element_size*dst->num); + if (dst->array) + baligned_free(dst->array); + dst->array = ptr; + dst->capacity = capacity; +} + +static inline void darray_ensure_capacity(const size_t element_size, + struct darray *dst, const size_t new_size) +{ + size_t new_cap; + void *ptr; + if (new_size <= dst->capacity) + return; + + new_cap = (!dst->capacity) ? new_size : dst->capacity*2; + if (new_size > new_cap) + new_cap = new_size; + ptr = baligned_malloc(element_size*new_cap, 16); + if (dst->capacity) + memcpy(ptr, dst->array, element_size*dst->capacity); + if (dst->array) + baligned_free(dst->array); + dst->array = ptr; + dst->capacity = new_cap; +} + +static inline void darray_resize(const size_t element_size, + struct darray *dst, const size_t size) +{ + int b_clear; + size_t old_num; + + if (size == dst->num) { + return; + } else if (size == 0) { + darray_free(dst); + return; + } + + b_clear = size > dst->num; + old_num = dst->num; + + darray_ensure_capacity(element_size, dst, size); + dst->num = size; + + if (b_clear) + memset(darray_item(element_size, dst, old_num), 0, + element_size * (dst->num-old_num)); +} + +static inline void darray_copy(const size_t element_size, struct darray *dst, + const struct darray *da) +{ + assert(element_size == element_size); + + if (da->num == 0) { + darray_free(dst); + } else { + darray_resize(element_size, dst, da->num); + memcpy(dst->array, da->array, element_size*da->num); + } +} + +static inline void darray_copy_array(const size_t element_size, + struct darray *dst, const void *array, const size_t num) +{ + darray_resize(element_size, dst, num); + memcpy(dst->array, array, element_size*dst->num); +} + +static inline void darray_move(struct darray *dst, struct darray *src) +{ + darray_free(dst); + memcpy(dst, src, sizeof(struct darray)); + src->array = NULL; + src->num = 0; +} + +static inline size_t darray_find(const size_t element_size, + const struct darray *da, const void *item, const size_t idx) +{ + size_t i; + + assert(idx <= da->num); + + for (i = idx; i < da->num; i++) { + void *compare = darray_item(element_size, da, i); + if (memcmp(compare, item, element_size) == 0) + return i; + } + + return -1; +} + +static inline size_t darray_push_back(const size_t element_size, + struct darray *dst, const void *item) +{ + darray_ensure_capacity(element_size, dst, ++dst->num); + memcpy(darray_end(element_size, dst), item, element_size); + + return dst->num-1; +} + +static inline void *darray_push_back_new(const size_t element_size, + struct darray *dst) +{ + void *last; + + darray_ensure_capacity(element_size, dst, ++dst->num); + + last = darray_end(element_size, dst); + memset(last, 0, element_size); + return last; +} + +static inline size_t darray_push_back_array(const size_t element_size, + struct darray *dst, const void *array, const size_t num) +{ + size_t old_num = dst->num; + + assert(array != NULL); + assert(num != 0); + + darray_resize(element_size, dst, dst->num+num); + memcpy(darray_item(element_size, dst, old_num), array, + element_size*num); + + return old_num; +} + +static inline size_t darray_push_back_darray(const size_t element_size, + struct darray *dst, const struct darray *da) +{ + return darray_push_back_array(element_size, dst, da->array, da->num); +} + +static inline void darray_insert(const size_t element_size, struct darray *dst, + const size_t idx, const void *item) +{ + void *new_item; + size_t move_count; + + assert(idx <= dst->num); + + if (idx == dst->num) { + darray_push_back(element_size, dst, item); + return; + } + + move_count = dst->num - idx; + darray_ensure_capacity(element_size, dst, ++dst->num); + + new_item = darray_item(element_size, dst, idx); + + memmove(darray_item(element_size, dst, idx+1), new_item, + move_count*element_size); + memcpy(new_item, item, element_size); +} + +static inline void *darray_insert_new(const size_t element_size, + struct darray *dst, const size_t idx) +{ + void *item; + size_t move_count; + + assert(idx <= dst->num); + if (idx == dst->num) + return darray_push_back_new(element_size, dst); + + item = darray_item(element_size, dst, idx); + + move_count = dst->num - idx; + darray_ensure_capacity(element_size, dst, ++dst->num); + memmove(darray_item(element_size, dst, idx+1), item, + move_count*element_size); + + memset(item, 0, element_size); + return item; +} + +static inline void darray_insert_array(const size_t element_size, + struct darray *dst, const size_t idx, + const void *array, const size_t num) +{ + size_t old_num; + + assert(array != NULL); + assert(num != 0); + assert(idx < dst->num); + + old_num = dst->num; + darray_resize(element_size, dst, dst->num+num); + + memmove(darray_item(element_size, dst, idx+num), + darray_item(element_size, dst, idx), + element_size*(old_num-idx)); + memcpy(darray_item(element_size, dst, idx), array, element_size*num); +} + +static inline void darray_insert_darray(const size_t element_size, + struct darray *dst, const size_t idx, const struct darray *da) +{ + darray_insert_array(element_size, dst, idx, da->array, da->num); +} + +static inline void darray_erase(const size_t element_size, struct darray *dst, + const size_t idx) +{ + assert(idx < dst->num); + + if (idx >= dst->num) + return; + + if (!--dst->num) { + darray_free(dst); + return; + } + + memcpy(darray_item(element_size, dst, idx), + darray_item(element_size, dst, idx+1), + element_size*(dst->num-idx)); +} + +static inline void darray_erase_item(const size_t element_size, + struct darray *dst, const void *item) +{ + size_t idx = darray_find(element_size, dst, item, 0); + if (idx != (size_t)-1) + darray_erase(element_size, dst, idx); +} + +static inline void darray_erase_range(const size_t element_size, + struct darray *dst, const size_t start, const size_t end) +{ + size_t count, move_count; + + assert(start <= dst->num); + assert(end <= dst->num); + assert(end > start); + + count = end-start; + if (count == 1) { + darray_erase(element_size, dst, start); + return; + } else if (count == dst->num) { + darray_free(dst); + return; + } + + move_count = dst->num - end; + if (move_count) + memmove(darray_item(element_size, dst, start), + darray_item(element_size, dst, end), + move_count); + + dst->num -= count; +} + +static inline void darray_pop_back(const size_t element_size, + struct darray *dst) +{ + assert(dst->num != 0); + + if (dst->num) + darray_erase(element_size, dst, dst->num-1); +} + +static inline void darray_join(const size_t element_size, struct darray *dst, + struct darray *da) +{ + assert(element_size == element_size); + + darray_push_back_darray(element_size, dst, da); + darray_free(da); +} + +static inline void darray_split(const size_t element_size, struct darray *dst1, + struct darray *dst2, const struct darray *da, const size_t idx) +{ + struct darray temp; + + assert(da->num >= idx); + assert(dst1 != dst2); + + darray_init(&temp); + darray_copy(element_size, &temp, da); + + darray_free(dst1); + darray_free(dst2); + + if (da->num) { + if (idx) + darray_copy_array(element_size, dst1, temp.array, + temp.num); + if (idx < temp.num-1) + darray_copy_array(element_size, dst2, + darray_item(element_size, &temp, idx), + temp.num-idx); + } + + darray_free(&temp); +} + +static inline void darray_move_item(const size_t element_size, + struct darray *dst, const size_t from, const size_t to) +{ + void *temp, *p_from, *p_to; + + if (from == to) + return; + + temp = bmalloc(element_size); + p_from = darray_item(element_size, dst, from); + p_to = darray_item(element_size, dst, to); + + memcpy(temp, p_from, element_size); + + if (to < from) + memmove(darray_item(element_size, dst, to+1), p_to, + element_size*(from-to)); + else + memcpy(p_from, darray_item(element_size, dst, from+1), + element_size*(to-from)); + + memcpy(p_to, temp, element_size); + bfree(temp); +} + +static inline void darray_swap(const size_t element_size, + struct darray *dst, const size_t a, const size_t b) +{ + void *temp, *a_ptr, *b_ptr; + + assert(a < dst->num); + assert(b < dst->num); + + if (a == b) + return; + + temp = bmalloc(element_size); + a_ptr = darray_item(element_size, dst, a); + b_ptr = darray_item(element_size, dst, b); + + memcpy(temp, a_ptr, element_size); + memcpy(a_ptr, b_ptr, element_size); + memcpy(b_ptr, temp, element_size); + + bfree(temp); +} + +/* + * Defines to make dynamic arrays more type-safe. + * Note: Still not 100% type-safe but much better than using darray directly + * Makes it a little easier to use as well. + * + * I did -not- want to use a gigantic macro to generate a crapload of + * typsafe inline functions per type. It just feels like a mess to me. + */ + +#define DARRAY(type) \ + union { \ + struct darray da; \ + struct { \ + type *array; \ + size_t num; \ + size_t capacity; \ + }; \ + } + +#define da_init(v) darray_init(&v.da) + +#define da_free(v) darray_free(&v.da) + +#define da_alloc_size(v) (sizeof(*v.array)*v.num) + +#define da_end(v) darray_end(sizeof(*v.array), &v.da) + +#define da_reserve(v, capacity) \ + darray_reserve(sizeof(*v.array), &v.da, capacity) + +#define da_resize(v, size) darray_resize(sizeof(*v.array), &v.da, size) + +#define da_copy(dst, src) \ + darray_copy(sizeof(*dst.array), &dst.da, &src.da) + +#define da_copy_array(dst, src_array, n) \ + darray_copy_array(sizeof(*dst.array), &dst.da, src_array, n) + +#define da_move(dst, src) darray_move(&dst.da, &src.da) + +#define da_find(v, item, idx) \ + darray_find(sizeof(*v.array), &v.da, item, idx) + +#define da_push_back(v, item) darray_push_back(sizeof(*v.array), &v.da, item) + +#define da_push_back_new(v) darray_push_back_new(sizeof(*v.array), &v.da) + +#define da_push_back_array(dst, src_array, n) \ + darray_push_back_array(sizeof(*dst.array), &dst.da, src_array, n) + +#define da_push_back_da(dst, src) \ + darray_push_back_darray(sizeof(*dst.array), &dst.da, &src.da) + +#define da_insert(v, idx, item) \ + darray_insert(sizeof(*v.array), &v.da, idx, item) + +#define da_insert_new(v, idx) \ + darray_insert_new(sizeof(*v.array), &v.da, idx) + +#define da_insert_array(dst, idx, src_array, n) \ + darray_insert_array(sizeof(*dst.array), &dst.da, idx, \ + src_array, n) + +#define da_insert_da(dst, idx, src) \ + darray_insert_darray(sizeof(*dst.array), &dst.da, idx, \ + &src.da) + +#define da_erase(dst, idx) \ + darray_erase(sizeof(*dst.array), &dst.da, idx) + +#define da_erase_item(dst, item) \ + darray_erase_item(sizeof(*dst.array), &dst.da, item) + +#define da_erase_range(dst, from, to) \ + darray_erase_range(sizeof(*dst.array), &dst.da, from, to) + +#define da_pop_back(dst) \ + darray_pop_back(sizeof(*dst.array), &dst.da); + +#define da_join(dst, src) \ + darray_join(sizeof(*dst.array), &dst.da, &src.da) + +#define da_split(dst1, dst2, src, idx) \ + darray_split(sizeof(*src.array), &dst1.da, &dst2.da, \ + &src.da, idx) + +#define da_move_item(v, from, to) \ + darray_move_item(sizeof(*v.array), &v.da, from, to) + +#define da_swap_item(v, idx1, idx2) \ + darray_swap(sizeof(v.array), &v.da, idx1, idx2) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/util/dstr.c b/libobs/util/dstr.c new file mode 100644 index 000000000..4b66a0822 --- /dev/null +++ b/libobs/util/dstr.c @@ -0,0 +1,611 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include "c99defs.h" +#include "dstr.h" +#include "bmem.h" +#include "utf8.h" +#include "lexer.h" +#include "platform.h" + +static const char *astrblank = ""; +static const wchar_t *wstrblank = L""; + +int astrcmpi(const char *str1, const char *str2) +{ + if (!str1) + str1 = astrblank; + if (!str2) + str2 = astrblank; + + do { + char ch1 = toupper(*str1); + char ch2 = toupper(*str2); + + if (ch1 < ch2) + return -1; + else if (ch1 > ch2) + return 1; + } while (*str1++ && *str2++); + + return 0; +} + +int wstrcmpi(const wchar_t *str1, const wchar_t *str2) +{ + if (!str1) + str1 = wstrblank; + if (!str2) + str2 = wstrblank; + + do { + wchar_t ch1 = towupper(*str1); + wchar_t ch2 = towupper(*str2); + + if (ch1 < ch2) + return -1; + else if (ch1 > ch2) + return 1; + } while (*str1++ && *str2++); + + return 0; +} + +int astrcmp_n(const char *str1, const char *str2, size_t n) +{ + if (!n) + return 0; + if (!str1) + str1 = astrblank; + if (!str2) + str2 = astrblank; + + do { + char ch1 = *str1; + char ch2 = *str2; + + if (ch1 < ch2) + return -1; + else if (ch1 > ch2) + return 1; + } while (*str1++ && *str2++ && --n); + + return 0; +} + +int wstrcmp_n(const wchar_t *str1, const wchar_t *str2, size_t n) +{ + if (!n) + return 0; + if (!str1) + str1 = wstrblank; + if (!str2) + str2 = wstrblank; + + do { + wchar_t ch1 = *str1; + wchar_t ch2 = *str2; + + if (ch1 < ch2) + return -1; + else if (ch1 > ch2) + return 1; + } while (*str1++ && *str2++ && --n); + + return 0; +} + +int astrcmpi_n(const char *str1, const char *str2, size_t n) +{ + if (!n) + return 0; + if (!str1) + str1 = astrblank; + if (!str2) + str2 = astrblank; + + do { + char ch1 = toupper(*str1); + char ch2 = toupper(*str2); + + if (ch1 < ch2) + return -1; + else if (ch1 > ch2) + return 1; + } while (*str1++ && *str2++ && --n); + + return 0; +} + +int wstrcmpi_n(const wchar_t *str1, const wchar_t *str2, size_t n) +{ + if (!n) + return 0; + if (!str1) + str1 = wstrblank; + if (!str2) + str2 = wstrblank; + + do { + wchar_t ch1 = towupper(*str1); + wchar_t ch2 = towupper(*str2); + + if (ch1 < ch2) + return -1; + else if (ch1 > ch2) + return 1; + } while (*str1++ && *str2++ && --n); + + return 0; +} + +char *strdepad(char *str) +{ + char *temp; + size_t len; + + if (!str) + return str; + if (!*str) + return str; + + temp = str; + + /* remove preceding spaces/tabs */ + while (*temp == ' ' || *temp == '\t') + ++temp; + + len = strlen(str); + if (temp != str) + memmove(str, temp, len + 1); + + if (len) { + temp = str + (len-1); + while (*temp == ' ' || *temp == '\t') + *(temp--) = 0; + } + + return str; +} + +wchar_t *wcsdepad(wchar_t *str) +{ + wchar_t *temp; + size_t len; + + if (!str) + return str; + if (!*str) + return str; + + temp = str; + + /* remove preceding spaces/tabs */ + while (*temp == ' ' || *temp == '\t') + ++temp; + + len = wcslen(str); + if (temp != str) + memmove(str, temp, (len+1) * sizeof(wchar_t)); + + if (len) { + temp = str + (len-1); + while (*temp == ' ' || *temp == '\t') + *(temp--) = 0; + } + + return str; +} + +void dstr_init_strref(struct dstr *dst, const struct strref *src) +{ + dstr_init(dst); + dstr_copy_strref(dst, src); +} + +void dstr_copy(struct dstr *dst, const char *array) +{ + size_t len; + + if (!array || !*array) { + dstr_free(dst); + return; + } + + len = strlen(array); + dstr_ensure_capacity(dst, len + 1); + memcpy(dst->array, array, len + 1); + dst->len = len; +} + +void dstr_copy_strref(struct dstr *dst, const struct strref *src) +{ + if (dst->array) + dstr_free(dst); + + dstr_ncopy(dst, src->array, src->len); +} + +static inline size_t size_min(size_t a, size_t b) +{ + return (a < b) ? a : b; +} + +void dstr_ncopy(struct dstr *dst, const char *array, const size_t len) +{ + if (dst->array) + dstr_free(dst); + + if (!len) + return; + + dst->array = bmemdup(array, len + 1); + dst->len = len; + + dst->array[len] = 0; +} + +void dstr_ncopy_dstr(struct dstr *dst, const struct dstr *str, const size_t len) +{ + size_t newlen; + + if (dst->array) + dstr_free(dst); + + if (!len) + return; + + newlen = size_min(len, str->len); + dst->array = bmemdup(str->array, newlen + 1); + dst->len = newlen; + + dst->array[newlen] = 0; +} + +void dstr_cat_dstr(struct dstr *dst, const struct dstr *str) +{ + size_t new_len; + if (!str->len) + return; + + new_len = dst->len + str->len; + + dstr_ensure_capacity(dst, new_len + 1); + memcpy(dst->array+dst->len, str->array, str->len + 1); + dst->len = new_len; +} + +void dstr_cat_strref(struct dstr *dst, const struct strref *str) +{ + dstr_ncat(dst, str->array, str->len); +} + +void dstr_ncat(struct dstr *dst, const char *array, const size_t len) +{ + size_t new_len; + if (!array || !*array || !len) + return; + + new_len = dst->len + len; + + dstr_ensure_capacity(dst, new_len + 1); + memcpy(dst->array+dst->len, array, len); + + dst->len = new_len; + dst->array[new_len] = 0; +} + +void dstr_ncat_dstr(struct dstr *dst, const struct dstr *str, const size_t len) +{ + size_t new_len, in_len; + if (!str->array || !*str->array || !len) + return; + + in_len = size_min(len, str->len); + new_len = dst->len + in_len; + + dstr_ensure_capacity(dst, new_len + 1); + memcpy(dst->array+dst->len, str->array, in_len); + + dst->len = new_len; + dst->array[new_len] = 0; +} + +void dstr_insert(struct dstr *dst, const size_t idx, const char *array) +{ + size_t new_len, len; + if (!array || !*array) + return; + if (idx == dst->len) { + dstr_cat(dst, array); + return; + } + + len = strlen(array); + new_len = dst->len + len; + + dstr_ensure_capacity(dst, new_len + 1); + dst->len = new_len; + + memmove(dst->array+idx+len, dst->array+idx, dst->len - idx + 1); + memcpy(dst->array+idx, array, len); +} + +void dstr_insert_dstr(struct dstr *dst, const size_t idx, + const struct dstr *str) +{ + size_t new_len; + if (!str->len) + return; + if (idx == dst->len) { + dstr_cat_dstr(dst, str); + return; + } + + new_len = dst->len + str->len; + + dstr_ensure_capacity(dst, (new_len+1)); + dst->len = new_len; + + memmove(dst->array+idx+str->len, dst->array+idx, dst->len - idx + 1); + memcpy(dst->array+idx, str->array, str->len); +} + +void dstr_insert_ch(struct dstr *dst, const size_t idx, const char ch) +{ + if (idx == dst->len) { + dstr_cat_ch(dst, ch); + return; + } + + dstr_ensure_capacity(dst, (++dst->len+1)); + memmove(dst->array+idx+1, dst->array+idx, dst->len - idx + 1); + dst->array[idx] = ch; +} + +void dstr_remove(struct dstr *dst, const size_t idx, const size_t count) +{ + size_t end; + if (!count) + return; + if (count == dst->len) { + dstr_free(dst); + return; + } + + end = idx+count; + if (end == dst->len) + dst->array[idx] = 0; + else + memmove(dst->array+idx, dst->array+end, dst->len - end + 1); + + dst->len -= count; +} + +void dstr_printf(struct dstr *dst, const char *format, ...) +{ + va_list args; + va_start(args, format); + dstr_vprintf(dst, format, args); + va_end(args); +} + +void dstr_catf(struct dstr *dst, const char *format, ...) +{ + va_list args; + va_start(args, format); + dstr_vcatf(dst, format, args); + va_end(args); +} + +void dstr_vprintf(struct dstr *dst, const char *format, va_list args) +{ + dstr_ensure_capacity(dst, 4096); + vsnprintf(dst->array, 4095, format, args); + + if (!*dst->array) { + dstr_free(dst); + return; + } + + dst->len = strlen(dst->array); +} + +void dstr_vcatf(struct dstr *dst, const char *format, va_list args) +{ + struct dstr temp; + dstr_init(&temp); + dstr_vprintf(&temp, format, args); + dstr_cat_dstr(dst, &temp); + dstr_free(&temp); +} + +void dstr_safe_printf(struct dstr *dst, const char *format, + const char *val1, const char *val2, const char *val3, + const char *val4) +{ + dstr_copy(dst, format); + if (val1) + dstr_replace(dst, "$1", val1); + if (val2) + dstr_replace(dst, "$2", val2); + if (val3) + dstr_replace(dst, "$3", val3); + if (val4) + dstr_replace(dst, "$4", val4); +} + +void dstr_replace(struct dstr *str, const char *find, + const char *replace) +{ + size_t find_len, replace_len; + char *temp; + + if (!replace) + replace = ""; + + find_len = strlen(find); + replace_len = strlen(replace); + temp = str->array; + + if (replace_len < find_len) { + int count = 0; + + while ((temp = strstr(temp, find)) != NULL) { + char *end = temp+find_len; + size_t end_len = strlen(end); + + if (end_len) { + memmove(temp+replace_len, end, end_len + 1); + if (replace_len) + memcpy(temp, replace, replace_len); + } else { + strcpy(temp, replace); + } + + temp += replace_len; + ++count; + } + + if (count) + str->len += (replace_len-find_len) * count; + + } else if (replace_len > find_len) { + int count = 0; + + while ((temp = strstr(temp, find)) != NULL) { + temp += find_len; + ++count; + } + + if (!count) + return; + + str->len += (replace_len-find_len) * count; + dstr_ensure_capacity(str, str->len + 1); + temp = str->array; + + while ((temp = strstr(temp, find)) != NULL) { + char *end = temp+find_len; + size_t end_len = strlen(end); + + if (end_len) { + memmove(temp+replace_len, end, end_len + 1); + memcpy(temp, replace, replace_len); + } else { + strcpy(temp, replace); + } + + temp += replace_len; + } + + } else { + while ((temp = strstr(temp, find)) != NULL) { + memcpy(temp, replace, replace_len); + temp += replace_len; + } + } +} + +void dstr_depad(struct dstr *str) +{ + if (str->array) { + str->array = strdepad(str->array); + if (*str->array) + str->len = strlen(str->array); + else + dstr_free(str); + } +} + +void dstr_left(struct dstr *dst, const struct dstr *str, const size_t pos) +{ + dstr_resize(dst, pos); + if (dst != str) + memcpy(dst->array, str->array, pos); +} + +void dstr_mid(struct dstr *dst, const struct dstr *str, const size_t start, + const size_t count) +{ + struct dstr temp; + dstr_init(&temp); + dstr_copy_dstr(&temp, str); + dstr_ncopy(dst, temp.array+start, count); + dstr_free(&temp); +} + +void dstr_right(struct dstr *dst, const struct dstr *str, const size_t pos) +{ + struct dstr temp; + dstr_init(&temp); + dstr_ncopy(&temp, str->array+pos, str->len-pos); + dstr_copy_dstr(dst, &temp); + dstr_free(&temp); +} + +void dstr_from_mbs(struct dstr *dst, const char *mbstr) +{ + dstr_free(dst); + dst->len = os_mbs_to_utf8(mbstr, 0, &dst->array); +} + +char *dstr_to_mbs(const struct dstr *str) +{ + char *dst; + os_mbs_to_utf8(str->array, str->len, &dst); + return dst; +} + +void dstr_from_wcs(struct dstr *dst, const wchar_t *wstr) +{ + size_t len = wchar_to_utf8(wstr, 0, NULL, 0, 0); + + if (len) { + dstr_resize(dst, len); + wchar_to_utf8(wstr, 0, dst->array, len+1, 0); + } else { + dstr_free(dst); + } +} + +wchar_t *dstr_to_utf8(const struct dstr *str) +{ + wchar_t *out = NULL; + size_t len = utf8_to_wchar(str->array, str->len, NULL, 0, 0); + + if (len) { + out = bmalloc((len+1) * sizeof(wchar_t)); + utf8_to_wchar(str->array, str->len, out, len+1, 0); + out[len] = 0; + } + + return out; +} diff --git a/libobs/util/dstr.h b/libobs/util/dstr.h new file mode 100644 index 000000000..c0f47227d --- /dev/null +++ b/libobs/util/dstr.h @@ -0,0 +1,310 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifndef DSTR_H +#define DSTR_H + +#include +#include +#include "c99defs.h" +#include "bmem.h" + +/* + * Dynamic string + * + * Helper struct/functions for dynamically sizing string buffers. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +struct strref; + +struct dstr { + char *array; + size_t len; /* number of characters, excluding null terminator */ + size_t capacity; +}; + +EXPORT int astrcmpi(const char *str1, const char *str2); +EXPORT int wstrcmpi(const wchar_t *str1, const wchar_t *str2); +EXPORT int astrcmp_n(const char *str1, const char *str2, size_t n); +EXPORT int wstrcmp_n(const wchar_t *str1, const wchar_t *str2, size_t n); +EXPORT int astrcmpi_n(const char *str1, const char *str2, size_t n); +EXPORT int wstrcmpi_n(const wchar_t *str1, const wchar_t *str2, size_t n); + +EXPORT char *strdepad(char *str); +EXPORT wchar_t *wcsdepad(wchar_t *str); + +static inline void dstr_init(struct dstr *dst); +static inline void dstr_init_move(struct dstr *dst, struct dstr *src); +static inline void dstr_init_move_array(struct dstr *dst, char *str); +static inline void dstr_init_copy(struct dstr *dst, const char *src); +static inline void dstr_init_copy_dstr(struct dstr *dst, + const struct dstr *src); +EXPORT void dstr_init_strref(struct dstr *dst, const struct strref *src); + +static inline void dstr_free(struct dstr *dst); +static inline void dstr_array_free(struct dstr *array, const size_t count); + +static inline void dstr_move(struct dstr *dst, struct dstr *src); +static inline void dstr_move_array(struct dstr *dst, char *str); + +EXPORT void dstr_copy(struct dstr *dst, const char *array); +static inline void dstr_copy_dstr(struct dstr *dst, const struct dstr *src); +EXPORT void dstr_copy_strref(struct dstr *dst, const struct strref *src); + +EXPORT void dstr_ncopy(struct dstr *dst, const char *array, + const size_t len); +EXPORT void dstr_ncopy_dstr(struct dstr *dst, const struct dstr *src, + const size_t len); + +static inline void dstr_resize(struct dstr *dst, const size_t num); +static inline void dstr_reserve(struct dstr *dst, const size_t num); + +static inline bool dstr_isempty(const struct dstr *str); + +static inline void dstr_cat(struct dstr *dst, const char *array); +EXPORT void dstr_cat_dstr(struct dstr *dst, const struct dstr *str); +EXPORT void dstr_cat_strref(struct dstr *dst, const struct strref *str); + +static inline void dstr_cat_ch(struct dstr *dst, char ch); + +EXPORT void dstr_ncat(struct dstr *dst, const char *array, const size_t len); +EXPORT void dstr_ncat_dstr(struct dstr *dst, const struct dstr *str, + const size_t len); + +EXPORT void dstr_cat_strref(struct dstr *dst, const struct strref *str); + +EXPORT void dstr_insert(struct dstr *dst, const size_t idx, + const char *array); +EXPORT void dstr_insert_dstr(struct dstr *dst, const size_t idx, + const struct dstr *str); +EXPORT void dstr_insert_ch(struct dstr *dst, const size_t idx, + const char ch); + +EXPORT void dstr_remove(struct dstr *dst, const size_t idx, const size_t count); + +EXPORT void dstr_printf(struct dstr *dst, const char *format, ...); +EXPORT void dstr_catf(struct dstr *dst, const char *format, ...); + +EXPORT void dstr_vprintf(struct dstr *dst, const char *format, va_list args); +EXPORT void dstr_vcatf(struct dstr *dst, const char *format, va_list args); + +EXPORT void dstr_safe_printf(struct dstr *dst, const char *format, + const char *val1, const char *val2, const char *val3, + const char *val4); + +static inline const char *dstr_find(const struct dstr *str, + const char *find); + +EXPORT void dstr_replace(struct dstr *str, const char *find, + const char *replace); + +static inline int dstr_cmp(const struct dstr *str1, const char *str2); +static inline int dstr_cmpi(const struct dstr *str1, const char *str2); +static inline int dstr_ncmp(const struct dstr *str1, const char *str2, + const size_t n); +static inline int dstr_ncmpi(const struct dstr *str1, const char *str2, + const size_t n); + +EXPORT void dstr_depad(struct dstr *dst); + +EXPORT void dstr_left(struct dstr *dst, const struct dstr *str, + const size_t pos); +EXPORT void dstr_mid(struct dstr *dst, const struct dstr *str, + const size_t start, const size_t count); +EXPORT void dstr_right(struct dstr *dst, const struct dstr *str, + const size_t pos); + +EXPORT void dstr_from_mbs(struct dstr *dst, const char *mbstr); +EXPORT char *dstr_to_mbs(const struct dstr *str); +EXPORT void dstr_from_wcs(struct dstr *dst, const wchar_t *wstr); +EXPORT wchar_t *dstr_to_wcs(const struct dstr *str); + +/* ------------------------------------------------------------------------- */ + +static inline void dstr_init(struct dstr *dst) +{ + dst->array = NULL; + dst->len = 0; + dst->capacity = 0; +} + +static inline void dstr_init_move_array(struct dstr *dst, char *str) +{ + dst->array = str; + dst->len = (!str) ? 0 : strlen(str); +} + +static inline void dstr_init_move(struct dstr *dst, struct dstr *src) +{ + *dst = *src; + dstr_init(src); +} + +static inline void dstr_init_copy(struct dstr *dst, const char *str) +{ + dstr_init(dst); + dstr_copy(dst, str); +} + +static inline void dstr_init_copy_dstr(struct dstr *dst, const struct dstr *src) +{ + dstr_init(dst); + dstr_copy_dstr(dst, src); +} + +static inline void dstr_free(struct dstr *dst) +{ + bfree(dst->array); + dst->array = NULL; + dst->len = 0; + dst->capacity = 0; +} + +static inline void dstr_array_free(struct dstr *array, const size_t count) +{ + size_t i; + for (i = 0; i < count; i++) + dstr_free(array+i); +} + +static inline void dstr_move_array(struct dstr *dst, char *str) +{ + dstr_free(dst); + dst->array = str; + dst->len = (!str) ? 0 : strlen(str); +} + +static inline void dstr_move(struct dstr *dst, struct dstr *src) +{ + dstr_free(dst); + dstr_init_move(dst, src); +} + +static inline void dstr_ensure_capacity(struct dstr *dst, const size_t new_size) +{ + size_t new_cap; + if (new_size <= dst->capacity) + return; + + new_cap = (!dst->capacity) ? new_size : dst->capacity*2; + if (new_size > new_cap) + new_cap = new_size; + dst->array = (char*)brealloc(dst->array, new_cap); + dst->capacity = new_cap; +} + +static inline void dstr_copy_dstr(struct dstr *dst, const struct dstr *src) +{ + if (dst->array) + dstr_free(dst); + + dstr_ensure_capacity(dst, src->len + 1); + memcpy(dst->array, src->array, src->len + 1); + dst->len = src->len; +} + +static inline void dstr_reserve(struct dstr *dst, const size_t capacity) +{ + if (capacity == 0 || capacity <= dst->len) + return; + + dst->array = (char*)brealloc(dst->array, capacity); + dst->capacity = capacity; +} + +static inline void dstr_resize(struct dstr *dst, const size_t num) +{ + if (!num) { + dstr_free(dst); + return; + } + + dstr_ensure_capacity(dst, num + 1); + dst->array[num] = 0; + dst->len = num; +} + +static inline bool dstr_isempty(const struct dstr *str) +{ + if (!str->array || !str->len) + return true; + if (!*str->array) + return true; + + return false; +} + +static inline void dstr_cat(struct dstr *dst, const char *array) +{ + size_t len; + if (!array || !*array) + return; + + len = strlen(array); + dstr_ncat(dst, array, len); +} + +static inline void dstr_cat_ch(struct dstr *dst, char ch) +{ + dstr_ensure_capacity(dst, ++dst->len + 1); + dst->array[dst->len-1] = ch; + dst->array[dst->len] = 0; +} + +static inline const char *dstr_find(const struct dstr *str, + const char *find) +{ + return strstr(str->array, find); +} + +static inline int dstr_cmp(const struct dstr *str1, const char *str2) +{ + return strcmp(str1->array, str2); +} + +static inline int dstr_cmpi(const struct dstr *str1, const char *str2) +{ + return astrcmpi(str1->array, str2); +} + +static inline int dstr_ncmp(const struct dstr *str1, const char *str2, + const size_t n) +{ + return astrcmp_n(str1->array, str2, n); +} + +static inline int dstr_ncmpi(const struct dstr *str1, const char *str2, + const size_t n) +{ + return astrcmpi_n(str1->array, str2, n); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/util/lexer.c b/libobs/util/lexer.c new file mode 100644 index 000000000..2bf26ee30 --- /dev/null +++ b/libobs/util/lexer.c @@ -0,0 +1,321 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#include +#include "lexer.h" + +static const char *astrblank = ""; + +static inline bool strref_is_empty(const struct strref *str) +{ + return !str || !str->array || !str->len || !*str->array; +} + +int strref_cmp(const struct strref *str1, const char *str2) +{ + size_t i = 0; + + if (strref_is_empty(str1)) + return (!str2 || !*str2) ? 0 : -1; + if (!str2) + str2 = astrblank; + + do { + char ch1, ch2; + + ch1 = (i < str1->len) ? str1->array[i] : 0; + ch2 = *str2; + + if (ch1 < ch2) + return -1; + else if (ch1 > ch2) + return 1; + } while (i++ < str1->len && *str2++); + + return 0; +} + +int strref_cmpi(const struct strref *str1, const char *str2) +{ + size_t i = 0; + + if (strref_is_empty(str1)) + return (!str2 || !*str2) ? 0 : -1; + if (!str2) + str2 = astrblank; + + do { + char ch1, ch2; + + ch1 = (i < str1->len) ? toupper(str1->array[i]) : 0; + ch2 = toupper(*str2); + + if (ch1 < ch2) + return -1; + else if (ch1 > ch2) + return 1; + } while (i++ < str1->len && *str2++); + + return 0; +} + +int strref_cmp_strref(const struct strref *str1, const struct strref *str2) +{ + size_t i = 0; + + if (strref_is_empty(str1)) + return strref_is_empty(str2) ? 0 : -1; + if (strref_is_empty(str2)) + return -1; + + do { + char ch1, ch2; + + ch1 = (i < str1->len) ? str1->array[i] : 0; + ch2 = (i < str2->len) ? str2->array[i] : 0; + + if (ch1 < ch2) + return -1; + else if (ch1 > ch2) + return 1; + + i++; + } while (i <= str1->len && i <= str2->len); + + return 0; +} + +int strref_cmpi_strref(const struct strref *str1, const struct strref *str2) +{ + size_t i = 0; + + if (strref_is_empty(str1)) + return strref_is_empty(str2) ? 0 : -1; + if (strref_is_empty(str2)) + return -1; + + do { + char ch1, ch2; + + ch1 = (i < str1->len) ? toupper(str1->array[i]) : 0; + ch2 = (i < str2->len) ? toupper(str2->array[i]) : 0; + + if (ch1 < ch2) + return -1; + else if (ch1 > ch2) + return 1; + + i++; + } while (i <= str1->len && i <= str2->len); + + return 0; +} +/* ------------------------------------------------------------------------- */ + +bool valid_int_str(const char *str, size_t n) +{ + bool found_num = false; + + if (!str) + return false; + if (!*str) + return false; + + if (!n) + n = strlen(str); + if (*str == '-' || *str == '+') + ++str; + + do { + if (*str > '9' || *str < '0') + return false; + + found_num = true; + } while(*++str && --n); + + return found_num; +} + +bool valid_float_str(const char *str, size_t n) +{ + bool found_num = false; + bool found_exp = false; + bool found_dec = false; + + if (!str) + return false; + if (!*str) + return false; + + if (!n) + n = strlen(str); + if (*str == '-' || *str == '+') + ++str; + + do { + if (*str == '.') { + if (found_dec || found_exp || !found_num) + return false; + + found_dec = true; + + } else if (*str == 'e') { + if (found_exp || !found_num) + return false; + + found_exp = true; + found_num = false; + + } else if (*str == '-' || *str == '+') { + if (!found_exp || !found_num) + return false; + + } else if (*str > '9' || *str < '0') { + return false; + } else { + found_num = true; + } + } while(*++str && --n); + + return found_num; +} + +/* ------------------------------------------------------------------------- */ + +void error_data_add(struct error_data *data, const char *file, + uint32_t row, uint32_t column, const char *msg, int level) +{ + struct error_item item; + + if (!data) + return; + + item.file = file; + item.row = row; + item.column = column; + item.level = level; + item.error = bstrdup(msg); + + da_push_back(data->errors, &item); +} + +char *error_data_buildstring(struct error_data *ed) +{ + struct dstr str; + struct error_item *items = ed->errors.array; + size_t i; + + dstr_init(&str); + for (i = 0; i < ed->errors.num; i++) { + struct error_item *item = items+i; + dstr_catf(&str, "%s (%u, %u): %s\n", item->file, item->row, + item->column, item->error); + } + + return str.array; +} + +/* ------------------------------------------------------------------------- */ + +static inline enum base_token_type get_char_token_type(const char ch) +{ + if (is_whitespace(ch)) + return BASETOKEN_WHITESPACE; + else if (isdigit(ch)) + return BASETOKEN_DIGIT; + else if (isalpha(ch)) + return BASETOKEN_ALPHA; + + return BASETOKEN_OTHER; +} + +bool lexer_getbasetoken(struct lexer *lex, struct base_token *token, + bool ignore_whitespace) +{ + const char *offset = lex->offset; + const char *token_start = NULL; + enum base_token_type type = BASETOKEN_NONE; + + if (!offset) + return false; + + while (*offset != 0) { + char ch = *(offset++); + enum base_token_type new_type = get_char_token_type(ch); + + if (type == BASETOKEN_NONE) { + if (new_type == BASETOKEN_WHITESPACE && + ignore_whitespace) + continue; + + token_start = offset-1; + type = new_type; + + if (type != BASETOKEN_DIGIT || + type != BASETOKEN_ALPHA) { + if (is_newline(ch) && + is_newline_pair(ch, *offset)) { + offset++; + } + break; + } + } else if (type != new_type) { + break; + } + } + + lex->offset = offset; + + if (token_start && offset > token_start) { + strref_set(&token->text, token_start, offset-token_start); + token->type = type; + return true; + } + + return false; +} + +void lexer_getstroffset(const struct lexer *lex, const char *str, + uint32_t *row, uint32_t *col) +{ + uint32_t cur_col = 1, cur_row = 1; + const char *text = lex->text; + + if (!str) + return; + + while (text < str) { + if (is_newline(*text)) { + text += newline_size(text)-1; + cur_col = 1; + cur_row++; + } else { + cur_col++; + } + + text++; + } + + *row = cur_row; + *col = cur_col; +} diff --git a/libobs/util/lexer.h b/libobs/util/lexer.h new file mode 100644 index 000000000..c81129188 --- /dev/null +++ b/libobs/util/lexer.h @@ -0,0 +1,294 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifndef LEXER_H +#define LEXER_H + +#include "c99defs.h" +#include "dstr.h" +#include "darray.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------------------------------------------------------------- */ +/* string reference (string segment within an already existing array) */ + +struct strref { + const char *array; + size_t len; +}; + +static inline void strref_clear(struct strref *dst) +{ + dst->array = NULL; + dst->len = 0; +} + +static inline void strref_set(struct strref *dst, const char *array, size_t len) +{ + dst->array = array; + dst->len = len; +} + +static inline void strref_copy(struct strref *dst, const struct strref *src) +{ + dst->array = src->array; + dst->len = src->len; +} + +static inline void strref_add(struct strref *dst, const struct strref *t) +{ + if (!dst->array) + strref_copy(dst, t); + else + dst->len += t->len; +} + +static inline bool strref_isempty(const struct strref *str) +{ + if (!str->array || !str->len) + return true; + if (!*str->array) + return true; + + return false; +} + +EXPORT int strref_cmp(const struct strref *str1, const char *str2); +EXPORT int strref_cmpi(const struct strref *str1, const char *str2); +EXPORT int strref_cmp_strref(const struct strref *str1, + const struct strref *str2); +EXPORT int strref_cmpi_strref(const struct strref *str1, + const struct strref *str2); + +/* ------------------------------------------------------------------------- */ + +EXPORT bool valid_int_str(const char *str, size_t n); +EXPORT bool valid_float_str(const char *str, size_t n); + +static inline bool valid_int_strref(const struct strref *str) +{ + return valid_int_str(str->array, str->len); +} + +static inline bool valid_float_strref(const struct strref *str) +{ + return valid_float_str(str->array, str->len); +} + +static inline bool is_whitespace(char ch) +{ + return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n'; +} + +static inline bool is_newline(char ch) +{ + return ch == '\r' || ch == '\n'; +} + +static inline bool is_space_or_tab(const char ch) +{ + return ch == ' ' || ch == '\t'; +} + +static inline bool is_newline_pair(char ch1, char ch2) +{ + return (ch1 == '\r' && ch2 == '\n') || + (ch1 == '\n' && ch2 == '\r'); +} + +static inline int newline_size(const char *array) +{ + if (strncmp(array, "\r\n", 2) == 0 || strncmp(array, "\n\r", 2) == 0) + return 2; + else if (*array == '\r' || *array == '\n') + return 1; + + return 0; +} + +/* ------------------------------------------------------------------------- */ + +/* + * A "base" token is one of four things: + * 1.) A sequence of alpha characters + * 2.) A sequence of numeric characters + * 3.) A single whitespace character if whitespace is not ignored + * 4.) A single character that does not fall into the above 3 categories + */ + +enum base_token_type { + BASETOKEN_NONE, + BASETOKEN_ALPHA, + BASETOKEN_DIGIT, + BASETOKEN_WHITESPACE, + BASETOKEN_OTHER, +}; + +struct base_token { + struct strref text; + enum base_token_type type; + bool passed_whitespace; +}; + +static inline void base_token_clear(struct base_token *t) +{ + memset(t, 0, sizeof(struct base_token)); +} + +static inline void base_token_copy(struct base_token *dst, + struct base_token *src) +{ + memcpy(dst, src, sizeof(struct base_token)); +} + +/* ------------------------------------------------------------------------- */ + +#define LEVEL_ERROR 0 +#define LEVEL_WARNING 1 + +struct error_item { + char *error; + const char *file; + uint32_t row, column; + int level; +}; + +static inline void error_item_init(struct error_item *ei) +{ + memset(ei, 0, sizeof(struct error_item)); +} + +static inline void error_item_free(struct error_item *ei) +{ + bfree(ei->error); + error_item_init(ei); +} + +static inline void error_item_array_free(struct error_item *array, size_t num) +{ + size_t i; + for (i = 0; i < num; i++) + error_item_free(array+i); +} + +/* ------------------------------------------------------------------------- */ + +struct error_data { + DARRAY(struct error_item) errors; +}; + +static inline void error_data_init(struct error_data *data) +{ + da_init(data->errors); +} + +static inline void error_data_free(struct error_data *data) +{ + error_item_array_free(data->errors.array, data->errors.num); + da_free(data->errors); +} + +static inline const struct error_item *error_data_item(struct error_data *ed, + size_t idx) +{ + return ed->errors.array+idx; +} + +EXPORT char *error_data_buildstring(struct error_data *ed); + +EXPORT void error_data_add(struct error_data *ed, const char *file, + uint32_t row, uint32_t column, const char *msg, int level); + +static inline size_t error_data_type_count(struct error_data *ed, + int type) +{ + size_t count = 0, i; + for (i = 0; i < ed->errors.num; i++) { + if (ed->errors.array[i].level == type) + count++; + } + + return count; +} + +static inline bool error_data_has_errors(struct error_data *ed) +{ + size_t i; + for (i = 0; i < ed->errors.num; i++) + if (ed->errors.array[i].level == LEVEL_ERROR) + return true; + + return false; +} + +/* ------------------------------------------------------------------------- */ + +struct lexer { + char *text; + const char *offset; +}; + +static inline void lexer_init(struct lexer *lex) +{ + memset(lex, 0, sizeof(struct lexer)); +} + +static inline void lexer_free(struct lexer *lex) +{ + bfree(lex->text); + lexer_init(lex); +} + +static inline void lexer_start(struct lexer *lex, const char *text) +{ + lexer_free(lex); + lex->text = bstrdup(text); + lex->offset = lex->text; +} + +static inline void lexer_start_move(struct lexer *lex, char *text) +{ + lexer_free(lex); + lex->text = text; + lex->offset = lex->text; +} + +static inline void lexer_reset(struct lexer *lex) +{ + lex->offset = lex->text; +} + +EXPORT bool lexer_getbasetoken(struct lexer *lex, struct base_token *t, + bool ignore_whitespace); + +EXPORT void lexer_getstroffset(const struct lexer *lex, const char *str, + uint32_t *row, uint32_t *col); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/util/platform-windows.c b/libobs/util/platform-windows.c new file mode 100644 index 000000000..66ef36392 --- /dev/null +++ b/libobs/util/platform-windows.c @@ -0,0 +1,139 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifdef _WIN32 + +#include +#include "base.h" +#include "platform.h" +#include "bmem.h" + +static bool have_clockfreq = false; +static LARGE_INTEGER clock_freq; +static uint32_t winver = 0; + +static inline uint64_t get_clockfreq(void) +{ + if (!have_clockfreq) + QueryPerformanceFrequency(&clock_freq); + return clock_freq.QuadPart; +} + +static inline uint32_t get_winver(void) +{ + if (!winver) { + OSVERSIONINFO osvi; + memset(&osvi, 0, sizeof(osvi)); + winver = (osvi.dwMajorVersion << 16) | (osvi.dwMinorVersion); + } + + return winver; +} + +void *os_dlopen(const char *path) +{ + wchar_t *wpath; + HMODULE h_library = NULL; + + os_utf8_to_wcs(path, 0, &wpath); + h_library = LoadLibraryW(wpath); + bfree(wpath); + + if (!h_library) + blog(LOG_INFO, "LoadLibrary failed for '%s', error: %u", + path, GetLastError()); + + return h_library; +} + +void *os_dlsym(void *module, const char *func) +{ + return (void*)GetProcAddress(module, func); +} + +void os_dlclose(void *module) +{ + FreeLibrary(module); +} + +void os_sleepto_ns(uint64_t time_target) +{ + uint64_t t = os_gettime_ns(); + uint32_t milliseconds; + + if (t >= time_target) + return; + + milliseconds = (uint32_t)((time_target - t)/1000000); + if (milliseconds > 1) + os_sleep_ms(milliseconds); + + for (;;) { + t = os_gettime_ns(); + if (t >= time_target) + return; + +#if 1 + Sleep(1); +#else + Sleep(0); +#endif + } +} + +void os_sleep_ms(uint32_t duration) +{ + /* windows 8+ appears to have decreased sleep precision */ + if (get_winver() >= 0x0602 && duration > 0) + duration--; + + Sleep(duration); +} + +uint64_t os_gettime_ns(void) +{ + LARGE_INTEGER current_time; + double time_val; + + QueryPerformanceCounter(¤t_time); + time_val = (double)current_time.QuadPart; + time_val *= 1000000000.0; + time_val /= (double)get_clockfreq(); + + return (uint64_t)time_val; +} + +uint64_t os_gettime_ms(void) +{ + LARGE_INTEGER current_time; + uint64_t time_val; + + QueryPerformanceCounter(¤t_time); + time_val = current_time.QuadPart; + time_val *= 1000; + time_val /= get_clockfreq(); + + return time_val; +} + +#endif diff --git a/libobs/util/platform.c b/libobs/util/platform.c new file mode 100644 index 000000000..aac39e4d7 --- /dev/null +++ b/libobs/util/platform.c @@ -0,0 +1,305 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#include +#include +#include "c99defs.h" +#include "platform.h" +#include "bmem.h" +#include "utf8.h" +#include "dstr.h" + +FILE *os_wfopen(const wchar_t *path, const char *mode) +{ + FILE *file; +#ifdef _MSC_VER + wchar_t *wcs_mode; + + os_utf8_to_wcs(mode, 0, &wcs_mode); + file = _wfopen(path, wcs_mode); + bfree(wcs_mode); +#else + char *mbs_path; + + os_wcs_to_utf8(path, 0, &mbs_path); + file = fopen(mbs_path, mode); + bfree(mbs_path); +#endif + return file; +} + +FILE *os_fopen(const char *path, const char *mode) +{ +#ifdef _WIN32 + wchar_t *wpath = NULL; + FILE *file = NULL; + os_utf8_to_wcs(path, 0, &wpath); + file = os_wfopen(wpath, mode); + bfree(wpath); + + return file; +#else + return fopen(path, mode); +#endif +} + +off_t os_fgetsize(FILE *file) +{ + off_t cur_offset = ftello(file); + off_t size; + int errval = 0; + + if (fseeko(file, 0, SEEK_END) == -1) + return -1; + + size = ftello(file); + if (size == -1) + errval = errno; + + if (fseeko(file, cur_offset, SEEK_SET) != 0 && errval != 0) + errno = errval; + + return size; +} + +size_t os_fread_mbs(FILE *file, char **pstr) +{ + off_t size = 0; + size_t len = 0; + + fseeko(file, 0, SEEK_END); + size = ftello(file); + + if (size > 0) { + char *mbstr = bmalloc(size+1); + + fseeko(file, 0, SEEK_SET); + fread(mbstr, 1, size, file); + mbstr[size] = 0; + len = os_mbs_to_utf8(mbstr, size, pstr); + bfree(mbstr); + } else { + *pstr = NULL; + } + + return len; +} + +size_t os_fread_utf8(FILE *file, char **pstr) +{ + off_t size = 0; + size_t len = 0; + + fseeko(file, 0, SEEK_END); + size = ftello(file); + + if (size > 0) { + char bom[3]; + char *utf8str = bmalloc(size+1); + off_t offset; + + /* remove the ghastly BOM if present */ + fseeko(file, 0, SEEK_SET); + fread(bom, 1, 3, file); + offset = (astrcmp_n(bom, "\xEF\xBB\xBF", 3) == 0) ? 3 : 0; + + fseeko(file, offset, SEEK_SET); + fread(utf8str, 1, size, file); + utf8str[size] = 0; + + *pstr = utf8str; + } else { + *pstr = NULL; + } + + return len; +} + +char *os_quick_read_mbs_file(const char *path) +{ + FILE *f = os_fopen(path, "rb"); + char *file_string = NULL; + + if (!f) + return NULL; + + os_fread_mbs(f, &file_string); + fclose(f); + + return file_string; +} + +char *os_quick_read_utf8_file(const char *path) +{ + FILE *f = os_fopen(path, "rb"); + char *file_string = NULL; + + if (!f) + return NULL; + + os_fread_utf8(f, &file_string); + fclose(f); + + return file_string; +} + +bool os_quick_write_mbs_file(const char *path, const char *str, size_t len) +{ + FILE *f = os_fopen(path, "wb"); + char *mbs = NULL; + size_t mbs_len = 0; + if (!f) + return false; + + mbs_len = os_utf8_to_mbs(str, len, &mbs); + if (mbs_len) + fwrite(mbs, 1, mbs_len, f); + bfree(mbs); + fclose(f); + + return true; +} + +bool os_quick_write_utf8_file(const char *path, const char *str, size_t len, + bool marker) +{ + FILE *f = os_fopen(path, "wb"); + if (!f) + return false; + + if (marker) + fwrite("\xEF\xBB\xBF", 1, 3, f); + if (len) + fwrite(str, 1, len, f); + fclose(f); + + return true; +} + +size_t os_mbs_to_wcs(const char *str, size_t len, wchar_t **pstr) +{ + size_t out_len = mbstowcs(NULL, str, len); + wchar_t *dst = NULL; + + if (len) { + dst = bmalloc((out_len+1) * sizeof(wchar_t)); + mbstowcs(dst, str, out_len+1); + dst[out_len] = 0; + } + + *pstr = dst; + return out_len; +} + +size_t os_utf8_to_wcs(const char *str, size_t len, wchar_t **pstr) +{ + size_t in_len = len ? len : strlen(str); + size_t out_len = utf8_to_wchar(str, in_len, NULL, 0, 0); + wchar_t *dst = NULL; + + if (out_len) { + dst = bmalloc((out_len+1) * sizeof(wchar_t)); + utf8_to_wchar(str, in_len, dst, out_len+1, 0); + dst[out_len] = 0; + } + + *pstr = dst; + return out_len; +} + +size_t os_wcs_to_mbs(const wchar_t *str, size_t len, char **pstr) +{ + size_t out_len = wcstombs(NULL, str, len); + char *dst = NULL; + + if (len) { + dst = bmalloc(out_len+1); + wcstombs(dst, str, out_len+1); + dst[out_len] = 0; + } + + *pstr = dst; + return out_len; +} + +size_t os_wcs_to_utf8(const wchar_t *str, size_t len, char **pstr) +{ + size_t in_len = wcslen(str); + size_t out_len = wchar_to_utf8(str, in_len, NULL, 0, 0); + char *dst = NULL; + + if (out_len) { + dst = bmalloc(out_len+1); + wchar_to_utf8(str, in_len, dst, out_len+1, 0); + dst[out_len] = 0; + } + + *pstr = dst; + return out_len; +} + +size_t os_utf8_to_mbs(const char *str, size_t len, char **pstr) +{ + wchar_t *wstr = NULL; + char *dst = NULL; + size_t wlen = os_utf8_to_wcs(str, len, &wstr); + size_t out_len = os_wcs_to_mbs(wstr, wlen, &dst); + + bfree(wstr); + *pstr = dst; + + return out_len; +} + +size_t os_mbs_to_utf8(const char *str, size_t len, char **pstr) +{ + wchar_t *wstr = NULL; + char *dst = NULL; + size_t wlen = os_mbs_to_wcs(str, len, &wstr); + size_t out_len = os_wcs_to_utf8(wstr, wlen, &dst); + + bfree(wstr); + *pstr = dst; + + return out_len; +} + +#ifdef _MSC_VER +int fseeko(FILE *stream, off_t offset, int whence) +{ +#if _FILE_OFFSET_BITS == 64 + return _fseeki64(stream, offset, whence); +#else + return fseek(stream, offset, whence); +#endif /* _FILE_OFFSET_BITS == 64 */ +} + +off_t ftello(FILE *stream) +{ +#if _FILE_OFFSET_BITS == 64 + return _ftelli64(stream); +#else + return ftell(stream); +#endif /* _FILE_OFFSET_BITS == 64 */ +} +#endif /* _MSC_VER */ diff --git a/libobs/util/platform.h b/libobs/util/platform.h new file mode 100644 index 000000000..9b0b84bcf --- /dev/null +++ b/libobs/util/platform.h @@ -0,0 +1,82 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifndef PLATFORM_H +#define PLATFORM_H + +#include +#include +#include +#include "c99defs.h" + +/* + * Platform-independent functions for Accessing files, encoding, DLLs, + * sleep, timer, and timing. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +EXPORT FILE *os_wfopen(const wchar_t *path, const char *mode); +EXPORT FILE *os_fopen(const char *path, const char *mode); +EXPORT off_t os_fgetsize(FILE *file); + +EXPORT size_t os_fread_mbs(FILE *file, char **pstr); +EXPORT size_t os_fread_utf8(FILE *file, char **pstr); + +/* functions purely for convenience */ +EXPORT char *os_quick_read_utf8_file(const char *path); +EXPORT bool os_quick_write_utf8_file(const char *path, const char *str, + size_t len, bool marker); + +EXPORT size_t os_mbs_to_wcs(const char *str, size_t len, wchar_t **pstr); +EXPORT size_t os_utf8_to_wcs(const char *str, size_t len, wchar_t **pstr); +EXPORT size_t os_wcs_to_mbs(const wchar_t *str, size_t len, char **pstr); +EXPORT size_t os_wcs_to_utf8(const wchar_t *str, size_t len, char **pstr); + +EXPORT size_t os_utf8_to_mbs(const char *str, size_t len, char **pstr); +EXPORT size_t os_mbs_to_utf8(const char *str, size_t len, char **pstr); + +EXPORT void *os_dlopen(const char *path); +EXPORT void *os_dlsym(void *module, const char *func); +EXPORT void os_dlclose(void *module); + +EXPORT void os_sleepto_ns(uint64_t time_target); +EXPORT void os_sleep_ms(uint32_t duration); + +EXPORT uint64_t os_gettime_ns(void); +EXPORT uint64_t os_gettime_ms(void); + +#ifdef _MSC_VER +EXPORT int fseeko(FILE *stream, off_t offset, int whence); +EXPORT off_t ftello(FILE *stream); +#endif + +#define strtoll _strtoi64 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/util/serializer.h b/libobs/util/serializer.h new file mode 100644 index 000000000..b749d48a8 --- /dev/null +++ b/libobs/util/serializer.h @@ -0,0 +1,128 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifndef SERIALIZER_H +#define SERIALIZER_H + +/* + * General programmable serialization functions. (A shared interface to + * various reading/writing to/from different inputs/outputs) + * + * TODO: Not currently implemented + */ + +#ifdef __cplusplus +extern "C" { +#endif + +enum serialize_seek_type { + SERIALIZE_SEEK_START, + SERIALIZE_SEEK_CURRENT, + SERIALIZE_SEEK_END +}; + +struct serializer { + void *param; + size_t (*serialize)(struct serializer, void *, size_t); + uint64_t (*seek)(struct serializer, int64_t, enum serialize_seek_type); + uint64_t (*getpos)(struct serializer); +}; + +static inline size_t serialize(struct serializer *s, void *data, size_t len) +{ + if (s->serialize) + return s->serialize(s, data, len); + + return 0; +} + +static inline uint64_t serializer_seek(struct serializer *s, int64_t offset, + enum serialize_seek_type seek_type) +{ + if (s->seek) + return s->seek(s, offset, seek_type); + return 0; +} + +static inline uint64_t serializer_getpos(struct serializer *s) +{ + if (s->getpos) + return s->getpos(s); + return 0; +} + +static inline void serializer_write_u8(struct serializer *s, uint8_t u8) +{ + serialize(s, &u8, sizeof(uint8_t)); +} + +static inline void serializer_write_i8(struct serializer *s, int8_t i8) +{ + serialize(s, &i8, sizeof(int8_t)); +} + +static inline void serializer_write_u16(struct serializer *s, uint16_t u16) +{ + serialize(s, &u16, sizeof(uint16_t)); +} + +static inline void serializer_write_i16(struct serializer *s, int16_t i16) +{ + serialize(s, &i16, sizeof(int16_t)); +} + +static inline void serializer_write_u32(struct serializer *s, uint32_t u32) +{ + serialize(s, &u32, sizeof(uint32_t)); +} + +static inline void serializer_write_i32(struct serializer *s, int32_t i32) +{ + serialize(s, &i32, sizeof(int32_t)); +} + +static inline void serializer_write_u64(struct serializer *s, uint32_t u64) +{ + serialize(s, &u64, sizeof(uint64_t)); +} + +static inline void serializer_write_i64(struct serializer *s, int32_t i64) +{ + serialize(s, &i64, sizeof(int64_t)); +} + +static inline void serializer_write_float(struct serializer *s, float f) +{ + serialize(s, &f, sizeof(float)); +} + +static inline void serializer_write_double(struct serializer *s, double d) +{ + serialize(s, &d, sizeof(double)); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/util/text-lookup.c b/libobs/util/text-lookup.c new file mode 100644 index 000000000..863269d37 --- /dev/null +++ b/libobs/util/text-lookup.c @@ -0,0 +1,371 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#include "dstr.h" +#include "darray.h" +#include "text-lookup.h" +#include "lexer.h" +#include "platform.h" + +/* ------------------------------------------------------------------------- */ + +struct text_leaf { + char *lookup, *value; +}; + +static inline void text_leaf_free(struct text_leaf *leaf) +{ + bfree(leaf->lookup); + bfree(leaf->value); +} + +/* ------------------------------------------------------------------------- */ + +struct text_node { + struct dstr str; + struct darray subnodes; /* struct text_node * */ + struct text_leaf *leaf; +}; + +static void text_node_destroy(struct text_node *node) +{ + struct text_node **subnodes; + size_t i; + + if (!node) + return; + + subnodes = node->subnodes.array; + dstr_free(&node->str); + for (i = 0; i < node->subnodes.num; i++) + text_node_destroy(subnodes[i]); + if (node->leaf) + text_leaf_free(node->leaf); + darray_free(&node->subnodes); + bfree(node); +} + +static struct text_node *text_node_bychar(struct text_node *node, char ch) +{ + size_t i; + struct text_node **subnodes = node->subnodes.array; + + for (i = 0; i < node->subnodes.num; i++) { + struct text_node *child = subnodes[i]; + if (!dstr_isempty(&child->str) && child->str.array[0] == ch) + return child; + } + + return NULL; +} + +static struct text_node *text_node_byname(struct text_node *node, + const char *name) +{ + size_t i; + struct text_node **subnodes = node->subnodes.array; + + for (i = 0; i < node->subnodes.num; i++) { + struct text_node *child = subnodes[i]; + if (astrcmpi_n(child->str.array, name, child->str.len) == 0) + return child; + } + + return NULL; +} + +static inline void text_node_removesubnode(struct text_node *node, + struct text_node *child, size_t idx) +{ + darray_erase(sizeof(struct text_node*), &node->subnodes, idx); + text_node_destroy(child); +} + +/* ------------------------------------------------------------------------- */ + +struct text_lookup { + struct dstr language; + struct text_node *top; +}; + +static void lookup_createsubnode(const char *lookup_val, + struct text_leaf *leaf, struct text_node *node) +{ + struct text_node *new = bmalloc(sizeof(struct text_node)); + memset(new, 0, sizeof(struct text_node)); + + new->leaf = leaf; + dstr_copy(&new->str, lookup_val); + + darray_push_back(sizeof(struct text_node*), &new->subnodes, &new); +} + +static void lookup_splitnode(const char *lookup_val, size_t len, + struct text_leaf *leaf, struct text_node *node) +{ + struct text_node *split = bmalloc(sizeof(struct text_node)); + memset(split, 0, sizeof(struct text_node)); + + dstr_copy(&split->str, node->str.array+len); + split->leaf = node->leaf; + darray_move(&split->subnodes, &node->subnodes); + + dstr_resize(&node->str, len); + darray_push_back(sizeof(struct text_node), &node->subnodes, &split); + + if (lookup_val[len] != 0) { + node->leaf = NULL; + lookup_createsubnode(lookup_val+len, leaf, node); + } else { + node->leaf = leaf; + } +} + +static bool lookup_addstring(const char *lookup_val, struct text_leaf *leaf, + struct text_node *node) +{ + struct text_node *child; + + if (!lookup_val || !*lookup_val) + return false; + + child = text_node_bychar(node, *lookup_val); + if (child) { + size_t len; + + for (len = 0; len < child->str.len; len++) { + char val1 = child->str.array[len], + val2 = lookup_val[len]; + + if (val1 >= 'A' && val1 <= 'Z') + val1 += 0x20; + if (val2 >= 'A' && val2 <= 'Z') + val2 += 0x20; + + if (val1 != val2) + break; + } + + if (len == child->str.len) + return lookup_addstring(lookup_val+len, leaf, child); + else + lookup_splitnode(lookup_val, len, leaf, child); + } else { + lookup_createsubnode(lookup_val, leaf, child); + } + + return true; +} + +static void lookup_getstringtoken(struct lexer *lex, struct strref *token) +{ + const char *temp = lex->offset; + bool was_backslash = false; + + while (*temp != 0 && *temp != '\n') { + if (!was_backslash) { + if (*temp == '\\') { + was_backslash = true; + } else if (*temp == '"') { + ++temp; + break; + } + } else { + was_backslash = false; + } + + ++temp; + } + + token->len += temp - lex->offset - 1; /* include starting " char */ + lex->offset = temp; +} + +static bool lookup_gettoken(struct lexer *lex, struct strref *str) +{ + struct base_token temp; + + base_token_clear(&temp); + strref_clear(str); + + while (lexer_getbasetoken(lex, &temp, false)) { + char ch = *temp.text.array; + + if (!str->array) { + /* comments are designated with a #, and end at LF */ + if (ch == '#') { + while(ch != '\n' && ch != 0) + ch = *(++lex->offset); + } else { + strref_copy(str, &temp.text); + } + } else { + if (temp.type == BASETOKEN_WHITESPACE) { + lex->offset -= temp.text.len; + break; + } + + if (ch == '"') { + lookup_getstringtoken(lex, str); + break; + } else if (ch == '#') { + lex->offset--; + break; + } + + str->len += temp.text.len; + } + } + + return (str->len != 0); +} + +static inline bool lookup_goto_nextline(struct lexer *p) +{ + struct strref val; + bool success = true; + + strref_clear(&val); + + while (true) { + if (!lookup_gettoken(p, &val)) { + success = false; + break; + } + if (*val.array == '\n') + break; + } + + return success; +} + +static void lookup_addfiledata(struct text_lookup *lookup, + const char *file_data) +{ + struct lexer lex; + struct strref name, value; + + lexer_start(&lex, file_data); + strref_clear(&name); + strref_clear(&value); + + while (lookup_gettoken(&lex, &name)) { + struct text_leaf *leaf; + bool got_eq = false; + + if (*name.array == '\n') + continue; +getval: + if (!lookup_gettoken(&lex, &value)) + break; + if (*value.array == '\n') + continue; + else if (!got_eq && *value.array == '=') { + got_eq = true; + goto getval; + } + + leaf = bmalloc(sizeof(struct text_leaf)); + leaf->lookup = bstrdup_n(name.array, name.len); + leaf->value = bstrdup_n(value.array, value.len); + + lookup_addstring(leaf->lookup, leaf, lookup->top); + + if (!lookup_goto_nextline(&lex)) + break; + } +} + +static inline bool lookup_getstring(const char *lookup_val, + const char **out, struct text_node *node) +{ + struct text_node *child; + char ch; + + if (!node) + return false; + + child = text_node_byname(node, lookup_val); + if (!child) + return false; + + lookup_val += child->str.len; + ch = *lookup_val; + if (ch) + return lookup_getstring(lookup_val, out, child); + + if (!child->leaf) + return false; + + *out = child->leaf->value; + return true; +} + +/* ------------------------------------------------------------------------- */ + +lookup_t text_lookup_create(const char *path) +{ + struct text_lookup *lookup; + struct dstr file_str; + char *temp = NULL; + FILE *file; + + file = os_fopen(path, "rb"); + if (!file) + return NULL; + + os_fread_utf8(file, &temp); + dstr_init_move_array(&file_str, temp); + fclose(file); + + if (!file_str.array) + return NULL; + + lookup = bmalloc(sizeof(struct text_lookup)); + memset(lookup, 0, sizeof(struct text_lookup)); + + lookup->top = bmalloc(sizeof(struct text_node)); + memset(lookup->top, 0, sizeof(struct text_node)); + + dstr_replace(&file_str, "\r", " "); + lookup_addfiledata(lookup, file_str.array); + dstr_free(&file_str); + + return lookup; +} + +void text_lookup_destroy(lookup_t lookup) +{ + if (lookup) { + dstr_free(&lookup->language); + text_node_destroy(lookup->top); + + bfree(lookup); + } +} + +bool text_lookup_getstr(lookup_t lookup, const char *lookup_val, + const char **out) +{ + return lookup_getstring(lookup_val, out, lookup->top); +} diff --git a/libobs/util/text-lookup.h b/libobs/util/text-lookup.h new file mode 100644 index 000000000..9367dd4f5 --- /dev/null +++ b/libobs/util/text-lookup.h @@ -0,0 +1,55 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifndef TEXT_LOOKUP_H +#define TEXT_LOOKUP_H + +/* + * Text Lookup interface + * + * Used for storing and looking up localized strings. Stores locazation + * strings in a radix/trie tree to efficiently look up associated strings via a + * unique string identifier name. + */ + +#include "c99defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* opaque typdef */ +struct text_lookup; +typedef struct text_lookup *lookup_t; + +/* functions */ +EXPORT lookup_t text_lookup_create(const char *path); +EXPORT void text_lookup_destroy(lookup_t lookup); +EXPORT bool text_lookup_getstr(lookup_t lookup, const char *lookup_val, + const char **out); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/util/threading.h b/libobs/util/threading.h new file mode 100644 index 000000000..fef9458b6 --- /dev/null +++ b/libobs/util/threading.h @@ -0,0 +1,133 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#ifndef BASE_THREADING_H +#define BASE_THREADING_H + +/* + * Allows posix thread usage on windows as well as other operating systems. + * Use this header if you want to make your code more platform independent. + * + * Also provides a custom platform-independent "event" handler via + * pthread conditional waits. + */ + +#include "c99defs.h" + +#ifdef _MSC_VER +#include "../../w32-pthreads/pthread.h" +#include "../../w32-pthreads/semaphore.h" +#else +#include +#include +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +struct event_data { + pthread_mutex_t mutex; + pthread_cond_t cond; + bool signalled; + bool manual; +}; + +typedef struct event_data event_t; + +static inline int event_init(event_t *event, bool manual) +{ + int code = 0; + + if ((code = pthread_mutex_init(&event->mutex, NULL)) < 0) + return code; + + if ((code = pthread_cond_init(&event->cond, NULL)) < 0) + pthread_mutex_destroy(&event->mutex); + + event->manual = manual; + event->signalled = false; + + return code; +} + +static inline void event_destroy(event_t *event) +{ + if (event) { + pthread_mutex_destroy(&event->mutex); + pthread_cond_destroy(&event->cond); + } +} + +static inline int event_wait(event_t *event) +{ + int code = 0; + pthread_mutex_lock(&event->mutex); + if ((code = pthread_cond_wait(&event->cond, &event->mutex)) == 0) { + if (!event->manual) + event->signalled = false; + pthread_mutex_unlock(&event->mutex); + } + + return code; +} + +static inline int event_try(event_t *event) +{ + pthread_mutex_lock(&event->mutex); + if (event->signalled) { + if (!event->manual) + event->signalled = false; + pthread_mutex_unlock(&event->mutex); + return 0; + } + pthread_mutex_unlock(&event->mutex); + + return EAGAIN; +} + +static inline int event_signal(event_t *event) +{ + int code = 0; + + pthread_mutex_lock(&event->mutex); + code = pthread_cond_signal(&event->cond); + event->signalled = true; + pthread_mutex_unlock(&event->mutex); + + return code; +} + +static inline void event_reset(event_t *event) +{ + pthread_mutex_lock(&event->mutex); + event->signalled = false; + pthread_mutex_unlock(&event->mutex); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libobs/util/utf8.c b/libobs/util/utf8.c new file mode 100644 index 000000000..2fb790345 --- /dev/null +++ b/libobs/util/utf8.c @@ -0,0 +1,320 @@ +/* + * Copyright (c) 2007 Alexey Vatchenko + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ +#include + +#include "utf8.h" + +#define _NXT 0x80 +#define _SEQ2 0xc0 +#define _SEQ3 0xe0 +#define _SEQ4 0xf0 +#define _SEQ5 0xf8 +#define _SEQ6 0xfc + +#define _BOM 0xfeff + +static int wchar_forbidden(wchar_t sym); +static int utf8_forbidden(unsigned char octet); + +static int wchar_forbidden(wchar_t sym) +{ + /* Surrogate pairs */ + if (sym >= 0xd800 && sym <= 0xdfff) + return -1; + + return 0; +} + +static int utf8_forbidden(unsigned char octet) +{ + switch (octet) { + case 0xc0: + case 0xc1: + case 0xf5: + case 0xff: + return -1; + } + + return 0; +} + +/* + * DESCRIPTION + * This function translates UTF-8 string into UCS-4 string (all symbols + * will be in local machine byte order). + * + * It takes the following arguments: + * in - input UTF-8 string. It can be null-terminated. + * insize - size of input string in bytes. If insize is 0, + * function continues until a null terminator is reached. + * out - result buffer for UCS-4 string. If out is NULL, + * function returns size of result buffer. + * outsize - size of out buffer in wide characters. + * + * RETURN VALUES + * The function returns size of result buffer (in wide characters). + * Zero is returned in case of error. + * + * CAVEATS + * 1. If UTF-8 string contains zero symbols, they will be translated + * as regular symbols. + * 2. If UTF8_IGNORE_ERROR or UTF8_SKIP_BOM flag is set, sizes may vary + * when `out' is NULL and not NULL. It's because of special UTF-8 + * sequences which may result in forbidden (by RFC3629) UNICODE + * characters. So, the caller must check return value every time and + * not prepare buffer in advance (\0 terminate) but after calling this + * function. + */ +size_t utf8_to_wchar(const char *in, size_t insize, wchar_t *out, + size_t outsize, int flags) +{ + unsigned char *p, *lim; + wchar_t *wlim, high; + size_t n, total, i, n_bits; + + if (in == NULL || (outsize == 0 && out != NULL)) + return 0; + + total = 0; + p = (unsigned char *)in; + lim = (insize != 0) ? (p + insize) : (unsigned char*)-1; + wlim = out + outsize; + + for (; p < lim; p += n) { + if (!*p) + break; + + if (utf8_forbidden(*p) != 0 && + (flags & UTF8_IGNORE_ERROR) == 0) + return 0; + + /* + * Get number of bytes for one wide character. + */ + n = 1; /* default: 1 byte. Used when skipping bytes. */ + if ((*p & 0x80) == 0) + high = (wchar_t)*p; + else if ((*p & 0xe0) == _SEQ2) { + n = 2; + high = (wchar_t)(*p & 0x1f); + } else if ((*p & 0xf0) == _SEQ3) { + n = 3; + high = (wchar_t)(*p & 0x0f); + } else if ((*p & 0xf8) == _SEQ4) { + n = 4; + high = (wchar_t)(*p & 0x07); + } else if ((*p & 0xfc) == _SEQ5) { + n = 5; + high = (wchar_t)(*p & 0x03); + } else if ((*p & 0xfe) == _SEQ6) { + n = 6; + high = (wchar_t)(*p & 0x01); + } else { + if ((flags & UTF8_IGNORE_ERROR) == 0) + return 0; + continue; + } + + /* does the sequence header tell us truth about length? */ + if ((size_t)(lim - p) <= n - 1) { + if ((flags & UTF8_IGNORE_ERROR) == 0) + return 0; + n = 1; + continue; /* skip */ + } + + /* + * Validate sequence. + * All symbols must have higher bits set to 10xxxxxx + */ + if (n > 1) { + for (i = 1; i < n; i++) { + if ((p[i] & 0xc0) != _NXT) + break; + } + if (i != n) { + if ((flags & UTF8_IGNORE_ERROR) == 0) + return 0; + n = 1; + continue; /* skip */ + } + } + + total++; + + if (out == NULL) + continue; + + if (out >= wlim) + return 0; /* no space left */ + + *out = 0; + n_bits = 0; + for (i = 1; i < n; i++) { + *out |= (wchar_t)(p[n - i] & 0x3f) << n_bits; + n_bits += 6; /* 6 low bits in every byte */ + } + *out |= high << n_bits; + + if (wchar_forbidden(*out) != 0) { + if ((flags & UTF8_IGNORE_ERROR) == 0) + return 0; /* forbidden character */ + else { + total--; + out--; + } + } else if (*out == _BOM && (flags & UTF8_SKIP_BOM) != 0) { + total--; + out--; + } + + out++; + } + + return total; +} + +/* + * DESCRIPTION + * This function translates UCS-4 symbols (given in local machine + * byte order) into UTF-8 string. + * + * It takes the following arguments: + * in - input unicode string. It can be null-terminated. + * insize - size of input string in wide characters. If insize is 0, + * function continues until a null terminator is reaches. + * out - result buffer for utf8 string. If out is NULL, + * function returns size of result buffer. + * outsize - size of result buffer. + * + * RETURN VALUES + * The function returns size of result buffer (in bytes). Zero is returned + * in case of error. + * + * CAVEATS + * If UCS-4 string contains zero symbols, they will be translated + * as regular symbols. + */ +size_t wchar_to_utf8(const wchar_t *in, size_t insize, char *out, + size_t outsize, int flags) +{ + wchar_t *w, *wlim, ch = 0; + unsigned char *p, *lim, *oc; + size_t total, n; + + if (in == NULL || (outsize == 0 && out != NULL)) + return 0; + + w = (wchar_t *)in; + wlim = (insize != 0) ? (w + insize) : (wchar_t*)-1; + p = (unsigned char *)out; + lim = p + outsize; + total = 0; + + for (; w < wlim; w++) { + if (!*w) + break; + + if (wchar_forbidden(*w) != 0) { + if ((flags & UTF8_IGNORE_ERROR) == 0) + return 0; + else + continue; + } + + if (*w == _BOM && (flags & UTF8_SKIP_BOM) != 0) + continue; + + if (*w < 0) { + if ((flags & UTF8_IGNORE_ERROR) == 0) + return 0; + continue; + } else if (*w <= 0x0000007f) + n = 1; + else if (*w <= 0x000007ff) + n = 2; + else if (*w <= 0x0000ffff) + n = 3; + else if (*w <= 0x001fffff) + n = 4; + else if (*w <= 0x03ffffff) + n = 5; + else /* if (*w <= 0x7fffffff) */ + n = 6; + + total += n; + + if (out == NULL) + continue; + + if ((size_t)(lim - p) <= n - 1) + return 0; /* no space left */ + + ch = *w; + oc = (unsigned char *)&ch; + switch (n) { + case 1: + *p = oc[0]; + break; + + case 2: + p[1] = _NXT | (oc[0] & 0x3f); + p[0] = _SEQ2 | (oc[0] >> 6) | ((oc[1] & 0x07) << 2); + break; + + case 3: + p[2] = _NXT | (oc[0] & 0x3f); + p[1] = _NXT | (oc[0] >> 6) | ((oc[1] & 0x0f) << 2); + p[0] = _SEQ3 | ((oc[1] & 0xf0) >> 4); + break; + + case 4: + p[3] = _NXT | (oc[0] & 0x3f); + p[2] = _NXT | (oc[0] >> 6) | ((oc[1] & 0x0f) << 2); + p[1] = _NXT | ((oc[1] & 0xf0) >> 4) | + ((oc[2] & 0x03) << 4); + p[0] = _SEQ4 | ((oc[2] & 0x1f) >> 2); + break; + + case 5: + p[4] = _NXT | (oc[0] & 0x3f); + p[3] = _NXT | (oc[0] >> 6) | ((oc[1] & 0x0f) << 2); + p[2] = _NXT | ((oc[1] & 0xf0) >> 4) | + ((oc[2] & 0x03) << 4); + p[1] = _NXT | (oc[2] >> 2); + p[0] = _SEQ5 | (oc[3] & 0x03); + break; + + case 6: + p[5] = _NXT | (oc[0] & 0x3f); + p[4] = _NXT | (oc[0] >> 6) | ((oc[1] & 0x0f) << 2); + p[3] = _NXT | (oc[1] >> 4) | ((oc[2] & 0x03) << 4); + p[2] = _NXT | (oc[2] >> 2); + p[1] = _NXT | (oc[3] & 0x3f); + p[0] = _SEQ6 | ((oc[3] & 0x40) >> 6); + break; + } + + /* + * NOTE: do not check here for forbidden UTF-8 characters. + * They cannot appear here because we do proper convertion. + */ + + p += n; + } + + return total; +} diff --git a/libobs/util/utf8.h b/libobs/util/utf8.h new file mode 100644 index 000000000..c289106ff --- /dev/null +++ b/libobs/util/utf8.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2007 Alexey Vatchenko + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* + * utf8: implementation of UTF-8 charset encoding (RFC3629). + */ +#ifndef _UTF8_H_ +#define _UTF8_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#define UTF8_IGNORE_ERROR 0x01 +#define UTF8_SKIP_BOM 0x02 + +size_t utf8_to_wchar(const char *in, size_t insize, wchar_t *out, + size_t outsize, int flags); +size_t wchar_to_utf8(const wchar_t *in, size_t insize, char *out, + size_t outsize, int flags); + +#ifdef __cplusplus +} +#endif + +#endif /* !_UTF8_H_ */ diff --git a/libobs/util/vc/stdbool.h b/libobs/util/vc/stdbool.h new file mode 100644 index 000000000..b9f1c5009 --- /dev/null +++ b/libobs/util/vc/stdbool.h @@ -0,0 +1,12 @@ +#ifndef _STDBOOL_H +#define _STDBOOL_H + +#if !defined(__cplusplus) +typedef int8_t _Bool; +#define bool _Bool +#define true 1 +#define false 0 +#define __bool_true_false_are_defined 1 +#endif + +#endif diff --git a/libobs/util/vc/stdint.h b/libobs/util/vc/stdint.h new file mode 100644 index 000000000..bfc8f5aa0 --- /dev/null +++ b/libobs/util/vc/stdint.h @@ -0,0 +1,204 @@ +/* ISO C9x 7.18 Integer types + * Based on ISO/IEC SC22/WG14 9899 Committee draft (SC22 N2794) + * + * THIS SOFTWARE IS NOT COPYRIGHTED + * + * Contributor: Danny Smith + * + * This source code is offered for use in the public domain. You may + * use, modify or distribute it freely. + * + * This code is distributed in the hope that it will be useful but + * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY + * DISCLAIMED. This includes but is not limited to warranties of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * Date: 2000-12-02 + */ + +#ifndef _STDINT_H +#define _STDINT_H +#define __need_wint_t +#define __need_wchar_t +#include + +/* 7.18.1.1 Exact-width integer types */ +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef short int16_t; +typedef unsigned short uint16_t; +typedef int int32_t; +typedef unsigned uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; + +/* 7.18.1.2 Minimum-width integer types */ +typedef signed char int_least8_t; +typedef unsigned char uint_least8_t; +typedef short int_least16_t; +typedef unsigned short uint_least16_t; +typedef int int_least32_t; +typedef unsigned uint_least32_t; +typedef __int64 int_least64_t; +typedef unsigned __int64 uint_least64_t; + +/* 7.18.1.3 Fastest minimum-width integer types + * Not actually guaranteed to be fastest for all purposes + * Here we use the exact-width types for 8 and 16-bit ints. + */ +typedef char int_fast8_t; +typedef unsigned char uint_fast8_t; +typedef short int_fast16_t; +typedef unsigned short uint_fast16_t; +typedef int int_fast32_t; +typedef unsigned int uint_fast32_t; +typedef __int64 int_fast64_t; +typedef unsigned __int64 uint_fast64_t; + +/* 7.18.1.4 Integer types capable of holding object pointers */ +/*typedef int intptr_t; +typedef unsigned uintptr_t;*/ + +/* 7.18.1.5 Greatest-width integer types */ +typedef __int64 intmax_t; +typedef unsigned __int64 uintmax_t; + +/* 7.18.2 Limits of specified-width integer types */ +#if !defined ( __cplusplus) || defined (__STDC_LIMIT_MACROS) + +/* 7.18.2.1 Limits of exact-width integer types */ +#define INT8_MIN (-128) +#define INT16_MIN (-32768) +#define INT32_MIN (-2147483647 - 1) +#define INT64_MIN (-9223372036854775807LL - 1) + +#define INT8_MAX 127 +#define INT16_MAX 32767 +#define INT32_MAX 2147483647 +#define INT64_MAX 9223372036854775807LL + +#define UINT8_MAX 0xff /* 255U */ +#define UINT16_MAX 0xffff /* 65535U */ +#define UINT32_MAX 0xffffffff /* 4294967295U */ +#define UINT64_MAX 0xffffffffffffffffULL /* 18446744073709551615ULL */ + +/* 7.18.2.2 Limits of minimum-width integer types */ +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST64_MIN INT64_MIN + +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MAX INT64_MAX + +#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST16_MAX UINT16_MAX +#define UINT_LEAST32_MAX UINT32_MAX +#define UINT_LEAST64_MAX UINT64_MAX + +/* 7.18.2.3 Limits of fastest minimum-width integer types */ +#define INT_FAST8_MIN INT8_MIN +#define INT_FAST16_MIN INT16_MIN +#define INT_FAST32_MIN INT32_MIN +#define INT_FAST64_MIN INT64_MIN + +#define INT_FAST8_MAX INT8_MAX +#define INT_FAST16_MAX INT16_MAX +#define INT_FAST32_MAX INT32_MAX +#define INT_FAST64_MAX INT64_MAX + +#define UINT_FAST8_MAX UINT8_MAX +#define UINT_FAST16_MAX UINT16_MAX +#define UINT_FAST32_MAX UINT32_MAX +#define UINT_FAST64_MAX UINT64_MAX + +/* 7.18.2.4 Limits of integer types capable of holding + object pointers */ +#if defined(_WIN64) || defined(__LP64__) +#define INTPTR_MIN INT64_MIN +#define INTPTR_MAX INT64_MAX +#define UINTPTR_MAX UINT64_MAX +#else +#define INTPTR_MIN INT32_MIN +#define INTPTR_MAX INT32_MAX +#define UINTPTR_MAX UINT32_MAX +#endif + +/* 7.18.2.5 Limits of greatest-width integer types */ +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX + +/* 7.18.3 Limits of other integer types */ +#if defined(_WIN64) || defined(__LP64__) +#define PTRDIFF_MIN INT64_MIN +#define PTRDIFF_MAX INT64_MAX +#else +#define PTRDIFF_MIN INT32_MIN +#define PTRDIFF_MAX INT32_MAX +#endif + +#define SIG_ATOMIC_MIN INT32_MIN +#define SIG_ATOMIC_MAX INT32_MAX + +#ifndef SIZE_MAX +#if defined(_WIN64) || defined(__LP64__) +#define SIZE_MAX UINT64_MAX +#else +#define SIZE_MAX UINT32_MAX +#endif +#endif + +#if 0 +#ifndef WCHAR_MIN /* also in wchar.h */ +#define WCHAR_MIN 0 +#define WCHAR_MAX ((wchar_t)-1) /* UINT16_MAX */ +#endif +#endif + +/* + * wint_t is unsigned short for compatibility with MS runtime + */ +#define WINT_MIN 0 +#define WINT_MAX ((wint_t)-1) /* UINT16_MAX */ + +#endif /* !defined ( __cplusplus) || defined __STDC_LIMIT_MACROS */ + + +/* 7.18.4 Macros for integer constants */ +#if !defined ( __cplusplus) || defined (__STDC_CONSTANT_MACROS) + +/* 7.18.4.1 Macros for minimum-width integer constants + + Accoding to Douglas Gwyn : + "This spec was changed in ISO/IEC 9899:1999 TC1; in ISO/IEC + 9899:1999 as initially published, the expansion was required + to be an integer constant of precisely matching type, which + is impossible to accomplish for the shorter types on most + platforms, because C99 provides no standard way to designate + an integer constant with width less than that of type int. + TC1 changed this to require just an integer constant + *expression* with *promoted* type." + + The trick used here is from Clive D W Feather. +*/ + +#define INT8_C(val) (INT_LEAST8_MAX-INT_LEAST8_MAX+(val)) +#define INT16_C(val) (INT_LEAST16_MAX-INT_LEAST16_MAX+(val)) +#define INT32_C(val) (INT_LEAST32_MAX-INT_LEAST32_MAX+(val)) +#define INT64_C(val) (INT_LEAST64_MAX-INT_LEAST64_MAX+(val)) + +#define UINT8_C(val) (UINT_LEAST8_MAX-UINT_LEAST8_MAX+(val)) +#define UINT16_C(val) (UINT_LEAST16_MAX-UINT_LEAST16_MAX+(val)) +#define UINT32_C(val) (UINT_LEAST32_MAX-UINT_LEAST32_MAX+(val)) +#define UINT64_C(val) (UINT_LEAST64_MAX-UINT_LEAST64_MAX+(val)) + +/* 7.18.4.2 Macros for greatest-width integer constants */ +#define INTMAX_C(val) (INTMAX_MAX-INTMAX_MAX+(val)) +#define UINTMAX_C(val) (UINTMAX_MAX-UINTMAX_MAX+(val)) + +#endif /* !defined ( __cplusplus) || defined __STDC_CONSTANT_MACROS */ + +#endif diff --git a/libobs/util/windows/ComPtr.hpp b/libobs/util/windows/ComPtr.hpp new file mode 100644 index 000000000..93451ac0c --- /dev/null +++ b/libobs/util/windows/ComPtr.hpp @@ -0,0 +1,92 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#pragma once + +template class ComPtr { + T *ptr; + + inline void Kill() + { + if (ptr) + ptr->Release(); + } + + inline void Replace(T *p) + { + if (ptr != p) { + if (p) p->AddRef(); + if (ptr) ptr->Release(); + ptr = p; + } + } + +public: + inline ComPtr() : ptr(NULL) {} + inline ComPtr(T *p) : ptr(p) {if (ptr) ptr->AddRef();} + inline ComPtr(const ComPtr &c) : ptr(c.ptr) {if (ptr) ptr->AddRef();} + inline ComPtr(ComPtr &&c) : ptr(c.ptr) {c.ptr = NULL;} + inline ~ComPtr() {Kill();} + + inline void Clear() + { + if (ptr) { + ptr->Release(); + ptr = NULL; + } + } + + inline ComPtr &operator=(T *p) + { + Replace(p); + return *this; + } + + inline ComPtr &operator=(const ComPtr &c) + { + Replace(c.ptr); + return *this; + } + + inline ComPtr &operator=(ComPtr &&c) + { + if (this != &c) { + Kill(); + ptr = c.ptr; + c.ptr = NULL; + } + + return *this; + } + + inline T **Assign() {Clear(); return &ptr;} + inline void Set(T *p) {Kill(); ptr = p;} + + inline operator T*() const {return ptr;} + inline T *operator->() const {return ptr;} + + inline bool operator==(T *p) const {return ptr == p;} + inline bool operator!=(T *p) const {return ptr != p;} + + inline bool operator!() const {return !ptr;} +}; diff --git a/libobs/util/windows/HRError.hpp b/libobs/util/windows/HRError.hpp new file mode 100644 index 000000000..a0bb09317 --- /dev/null +++ b/libobs/util/windows/HRError.hpp @@ -0,0 +1,34 @@ +/****************************************************************************** + Copyright (c) 2013 by Hugh Bailey + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +******************************************************************************/ + +#pragma once + +struct HRError { + const char *str; + HRESULT hr; + + inline HRError(const char *str, HRESULT hr) + : str(str), hr (hr) + { + } +}; diff --git a/makefile b/makefile new file mode 100644 index 000000000..94a63b871 --- /dev/null +++ b/makefile @@ -0,0 +1,13 @@ +include config.mak + +all: default + +PROJECTS=libobs test + +.PHONY: all default clean + +default: $(PROJECTS) + @$(foreach PROJECT, $(PROJECTS), $(MAKE) -C $(PROJECT);) + +clean: $(PROJECTS) + @$(foreach PROJECT, $(PROJECTS), $(MAKE) clean -C $(PROJECT);) diff --git a/test/makefile b/test/makefile new file mode 100644 index 000000000..e89894583 --- /dev/null +++ b/test/makefile @@ -0,0 +1,13 @@ +include ../config.mak + +all: default + +PROJECTS=test-input win + +.PHONY: all default clean + +default: $(PROJECTS) + @$(foreach PROJECT, $(PROJECTS), $(MAKE) -C $(PROJECT);) + +clean: $(PROJECTS) + @$(foreach PROJECT, $(PROJECTS), $(MAKE) clean -C $(PROJECT);) diff --git a/test/test-input/makefile b/test/test-input/makefile new file mode 100644 index 000000000..d23faaeb4 --- /dev/null +++ b/test/test-input/makefile @@ -0,0 +1,33 @@ +include ../../config.mak + +.PHONY: all default clean + +all: default + +SRCFILES=test-filter.c test-input.c test-random.c + +SONAME=../../build/test-input.$(SOEXT) + +OBJS += $(SRCFILES:%.c=%.$(OBJ)) + +CPPFLAGS += -iquote../../libobs +LDFLAGS += -L../../build -lobs + +default: $(SONAME) + +.depend: + @rm -f .depend + @$(foreach SRC, $(addprefix $(SRCPATH)/, $(SRCFILES)), $(CCDEP) \ + $(CPPFLAGS) $(SRC) \ + -MT $(SRC:$(SRCPATH)/%.c=%.$(OBJ)) -MM 1>> .depend;) + +$(SONAME): .depend $(OBJS) + $(LD)$@ $(LDFLAGS) $(OBJS) + +depend: .depend +ifneq ($(wildcard .depend),) +include .depend +endif + +clean: + rm -f $(OBJS) $(SONAME) *.a *.lib *.exp *.pdb .depend diff --git a/test/test-input/test-filter.c b/test/test-input/test-filter.c new file mode 100644 index 000000000..4f257813b --- /dev/null +++ b/test/test-input/test-filter.c @@ -0,0 +1,68 @@ +#include "test-filter.h" + +struct test_filter *test_create(const char *settings, source_t source) +{ + struct test_filter *tf = bmalloc(sizeof(struct test_filter)); + memset(tf, 0, sizeof(struct test_filter)); + + tf->source = source; + tf->whatever = gs_create_effect_from_file("test.effect", NULL); + if (!tf->whatever) { + test_destroy(tf); + return NULL; + } + + tf->texrender = texrender_create(GS_RGBA, GS_ZS_NONE); + + return tf; +} + +void test_destroy(struct test_filter *tf) +{ + if (tf) { + effect_destroy(tf->whatever); + texrender_destroy(tf->texrender); + bfree(tf); + } +} + +uint32_t test_get_output_flags(struct test_filter *tf) +{ + return SOURCE_VIDEO; +} + +void test_video_tick(struct test_filter *tf, float seconds) +{ + texrender_reset(tf->texrender); +} + +void test_video_render(struct test_filter *tf) +{ + source_t filter_target = filter_gettarget(tf->source); + int cx = source_getwidth(filter_target); + int cy = source_getheight(filter_target); + float fcx = (float)cx; + float fcy = (float)cy; + technique_t tech; + texture_t tex; + + if (texrender_begin(tf->texrender, cx, cy)) { + gs_ortho(0.0f, fcx, 0.0f, fcy, -100.0f, 100.0f); + source_video_render(filter_target); + texrender_end(tf->texrender); + } + + /* --------------------------- */ + + tex = texrender_gettexture(tf->texrender); + tech = effect_gettechnique(tf->whatever, "Default"); + effect_settexture(tf->whatever, effect_getparambyidx(tf->whatever, 1), + tex); + technique_begin(tech); + technique_beginpass(tech, 0); + + gs_draw_sprite(tex); + + technique_endpass(tech); + technique_end(tech); +} diff --git a/test/test-input/test-filter.h b/test/test-input/test-filter.h new file mode 100644 index 000000000..b9811db77 --- /dev/null +++ b/test/test-input/test-filter.h @@ -0,0 +1,27 @@ +#ifndef FILTER_TEST_H +#define FILTER_TEST_H + +#include "obs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct test_filter { + source_t source; + effect_t whatever; + texrender_t texrender; +}; + +EXPORT struct test_filter *test_create(const char *settings, source_t source); +EXPORT void test_destroy(struct test_filter *rt); +EXPORT uint32_t test_get_output_flags(struct test_filter *rt); + +EXPORT void test_video_tick(struct test_filter *rt, float seconds); +EXPORT void test_video_render(struct test_filter *rt); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/test/test-input/test-input-exports.h b/test/test-input/test-input-exports.h new file mode 100644 index 000000000..da410e6e0 --- /dev/null +++ b/test/test-input/test-input-exports.h @@ -0,0 +1,17 @@ +#ifndef OBS_CAPTURE_EXPORTS_H +#define OBS_CAPTURE_EXPORTS_H + +#include "util/c99defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +EXPORT bool enum_inputs(size_t idx, const char **name); +EXPORT bool enum_filters(size_t idx, const char **name); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/test/test-input/test-input.c b/test/test-input/test-input.c new file mode 100644 index 000000000..9d7aaf16b --- /dev/null +++ b/test/test-input/test-input.c @@ -0,0 +1,22 @@ +#include "test-input-exports.h" + +const char *inputs[] = {"random"}; +const char *filters[] = {"test"}; + +bool enum_inputs(size_t idx, const char **name) +{ + if (idx >= (sizeof(inputs)/sizeof(const char*))) + return false; + + *name = inputs[idx]; + return true; +} + +bool enum_filters(size_t idx, const char **name) +{ + if (idx >= (sizeof(filters)/sizeof(const char*))) + return false; + + *name = filters[idx]; + return true; +} diff --git a/test/test-input/test-random.c b/test/test-input/test-random.c new file mode 100644 index 000000000..30eade111 --- /dev/null +++ b/test/test-input/test-random.c @@ -0,0 +1,74 @@ +#include +#include "test-random.h" + +struct random_tex *random_create(const char *settings, source_t source) +{ + struct random_tex *rt = bmalloc(sizeof(struct random_tex)); + uint32_t *pixels = bmalloc(20*20*4); + size_t x, y; + + memset(rt, 0, sizeof(struct random_tex)); + + for (y = 0; y < 20; y++) { + for (x = 0; x < 20; x++) { + uint32_t pixel = 0xFF000000; + pixel |= (rand()%256); + pixel |= (rand()%256) << 8; + pixel |= (rand()%256) << 16; + pixels[y*20 + x] = pixel; + } + } + + rt->texture = gs_create_texture(20, 20, GS_RGBA, pixels, 0); + bfree(pixels); + + if (!rt->texture) { + random_destroy(rt); + return NULL; + } + + rt->whatever = gs_create_effect_from_file("draw.effect", NULL); + if (!rt->whatever) { + random_destroy(rt); + return NULL; + } + + return rt; +} + +void random_destroy(struct random_tex *rt) +{ + if (rt) { + effect_destroy(rt->whatever); + texture_destroy(rt->texture); + bfree(rt); + } +} + +uint32_t random_get_output_flags(struct random_tex *rt) +{ + return SOURCE_VIDEO; +} + +void random_video_render(struct random_tex *rt, source_t filter_target) +{ + technique_t tech = effect_gettechnique(rt->whatever, "Default"); + effect_settexture(rt->whatever, effect_getparambyidx(rt->whatever, 1), rt->texture); + technique_begin(tech); + technique_beginpass(tech, 0); + + gs_draw_sprite(rt->texture); + + technique_endpass(tech); + technique_end(tech); +} + +int random_getwidth(struct random_tex *rt) +{ + return texture_getwidth(rt->texture); +} + +int random_getheight(struct random_tex *rt) +{ + return texture_getheight(rt->texture); +} diff --git a/test/test-input/test-random.h b/test/test-input/test-random.h new file mode 100644 index 000000000..4204eafc2 --- /dev/null +++ b/test/test-input/test-random.h @@ -0,0 +1,28 @@ +#ifndef RANDOM_TEX_H +#define RANDOM_TEX_H + +#include "obs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct random_tex { + texture_t texture; + effect_t whatever; +}; + +EXPORT struct random_tex *random_create(const char *settings, source_t source); +EXPORT void random_destroy(struct random_tex *rt); +EXPORT uint32_t random_get_output_flags(struct random_tex *rt); + +EXPORT void random_video_render(struct random_tex *rt, source_t filter_target); + +EXPORT int random_getwidth(struct random_tex *rt); +EXPORT int random_getheight(struct random_tex *rt); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/test/win/makefile b/test/win/makefile new file mode 100644 index 000000000..a1ac2ec3d --- /dev/null +++ b/test/win/makefile @@ -0,0 +1,35 @@ +include ../../config.mak + +.PHONY: all default clean + +all: default + +SRCFILES=test.cpp + +NAME=../../build/wintest$(EXT) + +OBJS += $(SRCFILES:%.cpp=%.$(OBJ)) + +LD=g++ -o +LDFLAGS=-L../../build -lobs -Wl,--subsystem,windows + +CPPFLAGS += -I../../libobs -DUNICODE -D_UNICODE + +default: $(NAME) + +.depend: + @rm -f .depend + @$(foreach SRC, $(addprefix $(SRCPATH)/, $(SRCFILES)), $(CCDEP) \ + $(CPPFLAGS) $(SRC) \ + -MT $(SRC:$(SRCPATH)/%.c=%.$(OBJ)) -MM 1>> .depend;) + +$(NAME): .depend $(OBJS) + $(LD)$@ $(LDFLAGS) $(OBJS) + +depend: .depend +ifneq ($(wildcard .depend),) +include .depend +endif + +clean: + rm -f $(OBJS) $(NAME) *.a *.lib *.exp *.pdb .depend diff --git a/test/win/test.cpp b/test/win/test.cpp new file mode 100644 index 000000000..87c3db8d5 --- /dev/null +++ b/test/win/test.cpp @@ -0,0 +1,201 @@ +#include +#include +#include + +#include "util/base.h" +#include "obs.h" + +static const int cx = 800; +static const int cy = 600; + +/* --------------------------------------------------- */ + +class OBSContext { + obs_t obs; + +public: + inline OBSContext(obs_t obs) : obs(obs) {} + inline ~OBSContext() {obs_destroy(obs);} + inline operator obs_t() {return obs;} +}; + +/* --------------------------------------------------- */ + +class SourceContext { + source_t source; + +public: + inline SourceContext(source_t source) : source(source) {} + inline ~SourceContext() {source_destroy(source);} + inline operator source_t() {return source;} +}; + +/* --------------------------------------------------- */ + +class SceneContext { + scene_t scene; + +public: + inline SceneContext(scene_t scene) : scene(scene) {} + inline ~SceneContext() {scene_destroy(scene);} + inline operator scene_t() {return scene;} +}; + +/* --------------------------------------------------- */ + +static LRESULT CALLBACK sceneProc(HWND hwnd, UINT message, WPARAM wParam, + LPARAM lParam) +{ + switch (message) { + + case WM_CLOSE: + PostQuitMessage(0); + break; + + default: + return DefWindowProc(hwnd, message, wParam, lParam); + } + + return 0; +} + +static void do_log(enum log_type type, const char *msg, va_list args) +{ + char bla[4096]; + vsnprintf(bla, 4095, msg, args); + + OutputDebugStringA(bla); + OutputDebugStringA("\n"); +} + +static obs_t CreateOBS(HWND hwnd) +{ + struct video_info vi; + memset(&vi, 0, sizeof(struct video_info)); + vi.format = "RGBA"; + vi.fps_num = 30000; + vi.fps_den = 1001; + vi.width = cx; + vi.height = cy; + vi.name = "video"; + + struct gs_init_data gsid; + memset(&gsid, 0, sizeof(gsid)); + gsid.hwnd = hwnd; + gsid.cx = cx; + gsid.cy = cy; + gsid.num_backbuffers = 2; + gsid.format = GS_RGBA; + + obs_t obs = obs_create("libobs-d3d11.dll", &gsid, &vi, NULL); + if (!obs) + throw "Couldn't create OBS"; + + return obs; +} + +static void AddTestItems(scene_t scene, source_t source) +{ + sceneitem_t item = NULL; + struct vec2 v2; + + item = scene_add(scene, source); + vec2_set(&v2, 100.0f, 200.0f); + sceneitem_setpos(item, &v2); + sceneitem_setrot(item, 10.0f); + vec2_set(&v2, 20.0f, 2.0f); + sceneitem_setscale(item, &v2); + + item = scene_add(scene, source); + vec2_set(&v2, 200.0f, 100.0f); + sceneitem_setpos(item, &v2); + sceneitem_setrot(item, -45.0f); + vec2_set(&v2, 5.0f, 7.0f); + sceneitem_setscale(item, &v2); +} + +static HWND CreateTestWindow(HINSTANCE instance) +{ + WNDCLASS wc; + base_set_log_handler(do_log); + + memset(&wc, 0, sizeof(wc)); + wc.lpszClassName = L"bla"; + wc.hbrBackground = (HBRUSH)COLOR_WINDOW; + wc.hInstance = instance; + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.lpfnWndProc = (WNDPROC)sceneProc; + + if (!RegisterClass(&wc)) + return 0; + + return CreateWindow(L"bla", L"bla", WS_OVERLAPPEDWINDOW|WS_VISIBLE, + 1920/2 - cx/2, 1080/2 - cy/2, cx, cy, + NULL, NULL, instance, NULL); +} + +/* --------------------------------------------------- */ + +int WINAPI WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdLine, + int numCmd) +{ + HWND hwnd = NULL; + + try { + hwnd = CreateTestWindow(instance); + if (!hwnd) + throw "Couldn't create main window"; + + /* ------------------------------------------------------ */ + /* create OBS */ + OBSContext obs = CreateOBS(hwnd); + + /* ------------------------------------------------------ */ + /* load module */ + if (obs_load_module(obs, "test-input.dll") != 0) + throw "Couldn't load module"; + + /* ------------------------------------------------------ */ + /* create source */ + SourceContext source = source_create(obs, SOURCE_INPUT, + "random", NULL); + if (!source) + throw "Couldn't create random test source"; + + /* ------------------------------------------------------ */ + /* create filter */ + SourceContext filter = source_create(obs, SOURCE_FILTER, + "test", NULL); + if (!filter) + throw "Couldn't create test filter"; + source_filter_add(source, filter); + + /* ------------------------------------------------------ */ + /* create scene and add source to scene (twice) */ + SceneContext scene = scene_create(obs); + if (!scene) + throw "Couldn't create scene"; + + AddTestItems(scene, source); + + /* ------------------------------------------------------ */ + /* set the scene as the primary draw source and go */ + obs_set_primary_source(obs, scene_source(scene)); + + MSG msg; + while (GetMessage(&msg, NULL, 0, 0)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + + obs_set_primary_source(obs, NULL); + + } catch (char *error) { + MessageBoxA(NULL, error, NULL, 0); + } + + blog(LOG_INFO, "Number of memory leaks: %u", bnum_allocs()); + DestroyWindow(hwnd); + + return 0; +} diff --git a/vs/2010/OBS.sln b/vs/2010/OBS.sln new file mode 100644 index 000000000..f3b7d7b26 --- /dev/null +++ b/vs/2010/OBS.sln @@ -0,0 +1,78 @@ +ļ»æ +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libobs", "libobs\libobs.vcxproj", "{6F1AC2AE-6424-401A-AF9F-A771E6BEE026}" + ProjectSection(ProjectDependencies) = postProject + {E11367B7-20CC-4741-B8E0-C20E85302A40} = {E11367B7-20CC-4741-B8E0-C20E85302A40} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libobs-d3d11", "libobs-d3d11\libobs-d3d11.vcxproj", "{68A84F9A-5B89-4E7D-8183-87FEA5DC65F6}" + ProjectSection(ProjectDependencies) = postProject + {6F1AC2AE-6424-401A-AF9F-A771E6BEE026} = {6F1AC2AE-6424-401A-AF9F-A771E6BEE026} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pthreads", "pthreads\pthreads.vcxproj", "{E11367B7-20CC-4741-B8E0-C20E85302A40}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "wintest", "wintest\wintest.vcxproj", "{82C863C3-74C8-43BE-90CF-755EE698F2E8}" + ProjectSection(ProjectDependencies) = postProject + {6F1AC2AE-6424-401A-AF9F-A771E6BEE026} = {6F1AC2AE-6424-401A-AF9F-A771E6BEE026} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test-input", "test-input\test-input.vcxproj", "{760ECBBC-EA7C-464A-B60E-945A0BB1B100}" + ProjectSection(ProjectDependencies) = postProject + {6F1AC2AE-6424-401A-AF9F-A771E6BEE026} = {6F1AC2AE-6424-401A-AF9F-A771E6BEE026} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6F1AC2AE-6424-401A-AF9F-A771E6BEE026}.Debug|Win32.ActiveCfg = Debug|Win32 + {6F1AC2AE-6424-401A-AF9F-A771E6BEE026}.Debug|Win32.Build.0 = Debug|Win32 + {6F1AC2AE-6424-401A-AF9F-A771E6BEE026}.Debug|x64.ActiveCfg = Debug|x64 + {6F1AC2AE-6424-401A-AF9F-A771E6BEE026}.Debug|x64.Build.0 = Debug|x64 + {6F1AC2AE-6424-401A-AF9F-A771E6BEE026}.Release|Win32.ActiveCfg = Release|Win32 + {6F1AC2AE-6424-401A-AF9F-A771E6BEE026}.Release|Win32.Build.0 = Release|Win32 + {6F1AC2AE-6424-401A-AF9F-A771E6BEE026}.Release|x64.ActiveCfg = Release|x64 + {6F1AC2AE-6424-401A-AF9F-A771E6BEE026}.Release|x64.Build.0 = Release|x64 + {68A84F9A-5B89-4E7D-8183-87FEA5DC65F6}.Debug|Win32.ActiveCfg = Debug|Win32 + {68A84F9A-5B89-4E7D-8183-87FEA5DC65F6}.Debug|Win32.Build.0 = Debug|Win32 + {68A84F9A-5B89-4E7D-8183-87FEA5DC65F6}.Debug|x64.ActiveCfg = Debug|x64 + {68A84F9A-5B89-4E7D-8183-87FEA5DC65F6}.Debug|x64.Build.0 = Debug|x64 + {68A84F9A-5B89-4E7D-8183-87FEA5DC65F6}.Release|Win32.ActiveCfg = Release|Win32 + {68A84F9A-5B89-4E7D-8183-87FEA5DC65F6}.Release|Win32.Build.0 = Release|Win32 + {68A84F9A-5B89-4E7D-8183-87FEA5DC65F6}.Release|x64.ActiveCfg = Release|x64 + {68A84F9A-5B89-4E7D-8183-87FEA5DC65F6}.Release|x64.Build.0 = Release|x64 + {E11367B7-20CC-4741-B8E0-C20E85302A40}.Debug|Win32.ActiveCfg = Debug|Win32 + {E11367B7-20CC-4741-B8E0-C20E85302A40}.Debug|Win32.Build.0 = Debug|Win32 + {E11367B7-20CC-4741-B8E0-C20E85302A40}.Debug|x64.ActiveCfg = Debug|x64 + {E11367B7-20CC-4741-B8E0-C20E85302A40}.Debug|x64.Build.0 = Debug|x64 + {E11367B7-20CC-4741-B8E0-C20E85302A40}.Release|Win32.ActiveCfg = Release|Win32 + {E11367B7-20CC-4741-B8E0-C20E85302A40}.Release|Win32.Build.0 = Release|Win32 + {E11367B7-20CC-4741-B8E0-C20E85302A40}.Release|x64.ActiveCfg = Release|x64 + {E11367B7-20CC-4741-B8E0-C20E85302A40}.Release|x64.Build.0 = Release|x64 + {82C863C3-74C8-43BE-90CF-755EE698F2E8}.Debug|Win32.ActiveCfg = Debug|Win32 + {82C863C3-74C8-43BE-90CF-755EE698F2E8}.Debug|Win32.Build.0 = Debug|Win32 + {82C863C3-74C8-43BE-90CF-755EE698F2E8}.Debug|x64.ActiveCfg = Debug|x64 + {82C863C3-74C8-43BE-90CF-755EE698F2E8}.Debug|x64.Build.0 = Debug|x64 + {82C863C3-74C8-43BE-90CF-755EE698F2E8}.Release|Win32.ActiveCfg = Release|Win32 + {82C863C3-74C8-43BE-90CF-755EE698F2E8}.Release|Win32.Build.0 = Release|Win32 + {82C863C3-74C8-43BE-90CF-755EE698F2E8}.Release|x64.ActiveCfg = Release|x64 + {82C863C3-74C8-43BE-90CF-755EE698F2E8}.Release|x64.Build.0 = Release|x64 + {760ECBBC-EA7C-464A-B60E-945A0BB1B100}.Debug|Win32.ActiveCfg = Debug|Win32 + {760ECBBC-EA7C-464A-B60E-945A0BB1B100}.Debug|Win32.Build.0 = Debug|Win32 + {760ECBBC-EA7C-464A-B60E-945A0BB1B100}.Debug|x64.ActiveCfg = Debug|x64 + {760ECBBC-EA7C-464A-B60E-945A0BB1B100}.Debug|x64.Build.0 = Debug|x64 + {760ECBBC-EA7C-464A-B60E-945A0BB1B100}.Release|Win32.ActiveCfg = Release|Win32 + {760ECBBC-EA7C-464A-B60E-945A0BB1B100}.Release|Win32.Build.0 = Release|Win32 + {760ECBBC-EA7C-464A-B60E-945A0BB1B100}.Release|x64.ActiveCfg = Release|x64 + {760ECBBC-EA7C-464A-B60E-945A0BB1B100}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/vs/2010/OBS/OBS.vcxproj b/vs/2010/OBS/OBS.vcxproj new file mode 100644 index 000000000..d4db66c0f --- /dev/null +++ b/vs/2010/OBS/OBS.vcxproj @@ -0,0 +1,142 @@ +ļ»æ + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {C6CD0240-5A92-43F6-B0EE-FF3ACE10742F} + Win32Proj + OBS + + + + Application + true + Unicode + + + Application + true + Unicode + + + Application + false + true + Unicode + + + Application + false + true + Unicode + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Windows + true + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Windows + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Windows + true + true + true + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + + + Windows + true + true + true + + + + + + + + \ No newline at end of file diff --git a/vs/2010/OBS/OBS.vcxproj.filters b/vs/2010/OBS/OBS.vcxproj.filters new file mode 100644 index 000000000..d7ef6a1a3 --- /dev/null +++ b/vs/2010/OBS/OBS.vcxproj.filters @@ -0,0 +1,17 @@ +ļ»æ + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + \ No newline at end of file diff --git a/vs/2010/libobs-d3d11/libobs-d3d11.vcxproj b/vs/2010/libobs-d3d11/libobs-d3d11.vcxproj new file mode 100644 index 000000000..1a36ce78e --- /dev/null +++ b/vs/2010/libobs-d3d11/libobs-d3d11.vcxproj @@ -0,0 +1,176 @@ +ļ»æ + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {68A84F9A-5B89-4E7D-8183-87FEA5DC65F6} + Win32Proj + libobsd3d11 + + + + DynamicLibrary + true + Unicode + + + DynamicLibrary + true + Unicode + + + DynamicLibrary + false + true + Unicode + + + DynamicLibrary + false + true + Unicode + + + + + + + + + + + + + + + + + + + true + $(DXSDK_DIR)Include;$(IncludePath) + $(DXSDK_DIR)Lib\x86;$(LibraryPath) + + + true + $(DXSDK_DIR)Include;$(IncludePath) + $(DXSDK_DIR)Lib\x64;$(LibraryPath) + + + false + $(DXSDK_DIR)Include;$(IncludePath) + $(DXSDK_DIR)Lib\x86;$(LibraryPath) + + + false + $(DXSDK_DIR)Include;$(IncludePath) + $(DXSDK_DIR)Lib\x64;$(LibraryPath) + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBOBSD3D11_EXPORTS;%(PreprocessorDefinitions) + ../../../libobs + + + Windows + true + $(OutDir);%(AdditionalLibraryDirectories) + d3d11.lib;dxgi.lib;d3dcompiler.lib;libobs.lib;%(AdditionalDependencies) + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBOBSD3D11_EXPORTS;%(PreprocessorDefinitions) + ../../../libobs + + + Windows + true + $(OutDir);%(AdditionalLibraryDirectories) + d3d11.lib;dxgi.lib;d3dcompiler.lib;libobs.lib;%(AdditionalDependencies) + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBOBSD3D11_EXPORTS;%(PreprocessorDefinitions) + ../../../libobs + + + Windows + true + true + true + $(OutDir);%(AdditionalLibraryDirectories) + d3d11.lib;dxgi.lib;d3dcompiler.lib;libobs.lib;%(AdditionalDependencies) + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBOBSD3D11_EXPORTS;%(PreprocessorDefinitions) + ../../../libobs + + + Windows + true + true + true + $(OutDir);%(AdditionalLibraryDirectories) + d3d11.lib;dxgi.lib;d3dcompiler.lib;libobs.lib;%(AdditionalDependencies) + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/vs/2010/libobs-d3d11/libobs-d3d11.vcxproj.filters b/vs/2010/libobs-d3d11/libobs-d3d11.vcxproj.filters new file mode 100644 index 000000000..59a92ff8b --- /dev/null +++ b/vs/2010/libobs-d3d11/libobs-d3d11.vcxproj.filters @@ -0,0 +1,57 @@ +ļ»æ + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/vs/2010/libobs/libobs.vcxproj b/vs/2010/libobs/libobs.vcxproj new file mode 100644 index 000000000..96e927d2f --- /dev/null +++ b/vs/2010/libobs/libobs.vcxproj @@ -0,0 +1,235 @@ +ļ»æ + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {6F1AC2AE-6424-401A-AF9F-A771E6BEE026} + Win32Proj + libobs + + + + DynamicLibrary + true + Unicode + + + DynamicLibrary + true + Unicode + + + DynamicLibrary + false + true + Unicode + + + DynamicLibrary + false + true + Unicode + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBOBS_EXPORTS;%(PreprocessorDefinitions) + false + + + Windows + true + pthreads.lib;%(AdditionalDependencies) + $(OutDir);%(AdditionalLibraryDirectories) + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;LIBOBS_EXPORTS;%(PreprocessorDefinitions) + false + + + Windows + true + pthreads.lib;%(AdditionalDependencies) + $(OutDir);%(AdditionalLibraryDirectories) + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBOBS_EXPORTS;%(PreprocessorDefinitions) + false + + + Windows + true + true + true + pthreads.lib;%(AdditionalDependencies) + $(OutDir);%(AdditionalLibraryDirectories) + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBOBS_EXPORTS;%(PreprocessorDefinitions) + false + + + Windows + true + true + true + pthreads.lib;%(AdditionalDependencies) + $(OutDir);%(AdditionalLibraryDirectories) + + + + + + \ No newline at end of file diff --git a/vs/2010/libobs/libobs.vcxproj.filters b/vs/2010/libobs/libobs.vcxproj.filters new file mode 100644 index 000000000..d72aed36f --- /dev/null +++ b/vs/2010/libobs/libobs.vcxproj.filters @@ -0,0 +1,294 @@ +ļ»æ + + + + {f3623aed-c769-4a72-bce5-364a00fda8bf} + + + {db8567bf-5273-484d-958b-c343cbbb77a2} + + + {f91fb9b1-06e6-4fa0-a3a3-fe87c27af047} + + + {b00638f4-e338-45b7-b45b-95995e4b2905} + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {c90a618f-1096-41f5-9ce5-f2f78d978983} + h;hpp;hxx;hm;inl;inc;xsd + + + {21a99cbb-e167-4baf-82ae-47d23dc12c7d} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {b7228a18-6051-4cab-b53b-ff299eb969c0} + h;hpp;hxx;hm;inl;inc;xsd + + + {0f32a773-0c64-42e5-8539-1dae563eab6e} + h;hpp;hxx;hm;inl;inc;xsd + + + {788a1c62-630c-413a-8738-95ab0bfa535b} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {7ba51fc2-531b-4fd6-983d-e0836024eef5} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + libobs\Header Files + + + libobs\Header Files + + + libobs\Header Files + + + libobs\Header Files + + + libobs\Header Files + + + libobs\Header Files + + + libobs\Header Files + + + libobs\Header Files + + + media-io\Header Files + + + media-io\Header Files + + + media-io\Header Files + + + util\Header Files + + + util\Header Files + + + util\Header Files + + + util\Header Files + + + util\Header Files + + + util\Header Files + + + util\Header Files + + + util\Header Files + + + util\Header Files + + + util\Header Files + + + util\Header Files + + + util\Header Files + + + util\Header Files + + + util\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + graphics\Header Files + + + + + libobs\Source Files + + + libobs\Source Files + + + libobs\Source Files + + + libobs\Source Files + + + libobs\Source Files + + + libobs\Source Files + + + media-io\Soruce Files + + + media-io\Soruce Files + + + media-io\Soruce Files + + + util\Source Files + + + util\Source Files + + + util\Source Files + + + util\Source Files + + + util\Source Files + + + util\Source Files + + + util\Source Files + + + util\Source Files + + + util\Source Files + + + util\Source Files + + + util\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + graphics\Source Files + + + libobs\Source Files + + + graphics\Source Files + + + \ No newline at end of file diff --git a/vs/2010/pthreads/pthreads.vcxproj b/vs/2010/pthreads/pthreads.vcxproj new file mode 100644 index 000000000..b94af86b8 --- /dev/null +++ b/vs/2010/pthreads/pthreads.vcxproj @@ -0,0 +1,142 @@ +ļ»æ + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {E11367B7-20CC-4741-B8E0-C20E85302A40} + Win32Proj + pthreads + + + + StaticLibrary + true + MultiByte + + + StaticLibrary + true + MultiByte + + + StaticLibrary + false + true + MultiByte + + + StaticLibrary + false + true + MultiByte + + + + + + + + + + + + + + + + + + + + + + + Level3 + Disabled + __CLEANUP_C;WIN32;_DEBUG;_WINDOWS;_LIB;PTW32_BUILD;PTW32_STATIC_LIB;%(PreprocessorDefinitions) + false + + + Windows + true + + + + + + + Level3 + Disabled + __CLEANUP_C;WIN32;_DEBUG;_WINDOWS;_LIB;PTW32_BUILD;PTW32_STATIC_LIB;%(PreprocessorDefinitions) + false + + + Windows + true + + + + + Level3 + + + MaxSpeed + true + true + __CLEANUP_C;WIN32;NDEBUG;_WINDOWS;_LIB;PTW32_BUILD;PTW32_STATIC_LIB;%(PreprocessorDefinitions) + false + + + Windows + true + true + true + + + + + Level3 + + + MaxSpeed + true + true + __CLEANUP_C;WIN32;NDEBUG;_WINDOWS;_LIB;PTW32_BUILD;PTW32_STATIC_LIB;%(PreprocessorDefinitions) + false + + + Windows + true + true + true + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/vs/2010/pthreads/pthreads.vcxproj.filters b/vs/2010/pthreads/pthreads.vcxproj.filters new file mode 100644 index 000000000..4d37db780 --- /dev/null +++ b/vs/2010/pthreads/pthreads.vcxproj.filters @@ -0,0 +1,36 @@ +ļ»æ + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/vs/2010/test-input/test-input.vcxproj b/vs/2010/test-input/test-input.vcxproj new file mode 100644 index 000000000..8a6201c03 --- /dev/null +++ b/vs/2010/test-input/test-input.vcxproj @@ -0,0 +1,162 @@ +ļ»æ + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + + + + + + + + + + + {760ECBBC-EA7C-464A-B60E-945A0BB1B100} + Win32Proj + testinput + + + + DynamicLibrary + true + Unicode + + + DynamicLibrary + true + Unicode + + + DynamicLibrary + false + true + Unicode + + + DynamicLibrary + false + true + Unicode + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;TESTINPUT_EXPORTS;%(PreprocessorDefinitions) + ../../../libobs + + + Windows + true + $(OutDir);%(AdditionalLibraryDirectories) + libobs.lib;%(AdditionalDependencies) + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;_USRDLL;TESTINPUT_EXPORTS;%(PreprocessorDefinitions) + ../../../libobs + + + Windows + true + $(OutDir);%(AdditionalLibraryDirectories) + libobs.lib;%(AdditionalDependencies) + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;TESTINPUT_EXPORTS;%(PreprocessorDefinitions) + ../../../libobs + + + Windows + true + true + true + $(OutDir);%(AdditionalLibraryDirectories) + libobs.lib;%(AdditionalDependencies) + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;_USRDLL;TESTINPUT_EXPORTS;%(PreprocessorDefinitions) + ../../../libobs + + + Windows + true + true + true + $(OutDir);%(AdditionalLibraryDirectories) + libobs.lib;%(AdditionalDependencies) + + + + + + \ No newline at end of file diff --git a/vs/2010/test-input/test-input.vcxproj.filters b/vs/2010/test-input/test-input.vcxproj.filters new file mode 100644 index 000000000..c3dfeb37d --- /dev/null +++ b/vs/2010/test-input/test-input.vcxproj.filters @@ -0,0 +1,39 @@ +ļ»æ + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + Source Files + + + Source Files + + + \ No newline at end of file diff --git a/vs/2010/wintest/draw.effect b/vs/2010/wintest/draw.effect new file mode 100644 index 000000000..a36c104fe --- /dev/null +++ b/vs/2010/wintest/draw.effect @@ -0,0 +1,35 @@ +uniform float4x4 ViewProj; +uniform texture2d diffuse; + +sampler_state texSampler { + AddressU = Clamp; + AddressV = Clamp; + Filter = Linear; +}; + +struct VertexInOut { + float4 pos : POSITION; + float2 uv : TEXCOORD0; +}; + +VertexInOut VShader(VertexInOut input) +{ + VertexInOut output; + output.pos = mul(float4(input.pos.xyz, 1.0), ViewProj); + output.uv = input.uv; + return output; +} + +float4 PShader(VertexInOut input) : TARGET +{ + return diffuse.Sample(texSampler, input.uv); +} + +technique Default +{ + pass + { + vertex_shader = VShader(input); + pixel_shader = PShader(input); + } +} diff --git a/vs/2010/wintest/test.effect b/vs/2010/wintest/test.effect new file mode 100644 index 000000000..cfbea1f5b --- /dev/null +++ b/vs/2010/wintest/test.effect @@ -0,0 +1,37 @@ +uniform float4x4 ViewProj; +uniform texture2d diffuse; + +uniform float4 color = {0.0, 1.0, 0.0, 1.0}; + +sampler_state texSampler { + AddressU = Clamp; + AddressV = Clamp; + Filter = Linear; +}; + +struct VertexInOut { + float4 pos : POSITION; + float2 uv : TEXCOORD0; +}; + +VertexInOut VShader(VertexInOut input) +{ + VertexInOut output; + output.pos = mul(float4(input.pos.xyz, 1.0), ViewProj); + output.uv = input.uv; + return output; +} + +float4 PShader(VertexInOut input) : TARGET +{ + return diffuse.Sample(texSampler, input.uv) * color; +} + +technique Default +{ + pass + { + vertex_shader = VShader(input); + pixel_shader = PShader(input); + } +} diff --git a/vs/2010/wintest/wintest.vcxproj b/vs/2010/wintest/wintest.vcxproj new file mode 100644 index 000000000..978ae29a6 --- /dev/null +++ b/vs/2010/wintest/wintest.vcxproj @@ -0,0 +1,155 @@ +ļ»æ + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + + + + {82C863C3-74C8-43BE-90CF-755EE698F2E8} + Win32Proj + wintest + + + + Application + true + Unicode + + + Application + true + Unicode + + + Application + false + true + Unicode + + + Application + false + true + Unicode + + + + + + + + + + + + + + + + + + + true + + + true + + + false + + + false + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + ../../../libobs + + + Windows + true + libobs.lib;%(AdditionalDependencies) + $(OutDir);%(AdditionalLibraryDirectories) + + + + + + + Level3 + Disabled + WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + ../../../libobs + + + Windows + true + libobs.lib;%(AdditionalDependencies) + $(OutDir);%(AdditionalLibraryDirectories) + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + ../../../libobs + + + Windows + true + true + true + libobs.lib;%(AdditionalDependencies) + $(OutDir);%(AdditionalLibraryDirectories) + + + + + Level3 + + + MaxSpeed + true + true + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + ../../../libobs + + + Windows + true + true + true + libobs.lib;%(AdditionalDependencies) + $(OutDir);%(AdditionalLibraryDirectories) + + + + + + \ No newline at end of file diff --git a/vs/2010/wintest/wintest.vcxproj.filters b/vs/2010/wintest/wintest.vcxproj.filters new file mode 100644 index 000000000..c9e581782 --- /dev/null +++ b/vs/2010/wintest/wintest.vcxproj.filters @@ -0,0 +1,22 @@ +ļ»æ + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + \ No newline at end of file diff --git a/w32-pthreads/ANNOUNCE b/w32-pthreads/ANNOUNCE new file mode 100644 index 000000000..950c86ff0 --- /dev/null +++ b/w32-pthreads/ANNOUNCE @@ -0,0 +1,483 @@ +PTHREADS-WIN32 RELEASE 2.9.0 (2012-05-25) +----------------------------------------- +Web Site: http://sourceware.org/pthreads-win32/ +FTP Site: ftp://sourceware.org/pub/pthreads-win32 +Maintainer: Ross Johnson + + +We are pleased to announce the availability of a new release of +Pthreads-win32, an Open Source Software implementation of the +Threads component of the POSIX 1003.1 2001 Standard for Microsoft's +Win32 environment. Some functions from other sections of POSIX +1003.1 2001 are also supported including semaphores and scheduling +functions. + +Some common non-portable functions are also implemented for +additional compatibility, as are a few functions specific +to pthreads-win32 for easier integration with Win32 applications. + +Pthreads-win32 is free software, distributed under the GNU Lesser +General Public License (LGPL). + + +Acknowledgements +---------------- +This library is based originally on a Win32 pthreads +implementation contributed by John Bossom. + +The implementation of Condition Variables uses algorithms developed +by Alexander Terekhov and Louis Thomas. + +The implementation of POSIX mutexes has been improved by Thomas Pfaff +and later by Alexander Terekhov. + +The implementation of Spinlocks and Barriers was contributed +by Ross Johnson. + +The implementation of read/write locks was contributed by +Aurelio Medina and improved by Alexander Terekhov. + +Many others have contributed significant time and effort to solve crutial +problems in order to make the library workable, robust and reliable. + +Thanks to Xavier Leroy for granting permission to use and modify his +LinuxThreads manual pages. + +Thanks to The Open Group for making the Single Unix Specification +publicly available - many of the manual pages included in the package +were extracted from it. + +There is also a separate CONTRIBUTORS file. This file and others are +on the web site: + + http://sourceware.org/pthreads-win32 + +As much as possible, the ChangeLog file acknowledges contributions to the +code base in more detail. + + +Changes since the last release +------------------------------ +These are now documented in the NEWS file. +See the ChangeLog file also. + + +Known Bugs +---------- +These are now documented in the BUGS file. + + +Level of standards conformance +------------------------------ + +The following POSIX 1003.1 2001 options are defined and set to 200112L: + + _POSIX_THREADS + _POSIX_THREAD_SAFE_FUNCTIONS + _POSIX_THREAD_ATTR_STACKSIZE + _POSIX_THREAD_PRIORITY_SCHEDULING + _POSIX_SEMAPHORES + _POSIX_READER_WRITER_LOCKS + _POSIX_SPIN_LOCKS + _POSIX_BARRIERS + + +The following POSIX 1003.1 2001 options are defined and set to -1: + + _POSIX_THREAD_ATTR_STACKADDR + _POSIX_THREAD_PRIO_INHERIT + _POSIX_THREAD_PRIO_PROTECT + _POSIX_THREAD_PROCESS_SHARED + + +The following POSIX 1003.1 2001 limits are defined and set: + + _POSIX_THREAD_THREADS_MAX + _POSIX_SEM_VALUE_MAX + _POSIX_SEM_NSEMS_MAX + _POSIX_THREAD_KEYS_MAX + _POSIX_THREAD_DESTRUCTOR_ITERATIONS + PTHREAD_STACK_MIN + PTHREAD_THREADS_MAX + SEM_VALUE_MAX + SEM_NSEMS_MAX + PTHREAD_KEYS_MAX + PTHREAD_DESTRUCTOR_ITERATIONS + + +The following functions are implemented: + + --------------------------- + PThreads + --------------------------- + pthread_attr_init + pthread_attr_destroy + pthread_attr_getdetachstate + pthread_attr_getstackaddr + pthread_attr_getstacksize + pthread_attr_setdetachstate + pthread_attr_setstackaddr + pthread_attr_setstacksize + + pthread_create + pthread_detach + pthread_equal + pthread_exit + pthread_join + pthread_once + pthread_self + + pthread_cancel + pthread_cleanup_pop + pthread_cleanup_push + pthread_setcancelstate + pthread_setcanceltype + pthread_testcancel + + --------------------------- + Thread Specific Data + --------------------------- + pthread_key_create + pthread_key_delete + pthread_setspecific + pthread_getspecific + + --------------------------- + Mutexes + --------------------------- + pthread_mutexattr_init + pthread_mutexattr_destroy + pthread_mutexattr_getpshared + pthread_mutexattr_setpshared + pthread_mutexattr_gettype + pthread_mutexattr_settype (types: PTHREAD_MUTEX_DEFAULT + PTHREAD_MUTEX_NORMAL + PTHREAD_MUTEX_ERRORCHECK + PTHREAD_MUTEX_RECURSIVE ) + pthread_mutexattr_getrobust + pthread_mutexattr_setrobust (values: PTHREAD_MUTEX_STALLED + PTHREAD_MUTEX_ROBUST) + pthread_mutex_init + pthread_mutex_destroy + pthread_mutex_lock + pthread_mutex_trylock + pthread_mutex_timedlock + pthread_mutex_unlock + pthread_mutex_consistent + + --------------------------- + Condition Variables + --------------------------- + pthread_condattr_init + pthread_condattr_destroy + pthread_condattr_getpshared + pthread_condattr_setpshared + + pthread_cond_init + pthread_cond_destroy + pthread_cond_wait + pthread_cond_timedwait + pthread_cond_signal + pthread_cond_broadcast + + --------------------------- + Read/Write Locks + --------------------------- + pthread_rwlock_init + pthread_rwlock_destroy + pthread_rwlock_tryrdlock + pthread_rwlock_trywrlock + pthread_rwlock_rdlock + pthread_rwlock_timedrdlock + pthread_rwlock_rwlock + pthread_rwlock_timedwrlock + pthread_rwlock_unlock + pthread_rwlockattr_init + pthread_rwlockattr_destroy + pthread_rwlockattr_getpshared + pthread_rwlockattr_setpshared + + --------------------------- + Spin Locks + --------------------------- + pthread_spin_init + pthread_spin_destroy + pthread_spin_lock + pthread_spin_unlock + pthread_spin_trylock + + --------------------------- + Barriers + --------------------------- + pthread_barrier_init + pthread_barrier_destroy + pthread_barrier_wait + pthread_barrierattr_init + pthread_barrierattr_destroy + pthread_barrierattr_getpshared + pthread_barrierattr_setpshared + + --------------------------- + Semaphores + --------------------------- + sem_init + sem_destroy + sem_post + sem_wait + sem_trywait + sem_timedwait + sem_getvalue (# free if +ve, # of waiters if -ve) + sem_open (returns an error ENOSYS) + sem_close (returns an error ENOSYS) + sem_unlink (returns an error ENOSYS) + + --------------------------- + RealTime Scheduling + --------------------------- + pthread_attr_getschedparam + pthread_attr_setschedparam + pthread_attr_getinheritsched + pthread_attr_setinheritsched + pthread_attr_getschedpolicy (only supports SCHED_OTHER) + pthread_attr_setschedpolicy (only supports SCHED_OTHER) + pthread_getschedparam + pthread_setschedparam + pthread_getconcurrency + pthread_setconcurrency + pthread_attr_getscope + pthread_attr_setscope (only supports PTHREAD_SCOPE_SYSTEM) + sched_get_priority_max + sched_get_priority_min + sched_rr_get_interval (returns an error ENOTSUP) + sched_setscheduler (only supports SCHED_OTHER) + sched_getscheduler (only supports SCHED_OTHER) + sched_yield + + --------------------------- + Signals + --------------------------- + pthread_sigmask + pthread_kill (only supports zero sig value, + for thread validity checking) + + --------------------------- + Non-portable routines (see the README.NONPORTABLE file for usage) + --------------------------- + pthread_getw32threadhandle_np + pthread_timechange_handler_np + pthread_delay_np + pthread_getunique_np + pthread_mutexattr_getkind_np + pthread_mutexattr_setkind_np (types: PTHREAD_MUTEX_FAST_NP, + PTHREAD_MUTEX_ERRORCHECK_NP, + PTHREAD_MUTEX_RECURSIVE_NP, + PTHREAD_MUTEX_ADAPTIVE_NP, + PTHREAD_MUTEX_TIMED_NP) + pthread_num_processors_np + (The following four routines may be required when linking statically. + The process_* routines should not be needed for MSVC or GCC.) + pthread_win32_process_attach_np + pthread_win32_process_detach_np + (The following routines should only be needed to manage implicit + POSIX handles i.e. when Win native threads call POSIX thread routines + (other than pthread_create)) + pthread_win32_thread_attach_np + pthread_win32_thread_detach_np + + --------------------------- + Static Initializers + --------------------------- + PTHREAD_ONCE_INIT + PTHREAD_MUTEX_INITIALIZER + PTHREAD_RECURSIVE_MUTEX_INITIALIZER + PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP + PTHREAD_ERRORCHECK_MUTEX_INITIALIZER + PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP + PTHREAD_COND_INITIALIZER + PTHREAD_RWLOCK_INITIALIZER + PTHREAD_SPINLOCK_INITIALIZER + + +The library includes two non-API functions for creating cancellation +points in applications and libraries: + + pthreadCancelableWait + pthreadCancelableTimedWait + + +The following functions are not implemented: + + --------------------------- + RealTime Scheduling + --------------------------- + pthread_mutex_getprioceiling + pthread_mutex_setprioceiling + pthread_mutex_attr_getprioceiling + pthread_mutex_attr_getprotocol + pthread_mutex_attr_setprioceiling + pthread_mutex_attr_setprotocol + + --------------------------- + Fork Handlers + --------------------------- + pthread_atfork + + --------------------------- + Stdio + --------------------------- + flockfile + ftrylockfile + funlockfile + getc_unlocked + getchar_unlocked + putc_unlocked + putchar_unlocked + + --------------------------- + Thread-Safe C Runtime Library + --------------------------- + readdir_r + getgrgid_r + getgrnam_r + getpwuid_r + getpwnam_r + + --------------------------- + Signals + --------------------------- + sigtimedwait + sigwait + sigwaitinfo + + --------------------------- + General + --------------------------- + sysconf + + --------------------------- + Thread-Safe C Runtime Library (macros) + --------------------------- + strtok_r + asctime_r + ctime_r + gmtime_r + localtime_r + rand_r + + +Availability +------------ + +The prebuilt DLL, export libs (for both MSVC and Mingw32), and the header +files (pthread.h, semaphore.h, sched.h) are available along with the +complete source code. + +The source code can be found at: + + ftp://sources.redhat.com/pub/pthreads-win32 + +and as individual source code files at + + ftp://sources.redhat.com/pub/pthreads-win32/source + +The pre-built DLL, export libraries and include files can be found at: + + ftp://sources.redhat.com/pub/pthreads-win32/dll-latest + + + +Mailing List +------------ + +There is a mailing list for discussing pthreads on Win32. To join, +send email to: + + pthreads-win32-subscribe@sourceware.cygnus.com + + +Application Development Environments +------------------------------------ + +See the README file for more information. + +MSVC: +MSVC using SEH works. Distribute pthreadVSE.dll with your application. +MSVC using C++ EH works. Distribute pthreadVCE.dll with your application. +MSVC using C setjmp/longjmp works. Distribute pthreadVC.dll with your application. + + +Mingw32: +See the FAQ, Questions 6 and 10. + +Mingw using C++ EH works. Distribute pthreadGCE.dll with your application. +Mingw using C setjmp/longjmp works. Distribute pthreadGC.dll with your application. + + +Cygwin: (http://sourceware.cygnus.com/cygwin/) +Developers using Cygwin do not need pthreads-win32 since it has POSIX threads +support. Refer to its documentation for details and extent. + + +UWIN: +UWIN is a complete Unix-like environment for Windows from AT&T. Pthreads-win32 +doesn't currently support UWIN (and vice versa), but that may change in the +future. + +Generally: +For convenience, the following pre-built files are available on the FTP site +(see Availability above): + + pthread.h - for POSIX threads + semaphore.h - for POSIX semaphores + sched.h - for POSIX scheduling + pthreadVCE.dll - built with MSVC++ compiler using C++ EH + pthreadVCE.lib + pthreadVC.dll - built with MSVC compiler using C setjmp/longjmp + pthreadVC.lib + pthreadVSE.dll - built with MSVC compiler using SEH + pthreadVSE.lib + pthreadGCE.dll - built with Mingw32 G++ 2.95.2-1 + pthreadGC.dll - built with Mingw32 GCC 2.95.2-1 using setjmp/longjmp + libpthreadGCE.a - derived from pthreadGCE.dll + libpthreadGC.a - derived from pthreadGC.dll + gcc.dll - needed if distributing applications that use + pthreadGCE.dll (but see the FAQ Q 10 for the latest + related information) + +These are the only files you need in order to build POSIX threads +applications for Win32 using either MSVC or Mingw32. + +See the FAQ file in the source tree for additional information. + + +Documentation +------------- + +For the authoritative reference, see the online POSIX +standard reference at: + + http://www.OpenGroup.org + +For POSIX Thread API programming, several reference books are +available: + + Programming with POSIX Threads + David R. Butenhof + Addison-Wesley (pub) + + Pthreads Programming + By Bradford Nichols, Dick Buttlar & Jacqueline Proulx Farrell + O'Reilly (pub) + +On the web: see the links at the bottom of the pthreads-win32 site: + + http://sources.redhat.com/pthreads-win32/ + + Currently, there is no documentation included in the package apart + from the copious comments in the source code. + + + +Enjoy! + +Ross Johnson diff --git a/w32-pthreads/BUGS b/w32-pthreads/BUGS new file mode 100644 index 000000000..285ba4eb9 --- /dev/null +++ b/w32-pthreads/BUGS @@ -0,0 +1,141 @@ +---------- +Known bugs +---------- + +1. Not strictly a bug, more of a gotcha. + + Under MS VC++ (only tested with version 6.0), a term_func + set via the standard C++ set_terminate() function causes the + application to abort. + + Notes from the MSVC++ manual: + 1) A term_func() should call exit(), otherwise + abort() will be called on return to the caller. + A call to abort() raises SIGABRT and the default signal handler + for all signals terminates the calling program with + exit code 3. + 2) A term_func() must not throw an exception. Therefore + term_func() should not call pthread_exit(), which + works by throwing an exception (pthreadVCE or pthreadVSE) + or by calling longjmp (pthreadVC). + + Workaround: avoid using pthread_exit() in C++ applications. Exit + threads by dropping through the end of the thread routine. + +2. Cancellation problems in C++ builds + - Milan Gardian + + [Note: It's not clear if this problem isn't simply due to the context + switch in pthread_cancel() which occurs unless the QueueUserAPCEx + library and driver are installed and used. Just like setjmp/longjmp, + this is probably not going to work well in C++. In any case, unless for + some very unusual reason you really must use the C++ build then please + use the C build pthreadVC2.dll or pthreadGC2.dll, i.e. for C++ + applications.] + + This is suspected to be a compiler bug in VC6.0, and also seen in + VC7.0 and VS .NET 2003. The GNU C++ compiler does not have a problem + with this, and it has been reported that the Intel C++ 8.1 compiler + and Visual C++ 2005 Express Edition Beta2 pass tests\semaphore4.c + (which exposes the bug). + + Workaround [rpj - 2 Feb 2002] + ----------------------------- + [Please note: this workaround did not solve a similar problem in + snapshot-2004-11-03 or later, even though similar symptoms were seen. + tests\semaphore4.c fails in that snapshot for the VCE version of the + DLL.] + + The problem disappears when /Ob0 is used, i.e. /O2 /Ob0 works OK, + but if you want to use inlining optimisation you can be much more + specific about where it's switched off and on by using a pragma. + + So the inlining optimisation is interfering with the way that cleanup + handlers are run. It appears to relate to auto-inlining of class methods + since this is the only auto inlining that is performed at /O1 optimisation + (functions with the "inline" qualifier are also inlined, but the problem + doesn't appear to involve any such functions in the library or testsuite). + + In order to confirm the inlining culprit, the following use of pragmas + eliminate the problem but I don't know how to make it transparent, putting + it in, say, pthread.h where pthread_cleanup_push defined as a macro. + + #pragma inline_depth(0) + pthread_cleanup_push(handlerFunc, (void *) &arg); + + /* ... */ + + pthread_cleanup_pop(0); + #pragma inline_depth() + + Note the empty () pragma value after the pop macro. This resets depth to the + default. Or you can specify a non-zero depth here. + + The pragma is also needed (and now used) within the library itself wherever + cleanup handlers are used (condvar.c and rwlock.c). + + Use of these pragmas allows compiler optimisations /O1 and /O2 to be + used for either or both the library and applications. + + Experimenting further, I found that wrapping the actual cleanup handler + function with #pragma auto_inline(off|on) does NOT work. + + MSVC6.0 doesn't appear to support the C99 standard's _Pragma directive, + however, later versions may. This form is embeddable inside #define + macros, which would be ideal because it would mean that it could be added + to the push/pop macro definitions in pthread.h and hidden from the + application programmer. + + [/rpj] + + Original problem description + ---------------------------- + + The cancellation (actually, cleanup-after-cancel) tests fail when using VC + (professional) optimisation switches (/O1 or /O2) in pthreads library. I + have not investigated which concrete optimisation technique causes this + problem (/Og, /Oi, /Ot, /Oy, /Ob1, /Gs, /Gf, /Gy, etc.), but here is a + summary of builds and corresponding failures: + + * pthreads VSE (optimised tests): OK + * pthreads VCE (optimised tests): Failed "cleanup1" test (runtime) + + * pthreads VSE (DLL in CRT, optimised tests): OK + * pthreads VCE (DLL in CRT, optimised tests): Failed "cleanup1" test + (runtime) + + Please note that while in VSE version of the pthreads library the + optimisation does not really have any impact on the tests (they pass OK), in + VCE version addition of optimisation (/O2 in this case) causes the tests to + fail uniformly - either in "cleanup0" or "cleanup1" test cases. + + Please note that all the tests above use default pthreads DLL (no + optimisations, linked with either static or DLL CRT, based on test type). + Therefore the problem lies not within the pthreads DLL but within the + compiled client code (the application using pthreads -> involvement of + "pthread.h"). + + I think the message of this section is that usage of VCE version of pthreads + in applications relying on cancellation/cleanup AND using optimisations for + creation of production code is highly unreliable for the current version of + the pthreads library. + +3. The Borland Builder 5.5 version of the library produces memory read exceptions +in some tests. + +4. pthread_barrier_wait() can deadlock if the number of potential calling +threads for a particular barrier is greater than the barrier count parameter +given to pthread_barrier_init() for that barrier. + +This is due to the very lightweight implementation of pthread-win32 barriers. +To cope with more than "count" possible waiters, barriers must effectively +implement all the same safeguards as condition variables, making them much +"heavier" than at present. + +The workaround is to ensure that no more than "count" threads attempt to wait +at the barrier. + +5. Canceling a thread blocked on pthread_once appears not to work in the MSVC++ +version of the library "pthreadVCE.dll". The test case "once3.c" hangs. I have no +clues on this at present. All other versions pass this test ok - pthreadsVC.dll, +pthreadsVSE.dll, pthreadsGC.dll and pthreadsGCE.dll. diff --git a/w32-pthreads/Bmakefile b/w32-pthreads/Bmakefile new file mode 100644 index 000000000..ea25dec4f --- /dev/null +++ b/w32-pthreads/Bmakefile @@ -0,0 +1,268 @@ +# This makefile is compatible with BCB make. Use "make -fBMakefile" to compile. +# +# The variables $DLLDEST and $LIBDEST hold the destination directories for the +# dll and the lib, respectively. Probably all that needs to change is $DEVROOT. +# +# Currently only the recommended pthreadBC.dll is built by this makefile. +# + + +DLL_VER = 2 + +DEVROOT = . + +DLLDEST = $(DEVROOT)\DLL +LIBDEST = $(DEVROOT)\DLL + +DLLS = pthreadBC$(DLL_VER).dll + +OPTIM = /O2 + +RC = brcc32 +RCFLAGS = -i. + +CFLAGS = /q /I. /D_WIN32_WINNT=0x400 /DHAVE_PTW32_CONFIG_H=1 /4 /tWD /tWM \ + /w-aus /w-asc /w-par + +#C cleanup code +BCFLAGS = $(PTW32_FLAGS) $(CFLAGS) + +# Agregate modules for inlinability +DLL_OBJS = \ + attr.obj \ + barrier.obj \ + cancel.obj \ + cleanup.obj \ + condvar.obj \ + create.obj \ + dll.obj \ + errno.obj \ + exit.obj \ + fork.obj \ + global.obj \ + misc.obj \ + mutex.obj \ + nonportable.obj \ + private.obj \ + rwlock.obj \ + sched.obj \ + semaphore.obj \ + signal.obj \ + spin.obj \ + sync.obj \ + tsd.obj + +INCL = config.h implement.h semaphore.h pthread.h need_errno.h + +ATTR_SRCS = \ + pthread_attr_init.c \ + pthread_attr_destroy.c \ + pthread_attr_getdetachstate.c \ + pthread_attr_setdetachstate.c \ + pthread_attr_getstackaddr.c \ + pthread_attr_setstackaddr.c \ + pthread_attr_getstacksize.c \ + pthread_attr_setstacksize.c \ + pthread_attr_getscope.c \ + pthread_attr_setscope.c + +BARRIER_SRCS = \ + pthread_barrier_init.c \ + pthread_barrier_destroy.c \ + pthread_barrier_wait.c \ + pthread_barrierattr_init.c \ + pthread_barrierattr_destroy.c \ + pthread_barrierattr_setpshared.c \ + pthread_barrierattr_getpshared.c + +CANCEL_SRCS = \ + pthread_setcancelstate.c \ + pthread_setcanceltype.c \ + pthread_testcancel.c \ + pthread_cancel.c + +CONDVAR_SRCS = \ + ptw32_cond_check_need_init.c \ + pthread_condattr_destroy.c \ + pthread_condattr_getpshared.c \ + pthread_condattr_init.c \ + pthread_condattr_setpshared.c \ + pthread_cond_destroy.c \ + pthread_cond_init.c \ + pthread_cond_signal.c \ + pthread_cond_wait.c + +EXIT_SRCS = \ + pthread_exit.c + +MISC_SRCS = \ + pthread_equal.c \ + pthread_getconcurrency.c \ + pthread_once.c \ + pthread_self.c \ + pthread_setconcurrency.c \ + ptw32_calloc.c \ + ptw32_MCS_lock.c \ + ptw32_new.c \ + w32_CancelableWait.c + +MUTEX_SRCS = \ + ptw32_mutex_check_need_init.c \ + pthread_mutex_init.c \ + pthread_mutex_destroy.c \ + pthread_mutexattr_init.c \ + pthread_mutexattr_destroy.c \ + pthread_mutexattr_getpshared.c \ + pthread_mutexattr_setpshared.c \ + pthread_mutexattr_settype.c \ + pthread_mutexattr_gettype.c \ + pthread_mutexattr_setrobust.c \ + pthread_mutexattr_getrobust.c \ + pthread_mutex_lock.c \ + pthread_mutex_timedlock.c \ + pthread_mutex_unlock.c \ + pthread_mutex_trylock.c \ + pthread_mutex_consistent.c + +NONPORTABLE_SRCS = \ + pthread_mutexattr_setkind_np.c \ + pthread_mutexattr_getkind_np.c \ + pthread_getw32threadhandle_np.c \ + pthread_delay_np.c \ + pthread_num_processors_np.c \ + pthread_win32_attach_detach_np.c \ + pthread_timechange_handler_np.c + +PRIVATE_SRCS = \ + ptw32_is_attr.c \ + ptw32_processInitialize.c \ + ptw32_processTerminate.c \ + ptw32_threadStart.c \ + ptw32_threadDestroy.c \ + ptw32_tkAssocCreate.c \ + ptw32_tkAssocDestroy.c \ + ptw32_callUserDestroyRoutines.c \ + ptw32_timespec.c \ + ptw32_relmillisecs.c \ + ptw32_throw.c \ + ptw32_getprocessors.c + +RWLOCK_SRCS = \ + ptw32_rwlock_check_need_init.c \ + ptw32_rwlock_cancelwrwait.c \ + pthread_rwlock_init.c \ + pthread_rwlock_destroy.c \ + pthread_rwlockattr_init.c \ + pthread_rwlockattr_destroy.c \ + pthread_rwlockattr_getpshared.c \ + pthread_rwlockattr_setpshared.c \ + pthread_rwlock_rdlock.c \ + pthread_rwlock_timedrdlock.c \ + pthread_rwlock_wrlock.c \ + pthread_rwlock_timedwrlock.c \ + pthread_rwlock_unlock.c \ + pthread_rwlock_tryrdlock.c \ + pthread_rwlock_trywrlock.c + +SCHED_SRCS = \ + pthread_attr_setschedpolicy.c \ + pthread_attr_getschedpolicy.c \ + pthread_attr_setschedparam.c \ + pthread_attr_getschedparam.c \ + pthread_attr_setinheritsched.c \ + pthread_attr_getinheritsched.c \ + pthread_setschedparam.c \ + pthread_getschedparam.c \ + sched_get_priority_max.c \ + sched_get_priority_min.c \ + sched_setscheduler.c \ + sched_getscheduler.c \ + sched_yield.c + +SEMAPHORE_SRCS = \ + sem_init.c \ + sem_destroy.c \ + sem_trywait.c \ + sem_timedwait.c \ + sem_wait.c \ + sem_post.c \ + sem_post_multiple.c \ + sem_getvalue.c \ + sem_open.c \ + sem_close.c \ + sem_unlink.c + +SPIN_SRCS = \ + ptw32_spinlock_check_need_init.c \ + pthread_spin_init.c \ + pthread_spin_destroy.c \ + pthread_spin_lock.c \ + pthread_spin_unlock.c \ + pthread_spin_trylock.c + +SYNC_SRCS = \ + pthread_detach.c \ + pthread_join.c + +TSD_SRCS = \ + pthread_key_create.c \ + pthread_key_delete.c \ + pthread_setspecific.c \ + pthread_getspecific.c + + +all: clean $(DLLS) + +realclean: clean + if exist pthread*.dll del pthread*.dll + if exist pthread*.lib del pthread*.lib + if exist *.stamp del *.stamp + +clean: + if exist *.obj del *.obj + if exist *.ilk del *.ilk + if exist *.ilc del *.ilc + if exist *.ild del *.ild + if exist *.ilf del *.ilf + if exist *.ils del *.ils + if exist *.tds del *.tds + if exist *.pdb del *.pdb + if exist *.exp del *.exp + if exist *.map del *.map + if exist *.o del *.o + if exist *.i del *.i + if exist *.res del *.res + + +install: $(DLLS) + copy pthread*.dll $(DLLDEST) + copy pthread*.lib $(LIBDEST) + +$(DLLS): $(DLL_OBJS) version.res + ilink32 /Tpd /Gi c0d32x.obj $(DLL_OBJS), \ + $@, ,\ + cw32mti.lib import32.lib, ,\ + version.res + +.c.obj: + $(CC) $(OPTIM) $(BCFLAGS) -c $< + +.rc.res: + $(RC) $(RCFLAGS) $< + +attr.obj: attr.c $(ATTR_SRCS) $(INCL) +barrier.obj: barrier.c $(BARRIER_SRCS) $(INCL) +cancel.obj: cancel.c $(CANCEL_SRCS) $(INCL) +condvar.obj: condvar.c $(CONDVAR_SRCS) $(INCL) +exit.obj: exit.c $(EXIT_SRCS) $(INCL) +misc.obj: misc.c $(MISC_SRCS) $(INCL) +mutex.obj: mutex.c $(MUTEX_SRCS) $(INCL) +nonportable.obj: nonportable.c $(NONPORTABLE_SRCS) $(INCL) +private.obj: private.c $(PRIVATE_SRCS) $(INCL) +rwlock.obj: rwlock.c $(RWLOCK_SRCS) $(INCL) +sched.obj: sched.c $(SCHED_SRCS) $(INCL) +semaphore.obj: semaphore.c $(SEMAPHORE_SRCS) $(INCL) +spin.obj: spin.c $(SPIN_SRCS) $(INCL) +sync.obj: sync.c $(SYNC_SRCS) $(INCL) +tsd.obj: tsd.c $(TSD_SRCS) $(INCL) +version.res: version.rc $(INCL) diff --git a/w32-pthreads/CONTRIBUTORS b/w32-pthreads/CONTRIBUTORS new file mode 100644 index 000000000..da31ff266 --- /dev/null +++ b/w32-pthreads/CONTRIBUTORS @@ -0,0 +1,140 @@ +Contributors (in approximate order of appearance) + +[See also the ChangeLog file where individuals are +attributed in log entries. Likewise in the FAQ file.] + +Ben Elliston bje at cygnus dot com + Initiated the project; + setup the project infrastructure (CVS, web page, etc.); + early prototype routines. +Ross Johnson Ross dot Johnson at dot homemail dot com dot au + early prototype routines; + ongoing project coordination/maintenance; + implementation of spin locks and barriers; + various enhancements; + bug fixes; + documentation; + testsuite. +Robert Colquhoun rjc at trump dot net dot au + Early bug fixes. +John E. Bossom John dot Bossom at cognos dot com + Contributed substantial original working implementation; + bug fixes; + ongoing guidance and standards interpretation. +Anders Norlander anorland at hem2 dot passagen dot se + Early enhancements and runtime checking for supported + Win32 routines. +Tor Lillqvist tml at iki dot fi + General enhancements; + early bug fixes to condition variables. +Scott Lightner scott at curriculum dot com + Bug fix. +Kevin Ruland Kevin dot Ruland at anheuser-busch dot com + Various bug fixes. +Mike Russo miker at eai dot com + Bug fix. +Mark E. Armstrong avail at pacbell dot net + Bug fixes. +Lorin Hochstein lmh at xiphos dot ca + general bug fixes; bug fixes to condition variables. +Peter Slacik Peter dot Slacik at tatramed dot sk + Bug fixes. +Mumit Khan khan at xraylith dot wisc dot edu + Fixes to work with Mingw32. +Milan Gardian mg at tatramed dot sk + Bug fixes and reports/analyses of obscure problems. +Aurelio Medina aureliom at crt dot com + First implementation of read-write locks. +Graham Dumpleton Graham dot Dumpleton at ra dot pad dot otc dot telstra dot com dot au + Bug fix in condition variables. +Tristan Savatier tristan at mpegtv dot com + WinCE port. +Erik Hensema erik at hensema dot xs4all dot nl + Bug fixes. +Rich Peters rpeters at micro-magic dot com +Todd Owen towen at lucidcalm dot dropbear dot id dot au + Bug fixes to dll loading. +Jason Nye jnye at nbnet dot nb dot ca + Implementation of async cancelation. +Fred Forester fforest at eticomm dot net +Kevin D. Clark kclark at cabletron dot com +David Baggett dmb at itasoftware dot com + Bug fixes. +Paul Redondo paul at matchvision dot com +Scott McCaskill scott at 3dfx dot com + Bug fixes. +Jef Gearhart jgearhart at tpssys dot com + Bug fix. +Arthur Kantor akantor at bexusa dot com + Mutex enhancements. +Steven Reddie smr at essemer dot com dot au + Bug fix. +Alexander Terekhov TEREKHOV at de dot ibm dot com + Re-implemented and improved read-write locks; + (with Louis Thomas) re-implemented and improved + condition variables; + enhancements to semaphores; + enhancements to mutexes; + new mutex implementation in 'futex' style; + suggested a robust implementation of pthread_once + similar to that implemented by V.Kliathcko; + system clock change handling re CV timeouts; + bug fixes. +Thomas Pfaff tpfaff at gmx dot net + Changes to make C version usable with C++ applications; + re-implemented mutex routines to avoid Win32 mutexes + and TryEnterCriticalSection; + procedure to fix Mingw32 thread-safety issues. +Franco Bez franco dot bez at gmx dot de + procedure to fix Mingw32 thread-safety issues. +Louis Thomas lthomas at arbitrade dot com + (with Alexander Terekhov) re-implemented and improved + condition variables. +David Korn dgk at research dot att dot com + Ported to UWIN. +Phil Frisbie, Jr. phil at hawksoft dot com + Bug fix. +Ralf Brese Ralf dot Brese at pdb4 dot siemens dot de + Bug fix. +prionx at juno dot com prionx at juno dot com + Bug fixes. +Max Woodbury mtew at cds dot duke dot edu + POSIX versioning conditionals; + reduced namespace pollution; + idea to separate routines to reduce statically + linked image sizes. +Rob Fanner rfanner at stonethree dot com + Bug fix. +Michael Johnson michaelj at maine dot rr dot com + Bug fix. +Nicolas Barry boozai at yahoo dot com + Bug fixes. +Piet van Bruggen pietvb at newbridges dot nl + Bug fix. +Makoto Kato raven at oldskool dot jp + AMD64 port. +Panagiotis E. Hadjidoukas peh at hpclab dot ceid dot upatras dot gr + phadjido at cs dot uoi dot gr + Contributed the QueueUserAPCEx package which + makes preemptive async cancelation possible. +Will Bryant will dot bryant at ecosm dot com + Borland compiler patch and makefile. +Anuj Goyal anuj dot goyal at gmail dot com + Port to Digital Mars compiler. +Gottlob Frege gottlobfrege at gmail dot com + re-implemented pthread_once (version 2) + (pthread_once cancellation added by rpj). +Vladimir Kliatchko vladimir at kliatchko dot com + reimplemented pthread_once with the same form + as described by A.Terekhov (later version 2); + implementation of MCS (Mellor-Crummey/Scott) locks. +Ramiro Polla ramiro.polla at gmail dot com + static library auto init/cleanup on application + start/exit via RT hooks (MSC and GCC compilers only). +Daniel Richard G. skunk at iSKUNK dot org + Patches and cleanups for x86 and x64, particularly + across a range of MS build environments. +John Kamp john dot kamp at globalgraphics dot com + Patches to fix various problems on x64; brutal testing + particularly using high memory run environments. + diff --git a/w32-pthreads/COPYING b/w32-pthreads/COPYING new file mode 100644 index 000000000..5cfea0d0e --- /dev/null +++ b/w32-pthreads/COPYING @@ -0,0 +1,150 @@ + pthreads-win32 - a POSIX threads library for Microsoft Windows + + +This file is Copyrighted +------------------------ + + This file is covered under the following Copyright: + + Copyright (C) 2001,2006 Ross P. Johnson + All rights reserved. + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +Pthreads-win32 is covered by the GNU Lesser General Public License +------------------------------------------------------------------ + + Pthreads-win32 is open software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public License + as published by the Free Software Foundation version 2.1 of the + License. + + Pthreads-win32 is several binary link libraries, several modules, + associated interface definition files and scripts used to control + its compilation and installation. + + Pthreads-win32 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 Lesser General Public License for more details. + + A copy of the GNU Lesser General Public License is distributed with + pthreads-win32 under the filename: + + COPYING.LIB + + You should have received a copy of the version 2.1 GNU Lesser General + Public License with pthreads-win32; if not, write to: + + Free Software Foundation, Inc. + 59 Temple Place + Suite 330 + Boston, MA 02111-1307 + USA + + The contact addresses for pthreads-win32 is as follows: + + Web: http://sources.redhat.com/pthreads-win32 + Email: Ross Johnson + Please use: Firstname.Lastname@homemail.com.au + + + +Pthreads-win32 copyrights and exception files +--------------------------------------------- + + With the exception of the files listed below, Pthreads-win32 + is covered under the following GNU Lesser General Public License + Copyrights: + + Pthreads-win32 - POSIX Threads Library for Win32 + Copyright(C) 1998 John E. Bossom + Copyright(C) 1999,2006 Pthreads-win32 contributors + + The current list of contributors is contained + in the file CONTRIBUTORS included with the source + code distribution. The current list of CONTRIBUTORS + can also be seen at the following WWW location: + http://sources.redhat.com/pthreads-win32/contributors.html + + Contact Email: Ross Johnson + Please use: Firstname.Lastname@homemail.com.au + + These files are not covered under one of the Copyrights listed above: + + COPYING + COPYING.LIB + tests/rwlock7.c + + This file, COPYING, is distributed under the Copyright found at the + top of this file. It is important to note that you may distribute + verbatim copies of this file but you may not modify this file. + + The file COPYING.LIB, which contains a copy of the version 2.1 + GNU Lesser General Public License, is itself copyrighted by the + Free Software Foundation, Inc. Please note that the Free Software + Foundation, Inc. does NOT have a copyright over Pthreads-win32, + only the COPYING.LIB that is supplied with pthreads-win32. + + The file tests/rwlock7.c is derived from code written by + Dave Butenhof for his book 'Programming With POSIX(R) Threads'. + The original code was obtained by free download from his website + http://home.earthlink.net/~anneart/family/Threads/source.html + and did not contain a copyright or author notice. It is assumed to + be freely distributable. + + In all cases one may use and distribute these exception files freely. + And because one may freely distribute the LGPL covered files, the + entire pthreads-win32 source may be freely used and distributed. + + + +General Copyleft and License info +--------------------------------- + + For general information on Copylefts, see: + + http://www.gnu.org/copyleft/ + + For information on GNU Lesser General Public Licenses, see: + + http://www.gnu.org/copyleft/lesser.html + http://www.gnu.org/copyleft/lesser.txt + + +Why pthreads-win32 did not use the GNU General Public License +------------------------------------------------------------- + + The goal of the pthreads-win32 project has been to + provide a quality and complete implementation of the POSIX + threads API for Microsoft Windows within the limits imposed + by virtue of it being a stand-alone library and not + linked directly to other POSIX compliant libraries. For + example, some functions and features, such as those based + on POSIX signals, are missing. + + Pthreads-win32 is a library, available in several different + versions depending on supported compilers, and may be used + as a dynamically linked module or a statically linked set of + binary modules. It is not an application on it's own. + + It was fully intended that pthreads-win32 be usable with + commercial software not covered by either the GPL or the LGPL + licenses. Pthreads-win32 has many contributors to it's + code base, many of whom have done so because they have + used the library in commercial or proprietry software + projects. + + Releasing pthreads-win32 under the LGPL ensures that the + library can be used widely, while at the same time ensures + that bug fixes and improvements to the pthreads-win32 code + itself is returned to benefit all current and future users + of the library. + + Although pthreads-win32 makes it possible for applications + that use POSIX threads to be ported to Win32 platforms, the + broader goal of the project is to encourage the use of open + standards, and in particular, to make it just a little easier + for developers writing Win32 applications to consider + widening the potential market for their products. diff --git a/w32-pthreads/COPYING.LIB b/w32-pthreads/COPYING.LIB new file mode 100644 index 000000000..b1e3f5a26 --- /dev/null +++ b/w32-pthreads/COPYING.LIB @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +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 this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser 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 Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "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 +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY 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 +LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey 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 library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/w32-pthreads/ChangeLog b/w32-pthreads/ChangeLog new file mode 100644 index 000000000..42abcc457 --- /dev/null +++ b/w32-pthreads/ChangeLog @@ -0,0 +1,5211 @@ +2012-03-18 Ross Johnson + + * create.c (pthread_create): add __cdecl attribute to thread routine + arg + * implement.h (pthread_key_t): add __cdecl attribute to destructor + element + (ThreadParms): likewise for start element + * pthread.h (pthread_create): add __cdecl to prototype start arg + (pthread_once): likewise for init_routine arg + (pthread_key_create): likewise for destructor arg + (ptw32_cleanup_push): replace type of routine arg with previously + defined ptw32_cleanup_callback_t + * pthread_key_create.c: add __cdecl attribute to destructor arg + * pthread_once.c: add __cdecl attribute to init_routine arg + * ptw32_threadStart.c (start): add __cdecl to start variable type + + +2011-07-06 Ross Johnson + + * pthread_cond_wait.c (pragma inline_depth): this is almost redundant + now nevertheless fixed thei controlling MSC_VER from "< 800" to + "< 1400" (i.e. any prior to VC++ 8.0). + * pthread_once.ci (pragma inline_depth): Likewise. + * pthread_rwlock_timedwrlock.ci (pragma inline_depth): Likewise. + * pthread_rwlock_wrlock.ci (pragma inline_depth): Likewise. + * sem_timedwait.ci (pragma inline_depth): Likewise. + * sem_wait.ci (pragma inline_depth): Likewise. + +2011-07-05 Ross Johnson + + * pthread_win32_attach_detach_np.c: Use strncat_s if available + to removei a compile warning; MingW supports this routine but we + continue to use strncat anyway there because it is secure if + given the correct parameters; fix strncat param 3 to avoid + buffer overrun exploitation potential. + +2011-07-03 Ross Johnson + + * pthread_spin_unlock.c (EPERM): Return success if unlocking a lock + that is not locked, because single CPU machines wrap a + PTHREAD_MUTEX_NORMAL mutex, which returns success in this case. + * pthread_win32_attach_detach_np.c (QUSEREX.DLL): Load from an + absolute path only which must be the Windows System folder. + +2011-07-03 Daniel Richard G. + + * Makefile (_WIN32_WINNT): Removed; duplicate definition in + implement.h; more cleanup and enhancements. + +2011-07-02 Daniel Richard G. + + * Makefile: Cleanups and implovements. + * ptw32_MCS_locks.c: Casting fixes. + * implement.h: Interlocked call and argument casting macro fixes + to support older and newer build environments. + +2011-07-01 Ross Johnson + + * *.[ch] (PTW32_INTERLOCKED_*): Redo 23 and 64 bit versions of these + macros and re-apply in code to undo the incorrect changes from + 2011-06-29; remove some size_t casts which should not be required + and may be problematic.a + There are now two sets of macros: + PTW32_INTERLOCKED_*_LONG which work only on 32 bit integer variables; + PTW32_INTERLOCKED_*_SIZE which work on size_t integer variables, i.e. + LONG for 32 bit systems and LONGLONG for 64 bit systems. + * implement.h (MCS locks): nextFlag and waitFlag are now HANDLE type. + * ptw32_MCS_locks.c: Likewise. + * pthread.h (#include ): Removed. + * ptw32_throw.c (#include ): Added. + * ptw32_threadStart.c (#include ): Added. + * implement.h (#include ): Added. + +2011-06-30 Ross Johnson + + * pthread_once.c: Tighten 'if' statement casting; fix interlocked + pointer cast for 64 bit compatibility (missed yesterday); remove + the superfluous static cleanup routine and call the release routine + directly if popped. + * create.c (stackSize): Now type size_t. + * pthread.h (struct ptw32_thread_t_): Rearrange to fix element alignments. + +2011-06-29 Daniel Richard G. + + * ptw32_relmillisecs.c (ftime): + _ftime64_s() is only available in MSVC 2005 or later; + _ftime64() is available in MinGW or MSVC 2002 or later; + _ftime() is always available. + * pthread.h (long long): Not defined in older MSVC 6. + * implement.h (long long): Likewise. + * pthread_getunique_np.c (long long): Likewise. + +2011-06-29 Ross Johnson + + * *.[ch] (PTW32_INTERLOCKED_*): These macros should now work for + both 32 and 64 bit builds. The MingW versions are all inlined asm + while the MSVC versions expand to their Interlocked* or Interlocked*64 + counterparts appropriately. The argument type have also been changed + to cast to the appropriate value or pointer size for the architecture. + +2011-05-29 Ross Johnson + + * *.[ch] (#ifdef): Extended cleanup to whole project. + +2011-05-29 Daniel Richard G. + + * Makefile (CC): Define CC to allow use of other compatible + compilers such as the Intel compilter icl. + * implement.h (#if): Fix forms like #if HAVE_SOMETHING. + * pthread.h: Likewise. + * sched.h: Likewise; PTW32_LEVEL_* becomes PTW32_SCHED_LEVEL_*. + * semaphore.h: Likewise. + +2011-05-11 Ross Johnson + + * ptw32_callUserDestroyRoutines.c (terminate): Altered includes + to match ptw32_threadStart.c. + * GNUmakefile (GCE-inlined-debug, DOPT): Fixed. + +2011-04-31 Ross Johnson + + * (robust mutexes): Added this API. The API is not + mandatory for implementations that don't support PROCESS_SHARED + mutexes, nevertheless it was considered useful both functionally + and for source-level compatibility. + +2011-03-26 Ross Johnson + + * pthread_getunique_np.c: New non-POSIX interface for compatibility + with some other implementations; returns a 64 bit sequence number + that is unique to each thread in the process. + * pthread.h (pthread_getunique_np): Added. + * global.c: Add global sequence counter for above. + * implement.h: Likewise. + +2011-03-25 Ross Johnson + + * (cancelLock): Convert to an MCS lock and rename to stateLock. + * (threadLock): Likewise. + * (keyLock): Likewise. + * pthread_mutex*.c: First working robust mutexes. + +2011-03-11 Ross Johnson + + * implement.h (PTW32_INTERLOCKED_*CREMENT macros): increment/decrement + using ++/-- instead of add/subtract 1. + * ptw32_MCS_lock.c: Make casts consistent. + +2011-03-09 Ross Johnson + + * implement.h (ptw32_thread_t_): Add process unique sequence number. + * global.c: Replace global Critical Section objects with MCS + queue locks. + * implement.h: Likewise. + * pthread_cond_destroy.c: Likewise. + * pthread_cond_init.c: Likewise. + * pthread_detach.c: Likewise. + * pthread_join.c: Likewise. + * pthread_kill.c: Likewise. + * pthread_mutex_destroy.c: Likewise. + * pthread_rwlock_destroy.c: Likewise. + * pthread_spin_destroy.c: Likewise. + * pthread_timechange_handler_np.c: Likewise. + * ptw32_cond_check_need_init.c: Likewise. + * ptw32_mutex_check_need_init.c: Likewise. + * ptw32_processInitialize.c: Likewise. + * ptw32_processTerminate.c: Likewise. + * ptw32_reuse.c: Likewise. + * ptw32_rwlock_check_need_init.c: Likewise. + * ptw32_spinlock_check_need_init.c: Likewise. + +2011-03-06 Ross Johnson + + * several (MINGW64): Cast and call fixups for 64 bit compatibility; + clean build via x86_64-w64-mingw32 cross toolchain on Linux i686 + targeting x86_64 win64. + * ptw32_threadStart.c (ptw32_threadStart): Routine no longer attempts + to pass [unexpected C++] exceptions out of scope but ends the thread + normally setting EINTR as the exit status. + * ptw32_throw.c: Fix C++ exception throwing warnings; ignore + informational warning. + * implement.h: Likewise with the corresponding header definition. + +2011-03-04 Ross Johnson + + * implement.h (PTW32_INTERLOCKED_*): Mingw32 does not provide + the __sync_* intrinsics so implemented them here as macro + assembler routines. MSVS Interlocked* are emmitted as intrinsics + wherever possible, so we want mingw to match it; Extended to + include all interlocked routines used by the library; implemented + x86_64 versions also. + * ptw32_InterlockedCompareExchange.c: No code remaining here. + * ptw32_MCS_lock.c: Converted interlocked calls to use new macros. + * pthread_barrier_wait.c: Likewise. + * pthread_once.c: Likewise. + * ptw32_MCS_lock.c (ptw32_mcs_node_substitute): Name changed to + ptw32_mcs_node_transfer. + +2011-02-28 Ross Johnson + + * ptw32_relmillisecs.c: If possible, use _ftime64_s or _ftime64 + before resorting to _ftime. + +2011-02-27 Ross Johnson + + * sched_setscheduler.c: Ensure the handle is closed after use. + * sched_getscheduler.c: Likewise. + * pthread.h: Remove POSIX compatibility macros; don't define + timespec if already defined. + * context.h: Changes for 64 bit. + * pthread_cancel.c: Likewise. + * pthread_exit.c: Likewise. + * pthread_spin_destroy.c: Likewise. + * pthread_timechange_handler_np.c: Likewise. + * ptw32_MCS_lock.c: Likewise; some of these changes may + not be compatible with pre Windows 2000 systems; reverse the order of + the includes. + * ptw32_threadStart.c: Likewise. + * ptw32_throw.c: Likewise. + +2011-02-13 Ross Johnson + + * pthread_self: Add comment re returning 'nil' value to + indicate failure only to win32 threads that call us. + * pthread_attr_setstackaddr: Fix comments; note this + function and it's compliment are now removed from SUSv4. + +2011-02-12 Ross Johnson + + README.NONPORTABLE: Record a description of an obvious + method for nulling/comparing/hashing pthread_t using a + union; plus and investigation of a change of type for + pthread_t (to a union) to neutralise any padding bits and + bytes if they occur in pthread_t (the current pthread_t struct + does not contain padding AFAIK, but porting the library to a + future architecture may introduce them). Padding affects + byte-by-byte copies and compare operations. + +2010-11-16 Ross Johnson + + * ChangeLog: Add this entry ;-) + Restore entries from 2007 through 2009 that went missing + at the last update. + +2010-06-19 Ross Johnson + + * ptw32_MCS_lock.c (ptw32_mcs_node_substitute): Fix variable + names to avoid using C++ keyword ("new"). + * implement.h (ptw32_mcs_node_substitute): Likewise. + * pthread_barrier_wait.c: Fix signed/unsigned comparison warning. + +2010-06-18 Ramiro Polla + + * autostatic.c: New file; call pthread_win32_process_*() + libary init/cleanup routines automatically on application start + when statically linked. + * pthread.c (autostatic.c): Included. + * pthread.h (declspec): Remove import/export defines if compiler + is MINGW. + * sched.h (declspec): Likewise. + * semaphore.h (declspec): Likewise. + * need_errno.h (declspec): Likewise. + * Makefile (autostatic.obj): Add for small static builds. + * GNUmakefile (autostatic.o): Likewise. + * NEWS (Version 2.9.0): Add changes. + * README.NONPORTABLE (pthread_win32_process_*): Update + description. + +2010-06-15 Ramiro Polla + + * Makefile: Remove linkage with the winsock library by default. + * GNUmakefile: Likewise. + * pthread_getspecific.c: Likewise by removing calls to WSA + functions. + * config.h (RETAIN_WSALASTERROR): Can be defined if necessary. + +2010-01-26 Ross Johnson + + * ptw32_MCS_lock.c (ptw32_mcs_node_substitute): New routine + to allow relocating the lock owners thread-local node to somewhere + else, e.g. to global space so that another thread can release the + lock. Used in pthread_barrier_wait. + (ptw32_mcs_lock_try_acquire): New routine. + * pthread_barrier_init: Only one semaphore is used now. + * pthread_barrier_wait: Added an MCS guard lock with the last thread + to leave the barrier releasing the lock. This removes a deadlock bug + observed when there are greater than barrier-count threads + attempting to cross. + * pthread_barrier_destroy: Added an MCS guard lock. + +2009-03-03 Stephan O'Farrill + + * pthread_attr_getschedpolicy.c: Add "const" to function parameter + in accordance with SUSv3 (POSIX). + * pthread_attr_getinheritsched.c: Likewise. + * pthread_mutexattr_gettype.c: Likewise. + +2008-06-06 Robert Kindred + + * ptw32_throw.c (ptw32_throw): Remove possible reference to NULL + pointer. (At the same time made the switch block conditionally + included only if exitCode is needed - RPJ.) + * pthread_testcancel.c (pthread_testcancel): Remove duplicate and + misplaced pthread_mutex_unlock(). + +2008-02-21 Sebastian Gottschalk + + * pthread_attr_getdetachstate.c (pthread_attr_getdetachstate): + Remove potential and superfluous null pointer assignment. + +2007-11-22 Ivan Pizhenko + + * pthread.h (gmtime_r): gmtime returns 0 if tm represents a time + prior to 1/1/1970. Notice this to prevent raising an exception. + * pthread.h (localtime_r): Likewise for localtime. + +2007-07-14 Marcel Ruff + + * errno.c (_errno): Fix test for pthread_self() success. + * need_errno.h: Remove unintentional line wrap from #if line. + +2007-07-14 Mike Romanchuk + + * pthread.h (timespec): Fix tv_sec type. + +2007-01-07 Sinan Kaya + + * need_errno.h: Fix declaration of _errno - the local version of + _errno() is used, e.g. by WinCE. + +2007-01-06 Ross Johnson + + * ptw32_semwait.c: Add check for invalid sem_t after acquiring the + sem_t state guard mutex and before affecting changes to sema state. + +2007-01-06 Marcel Ruff + + * error.c: Fix reference to pthread handle exitStatus member for + builds that use NEED_ERRNO (i.e. WINCE). + * context.h: Add support for ARM processor (WinCE). + * mutex.c (process.h): Exclude for WINCE. + * create.c: Likewise. + * exit.c: Likewise. + * implement.h: Likewise. + * pthread_detach.c (signal.h): Exclude for WINCE. + * pthread_join.c: Likewise. + * pthread_kill.c: Likewise. + * pthread_rwlock_init.c (errno.h): Remove - included by pthread.h. + * pthread_rwlock_destroy.c: Likewise. + * pthread_rwlock_rdlock.c: Likewise. + * pthread_rwlock_timedrdlock.c: Likewise. + * pthread_rwlock_timedwrlock.c: Likewise. + * pthread_rwlock_tryrdlock.c: Likewise. + * pthread_rwlock_trywrlock.c: likewise. + * pthread_rwlock_unlock.c: Likewise. + * pthread_rwlock_wrlock.c: Likewise. + * pthread_rwlockattr_destroy.c: Likewise. + * pthread_rwlockattr_getpshared.c: Likewise. + * pthread_rwlockattr_init.c: Likewise. + * pthread_rwlockattr_setpshared.c: Likewise. + +2007-01-06 Romano Paolo Tenca + + * pthread_cond_destroy.c: Replace sem_wait() with non-cancelable + ptw32_semwait() since pthread_cond_destroy() is not a cancelation + point. + * implement.h (ptw32_spinlock_check_need_init): Add prototype. + * ptw32_MCS_lock.c: Reverse order of includes. + +2007-01-06 Eric Berge + + * pthread_cond_destroy.c: Add LeaveCriticalSection before returning + after errors. + +2007-01-04 Ross Johnson + + * ptw32_InterlockedCompareExchange.c: Conditionally skip for + Win64 as not required. + * pthread_win32_attach_detach_np.c (pthread_win32_process_attach_np): + Test for InterlockedCompareExchange is not required for Win64. + * context.h: New file. Included by pthread_cancel.h and any tests + that need it (e.g. context1.c). + * pthread_cancel.c: Architecture-dependent context macros moved + to context.h. + +2007-01-04 Kip Streithorst + + * implement.h (PTW32_INTERLOCKED_COMPARE_EXCHANGE): Add Win64 + support. + +2006-12-20 Ross Johnson + + * sem_destroy.c: Fix the race involving invalidation of the sema; + fix incorrect return of EBUSY resulting from the mutex trylock + on the private mutex guard. + * sem_wait.c: Add check for invalid sem_t after acquiring the + sem_t state guard mutex and before affecting changes to sema state. + * sem_trywait.c: Likewise. + * sem_timedwait.c: Likewise. + * sem_getvalue.c: Likewise. + * sem_post.c: Similar. + * sem_post_multiple.c: Likewise. + * sem_init.c: Set max Win32 semaphore count to SEM_VALUE_MAX (was + _POSIX_SEM_VALUE_MAX, which is a lower value - the minimum). + + * pthread_win32_attach_detach_np.c (pthread_win32_process_attach_np): + Load COREDLL.DLL under WINCE to check existence of + InterlockedCompareExchange() routine. This used to be done to test + for TryEnterCriticalSection() but was removed when this was no + longer needed. + +2006-01-25 Prashant Thakre + + * pthread_cancel.c: Added _M_IA64 register context support. + +2005-05-13 Ross Johnson + + * pthread_kill.c (pthread_kill): Remove check for Win32 thread + priority (to confirm HANDLE validity). Useless since thread HANDLEs + a not recycle-unique. + +2005-05-30 Vladimir Kliatchko + + * pthread_once.c: Re-implement using an MCS queue-based lock. The form + of pthread_once is as proposed by Alexander Terekhov (see entry of + 2005-03-13). The MCS lock implementation does not require a unique + 'name' to identify the lock between threads. Attempts to get the Event + or Semaphore based versions of pthread_once to a satisfactory level + of robustness have thus far failed. The last problem (avoiding races + involving non recycle-unique Win32 HANDLEs) was giving everyone + grey hair trying to solve it. + + * ptw32_MCS_lock.c: New MCS queue-based lock implementation. These + locks are efficient: they have very low overhead in the uncontended case; + are efficient in contention and minimise cache-coherence updates in + managing the user level FIFO queue; do not require an ABI change in the + library. + +2005-05-27 Alexander Gottwald + + * pthread.h: Some things, like HANDLE, were only defined if + PTW32_LEVEL was >= 3. They should always be defined. + +2005-05-25 Vladimir Kliatchko + + * pthread_once.c: Eliminate all priority operations and other + complexity by replacing the event with a semaphore. The advantage + of the change is the ability to release just one waiter if the + init_routine thread is cancelled yet still release all waiters when + done. Simplify once_control state checks to improve efficiency + further. + +2005-05-24 Mikael Magnusson + + * GNUmakefile: Patched to allow cross-compile with mingw32 on Linux. + It uses macros instead of referencing dlltool, gcc and g++ directly; + added a call to ranlib. For example the GC static library can be + built with: + make CC=i586-mingw32msvc-gcc RC=i586-mingw32msvc-windres \ + RANLIB=i586-mingw32msvc-ranlib clean GC-static + +2005-05-13 Ross Johnson + + * pthread_win32_attach_detach_np.c (pthread_win32_thread_detach_np): + Move on-exit-only stuff from ptw32_threadDestroy() to here. + * ptw32_threadDestroy.c: It's purpose is now only to reclaim thread + resources for detached threads, or via pthread_join() or + pthread_detach() on joinable threads. + * ptw32_threadStart.c: Calling user destruct routines has moved to + pthread_win32_thread_detach_np(); call pthread_win32_thread_detach_np() + directly if statically linking, otherwise do so via dllMain; store + thread return value in thread struct for all cases, including + cancellation and exception exits; thread abnormal exits go via + pthread_win32_thread_detach_np. + * pthread_join.c (pthread_join): Don't try to get return code from + Win32 thread - always get it from he thread struct. + * pthread_detach.c (pthread_detach): reduce extent of the thread + existence check since we now don't care if the Win32 thread HANDLE has + been closed; reclaim thread resources if the thread has exited already. + * ptw32_throw.c (ptw32_throw): For Win32 threads that are not implicit, + only Call thread cleanup if statically linking, otherwise leave it to + dllMain. + * sem_post.c (_POSIX_SEM_VALUE_MAX): Change to SEM_VALUE_MAX. + * sem_post_multiple.c: Likewise. + * sem_init.c: Likewise. + +2005-05-10 Ross Johnson + + * pthread_join.c (pthread_join): Add missing check for thread ID + reference count in thread existence test; reduce extent of the + existence test since we don't care if the Win32 thread HANDLE has + been closed. + +2005-05-09 Ross Johnson + + * ptw32_callUserDestroyRoutines.c: Run destructor process (i.e. + loop over all keys calling destructors) up to + PTHREAD_DESTRUCTOR_ITERATIONS times if TSD value isn't NULL yet; + modify assoc management. + * pthread_key_delete.c: Modify assoc management. + * ptw32_tkAssocDestroy.c: Fix error in assoc removal from chains. + * pthread.h + (_POSIX_THREAD_DESTRUCTOR_ITERATIONS): Define to value specified by + POSIX. + (_POSIX_THREAD_KEYS_MAX): Define to value specified by POSIX. + (PTHREAD_KEYS_MAX): Redefine [upward] to minimum required by POSIX. + (SEM_NSEMS_MAX): Define to implementation value. + (SEM_VALUE_MAX): Define to implementation value. + (_POSIX_SEM_NSEMS_MAX): Redefine to value specified by POSIX. + (_POSIX_SEM_VALUE_MAX): Redefine to value specified by POSIX. + +2005-05-06 Ross Johnson + + * signal.c (sigwait): Add a cancellation point to this otherwise + no-op. + * sem_init.c (sem_init): Check for and return ERANGE error. + * sem_post.c (sem_post): Likewise. + * sem_post_multiple.c (sem_post_multiple): Likewise. + * manual (directory): Added; see ChangeLog inside. + +2005-05-02 Ross Johnson + + * implement.h (struct pthread_key_t_): Change threadsLock to keyLock + so as not to be confused with the per thread lock 'threadlock'; + change all references to it. + * implement.h (struct ThreadKeyAssoc): Remove lock; add prevKey + and prevThread pointers; re-implemented all routines that use this + struct. The effect of this is to save one handle per association, + which could potentially equal the number of keys multiplied by the + number of threads, accumulating over time - and to free the + association memory as soon as it is no longer referenced by either + the key or the thread. Previously, the handle and memory were + released only after BOTH key and thread no longer referenced the + association. That is, often no association resources were released + until the process itself exited. In addition, at least one race + condition has been removed - where two threads could attempt to + release the association resources simultaneously - one via + ptw32_callUserDestroyRoutines and the other via + pthread_key_delete. + - thanks to Richard Hughes at Aculab for discovering the problem. + * pthread_key_create.c: See above. + * pthread_key_delete.c: See above. + * pthread_setspecific.c: See above. + * ptw32_callUserDestroyRoutines.c: See above. + * ptw32_tkAssocCreate.c: See above. + * ptw32_tkAssocDestroy.c: See above. + +2005-04-27 Ross Johnson + + * sem_wait.c (ptw32_sem_wait_cleanup): after cancellation re-attempt + to acquire the semaphore to avoid a race with a late sem_post. + * sem_timedwait.c: Modify comments. + +2005-04-25 Ross Johnson + + * ptw32_relmillisecs.c: New module; converts future abstime to + milliseconds relative to 'now'. + * pthread_mutex_timedlock.c: Use new ptw32_relmillisecs routine in + place of internal code; remove the NEED_SEM code - this routine is now + implemented for builds that define NEED_SEM (WinCE etc) + * sem_timedwait.c: Likewise; after timeout or cancellation, + re-attempt to acquire the semaphore in case one has been posted since + the timeout/cancel occurred. Thanks to Stefan Mueller. + * Makefile: Add ptw32_relmillisecs.c module; remove + ptw32_{in,de}crease_semaphore.c modules. + * GNUmakefile: Likewise. + * Bmakefile: Likewise. + + * sem_init.c: Re-write the NEED_SEM code to be consistent with the + non-NEED_SEM code, but retaining use of an event in place of the w32 sema + for w32 systems that don't include semaphores (WinCE); + the NEED_SEM versions of semaphores has been broken for a long time but is + now fixed and supports all of the same routines as the non-NEED_SEM case. + * sem_destroy.c: Likewise. + * sem_wait.c: Likewise. + * sem_post.c: Likewise. + * sem_post_multple.c: Likewise. + * implement.h: Likewise. + * sem_timedwait.c: Likewise; this routine is now + implemented for builds that define NEED_SEM (WinCE etc). + * sem_trywait.c: Likewise. + * sem_getvalue.c: Likewise. + + * pthread_once.c: Yet more changes, reverting closer to Gottlob Frege's + first design, but retaining cancellation, priority boosting, and adding + preservation of W32 error codes to make pthread_once transparent to + GetLastError. + +2005-04-11 Ross Johnson + + * pthread_once.c (pthread_once): Added priority boosting to + solve starvation problem after once_routine cancellation. + See notes in file. + +2005-04-06 Kevin Lussier + + * Makefile: Added debug targets for all versions of the library. + +2005-04-01 Ross Johnson + + * GNUmakefile: Add target to build libpthreadGC1.a as a static link + library. + * Makefile: Likewise for pthreadGC1.lib. + +2005-04-01 Kevin Lussier + + * sem_timedwait.c (sem_timedwait): Increase size of temp variables to + avoid int overflows for large timeout values. + * implement.h (int64_t): Include or define. + +2005-03-31 Dimitar Panayotov ^M + + * pthread.h: Fix conditional defines for static linking. + * sched.h: Liekwise. + * semaphore.h: Likewise. + * dll.c (PTW32_STATIC_LIB): Module is conditionally included + in the build. + +2005-03-16 Ross Johnson ^M + + * pthread_setcancelstate.c: Undo the last change. + +2005-03-16 Ross Johnson ^M + + * pthread_setcancelstate.c: Don't check for an async cancel event + if the library is using alertable async cancel.. + +2005-03-14 Ross Johnson + + * pthread_once.c (pthread_once): Downgrade interlocked operations to simple + memory operations where these are protected by the critical section; edit + comments. + +2005-03-13 Ross Johnson + + * pthread_once.c (pthread_once): Completely redesigned; a change was + required to the ABI (pthread_once_t_), and resulting in a version + compatibility index increment. + + NOTES: + The design (based on pseudo code contributed by Gottlob Frege) avoids + creating a kernel object if there is no contention. See URL for details:- + http://sources.redhat.com/ml/pthreads-win32/2005/msg00029.html + This uses late initialisation similar to the technique already used for + pthreads-win32 mutexes and semaphores (from Alexander Terekhov). + + The subsequent cancelation cleanup additions (by rpj) could not be implemented + without sacrificing some of the efficiency in Gottlob's design. In particular, + although each once_control uses it's own event to block on, a global CS is + required to manage it - since the event must be either re-usable or + re-creatable under cancelation. This is not needed in the non-cancelable + design because it is able to mark the event as closed (forever). + + When uncontested, a CS operation is equivalent to an Interlocked operation + in speed. So, in the final design with cancelability, an uncontested + once_control operation involves a minimum of five interlocked operations + (including the LeaveCS operation). + + ALTERNATIVES: + An alternative design from Alexander Terekhov proposed using a named mutex, + as sketched below:- + + if (!once_control) { // May be in TLS + named_mutex::guard guard(&once_control2); + if (!once_control2) { + + once_control2 = true; + } + once_control = true; + } + + A more detailed description of this can be found here:- + http://groups.yahoo.com/group/boost/message/15442 + + [Although the definition of a suitable PTHREAD_ONCE_INIT precludes use of the + TLS located flag, this is not critical.] + + There are three primary concerns though:- + 1) The [named] mutex is 'created' even in the uncontended case. + 2) A system wide unique name must be generated. + 3) Win32 mutexes are VERY slow even in the uncontended case. An uncontested + Win32 mutex lock operation can be 50 (or more) times slower than an + uncontested EnterCS operation. + + Ultimately, the named mutex trick is making use of the global locks maintained + by the kernel. + + * pthread.h (pthread_once_t_): One flag and an event HANDLE added. + (PTHREAD_ONCE_INIT): Additional values included. + +2005-03-08 Ross Johnson + + * pthread_once.c (pthread_once): Redesigned to elliminate potential + starvation problem. + - reported by Gottlob Frege + + * ptw32_threadDestroy.c (ptw32_threadDestroy): Implicit threads were + not closing their Win32 thread duplicate handle. + - reported by Dmitrii Semii + +2005-01-25 Ralf Kubis + + * Attempted acquisition of recursive mutex was causing waiting + threads to not be woken when the mutex is released. + + * GNUmakefile (GCE): Generate correct version resource comments. + +2005-01-01 Konstantin Voronkov + + * pthread_mutex_lock.c (pthread_mutex_lock): The new atomic exchange + mutex algorithm is known to allow a thread to steal the lock off + FIFO waiting threads. The next waiting FIFO thread gets a spurious + wake-up and must attempt to re-acquire the lock. The woken thread + was setting itself as the mutex's owner before the re-acquisition. + +2004-11-22 Ross Johnson + + * pthread_cond_wait.c (ptw32_cond_wait_cleanup): Undo change + from 2004-11-02. + * Makefile (DLL_VER): Added for DLL naming suffix - see README. + * GNUmakefile (DLL_VER): Likewise. + * Wmakefile (DLL_VER): Likewise. + * Bmakefile (DLL_VER): Likewise. + * pthread.dsw (version.rc): Added to MSVS workspace. + +2004-11-20 Boudewijn Dekker + + * pthread_getspecific.c (pthread_getspecific): Check for + invalid (NULL) key argument. + +2004-11-19 Ross Johnson + + * config.h (PTW32_THREAD_ID_REUSE_INCREMENT): Added to allow + building the library for either unique thread IDs like Solaris + or non-unique thread IDs like Linux; allows application developers + to override the library's default insensitivity to some apps + that may not be strictly POSIX compliant. + * version.rc: New resource module to encode version information + within the DLL. + * pthread.h: Added PTW32_VERSION* defines and grouped sections + required by resource compiler together; bulk of file is skipped + if RC_INVOKED. Defined some error numbers and other names for + Borland compiler. + +2004-11-02 Ross Johnson + + * pthread_cond_wait.c (ptw32_cond_wait_cleanup): Lock CV mutex at + start of cleanup handler rather than at the end. + * implement.h (PTW32_THREAD_REUSE_EMPTY): Renamed from *_BOTTOM. + (ptw32_threadReuseBottom): New global variable. + * global.c (ptw32_threadReuseBottom): Declare new variable. + * ptw32_reuse.c (ptw32_reuse): Change reuse LIFO stack to LILO queue + to more evenly distribute use of reusable thread IDs; use renamed + PTW32_THREAD_REUSE_EMPTY. + * ptw32_processTerminate.c (ptw2_processTerminate): Use renamed + PTW32_THREAD_REUSE_EMPTY. + +2004-10-31 Ross Johnson + + * implement.h (PThreadState): Add new state value + 'PThreadStateCancelPending'. + * pthread_testcancel.c (pthread_testcancel): Use new thread + 'PThreadStateCancelPending' state as short cut to avoid entering + kernel space via WaitForSingleObject() call. This was obviated + by user space sema acquisition in sem_wait() and sem_timedwait(), + which are also cancelation points. A call to pthread_testcancel() + was required, which introduced a kernel call, effectively nullifying + any gains made by the user space sem acquisition checks. + * pthread_cancel.c (pthread_cancel): Set new thread + 'PThreadStateCancelPending' state. + +2004-10-29 Ross Johnson + + * implement.h (pthread_t): Renamed to ptw32_thread_t; struct contains + all thread state. + * pthread.h (ptw32_handle_t): New general purpose struct to serve + as a handle for various reusable object IDs - currently only used + by pthread_t; contains a pointer to ptw32_thread_t (thread state) + and a general purpose uint for use as a reuse counter or flags etc. + (pthread_t): typedef'ed to ptw32_handle_t; the uint is the reuse + counter that allows the library to maintain unique POSIX thread IDs. + When the pthread struct reuse stack was introduced, threads would + often acquire an identical ID to a previously destroyed thread. The + same was true for the pre-reuse stack library, by virtue of pthread_t + being the address of the thread struct. The new pthread_t retains + the reuse stack but provides virtually unique thread IDs. + * sem_wait.c (ptw32_sem_wait_cleanup): New routine used for + cancelation cleanup. + * sem_timedwait.c (ptw32_sem_timedwait_cleanup): Likewise. + +2004-10-22 Ross Johnson + + * sem_init.c (sem_init): Introduce a 'lock' element in order to + replace the interlocked operations with conventional serialisation. + This is needed in order to be able to atomically modify the sema + value and perform Win32 sema release operations. Win32 semaphores are + used instead of events in order to support efficient multiple posting. + If the whole modify/release isn't atomic, a race between + sem_timedwait() and sem_post() could result in a release when there is + no waiting semaphore, which would cause too many threads to proceed. + * sem_wait.c (sem_wait): Use new 'lock'element. + * sem_timedwait.c (sem_timedwait): Likewise. + * sem_trywait.c (sem_trywait): Likewise. + * sem_post.c (sem_post): Likewise. + * sem_post_multiple.c (sem_post_multiple): Likewise. + * sem_getvalue.c (sem_getvalue): Likewise. + * ptw32_semwait.c (ptw32_semwait): Likewise. + * sem_destroy.c (sem_destroy): Likewise; also tightened the conditions + for semaphore destruction; in particular, a semaphore will not be + destroyed if it has waiters. + * sem_timedwait.c (sem_timedwait): Added cancel cleanup handler to + restore sema value when cancelled. + * sem_wait.c (sem_wait): Likewise. + +2004-10-21 Ross Johnson + + * pthread_mutex_unlock.c (pthread_mutex_unlock): Must use PulseEvent() + rather than SetEvent() to reset the event if there are no waiters. + +2004-10-19 Ross Johnson + + * sem_init.c (sem_init): New semaphore model based on the same idea + as mutexes, i.e. user space interlocked check to avoid + unnecessarily entering kernel space. Wraps the Win32 semaphore and + keeps it's own counter. Although the motivation to do this has existed + for a long time, credit goes to Alexander Terekhov for providing + the logic. I have deviated slightly from AT's logic to add the waiters + count, which has made the code more complicated by adding cancelation + cleanup. This also appears to have broken the VCE (C++ EH) version of + the library (the same problem as previously reported - see BUGS #2), + only apparently not fixable using the usual workaround, nor by turning + all optimisation off. The GCE version works fine, so it is presumed to + be a bug in MSVC++ 6.0. The cancelation exception is thrown and caught + correctly, but the cleanup class destructor is never called. The failing + test is tests\semaphore4.c. + * sem_wait.c (sem_wait): Implemented user space check model. + * sem_post.c (sem_post): Likewise. + * sem_trywait.c (sem_trywait): Likewise. + * sem_timedwait.c (sem_timedwait): Likewise. + * sem_post_multiple.c (sem_post_multiple): Likewise. + * sem_getvalue.c (sem_getvalue): Likewise. + * ptw32_semwait.c (ptw32_semwait): Likewise. + * implement.h (sem_t_): Add counter element. + +2004-10-15 Ross Johnson + + * implement.h (pthread_mutex_t_): Use an event in place of + the POSIX semaphore. + * pthread_mutex_init.c: Create the event; remove semaphore init. + * pthread_mutex_destroy.c: Delete the event. + * pthread_mutex_lock.c: Replace the semaphore wait with the event wait. + * pthread_mutex_trylock.c: Likewise. + * pthread_mutex_timedlock.c: Likewise. + * pthread_mutex_unlock.c: Set the event. + +2004-10-14 Ross Johnson + + * pthread_mutex_lock.c (pthread_mutex_lock): New algorithm using + Terekhov's xchg based variation of Drepper's cmpxchg model. + Theoretically, xchg uses fewer clock cycles than cmpxchg (using IA-32 + as a reference), however, in my opinion bus locking dominates the + equation on smp systems, so the model with the least number of bus + lock operations in the execution path should win, which is Terekhov's + variant. On IA-32 uni-processor systems, it's faster to use the + CMPXCHG instruction without locking the bus than to use the XCHG + instruction, which always locks the bus. This makes the two variants + equal for the non-contended lock (fast lane) execution path on up + IA-32. Testing shows that the xchg variant is faster on up IA-32 as + well if the test forces higher lock contention frequency, even though + kernel calls should be dominating the times (on up IA-32, both + variants used CMPXCHG instructions and neither locked the bus). + * pthread_mutex_timedlock.c pthread_mutex_timedlock(): Similarly. + * pthread_mutex_trylock.c (pthread_mutex_trylock): Similarly. + * pthread_mutex_unlock.c (pthread_mutex_unlock): Similarly. + * ptw32_InterlockedCompareExchange.c (ptw32_InterlockExchange): New + function. + (PTW32_INTERLOCKED_EXCHANGE): Sets up macro to use inlined + ptw32_InterlockedExchange. + * implement.h (PTW32_INTERLOCKED_EXCHANGE): Set default to + InterlockedExchange(). + * Makefile: Building using /Ob2 so that asm sections within inline + functions are inlined. + +2004-10-08 Ross Johnson + + * pthread_mutex_destroy.c (pthread_mutex_destroy): Critical Section + element is no longer required. + * pthread_mutex_init.c (pthread_mutex_init): Likewise. + * pthread_mutex_lock.c (pthread_mutex_lock): New algorithm following + Drepper's paper at http://people.redhat.com/drepper/futex.pdf, but + using the existing semaphore in place of the futex described in the + paper. Idea suggested by Alexander Terekhov - see: + http://sources.redhat.com/ml/pthreads-win32/2003/msg00108.html + * pthread_mutex_timedlock.c pthread_mutex_timedlock(): Similarly. + * pthread_mutex_trylock.c (pthread_mutex_trylock): Similarly. + * pthread_mutex_unlock.c (pthread_mutex_unlock): Similarly. + * pthread_barrier_wait.c (pthread_barrier_wait): Use inlined version + of InterlockedCompareExchange() if possible - determined at + build-time. + * pthread_spin_destroy.c pthread_spin_destroy(): Likewise. + * pthread_spin_lock.c pthread_spin_lock():Likewise. + * pthread_spin_trylock.c (pthread_spin_trylock):Likewise. + * pthread_spin_unlock.c (pthread_spin_unlock):Likewise. + * ptw32_InterlockedCompareExchange.c: Sets up macro for inlined use. + * implement.h (pthread_mutex_t_): Remove Critical Section element. + (PTW32_INTERLOCKED_COMPARE_EXCHANGE): Set to default non-inlined + version of InterlockedCompareExchange(). + * private.c: Include ptw32_InterlockedCompareExchange.c first for + inlining. + * GNUmakefile: Add commandline option to use inlined + InterlockedCompareExchange(). + * Makefile: Likewise. + +2004-09-27 Ross Johnson + + * pthread_mutex_lock.c (pthread_mutex_lock): Separate + PTHREAD_MUTEX_NORMAL logic since we do not need to keep or check some + state required by other mutex types; do not check mutex pointer arg + for validity - leave this to the system since we are only checking + for NULL pointers. This should improve speed of NORMAL mutexes and + marginally improve speed of other type. + * pthread_mutex_trylock.c (pthread_mutex_trylock): Likewise. + * pthread_mutex_unlock.c (pthread_mutex_unlock): Likewise; also avoid + entering the critical section for the no-waiters case, with approx. + 30% reduction in lock/unlock overhead for this case. + * pthread_mutex_timedlock.c (pthread_mutex_timedlock): Likewise; also + no longer keeps mutex if post-timeout second attempt succeeds - this + will assist applications that wish to impose strict lock deadlines, + rather than simply to escape from frozen locks. + +2004-09-09 Tristan Savatier + * pthread.h (struct pthread_once_t_): Qualify the 'done' element + as 'volatile'. + * pthread_once.c: Concerned about possible race condition, + specifically on MPU systems re concurrent access to multibyte types. + [Maintainer's note: the race condition is harmless on SPU systems + and only a problem on MPU systems if concurrent access results in an + exception (presumably generated by a hardware interrupt). There are + other instances of similar harmless race conditions that have not + been identified as issues.] + +2004-09-09 Ross Johnson + + * pthread.h: Declare additional types as volatile. + +2004-08-27 Ross Johnson + + * pthread_barrier_wait.c (pthread_barrier_wait): Remove excessive code + by substituting the internal non-cancelable version of sem_wait + (ptw32_semwait). + +2004-08-25 Ross Johnson + + * pthread_join.c (pthread_join): Rewrite and re-order the conditional + tests in an attempt to improve efficiency and remove a race + condition. + +2004-08-23 Ross Johnson + + * create.c (pthread_create): Don't create a thread if the thread + id pointer location (first arg) is inaccessible. A memory + protection fault will result if the thread id arg isn't an accessible + location. This is consistent with GNU/Linux but different to + Solaris or MKS (and possibly others), which accept NULL as meaning + 'don't return the created thread's ID'. Applications that run + using pthreads-win32 will run on all other POSIX threads + implementations, at least w.r.t. this feature. + + It was decided not to copy the Solaris et al behaviour because, + although it would have simplified some application porting (but only + from Solaris to Windows), the feature is not technically necessary, + and the alternative segfault behaviour helps avoid buggy application + code. + +2004-07-01 Anuj Goyal + + * builddmc.bat: New; Windows bat file to build the library. + * config.h (__DMC__): Support for Digital Mars compiler. + * create.c (__DMC__): Likewise. + * pthread_exit.c (__DMC__): Likewise. + * pthread_join.c (__DMC__): Likewise. + * ptw32_threadDestroy.c (__DMC__): Likewise. + * ptw32_threadStart.c (__DMC__): Likewise. + * ptw32_throw.c (__DMC__): Likewise. + +2004-06-29 Anuj Goyal + + * pthread.h (__DMC__): Initial support for Digital Mars compiler. + +2004-06-29 Will Bryant + + * README.Borland: New; description of Borland changes. + * Bmakefile: New makefile for the Borland make utility. + * ptw32_InterlockedCompareExchange.c: + Add Borland compatible asm code. + +2004-06-26 Jason Bard + + * pthread.h (HAVE_STRUCT_TIMESPEC): If undefined, define it + to avoid timespec struct redefined errors elsewhere in an + application. + +2004-06-21 Ross Johnson + + * pthread.h (PTHREAD_RECURSIVE_MUTEX_INITIALIZER): Mutex + initialiser added for compatibility with Linux threads and + others; currently not included in SUSV3. + * pthread.h (PTHREAD_ERRORCHECK_MUTEX_INITIALIZER): Likewise. + * pthread.h (PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP): Likewise. + * pthread.h (PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP): Likewise. + + * ptw32_mutex_check_need_init.c (ptw32_mutex_check_need_init): + Add new initialisers. + + * pthread_mutex_lock.c (pthread_mutex_lock): Check for new + initialisers. + * pthread_mutex_trylock.c (pthread_mutex_trylock): Likewise. + * pthread_mutex_timedlock.c (pthread_mutex_timedlock): Likewise. + * pthread_mutex_unlock.c (pthread_mutex_unlock): Likewise. + * pthread_mutex_destroy.c (pthread_mutex_destroy): Likewise. + +2004-05-20 Ross Johnson + + * README.NONPORTABLE: Document pthread_win32_test_features_np(). + * FAQ: Update various answers. + +2004-05-19 Ross Johnson + + * Makefile: Don't define _WIN32_WINNT on compiler command line. + * GNUmakefile: Likewise. + +2004-05-16 Ross Johnson + + * pthread_cancel.c (pthread_cancel): Adapted to use auto-detected + QueueUserAPCEx features at run-time. + (ptw32_RegisterCancelation): Drop in replacement for QueueUserAPCEx() + if it can't be used. Provides older style non-preemptive async + cancelation. + * pthread_win32_attach_detach_np.c (pthread_win32_attach_np): + Auto-detect quserex.dll and the availability of alertdrv.sys; + initialise and close on process attach/detach. + * global.c (ptw32_register_cancelation): Pointer to either + QueueUserAPCEx() or ptw32_RegisterCancelation() depending on + availability. QueueUserAPCEx makes pre-emptive async cancelation + possible. + * implement.h: Add definitions and prototypes related to QueueUserAPC. + +2004-05-16 Panagiotis E. Hadjidoukas + + * QueueUserAPCEx (separate contributed package): Provides preemptive + APC feature. + * pthread_cancel.c (pthread_cancel): Initial integration of + QueueUserAPCEx into pthreads-win32 to provide true pre-emptive + async cancelation of threads, including blocked threads. + +2004-05-06 Makoto Kato + + * pthread.h (DWORD_PTR): Define typedef for older MSVC. + * pthread_cancel.c (AMD64): Add architecture specific Context register. + * ptw32_getprocessors.c: Use correct types (DWORD_PTR) for mask + variables. + +2004-04-06 P. van Bruggen + + * ptw32_threadDestroy.c: Destroy threadLock mutex to + close a memory leak. + +2004-02-13 Gustav Hallberg + + * pthread_equal.c: Remove redundant equality logic. + +2003-12-10 Philippe Di Cristo + + * sem_timedwait.c (sem_timedwait): Fix timeout calculations. + +2003-10-20 Alexander Terekhov + + * pthread_mutex_timedlock.c (ptw32_semwait): Move to individual module. + * ptw32_semwait.c: New module. + * pthread_cond_wait.c (ptw32_cond_wait_cleanup): Replace cancelable + sem_wait() call with non-cancelable ptw32_semwait() call. + * pthread.c (private.c): Re-order for inlining. GNU C warned that + function ptw32_semwait() was defined 'inline' after it was called. + * pthread_cond_signal.c (ptw32_cond_unblock): Likewise. + * pthread_delay_np.c: Disable Watcom warning with comment. + * *.c (process.h): Remove include from .c files. This is conditionally + included by the common project include files. + +2003-10-20 James Ewing + + * ptw32_getprocessors.c: Some Win32 environments don't have + GetProcessAffinityMask(), so always return CPU count = 1 for them. + * config.h (NEED_PROCESSOR_AFFINITY_MASK): Define for WinCE. + +2003-10-15 Ross Johnson + + * Re-indented all .c files using default GNU style to remove assorted + editor ugliness (used GNU indent utility in default style). + +2003-10-15 Alex Blanco + + * sem_init.c (sem_init): Would call CreateSemaphore even if the sema + struct calloc failed; was not freeing calloced memory if either + CreateSemaphore or CreateEvent failed. + +2003-10-14 Ross Johnson + + * pthread.h: Add Watcom compiler compatibility. Esssentially just add + the cdecl attribute to all exposed function prototypes so that Watcom + generates function call code compatible with non-Watcom built libraries. + By default, Watcom uses registers to pass function args if possible rather + than pushing to stack. + * semaphore.h: Likewise. + * sched.h: Likewise. + * pthread_cond_wait.c (ptw32_cond_wait_cleanup): Define with cdecl attribute + for Watcom compatibility. This routine is called via pthread_cleanup_push so + it had to match function arg definition. + * Wmakefile: New makefile for Watcom builds. + +2003-09-14 Ross Johnson + + * pthread_setschedparam.c (pthread_setschedparam): Attempt to map + all priority levels between max and min (as returned by + sched_get_priority_min/max) to reasonable Win32 priority levels - i.e. + levels between THREAD_PRIORITY_LOWEST/IDLE to THREAD_PRIORITY_LOWEST and + between THREAD_PRIORITY_HIGHEST/TIME_CRITICAL to THREAD_PRIORITY_HIGHEST + while others remain unchanged; record specified thread priority level + for return by pthread_getschedparam. + + Note that, previously, specified levels not matching Win32 priority levels + would silently leave the current thread priority unaltered. + + * pthread_getschedparam.c (pthread_getschedparam): Return the priority + level specified by the latest pthread_setschedparam or pthread_create rather + than the actual running thread priority as returned by GetThreadPriority - as + required by POSIX. I.e. temporary or adjusted actual priority levels are not + returned by this routine. + + * pthread_create.c (pthread_create): For priority levels specified via + pthread attributes, attempt to map all priority levels between max and + min (as returned by sched_get_priority_min/max) to reasonable Win32 + priority levels; record priority level given via attributes, or + inherited from parent thread, for later return by pthread_getschedparam. + + * ptw32_new.c (ptw32_new): Initialise pthread_t_ sched_priority element. + + * pthread_self.c (pthread_self): Set newly created implicit POSIX thread + sched_priority to Win32 thread's current actual priority. Temporarily + altered priorities can't be avoided in this case. + + * implement.h (struct pthread_t_): Add new sched_priority element. + +2003-09-12 Ross Johnson + + * sched_get_priority_min.c (sched_get_priority_min): On error should return -1 + with errno set. + * sched_get_priority_max.c (sched_get_priority_max): Likewise. + +2003-09-03 Ross Johnson + + * w32_cancelableWait.c (ptw32_cancelable_wait): Allow cancelation + of implicit POSIX threads as well. + +2003-09-02 Ross Johnson + + * pthread_win32_attach_detach_np.c (pthread_win32_thread_detach_np): + Add comment. + + * pthread_exit.c (pthread_exit): Fix to recycle the POSIX thread handle in + addition to calling user TSD destructors. Move the implicit POSIX thread exit + handling to ptw32_throw to centralise the logic. + + * ptw32_throw.c (ptw32_throw): Implicit POSIX threads have no point + to jump or throw to, so cleanup and exit the thread here in this case. For + processes using the C runtime, the exit code will be set to the POSIX + reason for the throw (i.e. PTHREAD_CANCEL or the value given to pthread_exit). + Note that pthread_exit() already had similar logic, which has been moved to + here. + + * ptw32_threadDestroy.c (ptw32_threadDestroy): Don't close the Win32 handle + of implicit POSIX threads - expect this to be done by Win32? + +2003-09-01 Ross Johnson + + * pthread_self.c (pthread_self): The newly aquired pthread_t must be + assigned to the reuse stack, not freed, if the routine fails somehow. + +2003-08-13 Ross Johnson + + * pthread_getschedparam.c (pthread_getschedparam): An invalid thread ID + parameter was returning an incorrect error value; now uses a more exhaustive + check for validity. + + * pthread_setschedparam.c (pthread_setschedparam): Likewise. + + * pthread_join.c (pthread_join): Now uses a more exhaustive + check for validity. + + * pthread_detach.c (pthread_detach): Likewise. + + * pthread_cancel.c (pthread_cancel): Likewise. + + * ptw32_threadDestroy.c (ptw32_threadDestroy): pthread_t structs are + never freed - push them onto a stack for reuse. + + * ptw32_new.c (ptw32_new): Check for reusable pthread_t before dynamically + allocating new memory for the struct. + + * pthread_kill.c (pthread_kill): New file; new routine; takes only a zero + signal arg so that applications can check the thread arg for validity; checks + that the underlying Win32 thread HANDLE is valid. + + * pthread.h (pthread_kill): Add prototype. + + * ptw32_reuse.c (ptw32_threadReusePop): New file; new routine; pop a + pthread_t off the reuse stack. pthread_t_ structs that have been destroyed, i.e. + have exited detached or have been joined, are cleaned up and put onto a reuse + stack. Consequently, thread IDs are no longer freed once calloced. The library + will attempt to get a struct off this stack before asking the system to alloc + new memory when creating threads. The stack is guarded by a global mutex. + (ptw32_threadReusePush): New routine; push a pthread_t onto the reuse stack. + + * implement.h (ptw32_threadReusePush): Add new prototype. + (ptw32_threadReusePop): Likewise. + (pthread_t): Add new element. + + * ptw32_processTerminate.c (ptw32_processTerminate): Delete the thread + reuse lock; free all thread ID structs on the thread reuse stack. + + * ptw32_processInitialize.c (ptw32_processInitialize): Initialise the + thread reuse lock. + +2003-07-19 Ross Johnson + + * GNUmakefile: modified to work under MsysDTK environment. + * pthread_spin_lock.c (pthread_spin_lock): Check for NULL arg. + * pthread_spin_unlock.c (pthread_spin_unlock): Likewise. + * pthread_spin_trylock.c (pthread_spin_trylock): Likewise; + fix incorrect pointer value if lock is dynamically initialised by + this function. + * sem_init.c (sem_init): Initialise sem_t value to quell compiler warning. + * sem_destroy.c (sem_destroy): Likewise. + * ptw32_threadStart.c (non-MSVC code sections): Include rather + than old-style ; fix all std:: namespace entities such as + std::terminate_handler instances and associated methods. + * ptw32_callUserDestroyRoutines.c (non-MSVC code sections): Likewise. + +2003-06-24 Piet van Bruggen + + * pthread_spin_destroy.c (pthread_spin_destroy): Was not freeing the + spinlock struct. + +2003-06-22 Nicolas Barry + + * pthread_mutex_destroy.c (pthread_mutex_destroy): When called + with a recursive mutex that was locked by the current thread, the + function was failing with a success return code. + +2003-05-15 Steven Reddie + + * pthread_win32_attach_detach_np.c (pthread_win32_process_detach_np): + NULLify ptw32_selfThreadKey after the thread is destroyed, otherwise + destructors calling pthreads routines might resurrect it again, creating + memory leaks. Call the underlying Win32 Tls routine directly rather than + pthread_setspecific(). + (pthread_win32_thread_detach_np): Likewise. + +2003-05-14 Viv + + * pthread.dsp: Change /MT compile flag to /MD. + +2003-03-04 Alexander Terekhov + + * pthread_mutex_timedlock.c (pthread_mutex_timedlock): Fix failure to + set ownership of mutex on second grab after abstime timeout. + - bug reported by Robert Strycek + +2002-12-17 Thomas Pfaff + + * pthread_mutex_lock.c (ptw32_semwait): New static routine to provide + a non-cancelable sem_wait() function. This is consistent with the + way that pthread_mutex_timedlock.c does it. + (pthread_mutex_lock): Use ptw32_semwait() instead of sem_wait(). + +2002-12-11 Thomas Pfaff + + * pthread_mutex_trylock.c: Should return EBUSY rather than EDEADLK. + * pthread_mutex_destroy.c: Remove redundant ownership test (the + trylock call does this for us); do not destroy a recursively locked + mutex. + +2002-09-20 Michael Johnson + + * pthread_cond_destroy.c (pthread_cond_destroy): + When two different threads exist, and one is attempting to + destroy a condition variable while the other is attempting to + initialize a condition variable that was created with + PTHREAD_COND_INITIALIZER, a deadlock can occur. Shrink + the ptw32_cond_list_lock critical section to fix it. + +2002-07-31 Ross Johnson + + * ptw32_threadStart.c (ptw32_threadStart): Thread cancelLock + destruction moved to ptw32_threadDestroy(). + + * ptw32_threadDestroy.c (ptw32_threadDestroy): Destroy + the thread's cancelLock. Moved here from ptw32_threadStart.c + to cleanup implicit threads as well. + +2002-07-30 Alexander Terekhov + + * pthread_cond_wait.c (ptw32_cond_wait_cleanup): + Remove code designed to avoid/prevent spurious wakeup + problems. It is believed that the sem_timedwait() call + is consuming a CV signal that it shouldn't and this is + breaking the avoidance logic. + +2002-07-30 Ross Johnson + + * sem_timedwait.c (sem_timedwait): Tighten checks for + unreasonable abstime values - that would result in + unexpected timeout values. + + * w32_CancelableWait.c (ptw32_cancelable_wait): + Tighten up return value checking and add comments. + + +2002-06-08 Ross Johnson + + * sem_getvalue.c (sem_getvalue): Now returns a value for the + NEED_SEM version (i.e. earlier versions of WinCE). + + +2002-06-04 Rob Fanner + + * sem_getvalue.c (sem_getvalue): The Johnson M. Hart + approach didn't work - we are forced to take an + intrusive approach. We try to decrement the sema + and then immediately release it again to get the + value. There is a small probability that this may + block other threads, but only momentarily. + +2002-06-03 Ross Johnson + + * sem_init.c (sem_init): Initialise Win32 semaphores + to _POSIX_SEM_VALUE_MAX (which this implementation + defines in pthread.h) so that sem_getvalue() can use + the trick described in the comments in sem_getvalue(). + * pthread.h (_POSIX_SEM_VALUE_MAX): Defined. + (_POSIX_SEM_NSEMS_MAX): Defined - not used but may be + useful for source code portability. + +2002-06-03 Rob Fanner + + * sem_getvalue.c (sem_getvalue): Did not work on NT. + Use approach suggested by Johnson M. Hart in his book + "Win32 System Programming". + +2002-02-28 Ross Johnson + + * errno.c: Compiler directive was incorrectly including code. + * pthread.h: Conditionally added some #defines from config.h + needed when not building the library. e.g. NEED_ERRNO, NEED_SEM. + (PTW32_DLLPORT): Now only defined if _DLL defined. + (_errno): Compiler directive was incorrectly including prototype. + * sched.h: Conditionally added some #defines from config.h + needed when not building the library. + * semaphore.h: Replace an instance of NEED_SEM that should + have been NEED_ERRNO. This change currently has nil effect. + + * GNUmakefile: Correct some recent changes. + + * Makefile: Add rule to generate pre-processor output. + +2002-02-23 Ross Johnson + + * pthread_rwlock_timedrdlock.c: New - untested. + * pthread_rwlock_timedwrlock.c: New - untested. + + * Testsuite passed (except known MSVC++ problems) + + * pthread_cond_destroy.c: Expand the time change + critical section to solve deadlock problem. + + * pthread.c: Add all remaining C modules. + * pthread.h: Use dllexport/dllimport attributes on functions + to avoid using pthread.def. + * sched.h: Likewise. + * semaphore.h: Likewise. + * GNUmakefile: Add new targets for single translation + unit build to maximise inlining potential; generate + pthread.def automatically. + * Makefile: Likewise, but no longer uses pthread.def. + +2002-02-20 Ross Johnson + + * pthread_cond_destroy.c (pthread_cond_destroy): + Enter the time change critical section earlier. + +2002-02-17 Ross Johnson + + * nonportable.c (pthread_delay_np): Make a true + cancelation point. Deferred cancels will interrupt the + wait. + +2002-02-07 Ross Johnson + + Reduced name space pollution. + ----------------------------- + When the appropriate symbols are defined, the headers + will restrict the definitions of new names. In particular, + it must be possible to NOT include the + header and related definitions with some combination + of symbol definitions. Secondly, it should be possible + that additional definitions should be limited to POSIX + compliant symbols by the definition of appropriate symbols. + + * pthread.h: POSIX conditionals. + * sched.h: POSIX conditionals. + * semaphore.h: POSIX conditionals. + + * semaphore.c: Included . + (sem_init): Changed magic 0x7FFFFFFFL to INT_MAX. + (sem_getvalue): Trial version. + + Reduce executable size. + ----------------------- + When linking with the static library, only those + routines actually called, either directly or indirectly + should be included. + + [Gcc has the -ffunction-segments option to do this but MSVC + doesn't have this feature as far as I can determine. Other + compilers are undetermined as well. - rpj] + + * semaphore.c: All routines are now in separate compilation units; + This file is used to congregate the separate modules for + potential inline optimisation and backward build compatibility. + * sem_close.c: Separated routine from semaphore.c. + * ptw32_decrease_semaphore.c: Likewise. + * sem_destroy.c: Likewise. + * sem_getvalue.c: Likewise. + * ptw32_increase_semaphore.c: Likewise. + * sem_init.c: Likewise. + * sem_open.c: Likewise. + * sem_post.c: Likewise. + * sem_post_multiple.c: Likewise. + * sem_timedwait.c: Likewise. + * sem_trywait.c: Likewise. + * sem_unlink.c: Likewise. + * sem_wait.c: Likewise. + +2002-02-04 Ross Johnson + + The following extends the idea above to the rest of pthreads-win32 - rpj + + * attr.c: All routines are now in separate compilation units; + This file is used to congregate the separate modules for + potential inline optimisation and backward build compatibility. + * pthread_attr_destroy.c: Separated routine from attr.c. + * pthread_attr_getdetachstate.c: Likewise. + * pthread_attr_getscope.c: Likewise. + * pthread_attr_getstackaddr.c: Likewise. + * pthread_attr_getstacksize.c: Likewise. + * pthread_attr_init.c: Likewise. + * pthread_attr_is_attr.c: Likewise. + * pthread_attr_setdetachstate.c: Likewise. + * pthread_attr_setscope.c: Likewise. + * pthread_attr_setstackaddr.c: Likewise. + * pthread_attr_setstacksize.c: Likewise. + + * pthread.c: Agregation of agregate modules for super-inlineability. + +2002-02-02 Ross Johnson + + * cancel.c: Rearranged some code and introduced checks + to disable cancelation at the start of a thread's cancelation + run to prevent double cancelation. The main problem + arises if a thread is canceling and then receives a subsequent + async cancel request. + * private.c: Likewise. + * condvar.c: Place pragmas around cleanup_push/pop to turn + off inline optimisation (/Obn where n>0 - MSVC only). Various + optimisation switches in MSVC turn this on, which interferes with + the way that cleanup handlers are run in C++ EH and SEH + code. Application code compiled with inline optimisation must + also wrap cleanup_push/pop blocks with the pragmas, e.g. + #pragma inline_depth(0) + pthread_cleanup_push(...) + ... + pthread_cleanup_pop(...) + #pragma inline_depth(8) + * rwlock.c: Likewise. + * mutex.c: Remove attempts to inline some functions. + * signal.c: Modify misleading comment. + +2002-02-01 Ross Johnson + + * semaphore.c (sem_trywait): Fix missing errno return + for systems that define NEED_SEM (e.g. early WinCE). + * mutex.c (pthread_mutex_timedlock): Return ENOTSUP + for systems that define NEED_SEM since they don't + have sem_trywait(). + +2002-01-27 Ross Johnson + + * mutex.c (pthread_mutex_timedlock): New function suggested by + Alexander Terekhov. The logic required to implement this + properly came from Alexander, with some collaboration + with Thomas Pfaff. + (pthread_mutex_unlock): Wrap the waiters check and sema + post in a critical section to prevent a race with + pthread_mutex_timedlock. + (ptw32_timed_semwait): New function; + returns a special result if the absolute timeout parameter + represents a time already passed when called; used by + pthread_mutex_timedwait(). Have deliberately not reused + the name "ptw32_sem_timedwait" because they are not the same + routine. + * condvar.c (ptw32_cond_timedwait): Use the new sem_timedwait() + instead of ptw32_sem_timedwait(), which now has a different + function. See previous. + * implement.h: Remove prototype for ptw32_sem_timedwait. + See next. + (pthread_mutex_t_): Add critical section element for access + to lock_idx during mutex post-timeout processing. + * semaphore.h (sem_timedwait): See next. + * semaphore.c (sem_timedwait): See next. + * private.c (ptw32_sem_timedwait): Move to semaphore.c + and rename as sem_timedwait(). + +2002-01-18 Ross Johnson + + * sync.c (pthread_join): Was getting the exit code from the + calling thread rather than the joined thread if + defined(__MINGW32__) && !defined(__MSVCRT__). + +2002-01-15 Ross Johnson + + * pthread.h: Unless the build explicitly defines __CLEANUP_SEH, + __CLEANUP_CXX, or __CLEANUP_C, then the build defaults to + __CLEANUP_C style cleanup. This style uses setjmp/longjmp + in the cancelation and thread exit implementations and therefore + won't do stack unwinding if linked to applications that have it + (e.g. C++ apps). This is currently consistent with most/all + commercial Unix POSIX threads implementations. + + * spin.c (pthread_spin_init): Edit renamed function call. + * nonportable.c (pthread_num_processors_np): New. + (pthread_getprocessors_np): Renamed to ptw32_getprocessors + and moved to private.c. + * private.c (pthread_getprocessors): Moved here from + nonportable.c. + * pthread.def (pthread_getprocessors_np): Removed + from export list. + + * rwlock.c (pthread_rwlockattr_init): New. + (pthread_rwlockattr_destroy): New. + (pthread_rwlockattr_getpshared): New. + (pthread_rwlockattr_setpshared): New. + +2002-01-14 Ross Johnson + + * attr.c (pthread_attr_setscope): Fix struct pointer + indirection error introduced 2002-01-04. + (pthread_attr_getscope): Likewise. + +2002-01-12 Ross Johnson + + * pthread.dsp (SOURCE): Add missing source files. + +2002-01-08 Ross Johnson + + * mutex.c (pthread_mutex_trylock): use + ptw32_interlocked_compare_exchange function pointer + rather than ptw32_InterlockedCompareExchange() directly + to retain portability to non-iX86 processors, + e.g. WinCE etc. The pointer will point to the native + OS version of InterlockedCompareExchange() if the + OS supports it (see ChangeLog entry of 2001-10-17). + +2002-01-07 Thomas Pfaff , Alexander Terekhov + + * mutex.c (pthread_mutex_init): Remove critical + section calls. + (pthread_mutex_destroy): Likewise. + (pthread_mutex_unlock): Likewise. + (pthread_mutex_trylock): Likewise; uses + ptw32_InterlockedCompareExchange() to avoid need for + critical section; library is no longer i386 compatible; + recursive mutexes now increment the lock count rather + than return EBUSY; errorcheck mutexes return EDEADLCK + rather than EBUSY. This behaviour is consistent with the + Solaris pthreads implementation. + * implement.h (pthread_mutex_t_): Remove critical + section element - no longer needed. + + +2002-01-04 Ross Johnson + + * attr.c (pthread_attr_setscope): Add more error + checking and actually store the scope value even + though it's not really necessary. + (pthread_attr_getscope): Return stored value. + * implement.h (pthread_attr_t_): Add new scope element. + * ANNOUNCE: Fix out of date comment next to + pthread_attr_setscope in conformance section. + +2001-12-21 Alexander Terekhov + + * mutex.c (pthread_mutex_lock): Decrementing lock_idx was + not thread-safe. + (pthread_mutex_trylock): Likewise. + +2001-10-26 prionx@juno.com + + * semaphore.c (sem_init): Fix typo and missing bracket + in conditionally compiled code. Only older versions of + WinCE require this code, hence it doesn't normally get + tested; somehow when sem_t reverted to an opaque struct + the calloc NULL check was left in the conditionally included + section. + (sem_destroy): Likewise, the calloced sem_t wasn't being freed. + +2001-10-25 Ross Johnson + + * GNUmakefile (libwsock32): Add to linker flags for + WSAGetLastError() and WSASetLastError(). + * Makefile (wsock32.lib): Likewise. + * create.c: Minor mostly inert changes. + * implement.h (PTW32_MAX): Move into here and renamed + from sched.h. + (PTW32_MIN): Likewise. + * GNUmakefile (TEST_ICE): Define if testing internal + implementation of InterlockedCompareExchange. + * Makefile (TEST_ICE): Likewise. + * private.c (TEST_ICE): Likewise. + +2001-10-24 Ross Johnson + + * attr.c (pthread_attr_setstacksize): Quell warning + from LCC by conditionally compiling the stacksize + validity check. LCC correctly warns that the condition + (stacksize < PTHREAD_STACK_MIN) is suspicious + because STACK_MIN is 0 and stacksize is of type + size_t (or unsigned int). + +2001-10-17 Ross Johnson + + * barrier.c: Move _LONG and _LPLONG defines into + implement.h; rename to PTW32_INTERLOCKED_LONG and + PTW32_INTERLOCKED_LPLONG respectively. + * spin.c: Likewise; ptw32_interlocked_compare_exchange used + in place of InterlockedCompareExchange directly. + * global.c (ptw32_interlocked_compare_exchange): Add + prototype for this new routine pointer to be used when + InterlockedCompareExchange isn't supported by Windows. + * nonportable.c (pthread_win32_process_attach_np): Check for + support of InterlockedCompareExchange in kernel32 and assign its + address to ptw32_interlocked_compare_exchange if it exists, or + our own ix86 specific implementation ptw32_InterlockedCompareExchange. + *private.c (ptw32_InterlockedCompareExchange): An + implementation of InterlockedCompareExchange() which is + specific to ix86; written directly in assembler for either + MSVC or GNU C; needed because Windows 95 doesn't support + InterlockedCompareExchange(). + + * sched.c (sched_get_priority_min): Extend to return + THREAD_PRIORITY_IDLE. + (sched_get_priority_max): Extend to return + THREAD_PRIORITY_CRITICAL. + +2001-10-15 Ross Johnson + + * spin.c (pthread_spin_lock): PTHREAD_SPINLOCK_INITIALIZER + was causing a program fault. + (pthread_spin_init): Could have alloced memory + without freeing under some error conditions. + + * mutex.c (pthread_mutex_init): Move memory + allocation of mutex struct after checking for + PROCESS_SHARED. + +2001-10-12 Ross Johnson + + * spin.c (pthread_spin_unlock): Was not returning + EPERM if the spinlock was not locked, for multi CPU + machines. + +2001-10-08 Ross Johnson + + * spin.c (pthread_spin_trylock): Was not returning + EBUSY for multi CPU machines. + +2001-08-24 Ross Johnson + + * condvar.c (pthread_cond_destroy): Remove cv element + that is no longer used. + * implement.h: Likewise. + +2001-08-23 Alexander Terekhov + + * condvar.c (pthread_cond_destroy): fix bug with + respect to deadlock in the case of concurrent + _destroy/_unblock; a condition variable can be destroyed + immediately after all the threads that are blocked on + it are awakened. + +2001-08-23 Phil Frisbie, Jr. + + * tsd.c (pthread_getspecific): Preserve the last + winsock error [from WSAGetLastError()]. + +2001-07-18 Scott McCaskill + + * mutex.c (pthread_mutexattr_init): Return ENOMEM + immediately and don't dereference the NULL pointer + if calloc fails. + (pthread_mutexattr_getpshared): Don't dereference + a pointer that is possibly NULL. + * barrier.c (pthread_barrierattr_init): Likewise + (pthread_barrierattr_getpshared): Don't dereference + a pointer that is possibly NULL. + * condvar.c (pthread_condattr_getpshared): Don't dereference + a pointer that is possibly NULL. + +2001-07-15 Ross Johnson + + * rwlock.c (pthread_rwlock_wrlock): Is allowed to be + a cancelation point; re-enable deferred cancelability + around the CV call. + +2001-07-10 Ross Johnson + + * barrier.c: Still more revamping. The exclusive access + mutex isn't really needed so it has been removed and replaced + by an InterlockedDecrement(). nSerial has been removed. + iStep is now dual-purpose. The process shared attribute + is now stored in the barrier struct. + * implement.h (pthread_barrier_t_): Lost some/gained one + elements. + * private.c (ptw32_threadStart): Removed some comments. + +2001-07-10 Ross Johnson + + * barrier.c: Revamped to fix the race condition. Two alternating + semaphores are used instead of the PulseEvent. Also improved + overall throughput by returning PTHREAD_BARRIER_SERIAL_THREAD + to the first waking thread. + * implement.h (pthread_barrier_t_): Revamped. + +2001-07-09 Ross Johnson + + * barrier.c: Fix several bugs in all routines. Now passes + tests/barrier5.c which is fairly rigorous. There is still + a non-optimal work-around for a race condition between + the barrier breeched event signal and event wait. Basically + the last (signalling) thread to hit the barrier yields + to allow any other threads, which may have lost the race, + to complete. + +2001-07-07 Ross Johnson + + * barrier.c: Changed synchronisation mechanism to a + Win32 manual reset Event and use PulseEvent to signal + waiting threads. If the implementation continued to use + a semaphore it would require a second semaphore and + some management to use them alternately as barriers. A + single semaphore allows threads to cascade from one barrier + through the next, leaving some threads blocked at the first. + * implement.h (pthread_barrier_t_): As per above. + * general: Made a number of other routines inlinable. + +2001-07-07 Ross Johnson + + * spin.c: Revamped and working; included static initialiser. + Now beta level. + * barrier.c: Likewise. + * condvar.c: Macro constant change; inline auto init routine. + * mutex.c: Likewise. + * rwlock.c: Likewise. + * private.c: Add support for spinlock initialiser. + * global.c: Likewise. + * implement.h: Likewise. + * pthread.h (PTHREAD_SPINLOCK_INITIALIZER): Fix typo. + +2001-07-05 Ross Johnson + + * barrier.c: Remove static initialisation - irrelevent + for this object. + * pthread.h (PTHREAD_BARRIER_INITIALIZER): Removed. + * rwlock.c (pthread_rwlock_wrlock): This routine is + not a cancelation point - disable deferred + cancelation around call to pthread_cond_wait(). + +2001-07-05 Ross Johnson + + * spin.c: New module implementing spin locks. + * barrier.c: New module implementing barriers. + * pthread.h (_POSIX_SPIN_LOCKS): defined. + (_POSIX_BARRIERS): Defined. + (pthread_spin_*): Defined. + (pthread_barrier*): Defined. + (PTHREAD_BARRIER_SERIAL_THREAD): Defined. + * implement.h (pthread_spinlock_t_): Defined. + (pthread_barrier_t_): Defined. + (pthread_barrierattr_t_): Defined. + + * mutex.c (pthread_mutex_lock): Return with the error + if an auto-initialiser initialisation fails. + + * nonportable.c (pthread_getprocessors_np): New; gets the + number of available processors for the current process. + +2001-07-03 Ross Johnson + + * pthread.h (_POSIX_READER_WRITER_LOCKS): Define it + if not already defined. + +2001-07-01 Alexander Terekhov + + * condvar.c: Fixed lost signal bug reported by Timur Aydin + (taydin@snet.net). + [RPJ (me) didn't translate the original algorithm + correctly.] + * semaphore.c: Added sem_post_multiple; this is a useful + routine, but it doesn't appear to be standard. For now it's + not an exported function. + +2001-06-25 Ross Johnson + + * create.c (pthread_create): Add priority inheritance + attributes. + * mutex.c (pthread_mutex_lock): Remove some overhead for + PTHREAD_MUTEX_NORMAL mutex types. Specifically, avoid + calling pthread_self() and pthread_equal() to check/set + the mutex owner. Introduce a new pseudo owner for this + type. Test results suggest increases in speed of up to + 90% for non-blocking locks. + This is the default type of mutex used internally by other + synchronising objects, ie. condition variables and + read-write locks. The test rwlock7.c shows about a + 30-35% speed increase over snapshot 2001-06-06. The + price of this is that the application developer + must ensure correct behaviour, or explicitly set the + mutex to a safer type such as PTHREAD_MUTEX_ERRORCHECK. + For example, PTHREAD_MUTEX_NORMAL (or PTHREAD_MUTEX_DEFAULT) + type mutexes will not return an error if a thread which is not + the owner calls pthread_mutex_unlock. The call will succeed + in unlocking the mutex if it is currently locked, but a + subsequent unlock by the true owner will then fail with EPERM. + This is however consistent with some other implementations. + (pthread_mutex_unlock): Likewise. + (pthread_mutex_trylock): Likewise. + (pthread_mutex_destroy): Likewise. + * attr.c (pthread_attr_init): PTHREAD_EXPLICIT_SCHED is the + default inheritance attribute; THREAD_PRIORITY_NORMAL is + the default priority for new threads. + * sched.c (pthread_attr_setschedpolicy): Added routine. + (pthread_attr_getschedpolicy): Added routine. + (pthread_attr_setinheritsched): Added routine. + (pthread_attr_getinheritsched): Added routine. + * pthread.h (sched_rr_set_interval): Added as a macro; + returns -1 with errno set to ENOSYS. + +2001-06-23 Ross Johnson + + *sched.c (pthread_attr_setschedparam): Add priority range + check. + (sched_setscheduler): New function; checks for a valid + pid and policy; checks for permission to set information + in the target process; expects pid to be a Win32 process ID, + not a process handle; the only scheduler policy allowed is + SCHED_OTHER. + (sched_getscheduler): Likewise, but checks for permission + to query. + * pthread.h (SCHED_*): Moved to sched.h as defined in the + POSIX standard. + * sched.h (SCHED_*): Moved from pthread.h. + (pid_t): Defined if necessary. + (sched_setscheduler): Defined. + (sched_getscheduler): Defined. + * pthread.def (sched_setscheduler): Exported. + (sched_getscheduler): Likewise. + +2001-06-23 Ralf Brese + + * create.c (pthread_create): Set thread priority from + thread attributes. + +2001-06-18 Ross Johnson + + * Made organisational-only changes to UWIN additions. + * dll.c (dllMain): Moved UWIN process attach code + to pthread_win32_process_attach_np(); moved + instance of pthread_count to global.c. + * global.c (pthread_count): Moved from dll.c. + * nonportable.c (pthread_win32_process_attach_np): + Moved _UWIN code to here from dll.c. + * implement.h (pthread_count): Define extern int. + * create.c (pthread_count): Remove extern int. + * private.c (pthread_count): Likewise. + * exit.c (pthread_count): Likewise. + +2001-06-18 David Korn + + * dll.c: Added changes necessary to work with UWIN. + * create.c: Likewise. + * pthread.h: Likewise. + * misc.c: Likewise. + * exit.c: Likewise. + * private.c: Likewise. + * implement.h: Likewise. + There is some room at the start of struct pthread_t_ + to implement the signal semantics in UWIN's posix.dll + although this is not yet complete. + * Nmakefile: Compatible with UWIN's Nmake utility. + * Nmakefile.tests: Likewise - for running the tests. + +2001-06-08 Ross Johnson + + * semaphore.h (sem_t): Fixed for compile and test. + * implement.h (sem_t_): Likewise. + * semaphore.c: Likewise. + * private.c (ptw32_sem_timedwait): Updated to use new + opaque sem_t. + +2001-06-06 Ross Johnson + + * semaphore.h (sem_t): Is now an opaque pointer; + moved actual definition to implement.h. + * implement.h (sem_t_): Move here from semaphore.h; + was the definition of sem_t. + * semaphore.c: Wherever necessary, changed use of sem + from that of a pointer to a pointer-pointer; added + extra checks for a valid sem_t; NULL sem_t when + it is destroyed; added extra checks when creating + and destroying sem_t elements in the NEED_SEM + code branches; changed from using a pthread_mutex_t + ((*sem)->mutex) to CRITICAL_SECTION ((*sem)->sem_lock_cs) + in NEED_SEM branches for access serialisation. + +2001-06-06 Ross Johnson + + * mutex.c (pthread_mutexattr_init): Remove + ptw32_mutex_default_kind. + +2001-06-05 Ross Johnson + + * nonportable.c (pthread_mutex_setdefaultkind_np): + Remove - should not have been included in the first place. + (pthread_mutex_getdefaultkind_np): Likewise. + * global.c (ptw32_mutex_default_kind): Likewise. + * mutex.c (pthread_mutex_init): Remove use of + ptw32_mutex_default_kind. + * pthread.h (pthread_mutex_setdefaultkind_np): Likewise. + (pthread_mutex_getdefaultkind_np): Likewise. + * pthread.def (pthread_mutexattr_setkind_np): Added. + (pthread_mutexattr_getkind_np): Likewise. + + * README: Many changes that should have gone in before + the last snapshot. + * README.NONPORTABLE: New - referred to by ANNOUNCE + but never created; documents the non-portable routines + included in the library - moved from README with new + routines added. + * ANNOUNCE (pthread_mutexattr_setkind_np): Added to + compliance list. + (pthread_mutexattr_getkind_np): Likewise. + +2001-06-04 Ross Johnson + + * condvar.c: Add original description of the algorithm as + developed by Terekhov and Thomas, plus reference to + README.CV. + +2001-06-03 Alexander Terekhov , Louis Thomas + + * condvar.c (pthread_cond_init): Completely revamped. + (pthread_cond_destroy): Likewise. + (ptw32_cond_wait_cleanup): Likewise. + (ptw32_cond_timedwait): Likewise. + (ptw32_cond_unblock): New general signaling routine. + (pthread_cond_signal): Now calls ptw32_cond_unblock. + (pthread_cond_broadcast): Likewise. + * implement.h (pthread_cond_t_): Revamped. + * README.CV: New; explanation of the above changes. + +2001-05-30 Ross Johnson + + * pthread.h (rand_r): Fake using _seed argument to quell + compiler warning (compiler should optimise this away later). + + * GNUmakefile (OPT): Leave symbolic information out of the library + and increase optimisation level - for smaller faster prebuilt + dlls. + +2001-05-29 Milan Gardian + + * Makefile: fix typo. + * pthreads.h: Fix problems with stdcall/cdecl conventions, in particular + remove the need for PT_STDCALL everywhere; remove warning supression. + * (errno): Fix the longstanding "inconsistent dll linkage" problem + with errno; now also works with /MD debugging libs - + warnings emerged when compiling pthreads library with /MD (or /MDd) + compiler switch, instead of /MT (or /MTd) (i.e. when compiling pthreads + using Multithreaded DLL CRT instead of Multithreaded statically linked + CRT). + * create.c (pthread_create): Likewise; fix typo. + * private.c (ptw32_threadStart): Eliminate use of terminate() which doesn't + throw exceptions. + * Remove unnecessary #includes from a number of modules - + [I had to #include malloc.h in implement.h for gcc - rpj]. + +2001-05-29 Thomas Pfaff + + * pthread.h (PTHREAD_MUTEX_DEFAULT): New; equivalent to + PTHREAD_MUTEX_DEFAULT_NP. + * (PTHREAD_MUTEX_NORMAL): Similarly. + * (PTHREAD_MUTEX_ERRORCHECK): Similarly. + * (PTHREAD_MUTEX_RECURSIVE): Similarly. + * (pthread_mutex_setdefaultkind_np): New; Linux compatibility stub + for pthread_mutexattr_settype. + * (pthread_mutexattr_getkind_np): New; Linux compatibility stub + for pthread_mutexattr_gettype. + * mutex.c (pthread_mutexattr_settype): New; allow + the following types of mutex: + PTHREAD_MUTEX_DEFAULT_NP + PTHREAD_MUTEX_NORMAL_NP + PTHREAD_MUTEX_ERRORCHECK_NP + PTHREAD_MUTEX_RECURSIVE_NP + * Note that PTHREAD_MUTEX_DEFAULT is equivalent to + PTHREAD_MUTEX_NORMAL - ie. mutexes should no longer + be recursive by default, and a thread will deadlock if it + tries to relock a mutex it already owns. This is inline with + other pthreads implementations. + * (pthread_mutex_lock): Process the lock request + according to the mutex type. + * (pthread_mutex_init): Eliminate use of Win32 mutexes as the + basis of POSIX mutexes - instead, a combination of one critical section + and one semaphore are used in conjunction with Win32 Interlocked* routines. + * (pthread_mutex_destroy): Likewise. + * (pthread_mutex_lock): Likewise. + * (pthread_mutex_trylock): Likewise. + * (pthread_mutex_unlock): Likewise. + * Use longjmp/setjmp to implement cancelation when building the library + using a C compiler which doesn't support exceptions, e.g. gcc -x c (note + that gcc -x c++ uses exceptions). + * Also fixed some of the same typos and eliminated PT_STDCALL as + Milan Gardian's patches above. + +2001-02-07 Alexander Terekhov + + * rwlock.c: Revamped. + * implement.h (pthread_rwlock_t_): Redefined. + This implementation does not have reader/writer starvation problem. + Rwlock attempts to behave more like a normal mutex with + races and scheduling policy determining who is more important; + It also supports recursive locking, + has less synchronization overhead (no broadcasts at all, + readers are not blocked on any condition variable) and seem to + be faster than the current implementation [W98 appears to be + approximately 15 percent faster at least - on top of speed increase + from Thomas Pfaff's changes to mutex.c - rpj]. + +2000-12-29 Ross Johnson + + * Makefile: Back-out "for" loops which don't work. + + * GNUmakefile: Remove the fake.a target; add the "realclean" + target; don't remove built libs under the "clean" target. + + * config.h: Add a guard against multiple inclusion. + + * semaphore.h: Add some defines from config.h to make + semaphore.h independent of config.h when building apps. + + * pthread.h (_errno): Back-out previous fix until we know how to + fix it properly. + + * implement.h (lockCount): Add missing element to pthread_mutex_t_. + + * sync.c (pthread_join): Spelling fix in comment. + + * private.c (ptw32_threadStart): Reset original termination + function (C++). + (ptw32_threadStart): Cleanup detached threads early in case + the library is statically linked. + (ptw32_callUserDestroyRoutines): Remove [SEH] __try block from + destructor call so that unhandled exceptions will be passed through + to the system; call terminate() from [C++] try block for the same + reason. + + * tsd.c (pthread_getspecific): Add comment. + + * mutex.c (pthread_mutex_init): Initialise new elements in + pthread_mutex_t. + (pthread_mutex_unlock): Invert "pthread_equal()" test. + +2000-12-28 Ross Johnson + + * semaphore.c (mode_t): Use ifndef HAVE_MODE_T to include definition. + + * config.h.in (HAVE_MODE_T): Added. + (_UWIN): Start adding defines for the UWIN package. + + * private.c (ptw32_threadStart): Unhandled exceptions are + now passed through to the system to deal with. This is consistent + with normal Windows behaviour. C++ applications may use + set_terminate() to override the default behaviour which is + to call ptw32_terminate(). Ptw32_terminate() cleans up some + POSIX thread stuff before calling the system default function + which calls abort(). The users termination function should conform + to standard C++ semantics which is to not return. It should + exit the thread (call pthread_exit()) or exit the application. + * private.c (ptw32_terminate): Added as the default set_terminate() + function. It calls the system default function after cleaning up + some POSIX thread stuff. + + * implement.h (ptw32_try_enter_critical_section): Move + declaration. + * global.c (ptw32_try_enter_critical_section): Moved + from dll.c. + * dll.c: Move process and thread attach/detach code into + functions in nonportable.c. + * nonportable.c (pthread_win32_process_attach_np): Process + attach code from dll.c is now available to static linked + applications. + * nonportable.c (pthread_win32_process_detach_np): Likewise. + * nonportable.c (pthread_win32_thread_attach_np): Likewise. + * nonportable.c (pthread_win32_thread_detach_np): Likewise. + + * pthread.h: Add new non-portable prototypes for static + linked applications. + + * GNUmakefile (OPT): Increase optimisation flag and remove + debug info flag. + + * pthread.def: Add new non-portable exports for static + linked applications. + +2000-12-11 Ross Johnson + + * FAQ: Update Answer 6 re getting a fully working + Mingw32 built library. + +2000-10-10 Steven Reddie + + * misc.c (pthread_self): Restore Win32 "last error" + cleared by TlsGetValue() call in + pthread_getspecific() + +2000-09-20 Arthur Kantor + + * mutex.c (pthread_mutex_lock): Record the owner + of the mutex. This requires also keeping count of + recursive locks ourselves rather than leaving it + to Win32 since we need to know when to NULL the + thread owner when the mutex is unlocked. + (pthread_mutex_trylock): Likewise. + (pthread_mutex_unlock): Check that the calling + thread owns the mutex, decrement the recursive + lock count, and NULL the owner if zero. Return + EPERM if the mutex is owned by another thread. + * implement.h (pthread_mutex_t_): Add ownerThread + and lockCount members. + +2000-09-13 Jef Gearhart + + * mutex.c (pthread_mutex_init): Call + TryEnterCriticalSection through the pointer + rather than directly so that the dll can load + on Windows versions that can't resolve the + function, eg. Windows 95 + +2000-09-09 Ross Johnson + + * pthread.h (ctime_r): Fix arg. + +2000-09-08 Ross Johnson + + * GNUmakefile(_WIN32_WINNT=0x400): Define in CFLAGS; + doesn't seem to be needed though. + + * cancel.c (pthread_cancel): Must get "self" through + calling pthread_self() which will ensure a POSIX thread + struct is built for non-POSIX threads; return an error + if this fails + - Ollie Leahy + (pthread_setcancelstate): Likewise. + (pthread_setcanceltype): Likewise. + * misc.c (ptw32_cancelable_wait): Likewise. + + * private.c (ptw32_tkAssocCreate): Remove unused #if 0 + wrapped code. + + * pthread.h (ptw32_get_exception_services_code): + Needed to be forward declared unconditionally. + +2000-09-06 Ross Johnson + + * cancel.c (pthread_cancel): If called from the main + thread "self" would be NULL; get "self" via pthread_self() + instead of directly from TLS so that an implicit + pthread object is created. + + * misc.c (pthread_equal): Strengthen test for NULLs. + +2000-09-02 Ross Johnson + + * condvar.c (ptw32_cond_wait_cleanup): Ensure that all + waking threads check if they are the last, and notify + the broadcaster if so - even if an error occurs in the + waiter. + + * semaphore.c (_decrease_semaphore): Should be + a call to ptw32_decrease_semaphore. + (_increase_semaphore): Should be a call to + ptw32_increase_semaphore. + + * misc.c (ptw32_cancelable_wait): Renamed from + CancelableWait. + * rwlock.c (_rwlock_check*): Renamed to + ptw32_rwlock_check*. + * mutex.c (_mutex_check*): Renamed to ptw32_mutex_check*. + * condvar.c (cond_timed*): Renamed to ptw32_cond_timed*. + (_cond_check*): Renamed to ptw32_cond_check*. + (cond_wait_cleanup*): Rename to ptw32_cond_wait_cleanup*. + (ptw32_cond_timedwait): Add comments. + +2000-08-22 Ross Johnson + + * private.c (ptw32_throw): Fix exception test; + move exceptionInformation declaration. + + * tsd.c (pthread_key_create): newkey wrongly declared. + + * pthread.h: Fix comment block. + +2000-08-18 Ross Johnson + + * mutex.c (pthread_mutex_destroy): Check that the mutex isn't + held; invalidate the mutex as early as possible to avoid + contention; not perfect - FIXME! + + * rwlock.c (pthread_rwlock_init): Remove redundant assignment + to "rw". + (pthread_rwlock_destroy): Invalidate the rwlock before + freeing up any of it's resources - to avoid contention. + + * private.c (ptw32_tkAssocCreate): Change assoc->lock + to use a dynamically initialised mutex - only consumes + a W32 mutex or critical section when first used, + not before. + + * mutex.c (pthread_mutex_init): Remove redundant assignment + to "mx". + (pthread_mutexattr_destroy): Set attribute to NULL + before freeing it's memory - to avoid contention. + + * implement.h (PTW32_EPS_CANCEL/PTW32_EPS_EXIT): + Must be defined for all compilers - used as generic + exception selectors by ptw32_throw(). + + * Several: Fix typos from scripted edit session + yesterday. + + * nonportable.c (pthread_mutexattr_setforcecs_np): + Moved this function from mutex.c. + (pthread_getw32threadhandle_np): New function to + return the win32 thread handle that the POSIX + thread is using. + * mutex.c (pthread_mutexattr_setforcecs_np): + Moved to new file "nonportable.c". + + * pthread.h (PTW32_BUILD): Only redefine __except + and catch compiler keywords if we aren't building + the library (ie. PTW32_BUILD is not defined) - + this is safer than defining and then undefining + if not building the library. + * implement.h: Remove __except and catch undefines. + * Makefile (CFLAGS): Define PTW32_BUILD. + * GNUmakefile (CFLAGS): Define PTW32_BUILD. + + * All appropriate: Change Pthread_exception* to + ptw32_exception* to be consistent with internal + identifier naming. + + * private.c (ptw32_throw): New function to provide + a generic exception throw for all internal + exceptions and EH schemes. + (ptw32_threadStart): pthread_exit() value is now + returned via the thread structure exitStatus + element. + * exit.c (pthread_exit): pthread_exit() value is now + returned via the thread structure exitStatus + element. + * cancel.c (ptw32_cancel_self): Now uses ptw32_throw. + (pthread_setcancelstate): Ditto. + (pthread_setcanceltype): Ditto. + (pthread_testcancel): Ditto. + (pthread_cancel): Ditto. + * misc.c (CancelableWait): Ditto. + * exit.c (pthread_exit): Ditto. + * All applicable: Change PTW32_ prefix to + PTW32_ prefix to remove leading underscores + from private library identifiers. + +2000-08-17 Ross Johnson + + * All applicable: Change _pthread_ prefix to + ptw32_ prefix to remove leading underscores + from private library identifiers (single + and double leading underscores are reserved in the + ANSI C standard for compiler implementations). + + * tsd.c (pthread_create_key): Initialise temporary + key before returning it's address to avoid race + conditions. + +2000-08-13 Ross Johnson + + * errno.c: Add _MD precompile condition; thus far + had no effect when using /MD compile option but I + thnk it should be there. + + * exit.c: Add __cplusplus to various #if lines; + was compiling SEH code even when VC++ had + C++ compile options. + + * private.c: ditto. + + * create.c (pthread_create): Add PT_STDCALL macro to + function pointer arg in _beginthread(). + + * pthread.h: PT_STDCALL really does need to be defined + in both this and impliment.h; don't set it to __cdecl + - this macro is only used to extend function pointer + casting for functions that will be passed as parameters. + (~PThreadCleanup): add cast and group expression. + (_errno): Add _MD compile conditional. + (PtW32NoCatchWarn): Change pragma message. + + * implement.h: Move and change PT_STDCALL define. + + * need_errno.h: Add _MD to compilation conditional. + + * GNUmakefile: Substantial rewrite for new naming + convention; set for nil optimisation (turn it up + when we have a working library build; add target + "fake.a" to build a libpthreadw32.a from the VC++ + built DLL pthreadVCE.dll. + + * pthread.def (LIBRARY): Don't specify in the .def + file - it is specified on the linker command line + since we now use the same .def file for variously + named .dlls. + + * Makefile: Substantial rewrite for new naming + convention; default nmake target only issues a + help message; run nmake with specific target + corresponding to the EH scheme being used. + + * README: Update information; add naming convention + explanation. + + * ANNOUNCE: Update information. + +2000-08-12 Ross Johnson + + * pthread.h: Add compile-time message when using + MSC_VER compiler and C++ EH to warn application + programmers to use PtW32Catch instead of catch(...) + if they want cancelation and pthread_exit to work. + + * implement.h: Remove #include ; we + use our own local semaphore.h. + +2000-08-10 Ross Johnson + + * cleanup.c (pthread_pop_cleanup): Remove _pthread + prefix from __except and catch keywords; implement.h + now simply undefines ptw32__except and + ptw32_catch if defined; VC++ was not textually + substituting ptw32_catch etc back to catch as + it was redefined; the reason for using the prefixed + version was to make it clear that it was not using + the pthread.h redefined catch keyword. + + * private.c (ptw32_threadStart): Ditto. + (ptw32_callUserDestroyRoutines): Ditto. + + * implement.h (ptw32__except): Remove #define. + (ptw32_catch): Remove #define. + + * GNUmakefile (pthread.a): New target to build + libpthread32.a from pthread.dll using dlltool. + + * buildlib.bat: Duplicate cl commands with args to + build C++ EH version of pthread.dll; use of .bat + files is redundant now that nmake compatible + Makefile is included; used as a kludge only now. + + * Makefile: Localise some macros and fix up the clean: + target to extend it and work properly. + + * CONTRIBUTORS: Add contributors. + + * ANNOUNCE: Updated. + + * README: Updated. + +2000-08-06 Ross Johnson + + * pthread.h: Remove #warning - VC++ doesn't accept it. + +2000-08-05 Ross Johnson + + * pthread.h (PtW32CatchAll): Add macro. When compiling + applications using VC++ with C++ EH rather than SEH + 'PtW32CatchAll' must be used in place of any 'catch( ... )' + if the application wants pthread cancelation or + pthread_exit() to work. + +2000-08-03 Ross Johnson + + * pthread.h: Add a base class ptw32_exception for + library internal exceptions and change the "catch" + re-define macro to use it. + +2000-08-02 Ross Johnson + + * GNUmakefile (CFLAGS): Add -mthreads. + Add new targets to generate cpp and asm output. + + * sync.c (pthread_join): Remove dead code. + +2000-07-25 Tristan Savatier + + * sched.c (sched_get_priority_max): Handle different WinCE and + Win32 priority values together. + (sched_get_priority_min): Ditto. + +2000-07-25 Ross Johnson + + * create.c (pthread_create): Force new threads to wait until + pthread_create has the new thread's handle; we also retain + a local copy of the handle for internal use until + pthread_create returns. + + * private.c (ptw32_threadStart): Initialise ei[]. + (ptw32_threadStart): When beginthread is used to start the + thread, force waiting until the creator thread had the + thread handle. + + * cancel.c (ptw32_cancel_thread): Include context switch + code for defined(_X86_) environments in addition to _M_IX86. + + * rwlock.c (pthread_rwlock_destroy): Assignment changed + to avoid compiler warning. + + * private.c (ptw32_get_exception_services_code): Cast + NULL return value to avoid compiler warning. + + * cleanup.c (pthread_pop_cleanup): Initialise "cleanup" variable + to avoid compiler warnings. + + * misc.c (ptw32_new): Change "new" variable to "t" to avoid + confusion with the C++ keyword of the same name. + + * condvar.c (cond_wait_cleanup): Initialise lastWaiter variable. + (cond_timedwait): Remove unused local variables. to avoid + compiler warnings. + + * dll.c (dllMain): Remove 2000-07-21 change - problem + appears to be in pthread_create(). + +2000-07-22 Ross Johnson + + * tsd.c (pthread_key_create): If a destructor was given + and the pthread_mutex_init failed, then would try to + reference a NULL pointer (*key); eliminate this section of + code by using a dynamically initialised mutex + (PTHREAD_MUTEX_INITIALIZER). + + * tsd.c (pthread_setspecific): Return an error if + unable to set the value; simplify cryptic conditional. + + * tsd.c (pthread_key_delete): Locking threadsLock relied + on mutex_lock returning an error if the key has no destructor. + ThreadsLock is only initialised if the key has a destructor. + Making this mutex a static could reduce the number of mutexes + used by an application since it is actually created only at + first use and it's often destroyed soon after. + +2000-07-22 Ross Johnson + + * FAQ: Added Q5 and Q6. + +2000-07-21 David Baggett + + * dll.c: Include resource leakage work-around. This is a + partial FIXME which doesn't stop all leakage. The real + problem needs to be found and fixed. + +2000-07-21 Ross Johnson + + * create.c (pthread_create): Set threadH to 0 (zero) + everywhere. Some assignments were using NULL. Maybe + it should be NULL everywhere - need to check. (I know + they are nearly always the same thing - but not by + definition.) + + * misc.c (pthread_self): Try to catch NULL thread handles + at the point where they might be generated, even though + they should always be valid at this point. + + * tsd.c (pthread_setspecific): return an error value if + pthread_self() returns NULL. + + * sync.c (pthread_join): return an error value if + pthread_self() returns NULL. + + * signal.c (pthread_sigmask): return an error value if + pthread_self() returns NULL. + +2000-03-02 Ross Johnson + + * attr.c (pthread_attr_init): Set default stacksize to zero (0) + rather than PTHREAD_STACK_MIN even though these are now the same. + + * pthread.h (PTHREAD_STACK_MIN): Lowered to 0. + +2000-01-28 Ross Johnson + + * mutex.c (pthread_mutex_init): Free mutex if it has been alloced; + if critical sections can be used instead of Win32 mutexes, test + that the critical section works and return an error if not. + +2000-01-07 Ross Johnson + + * cleanup.c (pthread_pop_cleanup): Include SEH code only if MSC is not + compiling as C++. + (pthread_push_cleanup): Include SEH code only if MSC is not + compiling as C++. + + * pthread.h: Include SEH code only if MSC is not + compiling as C++. + + * implement.h: Include SEH code only if MSC is not + compiling as C++. + + * cancel.c (ptw32_cancel_thread): Add _M_IX86 check. + (pthread_testcancel): Include SEH code only if MSC is not + compiling as C++. + (ptw32_cancel_self): Include SEH code only if MSC is not + compiling as C++. + +2000-01-06 Erik Hensema + + * Makefile: Remove inconsistencies in 'cl' args + +2000-01-04 Ross Johnson + + * private.c (ptw32_get_exception_services_code): New; returns + value of EXCEPTION_PTW32_SERVICES. + (ptw32_processInitialize): Remove initialisation of + ptw32_exception_services which is no longer needed. + + * pthread.h (ptw32_exception_services): Remove extern. + (ptw32_get_exception_services_code): Add function prototype; + use this to return EXCEPTION_PTW32_SERVICES value instead of + using the ptw32_exception_services variable which I had + trouble exporting through pthread.def. + + * global.c (ptw32_exception_services): Remove declaration. + +1999-11-22 Ross Johnson + + * implement.h: Forward declare ptw32_new(); + + * misc.c (ptw32_new): New; alloc and initialise a new pthread_t. + (pthread_self): New thread struct is generated by new routine + ptw32_new(). + + * create.c (pthread_create): New thread struct is generated + by new routine ptw32_new(). + +1999-11-21 Ross Johnson + + * global.c (ptw32_exception_services): Declare new variable. + + * private.c (ptw32_threadStart): Destroy thread's + cancelLock mutex; make 'catch' and '__except' usageimmune to + redfinitions in pthread.h. + (ptw32_processInitialize): Init new constant ptw32_exception_services. + + * create.c (pthread_create): Initialise thread's cancelLock + mutex. + + * cleanup.c (pthread_pop_cleanup): Make 'catch' and '__except' + usage immune to redfinition s in pthread.h. + + * private.c: Ditto. + + * pthread.h (catch): Redefine 'catch' so that C++ applications + won't catch our internal exceptions. + (__except): ditto for __except. + + * implement.h (ptw32_catch): Define internal version + of 'catch' because 'catch' is redefined by pthread.h. + (__except): ditto for __except. + (struct pthread_t_): Add cancelLock mutex for async cancel + safety. + +1999-11-21 Jason Nye , Erik Hensema + + * cancel.c (ptw32_cancel_self): New; part of the async + cancellation implementation. + (ptw32_cancel_thread): Ditto; this function is X86 + processor specific. + (pthread_setcancelstate): Add check for pending async + cancel request and cancel the calling thread if + required; add async-cancel safety lock. + (pthread_setcanceltype): Ditto. + +1999-11-13 Erik Hensema + + * configure.in (AC_OUTPUT): Put generated output into GNUmakefile + rather than Makefile. Makefile will become the MSC nmake compatible + version + +1999-11-13 John Bossom (John.Bossom@cognos.com> + + * misc.c (pthread_self): Add a note about GetCurrentThread + returning a pseudo-handle + +1999-11-10 Todd Owen + + * dll.c (dllMain): Free kernel32 ASAP. + If TryEnterCriticalSection is not being used, then free + the kernel32.dll handle now, rather than leaving it until + DLL_PROCESS_DETACH. + + Note: this is not a pedantic exercise in freeing unused + resources! It is a work-around for a bug in Windows 95 + (see microsoft knowledge base article, Q187684) which + does Bad Things when FreeLibrary is called within + the DLL_PROCESS_DETACH code, in certain situations. + Since w95 just happens to be a platform which does not + provide TryEnterCriticalSection, the bug will be + effortlessly avoided. + +1999-11-10 Ross Johnson + + * sync.c (pthread_join): Make it a deferred cancelation point. + + * misc.c (pthread_self): Explicitly initialise implicitly + created thread state to default values. + +1999-11-05 Tristan Savatier + + * pthread.h (winsock.h): Include unconditionally. + (ETIMEDOUT): Change fallback value to that defined by winsock.h. + + * general: Patched for portability to WinCE. The details are + described in the file WinCE-PORT. Follow the instructions + in README.WinCE to make the appropriate changes in config.h. + +1999-10-30 Erik Hensema + + * create.c (pthread_create): Explicitly initialise thread state to + default values. + + * cancel.c (pthread_setcancelstate): Check for NULL 'oldstate' + for compatibility with Solaris pthreads; + (pthread_setcanceltype): ditto: + +1999-10-23 Erik Hensema + + * pthread.h (ctime_r): Fix incorrect argument "_tm" + +1999-10-21 Aurelio Medina + + * pthread.h (_POSIX_THREADS): Only define it if it isn't + already defined. Projects may need to define this on + the CC command line under Win32 as it doesn't have unistd.h + +1999-10-17 Ross Johnson + + * rwlock.c (pthread_rwlock_destroy): Add cast to remove compile + warning. + + * condvar.c (pthread_cond_broadcast): Only release semaphores + if there are waiting threads. + +1999-10-15 Lorin Hochstein , Peter Slacik + + * condvar.c (cond_wait_cleanup): New static cleanup handler for + cond_timedwait; + (cond_timedwait): pthread_cleanup_push args changed; + canceling a thread while it's in pthread_cond_wait + will now decrement the waiters count and cleanup if it's the + last waiter. + +1999-10-15 Graham Dumpleton + + * condvar.c (cond_wait_cleanup): the last waiter will now reset the CV's + wasBroadcast flag + +Thu Sep 16 1999 Ross Johnson + + * rwlock.c (pthread_rwlock_destroy): Add serialisation. + (_rwlock_check_need_init): Check for detroyed rwlock. + * rwlock.c: Check return codes from _rwlock_check_need_init(); + modify comments; serialise access to rwlock objects during + operations; rename rw_mutex to rw_lock. + * implement.h: Rename rw_mutex to rw_lock. + * mutex.c (pthread_mutex_destroy): Add serialisation. + (_mutex_check_need_init): Check for detroyed mutex. + * condvar.c (pthread_cond_destroy): Add serialisation. + (_cond_check_need_init): Check for detroyed condvar. + * mutex.c: Modify comments. + * condvar.c: Modify comments. + +1999-08-10 Aurelio Medina + + * implement.h (pthread_rwlock_t_): Add. + * pthread.h (pthread_rwlock_t): Add. + (PTHREAD_RWLOCK_INITIALIZER): Add. + Add rwlock function prototypes. + * rwlock.c: New module. + * pthread.def: Add new rwlock functions. + * private.c (ptw32_processInitialize): initialise + ptw32_rwlock_test_init_lock critical section. + * global.c (ptw32_rwlock_test_init_lock): Add. + + * mutex.c (pthread_mutex_destroy): Don't free mutex memory + if mutex is PTHREAD_MUTEX_INITIALIZER and has not been + initialised yet. + +1999-08-08 Milan Gardian + + * mutex.c (pthread_mutex_destroy): Free mutex memory. + +1999-08-22 Ross Johnson + + * exit.c (pthread_exit): Fix reference to potentially + uninitialised pointer. + +1999-08-21 Ross Johnson + + * private.c (ptw32_threadStart): Apply fix of 1999-08-19 + this time to C++ and non-trapped C versions. Ommitted to + do this the first time through. + +1999-08-19 Ross Johnson + + * private.c (ptw32_threadStart): Return exit status from + the application thread startup routine. + - Milan Gardian + +1999-08-18 John Bossom + + * exit.c (pthread_exit): Put status into pthread_t->exitStatus + * private.c (ptw32_threadStart): Set pthread->exitStatus + on exit of try{} block. + * sync.c (pthread_join): use pthread_exitStatus value if the + thread exit doesn't return a value (for Mingw32 CRTDLL + which uses endthread instead of _endthreadex). + +Tue Aug 17 20:17:58 CDT 1999 Mumit Khan + + * create.c (pthread_create): Add CRTDLL suppport. + * exit.c (pthread_exit): Likewise. + * private.c (ptw32_threadStart): Likewise. + (ptw32_threadDestroy): Likewise. + * sync.c (pthread_join): Likewise. + * tests/join1.c (main): Warn about partial support for CRTDLL. + +Tue Aug 17 20:00:08 1999 Mumit Khan + + * Makefile.in (LD): Delete entry point. + * acconfig.h (STDCALL): Delete unused macro. + * configure.in: Remove test for STDCALL. + * config.h.in: Regenerate. + * errno.c (_errno): Fix self type. + * pthread.h (PT_STDCALL): Move from here to + * implement.h (PT_STDCALL): here. + (ptw32_threadStart): Fix prototype. + * private.c (ptw32_threadStart): Likewise. + +1999-08-14 Ross Johnson + + * exit.c (pthread_exit): Don't call pthread_self() but + get thread handle directly from TSD for efficiency. + +1999-08-12 Ross Johnson + + * private.c (ptw32_threadStart): ei[] only declared if _MSC_VER. + + * exit.c (pthread_exit): Check for implicitly created threads + to avoid raising an unhandled exception. + +1999-07-12 Peter Slacik + + * condvar.c (pthread_cond_destroy): Add critical section. + (cond_timedwait): Add critical section; check for timeout + waiting on semaphore. + (pthread_cond_broadcast): Add critical section. + +1999-07-09 Lorin Hochstein , John Bossom + + The problem was that cleanup handlers were not executed when + pthread_exit() was called. + + * implement.h (pthread_t_): Add exceptionInformation element for + C++ per-thread exception information. + (general): Define and rename exceptions. + +1999-07-09 Ross Johnson + + * misc.c (CancelableWait): PTW32_EPS_CANCEL (SEH) and + ptw32_exception_cancel (C++) used to identify the exception. + + * cancel.c (pthread_testcancel): PTW32_EPS_CANCEL (SEH) and + ptw32_exception_cancel (C++) used to identify the exception. + + * exit.c (pthread_exit): throw/raise an exception to return to + ptw32_threadStart() to exit the thread. PTW32_EPS_EXIT (SEH) + and ptw32_exception_exit (C++) used to identify the exception. + + * private.c (ptw32_threadStart): Add pthread_exit exception trap; + clean up and exit the thread directly rather than via pthread_exit(). + +Sun May 30 00:25:02 1999 Ross Johnson + + * semaphore.h (mode_t): Conditionally typedef it. + +Fri May 28 13:33:05 1999 Mark E. Armstrong + + * condvar.c (pthread_cond_broadcast): Fix possible memory fault + +Thu May 27 13:08:46 1999 Peter Slacik + + * condvar.c (pthread_cond_broadcast): Fix logic bug + +Thu May 27 13:08:46 1999 Bossom, John + + * condvar.c (pthread_cond_broadcast): optimise sem_post loop + +Fri May 14 12:13:18 1999 Mike Russo + + * attr.c (pthread_attr_setdetachstate): Fix logic bug + +Sat May 8 09:42:30 1999 Ross Johnson + + * pthread.def (sem_open): Add. + (sem_close): Add. + (sem_unlink): Add. + (sem_getvalue): Add. + + * FAQ (Question 3): Add. + +Thu Apr 8 01:16:23 1999 Ross Johnson + + * semaphore.c (sem_open): New function; returns an error (ENOSYS). + (sem_close): ditto. + (sem_unlink): ditto. + (sem_getvalue): ditto. + + * semaphore.h (_POSIX_SEMAPHORES): define. + +Wed Apr 7 14:09:52 1999 Ross Johnson + + * errno.c (_REENTRANT || _MT): Invert condition. + + * pthread.h (_errno): Conditionally include prototype. + +Wed Apr 7 09:37:00 1999 Ross Johnson + + * *.c (comments): Remove individual attributions - these are + documented sufficiently elsewhere. + + * implement.h (pthread.h): Remove extraneous include. + +Sun Apr 4 11:05:57 1999 Ross Johnson + + * sched.c (sched.h): Include. + + * sched.h: New file for POSIX 1b scheduling. + + * pthread.h: Move opaque structures to implement.h; move sched_* + prototypes out and into sched.h. + + * implement.h: Add opaque structures from pthread.h. + + * sched.c (sched_yield): New function. + + * condvar.c (ptw32_sem_*): Rename to sem_*; except for + ptw32_sem_timedwait which is an private function. + +Sat Apr 3 23:28:00 1999 Ross Johnson + + * Makefile.in (OBJS): Add errno.o. + +Fri Apr 2 11:08:50 1999 Ross Johnson + + * implement.h (ptw32_sem_*): Remove prototypes now defined in + semaphore.h. + + * pthread.h (sempahore.h): Include. + + * semaphore.h: New file for POSIX 1b semaphores. + + * semaphore.c (ptw32_sem_timedwait): Moved to private.c. + + * pthread.h (ptw32_sem_t): Change to sem_t. + + * private.c (ptw32_sem_timedwait): Moved from semaphore.c; + set errno on error. + + * pthread.h (pthread_t_): Add per-thread errno element. + +Fri Apr 2 11:08:50 1999 John Bossom + + * semaphore.c (ptw32_sem_*): Change to sem_*; these functions + will be exported from the library; set errno on error. + + * errno.c (_errno): New file. New function. + +Fri Mar 26 14:11:45 1999 Tor Lillqvist + + * semaphore.c (ptw32_sem_timedwait): Check for negative + milliseconds. + +Wed Mar 24 11:32:07 1999 John Bossom + + * misc.c (CancelableWait): Initialise exceptionInformation[2]. + (pthread_self): Get a real Win32 thread handle for implicit threads. + + * cancel.c (pthread_testcancel): Initialise exceptionInformation[2]. + + * implement.h (SE_INFORMATION): Fix values. + + * private.c (ptw32_threadDestroy): Close the thread handle. + +Fri Mar 19 12:57:27 1999 Ross Johnson + + * cancel.c (comments): Update and cleanup. + +Fri Mar 19 09:12:59 1999 Ross Johnson + + * private.c (ptw32_threadStart): status returns PTHREAD_CANCELED. + + * pthread.h (PTHREAD_CANCELED): defined. + +Tue Mar 16 1999 Ross Johnson + + * all: Add GNU LGPL and Copyright and Warranty. + +Mon Mar 15 00:20:13 1999 Ross Johnson + + * condvar.c (pthread_cond_init): fix possible uninitialised use + of cv. + +Sun Mar 14 21:01:59 1999 Ross Johnson + + * condvar.c (pthread_cond_destroy): don't do full cleanup if + static initialised cv has never been used. + (cond_timedwait): check result of auto-initialisation. + +Thu Mar 11 09:01:48 1999 Ross Johnson + + * pthread.h (pthread_mutex_t): revert to (pthread_mutex_t *); + define a value to serve as PTHREAD_MUTEX_INITIALIZER. + (pthread_mutex_t_): remove staticinit and valid elements. + (pthread_cond_t): revert to (pthread_cond_t_ *); + define a value to serve as PTHREAD_COND_INITIALIZER. + (pthread_cond_t_): remove staticinit and valid elements. + + * mutex.c (pthread_mutex_t args): adjust indirection of references. + (all functions): check for PTHREAD_MUTEX_INITIALIZER value; + check for NULL (invalid). + + * condvar.c (pthread_cond_t args): adjust indirection of references. + (all functions): check for PTHREAD_COND_INITIALIZER value; + check for NULL (invalid). + +Wed Mar 10 17:18:12 1999 Ross Johnson + + * misc.c (CancelableWait): Undo changes from Mar 8 and 7. + +Mon Mar 8 11:18:59 1999 Ross Johnson + + * misc.c (CancelableWait): Ensure cancelEvent handle is the lowest + indexed element in the handles array. Enhance test for abandoned + objects. + + * pthread.h (PTHREAD_MUTEX_INITIALIZER): Trailing elements not + initialised are set to zero by the compiler. This avoids the + problem of initialising the opaque critical section element in it. + (PTHREAD_COND_INITIALIZER): Ditto. + + * semaphore.c (ptw32_sem_timedwait): Check sem == NULL earlier. + +Sun Mar 7 12:31:14 1999 Ross Johnson + + * condvar.c (pthread_cond_init): set semaphore initial value + to 0, not 1. cond_timedwait was returning signaled immediately. + + * misc.c (CancelableWait): Place the cancel event handle first + in the handle table for WaitForMultipleObjects. This ensures that + the cancel event is recognised and acted apon if both objects + happen to be signaled together. + + * private.c (ptw32_cond_test_init_lock): Initialise and destroy. + + * implement.h (ptw32_cond_test_init_lock): Add extern. + + * global.c (ptw32_cond_test_init_lock): Add declaration. + + * condvar.c (pthread_cond_destroy): check for valid initialised CV; + flag destroyed CVs as invalid. + (pthread_cond_init): pthread_cond_t is no longer just a pointer. + This is because PTHREAD_COND_INITIALIZER needs state info to reside + in pthread_cond_t so that it can initialise on first use. Will work on + making pthread_cond_t (and other objects like it) opaque again, if + possible, later. + (cond_timedwait): add check for statically initialisation of + CV; initialise on first use. + (pthread_cond_signal): check for valid CV. + (pthread_cond_broadcast): check for valid CV. + (_cond_check_need_init): Add. + + * pthread.h (PTHREAD_COND_INITIALIZER): Fix. + (pthread_cond_t): no longer a pointer to pthread_cond_t_. + (pthread_cond_t_): add 'staticinit' and 'valid' elements. + +Sat Mar 6 1999 Ross Johnson + + * implement.h: Undate comments. + +Sun Feb 21 1999 Ross Johnson + + * pthread.h (PTHREAD_MUTEX_INITIALIZER): missing braces around + cs element initialiser. + +1999-02-21 Ben Elliston + + * pthread.h (pthread_exit): The return type of this function is + void, not int. + + * exit.c (pthread_exit): Do not return 0. + +Sat Feb 20 16:03:30 1999 Ross Johnson + + * dll.c (DLLMain): Expand TryEnterCriticalSection support test. + + * mutex.c (pthread_mutex_trylock): The check for + ptw32_try_enter_critical_section == NULL should have been + removed long ago. + +Fri Feb 19 16:03:30 1999 Ross Johnson + + * sync.c (pthread_join): Fix pthread_equal() test. + + * mutex.c (pthread_mutex_trylock): Check mutex != NULL before + using it. + +Thu Feb 18 16:17:30 1999 Ross Johnson + + * misc.c (pthread_equal): Fix inverted result. + + * Makefile.in: Use libpthread32.a as the name of the DLL export + library instead of pthread.lib. + + * condvar.c (pthread_cond_init): cv could have been used unitialised; + initialise. + + * create.c (pthread_create): parms could have been used unitialised; + initialise. + + * pthread.h (struct pthread_once_t_): Remove redefinition. + +Sat Feb 13 03:03:30 1999 Ross Johnson + + * pthread.h (struct pthread_once_t_): Replaced. + + * misc.c (pthread_once): Replace with John Bossom's version; + has lighter weight serialisation; fixes problem of not holding + competing threads until after the init_routine completes. + +Thu Feb 11 13:34:14 1999 Ross Johnson + + * misc.c (CancelableWait): Change C++ exception throw. + + * sync.c (pthread_join): Change FIXME comment - issue resolved. + +Wed Feb 10 12:49:11 1999 Ross Johnson + + * configure: Various temporary changes. + - Kevin Ruland + + * README: Update. + + * pthread.def (pthread_attr_getstackaddr): uncomment + (pthread_attr_setstackaddr): uncomment + +Fri Feb 5 13:42:30 1999 Ross Johnson + + * semaphore.c: Comment format changes. + +Thu Feb 4 10:07:28 1999 Ross Johnson + + * global.c: Remove ptw32_exception instantiation. + + * cancel.c (pthread_testcancel): Change C++ exception throw. + + * implement.h: Remove extern declaration. + +Wed Feb 3 13:04:44 1999 Ross Johnson + + * cleanup.c: Rename ptw32_*_cleanup() to pthread_*_cleanup(). + + * pthread.def: Ditto. + + * pthread.h: Ditto. + + * pthread.def (pthread_cleanup_push): Remove from export list; + the function is defined as a macro under all compilers. + (pthread_cleanup_pop): Ditto. + + * pthread.h: Remove #if defined(). + +Wed Feb 3 10:13:48 1999 Ross Johnson + + * sync.c (pthread_join): Check for NULL value_ptr arg; + check for detached threads. + +Tue Feb 2 18:07:43 1999 Ross Johnson + + * implement.h: Add #include . + Change sem_t to ptw32_sem_t. + +Tue Feb 2 18:07:43 1999 Kevin Ruland + + * signal.c (pthread_sigmask): Add and modify casts. + Reverse LHS/RHS bitwise assignments. + + * pthread.h: Remove #include . + (PTW32_ATTR_VALID): Add cast. + (struct pthread_t_): Add sigmask element. + + * dll.c: Add "extern C" for DLLMain. + (DllMain): Add cast. + + * create.c (pthread_create): Set sigmask in thread. + + * condvar.c: Remove #include. Change sem_* to ptw32_sem_*. + + * attr.c: Changed #include. + + * Makefile.in: Additional targets and changes to build the library + as a DLL. + +Fri Jan 29 11:56:28 1999 Ross Johnson + + * Makefile.in (OBJS): Add semaphore.o to list. + + * semaphore.c (ptw32_sem_timedwait): Move from private.c. + Rename sem_* to ptw32_sem_*. + + * pthread.h (pthread_cond_t): Change type of sem_t. + _POSIX_SEMAPHORES no longer defined. + + * semaphore.h: Contents moved to implement.h. + Removed from source tree. + + * implement.h: Add semaphore function prototypes and rename all + functions to prepend 'ptw32_'. They are + now private to the pthreads-win32 implementation. + + * private.c: Change #warning. + Move ptw32_sem_timedwait() to semaphore.c. + + * cleanup.c: Change #warning. + + * misc.c: Remove #include + + * pthread.def: Cleanup CVS merge conflicts. + + * global.c: Ditto. + + * ChangeLog: Ditto. + + * cleanup.c: Ditto. + +Sun Jan 24 01:34:52 1999 Ross Johnson + + * semaphore.c (sem_wait): Remove second arg to + pthreadCancelableWait() call. + +Sat Jan 23 17:36:40 1999 Ross Johnson + + * pthread.def: Add new functions to export list. + + * pthread.h (PTHREAD_MUTEX_AUTO_CS_NP): New. + (PTHREAD_MUTEX_FORCE_CS_NP): New. + + * README: Updated. + +Fri Jan 22 14:31:59 1999 Ross Johnson + + * Makefile.in (CFLAGS): Remove -fhandle-exceptions. Not needed + with egcs. Add -g for debugging. + + * create.c (pthread_create): Replace __stdcall with PT_STDCALL + macro. This is a hack and must be fixed. + + * misc.c (CancelableWait): Remove redundant statement. + + * mutex.c (pthread_mutexattr_init): Cast calloc return value. + + * misc.c (CancelableWait): Add cast. + (pthread_self): Add cast. + + * exit.c (pthread_exit): Add cast. + + * condvar.c (pthread_condattr_init): Cast calloc return value. + + * cleanup.c: Reorganise conditional compilation. + + * attr.c (pthread_attr_init): Remove unused 'result'. + Cast malloc return value. + + * private.c (ptw32_callUserDestroyRoutines): Redo conditional + compilation. + + * misc.c (CancelableWait): C++ version uses 'throw'. + + * cancel.c (pthread_testcancel): Ditto. + + * implement.h (class ptw32_exception): Define for C++. + + * pthread.h: Fix C, C++, and Win32 SEH condition compilation + mayhem around pthread_cleanup_* defines. C++ version now uses John + Bossom's cleanup handlers. + (pthread_attr_t): Make 'valid' unsigned. + Define '_timeb' as 'timeb' for Ming32. + Define PT_STDCALL as nothing for Mingw32. May be temporary. + + * cancel.c (pthread_testcancel): Cast return value. + +Wed Jan 20 09:31:28 1999 Ross Johnson + + * pthread.h (pthread_mutexattr_t): Changed to a pointer. + + * mutex.c (pthread_mutex_init): Conditionally create Win32 mutex + - from John Bossom's implementation. + (pthread_mutex_destroy): Conditionally close Win32 mutex + - from John Bossom's implementation. + (pthread_mutexattr_init): Replaced by John Bossom's version. + (pthread_mutexattr_destroy): Ditto. + (pthread_mutexattr_getpshared): New function from John Bossom's + implementation. + (pthread_mutexattr_setpshared): New function from John Bossom's + implementation. + +Tue Jan 19 18:27:42 1999 Ross Johnson + + * pthread.h (pthreadCancelableTimedWait): New prototype. + (pthreadCancelableWait): Remove second argument. + + * misc.c (CancelableWait): New static function is + pthreadCancelableWait() renamed. + (pthreadCancelableWait): Now just calls CancelableWait() with + INFINITE timeout. + (pthreadCancelableTimedWait): Just calls CancelableWait() + with passed in timeout. + +Tue Jan 19 18:27:42 1999 Scott Lightner + + * private.c (ptw32_sem_timedwait): 'abstime' arg really is + absolute time. Calculate relative time to wait from current + time before passing timeout to new routine + pthreadCancelableTimedWait(). + +Tue Jan 19 10:27:39 1999 Ross Johnson + + * pthread.h (pthread_mutexattr_setforcecs_np): New prototype. + + * mutex.c (pthread_mutexattr_init): Init 'pshared' and 'forcecs' + attributes to 0. + (pthread_mutexattr_setforcecs_np): New function (not portable). + + * pthread.h (pthread_mutex_t): + Add 'mutex' element. Set to NULL in PTHREAD_MUTEX_INITIALIZER. + The pthread_mutex_*() routines will try to optimise performance + by choosing either mutexes or critical sections as the basis + for pthread mutexes for each indevidual mutex. + (pthread_mutexattr_t_): Add 'forcecs' element. + Some applications may choose to force use of critical sections + if they know that:- + the mutex is PROCESS_PRIVATE and, + either the OS supports TryEnterCriticalSection() or + pthread_mutex_trylock() will never be called on the mutex. + This attribute will be setable via a non-portable routine. + + Note: We don't yet support PROCESS_SHARED mutexes, so the + implementation as it stands will default to Win32 mutexes only if + the OS doesn't support TryEnterCriticalSection. On Win9x, and early + versions of NT 'forcecs' will need to be set in order to get + critical section based mutexes. + +Sun Jan 17 12:01:26 1999 Ross Johnson + + * pthread.h (PTHREAD_MUTEX_INITIALIZER): Init new 'staticinit' + value to '1' and existing 'valid' value to '1'. + + * global.c (ptw32_mutex_test_init_lock): Add. + + * implement.h (ptw32_mutex_test_init_lock.): Add extern. + + * private.c (ptw32_processInitialize): Init critical section for + global lock used by _mutex_check_need_init(). + (ptw32_processTerminate): Ditto (:s/Init/Destroy/). + + * dll.c (dllMain): Move call to FreeLibrary() so that it is only + called once when the process detaches. + + * mutex.c (_mutex_check_need_init): New static function to test + and init PTHREAD_MUTEX_INITIALIZER mutexes. Provides serialised + access to the internal state of the uninitialised static mutex. + Called from pthread_mutex_trylock() and pthread_mutex_lock() which + do a quick unguarded test to check if _mutex_check_need_init() + needs to be called. This is safe as the test is conservative + and is repeated inside the guarded section of + _mutex_check_need_init(). Thus in all calls except the first + calls to lock static mutexes, the additional overhead to lock any + mutex is a single memory fetch and test for zero. + + * pthread.h (pthread_mutex_t_): Add 'staticinit' member. Mutexes + initialised by PTHREAD_MUTEX_INITIALIZER aren't really initialised + until the first attempt to lock it. Using the 'valid' + flag (which flags the mutex as destroyed or not) to record this + information would be messy. It is possible for a statically + initialised mutex such as this to be destroyed before ever being + used. + + * mutex.c (pthread_mutex_trylock): Call _mutex_check_need_init() + to test/init PTHREAD_MUTEX_INITIALIZER mutexes. + (pthread_mutex_lock): Ditto. + (pthread_mutex_unlock): Add check to ensure we don't try to unlock + an unitialised static mutex. + (pthread_mutex_destroy): Add check to ensure we don't try to delete + a critical section that we never created. Allows us to destroy + a static mutex that has never been locked (and hence initialised). + (pthread_mutex_init): Set 'staticinit' flag to 0 for the new mutex. + +Sun Jan 17 12:01:26 1999 Ross Johnson + + * private.c (ptw32_sem_timedwait): Move from semaphore.c. + + * semaphore.c : Remove redundant #includes. + (ptw32_sem_timedwait): Move to private.c. + (sem_wait): Add missing abstime arg to pthreadCancelableWait() call. + +Fri Jan 15 23:38:05 1999 Ross Johnson + + * condvar.c (cond_timedwait): Remove comment. + +Fri Jan 15 15:41:28 1999 Ross Johnson + + * pthread.h: Add new 'abstime' arg to pthreadCancelableWait() + prototype. + + * condvar.c (cond_timedwait): New generalised function called by + both pthread_cond_wait() and pthread_cond_timedwait(). This is + essentially pthread_cond_wait() renamed and modified to add the + 'abstime' arg and call the new ptw32_sem_timedwait() instead of + sem_wait(). + (pthread_cond_wait): Now just calls the internal static + function cond_timedwait() with an INFINITE wait. + (pthread_cond_timedwait): Now implemented. Calls the internal + static function cond_timedwait(). + + * implement.h (ptw32_sem_timedwait): New internal function + prototype. + + * misc.c (pthreadCancelableWait): Added new 'abstime' argument + to allow shorter than INFINITE wait. + + * semaphore.c (ptw32_sem_timedwait): New function for internal + use. This is essentially sem_wait() modified to add the + 'abstime' arg and call the modified (see above) + pthreadCancelableWait(). + +Thu Jan 14 14:27:13 1999 Ross Johnson + + * cleanup.c: Correct _cplusplus to __cplusplus wherever used. + + * Makefile.in: Add CC=g++ and add -fhandle-exceptions to CFLAGS. + The derived Makefile will compile all units of the package as C++ + so that those which include try/catch exception handling should work + properly. The package should compile ok if CC=gcc, however, exception + handling will not be included and thus thread cancellation, for + example, will not work. + + * cleanup.c (ptw32_pop_cleanup): Add #warning to compile this + file as C++ if using a cygwin32 environment. Perhaps the whole package + should be compiled using g++ under cygwin. + + * private.c (ptw32_threadStart): Change #error directive + into #warning and bracket for __CYGWIN__ and derivative compilers. + +Wed Jan 13 09:34:52 1999 Ross Johnson + + * build.bat: Delete old binaries before compiling/linking. + +Tue Jan 12 09:58:38 1999 Tor Lillqvist + + * dll.c: The Microsoft compiler pragmas probably are more + appropriately protected by _MSC_VER than by _WIN32. + + * pthread.h: Define ETIMEDOUT. This should be returned by + pthread_cond_timedwait which is not implemented yet as of + snapshot-1999-01-04-1305. It was implemented in the older version. + The Microsoft compiler pragmas probably are more appropriately + protected by _MSC_VER than by _WIN32. + + * pthread.def: pthread_mutex_destroy was missing from the def file + + * condvar.c (pthread_cond_broadcast): Ensure we only wait on threads + if there were any waiting on the condition. + I think pthread_cond_broadcast should do the WaitForSingleObject + only if cv->waiters > 0? Otherwise it seems to hang, at least in the + testg thread program from glib. + +Tue Jan 12 09:58:38 1999 Ross Johnson + + * condvar.c (pthread_cond_timedwait): Fix function description + comments. + + * semaphore.c (sem_post): Correct typo in comment. + +Mon Jan 11 20:33:19 1999 Ross Johnson + + * pthread.h: Re-arrange conditional compile of pthread_cleanup-* + macros. + + * cleanup.c (ptw32_push_cleanup): Provide conditional + compile of cleanup->prev. + +1999-01-11 Tor Lillqvist + + * condvar.c (pthread_cond_init): Invert logic when testing the + return value from calloc(). + +Sat Jan 9 14:32:08 1999 Ross Johnson + + * implement.h: Compile-time switch for CYGWIN derived environments + to use CreateThread instead of _beginthreadex. Ditto for ExitThread. + Patch provided by Anders Norlander . + +Tue Jan 5 16:33:04 1999 Ross Johnson + + * cleanup.c (ptw32_pop_cleanup): Add C++ version of __try/__except + block. Move trailing "}" out of #ifdef _WIN32 block left there by + (rpj's) mistake. + + * private.c: Remove #include which is included by pthread.h. + +1998-12-11 Ben Elliston + + * README: Update info about subscribing to the mailing list. + +Mon Jan 4 11:23:40 1999 Ross Johnson + + * all: No code changes, just cleanup. + - remove #if 0 /* Pre Bossom */ enclosed code. + - Remove some redundant #includes. + * pthread.h: Update implemented/unimplemented routines list. + * Tag the bossom merge branch getting ready to merge back to main + trunk. + +Tue Dec 29 13:11:16 1998 Ross Johnson + + * implement.h: Move the following struct definitions to pthread.h: + pthread_t_, pthread_attr_t_, pthread_mutex_t_, pthread_mutex_t_, + pthread_mutexattr_t_, pthread_key_t_, pthread_cond_t_, + pthread_condattr_t_, pthread_once_t_. + + * pthread.h: Add "_" prefix to pthread_push_cleanup and + pthread_pop_cleanup internal routines, and associated struct and + typedefs. + + * buildlib.bat: Add compile command for semaphore.c + + * pthread.def: Comment out pthread_atfork routine name. + Now unimplemented. + + * tsd.c (pthread_setspecific): Rename tkAssocCreate to + ptw32_tkAssocCreate. + (pthread_key_delete): Rename tkAssocDestroy to + ptw32_tkAssocDestroy. + + * sync.c (pthread_join): Rename threadDestroy to ptw32_threadDestroy + + * sched.c (is_attr): attr is now **attr (was *attr), so add extra + NULL pointer test. + (pthread_attr_setschedparam): Increase redirection for attr which is + now a **. + (pthread_attr_getschedparam): Ditto. + (pthread_setschedparam): Change thread validation and rename "thread" + Win32 thread Handle element name to match John Bossom's version. + (pthread_getschedparam): Ditto. + + * private.c (ptw32_threadDestroy): Rename call to + callUserDestroyRoutines() as ptw32_callUserDestroyRoutines() + + * misc.c: Add #include "implement.h". + + * dll.c: Remove defined(KLUDGE) wrapped code. + + * fork.c: Remove redefinition of ENOMEM. + Remove pthread_atfork() and fork() with #if 0/#endif. + + * create.c (pthread_create): Rename threadStart and threadDestroy calls + to ptw32_threadStart and ptw32_threadDestroy. + + * implement.h: Rename "detachedstate" to "detachstate". + + * attr.c: Rename "detachedstate" to "detachstate". + +Mon Dec 28 09:54:39 1998 John Bossom + + * semaphore.c: Initial version. + * semaphore.h: Initial version. + +Mon Dec 28 09:54:39 1998 Ross Johnson + + * pthread.h (pthread_attr_t_): Change to *pthread_attr_t. + +Mon Dec 28 09:54:39 1998 John Bossom, Ben Elliston + + * attr.c (pthread_attr_setstacksize): Merge with John's version. + (pthread_attr_getstacksize): Merge with John's version. + (pthread_attr_setstackaddr): Merge with John's version. + (pthread_attr_getstackaddr): Merge with John's version. + (pthread_attr_init): Merge with John's version. + (pthread_attr_destroy): Merge with John's version. + (pthread_attr_getdetachstate): Merge with John's version. + (pthread_attr_setdetachstate): Merge with John's version. + (is_attr): attr is now **attr (was *attr), so add extra NULL pointer + test. + +Mon Dec 28 09:54:39 1998 Ross Johnson + + * implement.h (pthread_attr_t_): Add and rename elements in JEB's + version to correspond to original, so that it can be used with + original attr routines. + + * pthread.h: Add #endif at end which was truncated in merging. + +Sun Dec 20 14:51:58 1998 Ross Johnson + + * misc.c (pthreadCancelableWait): New function by John Bossom. Non-standard + but provides a hook that can be used to implement cancellation points in + applications that use this library. + + * pthread.h (pthread_cleanup_pop): C++ (non-WIN32) version uses + try/catch to emulate John Bossom's WIN32 __try/__finally behaviour. + In the WIN32 version __finally block, add a test for AbnormalTermination otherwise + cleanup is only run if the cleanup_pop execute arg is non-zero. Cancellation + should cause the cleanup to run irrespective of the execute arg. + + * condvar.c (pthread_condattr_init): Replaced by John Bossom's version. + (pthread_condattr_destroy): Replaced by John Bossom's version. + (pthread_condattr_getpshared): Replaced by John Bossom's version. + (pthread_condattr_setpshared): Replaced by John Bossom's version. + (pthread_cond_init): Replaced by John Bossom's version. + Fix comment (refered to mutex rather than condition variable). + (pthread_cond_destroy): Replaced by John Bossom's version. + (pthread_cond_wait): Replaced by John Bossom's version. + (pthread_cond_timedwait): Replaced by John Bossom's version. + (pthread_cond_signal): Replaced by John Bossom's version. + (pthread_cond_broadcast): Replaced by John Bossom's version. + +Thu Dec 17 19:10:46 1998 Ross Johnson + + * tsd.c (pthread_key_create): Replaced by John Bossom's version. + (pthread_key_delete): Replaced by John Bossom's version. + (pthread_setspecific): Replaced by John Bossom's version. + (pthread_getspecific): Replaced by John Bossom's version. + +Mon Dec 7 09:44:40 1998 John Bossom + + * cancel.c (pthread_setcancelstate): Replaced. + (pthread_setcanceltype): Replaced. + (pthread_testcancel): Replaced. + (pthread_cancel): Replaced. + + * exit.c (pthread_exit): Replaced. + + * misc.c (pthread_self): Replaced. + (pthread_equal): Replaced. + + * sync.c (pthread_detach): Replaced. + (pthread_join): Replaced. + + * create.c (pthread_create): Replaced. + + * private.c (ptw32_processInitialize): New. + (ptw32_processTerminate): New. + (ptw32_threadStart): New. + (ptw32_threadDestroy): New. + (ptw32_cleanupStack): New. + (ptw32_tkAssocCreate): New. + (ptw32_tkAssocDestroy): New. + (ptw32_callUserDestroyRoutines): New. + + * implement.h: Added non-API structures and declarations. + + * dll.c (PthreadsEntryPoint): Cast return value of GetProcAddress + to resolve compile warning from MSVC. + + * dll.c (DLLmain): Replaced. + * dll.c (PthreadsEntryPoint): + Re-applied Anders Norlander's patch:- + Initialize ptw32_try_enter_critical_section at startup + and release kernel32 handle when DLL is being unloaded. + +Sun Dec 6 21:54:35 1998 Ross Johnson + + * buildlib.bat: Fix args to CL when building the .DLL + + * cleanup.c (ptw32_destructor_run_all): Fix TSD key management. + This is a tidy-up before TSD and Thread management is completely + replaced by John Bossom's code. + + * tsd.c (pthread_key_create): Fix TSD key management. + + * global.c (ptw32_key_virgin_next): Initialise. + + * build.bat: New DOS script to compile and link a pthreads app + using Microsoft's CL compiler linker. + * buildlib.bat: New DOS script to compile all the object files + and create pthread.lib and pthread.dll using Microsoft's CL + compiler linker. + +1998-12-05 Anders Norlander + + * implement.h (ptw32_try_enter_critical_section): New extern + * dll.c (ptw32_try_enter_critical_section): New pointer to + TryEnterCriticalSection if it exists; otherwise NULL. + * dll.c (PthreadsEntryPoint): + Initialize ptw32_try_enter_critical_section at startup + and release kernel32 handle when DLL is being unloaded. + * mutex.c (pthread_mutex_trylock): Replaced check for NT with + a check if ptw32_try_enter_critical_section is valid + pointer to a function. Call ptw32_try_enter_critical_section + instead of TryEnterCriticalSection to avoid errors on Win95. + +Thu Dec 3 13:32:00 1998 Ross Johnson + + * README: Correct cygwin32 compatibility statement. + +Sun Nov 15 21:24:06 1998 Ross Johnson + + * cleanup.c (ptw32_destructor_run_all): Declare missing void * arg. + Fixup CVS merge conflicts. + +1998-10-30 Ben Elliston + + * condvar.c (cond_wait): Fix semantic error. Test for equality + instead of making an assignment. + +Fri Oct 30 15:15:50 1998 Ross Johnson + + * cleanup.c (ptw32_handler_push): Fixed bug appending new + handler to list reported by Peter Slacik + . + (new_thread): Rename poorly named local variable to + "new_handler". + +Sat Oct 24 18:34:59 1998 Ross Johnson + + * global.c: Add TSD key management array and index declarations. + + * implement.h: Ditto for externs. + +Fri Oct 23 00:08:09 1998 Ross Johnson + + * implement.h (PTW32_TSD_KEY_REUSE): Add enum. + + * private.c (ptw32_delete_thread): Add call to + ptw32_destructor_run_all() to clean up the threads keys. + + * cleanup.c (ptw32_destructor_run_all): Check for no more dirty + keys to run destructors on. Assume that the destructor call always + succeeds and set the key value to NULL. + +Thu Oct 22 21:44:44 1998 Ross Johnson + + * tsd.c (pthread_setspecific): Add key management code. + (pthread_key_create): Ditto. + (pthread_key_delete): Ditto. + + * implement.h (struct ptw32_tsd_key): Add status member. + + * tsd.c: Add description of pthread_key_delete() from the + standard as a comment. + +Fri Oct 16 17:38:47 1998 Ross Johnson + + * cleanup.c (ptw32_destructor_run_all): Fix and improve + stepping through the key table. + +Thu Oct 15 14:05:01 1998 Ross Johnson + + * private.c (ptw32_new_thread): Remove init of destructorstack. + No longer an element of pthread_t. + + * tsd.c (pthread_setspecific): Fix type declaration and cast. + (pthread_getspecific): Ditto. + (pthread_getspecific): Change error return value to NULL if key + is not in use. + +Thu Oct 15 11:53:21 1998 Ross Johnson + + * global.c (ptw32_tsd_key_table): Fix declaration. + + * implement.h(ptw32_TSD_keys_TlsIndex): Add missing extern. + (ptw32_tsd_mutex): Ditto. + + * create.c (ptw32_start_call): Fix "keys" array declaration. + Add comment. + + * tsd.c (pthread_setspecific): Fix type declaration and cast. + (pthread_getspecific): Ditto. + + * cleanup.c (ptw32_destructor_run_all): Declare missing loop + counter. + +Wed Oct 14 21:09:24 1998 Ross Johnson + + * private.c (ptw32_new_thread): Increment ptw32_threads_count. + (ptw32_delete_thread): Decrement ptw32_threads_count. + Remove some comments. + + * exit.c (ptw32_exit): : Fix two pthread_mutex_lock() calls that + should have been pthread_mutex_unlock() calls. + (ptw32_vacuum): Remove call to ptw32_destructor_pop_all(). + + * create.c (pthread_create): Fix two pthread_mutex_lock() calls that + should have been pthread_mutex_unlock() calls. + + * global.c (ptw32_tsd_mutex): Add mutex for TSD operations. + + * tsd.c (pthread_key_create): Add critical section. + (pthread_setspecific): Ditto. + (pthread_getspecific): Ditto. + (pthread_key_delete): Ditto. + + * sync.c (pthread_join): Fix two pthread_mutex_lock() calls that + should have been pthread_mutex_unlock() calls. + +Mon Oct 12 00:00:44 1998 Ross Johnson + + * implement.h (ptw32_tsd_key_table): New. + + * create.c (ptw32_start_call): Initialise per-thread TSD keys + to NULL. + + * misc.c (pthread_once): Correct typo in comment. + + * implement.h (ptw32_destructor_push): Remove. + (ptw32_destructor_pop): Remove. + (ptw32_destructor_run_all): Rename from ptw32_destructor_pop_all. + (PTW32_TSD_KEY_DELETED): Add enum. + (PTW32_TSD_KEY_INUSE): Add enum. + + * cleanup.c (ptw32_destructor_push): Remove. + (ptw32_destructor_pop): Remove. + (ptw32_destructor_run_all): Totally revamped TSD. + + * dll.c (ptw32_TSD_keys_TlsIndex): Initialise. + + * tsd.c (pthread_setspecific): Totally revamped TSD. + (pthread_getspecific): Ditto. + (pthread_create): Ditto. + (pthread_delete): Ditto. + +Sun Oct 11 22:44:55 1998 Ross Johnson + + * global.c (ptw32_tsd_key_table): Add new global. + + * implement.h (ptw32_tsd_key_t and struct ptw32_tsd_key): + Add. + (struct _pthread): Remove destructorstack. + + * cleanup.c (ptw32_destructor_run_all): Rename from + ptw32_destructor_pop_all. The key destructor stack was made + global rather than per-thread. No longer removes destructor nodes + from the stack. Comments updated. + +1998-10-06 Ben Elliston + + * condvar.c (cond_wait): Use POSIX, not Win32 mutex calls. + (pthread_cond_broadcast): Likewise. + (pthread_cond_signal): Likewise. + +1998-10-05 Ben Elliston + + * pthread.def: Update. Some functions aren't available yet, others + are macros in . + + * tests/join.c: Remove; useless. + +Mon Oct 5 14:25:08 1998 Ross Johnson + + * pthread.def: New file for building the DLL. + +1998-10-05 Ben Elliston + + * misc.c (pthread_equal): Correct inverted logic bug. + (pthread_once): Use the POSIX mutex primitives, not Win32. Remove + irrelevant FIXME comment. + + * global.c (PTHREAD_MUTEX_INITIALIZER): Move to pthread.h. + + * pthread.h (PTHREAD_MUTEX_INITIALIZER): Define. + (pthread_mutex_t): Reimplement as a struct containing a valid + flag. If the flag is ever down upon entry to a mutex operation, + we call pthread_mutex_create() to initialise the object. This + fixes the problem of how to handle statically initialised objects + that can't call InitializeCriticalSection() due to their context. + (PTHREAD_ONCE_INIT): Define. + + * mutex.c (pthread_mutex_init): Set valid flag. + (pthread_mutex_destroy): Clear valid flag. + (pthread_mutex_lock): Check and handle the valid flag. + (pthread_mutex_unlock): Likewise. + (pthread_mutex_trylock): Likewise. + + * tests/mutex3.c: New file; test for the static initialisation + macro. Passes. + + * tests/create1.c: New file; test pthread_create(). Passes. + + * tests/equal.c: Poor test; remove. + + * tests/equal1.c New file; test pthread_equal(). Passes. + + * tests/once1.c: New file; test for pthread_once(). Passes. + + * tests/self.c: Remove; rename to self1.c. + + * tests/self1.c: This is the old self.c. + + * tests/self2.c: New file. Test pthread_self() with a single + thread. Passes. + + * tests/self3.c: New file. Test pthread_self() with a couple of + threads to ensure their thread IDs differ. Passes. + +1998-10-04 Ben Elliston + + * tests/mutex2.c: Test pthread_mutex_trylock(). Passes. + + * tests/mutex1.c: New basic test for mutex functions (it passes). + (main): Eliminate warning. + + * configure.in: Test for __stdcall, not _stdcall. Typo. + + * configure: Regenerate. + + * attr.c (pthread_attr_setstackaddr): Remove FIXME comment. Win32 + does know about ENOSYS after all. + (pthread_attr_setstackaddr): Likewise. + +1998-10-03 Ben Elliston + + * configure.in: Test for the `_stdcall' keyword. Define `STDCALL' + to `_stdcall' if we have it, null otherwise. + + * configure: Regenerate. + + * acconfig.h (STDCALL): New define. + + * config.h.in: Regenerate. + + * create.c (ptw32_start_call): Add STDCALL prefix. + + * mutex.c (pthread_mutex_init): Correct function signature. + + * attr.c (pthread_attr_init): Only zero out the `sigmask' member + if we have the sigset_t type. + + * pthread.h: No need to include . It doesn't even exist + on Win32! Again, an artifact of cross-compilation. + (pthread_sigmask): Only provide if we have the sigset_t type. + + * process.h: Remove. This was a stand-in before we started doing + native compilation under Win32. + + * pthread.h (pthread_mutex_init): Make `attr' argument const. + +1998-10-02 Ben Elliston + + * COPYING: Remove. + + * COPYING.LIB: Add. This library is under the LGPL. + +1998-09-13 Ben Elliston + + * configure.in: Test for required system features. + + * configure: Generate. + + * acconfig.h: New file. + + * config.h.in: Generate. + + * Makefile.in: Renamed from Makefile. + + * COPYING: Import from a recent GNU package. + + * config.guess: Likewise. + + * config.sub: Likewise. + + * install-sh: Likewise. + + * config.h: Remove. + + * Makefile: Likewise. + +1998-09-12 Ben Elliston + + * windows.h: No longer needed; remove. + + * windows.c: Likewise. + +Sat Sep 12 20:09:24 1998 Ross Johnson + + * windows.h: Remove error number definitions. These are in + + * tsd.c: Add comment explaining rationale for not building + POSIX TSD on top of Win32 TLS. + +1998-09-12 Ben Elliston + + * {most}.c: Include to get POSIX error values. + + * signal.c (pthread_sigmask): Only provide if HAVE_SIGSET_T is + defined. + + * config.h: #undef features, don't #define them. This will be + generated by autoconf very soon. + +1998-08-11 Ben Elliston + + * Makefile (LIB): Define. + (clean): Define target. + (all): Build a library not just the object files. + + * pthread.h: Provide a definition for struct timespec if we don't + already have one. + + * windows.c (TlsGetValue): Bug fix. + +Thu Aug 6 15:19:22 1998 Ross Johnson + + * misc.c (pthread_once): Fix arg 1 of EnterCriticalSection() + and LeaveCriticalSection() calls to pass address-of lock. + + * fork.c (pthread_atfork): Typecast (void (*)(void *)) funcptr + in each ptw32_handler_push() call. + + * exit.c (ptw32_exit): Fix attr arg in + pthread_attr_getdetachstate() call. + + * private.c (ptw32_new_thread): Typecast (HANDLE) NULL. + (ptw32_delete_thread): Ditto. + + * implement.h: (PTW32_MAX_THREADS): Add define. This keeps + changing in an attempt to make thread administration data types + opaque and cleanup DLL startup. + + * dll.c (PthreadsEntryPoint): + (ptw32_virgins): Remove malloc() and free() calls. + (ptw32_reuse): Ditto. + (ptw32_win32handle_map): Ditto. + (ptw32_threads_mutex_table): Ditto. + + * global.c (_POSIX_THREAD_THREADS_MAX): Initialise with + PTW32_MAX_THREADS. + (ptw32_virgins): Ditto. + (ptw32_reuse): Ditto. + (ptw32_win32handle_map): Ditto. + (ptw32_threads_mutex_table): Ditto. + + * create.c (pthread_create): Typecast (HANDLE) NULL. + Typecast (unsigned (*)(void *)) start_routine. + + * condvar.c (pthread_cond_init): Add address-of operator & to + arg 1 of pthread_mutex_init() call. + (pthread_cond_destroy): Add address-of operator & to + arg 1 of pthread_mutex_destroy() call. + + * cleanup.c (ptw32_destructor_pop_all): Add (int) cast to + pthread_getspecific() arg. + (ptw32_destructor_pop): Add (void *) cast to "if" conditional. + (ptw32_destructor_push): Add (void *) cast to + ptw32_handler_push() "key" arg. + (malloc.h): Add include. + + * implement.h (ptw32_destructor_pop): Add prototype. + + * tsd.c (implement.h): Add include. + + * sync.c (pthread_join): Remove target_thread_mutex and it's + initialisation. Rename getdetachedstate to getdetachstate. + Remove unused variable "exitcode". + (pthread_detach): Remove target_thread_mutex and it's + initialisation. Rename getdetachedstate to getdetachstate. + Rename setdetachedstate to setdetachstate. + + * signal.c (pthread_sigmask): Rename SIG_SET to SIG_SETMASK. + Cast "set" to (long *) in assignment to passify compiler warning. + Add address-of operator & to thread->attr.sigmask in memcpy() call + and assignment. + (pthread_sigmask): Add address-of operator & to thread->attr.sigmask + in memcpy() call and assignment. + + * windows.h (THREAD_PRIORITY_ERROR_RETURN): Add. + (THREAD_PRIORITY_LOWEST): Add. + (THREAD_PRIORITY_HIGHEST): Add. + + * sched.c (is_attr): Add function. + (implement.h): Add include. + (pthread_setschedparam): Rename all instances of "sched_policy" + to "sched_priority". + (pthread_getschedparam): Ditto. + +Tue Aug 4 16:57:58 1998 Ross Johnson + + * private.c (ptw32_delete_thread): Fix typo. Add missing ';'. + + * global.c (ptw32_virgins): Change types from pointer to + array pointer. + (ptw32_reuse): Ditto. + (ptw32_win32handle_map): Ditto. + (ptw32_threads_mutex_table): Ditto. + + * implement.h(ptw32_virgins): Change types from pointer to + array pointer. + (ptw32_reuse): Ditto. + (ptw32_win32handle_map): Ditto. + (ptw32_threads_mutex_table): Ditto. + + * private.c (ptw32_delete_thread): Fix "entry" should be "thread". + + * misc.c (pthread_self): Add extern for ptw32_threadID_TlsIndex. + + * global.c: Add comment. + + * misc.c (pthread_once): Fix member -> dereferences. + Change ptw32_once_flag to once_control->flag in "if" test. + +Tue Aug 4 00:09:30 1998 Ross Johnson + + * implement.h(ptw32_virgins): Add extern. + (ptw32_virgin_next): Ditto. + (ptw32_reuse): Ditto. + (ptw32_reuse_top): Ditto. + (ptw32_win32handle_map): Ditto. + (ptw32_threads_mutex_table): Ditto. + + * global.c (ptw32_virgins): Changed from array to pointer. + Storage allocation for the array moved into dll.c. + (ptw32_reuse): Ditto. + (ptw32_win32handle_map): Ditto. + (ptw32_threads_mutex_table): Ditto. + + * dll.c (PthreadsEntryPoint): Set up thread admin storage when + DLL is loaded. + + * fork.c (pthread_atfork): Fix function pointer arg to all + ptw32_handler_push() calls. Change "arg" arg to NULL in child push. + + * exit.c: Add windows.h and process.h includes. + (ptw32_exit): Add local detachstate declaration. + (ptw32_exit): Fix incorrect name for pthread_attr_getdetachstate(). + + * pthread.h (_POSIX_THREAD_ATTR_STACKSIZE): Move from global.c + (_POSIX_THREAD_ATTR_STACKADDR): Ditto. + + * create.c (pthread_create): Fix #if should be #ifdef. + (ptw32_start_call): Remove usused variables. + + * process.h: Create. + + * windows.h: Move _beginthreadex and _endthreadex into + process.h + +Mon Aug 3 21:19:57 1998 Ross Johnson + + * condvar.c (pthread_cond_init): Add NULL attr to + pthread_mutex_init() call - default attributes will be used. + (cond_wait): Fix typo. + (cond_wait): Fix typo - cv was ev. + (pthread_cond_broadcast): Fix two identical typos. + + * cleanup.c (ptw32_destructor_pop_all): Remove _ prefix from + PTHREAD_DESTRUCTOR_ITERATIONS. + + * pthread.h: Move _POSIX_* values into posix.h + + * pthread.h: Fix typo in pthread_mutex_init() prototype. + + * attr.c (pthread_attr_init): Fix error in priority member init. + + * windows.h (THREAD_PRIORITY_NORMAL): Add. + + * pthread.h (sched_param): Add missing ';' to struct definition. + + * attr.c (pthread_attr_init): Remove obsolete pthread_attr_t + member initialisation - cancelstate, canceltype, cancel_pending. + (is_attr): Make arg "attr" a const. + + * implement.h (PTW32_HANDLER_POP_LIFO): Remove definition. + (PTW32_HANDLER_POP_FIFO): Ditto. + (PTW32_VALID): Add missing newline escape (\). + (ptw32_handler_node): Make element "next" a pointer. + +1998-08-02 Ben Elliston + + * windows.h: Remove duplicate TlsSetValue() prototype. Add + TlsGetValue() prototype. + (FALSE): Define. + (TRUE): Likewise. + Add forgotten errno values. Guard against multiple #includes. + + * windows.c: New file. Implement stubs for Win32 functions. + + * Makefile (SRCS): Remove. Not explicitly needed. + (CFLAGS): Add -Wall for all warnings with GCC. + +Sun Aug 2 19:03:42 1998 Ross Johnson + + * config.h: Create. This is a temporary stand-in for autoconf yet + to be done. + (HAVE_SIGNAL_H): Add. + + * pthread.h: Minor rearrangement for temporary config.h. + +Fri Jul 31 14:00:29 1998 Ross Johnson + + * cleanup.c (ptw32_destructor_pop): Implement. Removes + destructors associated with a key without executing them. + (ptw32_destructor_pop_all): Add FIXME comment. + + * tsd.c (pthread_key_delete): Add call to ptw32_destructor_pop(). + +Fri Jul 31 00:05:45 1998 Ross Johnson + + * tsd.c (pthread_key_create): Update to properly associate + the destructor routine with the key. + (pthread_key_delete): Add FIXME comment. + + * exit.c (ptw32_vacuum): Add call to + ptw32_destructor_pop_all(). + + * implement.h (ptw32_handler_pop_all): Add prototype. + (ptw32_destructor_pop_all): Ditto. + + * cleanup.c (ptw32_destructor_push): Implement. This is just a + call to ptw32_handler_push(). + (ptw32_destructor_pop_all): Implement. This is significantly + different to ptw32_handler_pop_all(). + + * Makefile (SRCS): Create. Preliminary. + + * windows.h: Create. Contains Win32 definitions for compile + testing. This is just a standin for the real one. + + * pthread.h (SIG_UNBLOCK): Fix typo. Was SIG_BLOCK. + (windows.h): Add include. Required for CRITICAL_SECTION. + (pthread_cond_t): Move enum declaration outside of struct + definition. + (unistd.h): Add include - may be temporary. + + * condvar.c (windows.h): Add include. + + * implement.h (PTW32_THIS): Remove - no longer required. + (PTW32_STACK): Use pthread_self() instead of PTW32_THIS. + +Thu Jul 30 23:12:45 1998 Ross Johnson + + * implement.h: Remove ptw32_find_entry() prototype. + + * private.c: Extend comments. + Remove ptw32_find_entry() - no longer needed. + + * create.c (ptw32_start_call): Add call to TlsSetValue() to + store the thread ID. + + * dll.c (PthreadsEntryPoint): Implement. This is called + whenever a process loads the DLL. Used to initialise thread + local storage. + + * implement.h: Add ptw32_threadID_TlsIndex. + Add ()s around PTW32_VALID expression. + + * misc.c (pthread_self): Re-implement using Win32 TLS to store + the threads own ID. + +Wed Jul 29 11:39:03 1998 Ross Johnson + + * private.c: Corrections in comments. + (ptw32_new_thread): Alter "if" flow to be more natural. + + * cleanup.c (ptw32_handler_push): Same as below. + + * create.c (pthread_create): Same as below. + + * private.c (ptw32_new_thread): Rename "new" to "new_thread". + Since when has a C programmer been required to know C++? + +Tue Jul 28 14:04:29 1998 Ross Johnson + + * implement.h: Add PTW32_VALID macro. + + * sync.c (pthread_join): Modify to use the new thread + type and ptw32_delete_thread(). Rename "target" to "thread". + Remove extra local variable "target". + (pthread_detach): Ditto. + + * signal.c (pthread_sigmask): Move init of "us" out of inner block. + Fix instance of "this" should have been "us". Rename "us" to "thread". + + * sched.c (pthread_setschedparam): Modify to use the new thread + type. + (pthread_getschedparam): Ditto. + + * private.c (ptw32_find_thread): Fix return type and arg. + + * implement.h: Remove PTW32_YES and PTW32_NO. + (ptw32_new_thread): Add prototype. + (ptw32_find_thread): Ditto. + (ptw32_delete_thread): Ditto. + (ptw32_new_thread_entry): Remove prototype. + (ptw32_find_thread_entry): Ditto. + (ptw32_delete_thread_entry): Ditto. + ( PTW32_NEW, PTW32_INUSE, PTW32_EXITED, PTW32_REUSE): + Add. + + + * create.c (pthread_create): Minor rename "us" to "new" (I need + these cues but it doesn't stop me coming out with some major bugs + at times). + Load start_routine and arg into the thread so the wrapper can + call it. + + * exit.c (pthread_exit): Fix pthread_this should be pthread_self. + + * cancel.c (pthread_setcancelstate): Change + ptw32_threads_thread_t * to pthread_t and init with + pthread_this(). + (pthread_setcanceltype): Ditto. + + * exit.c (ptw32_exit): Add new pthread_t arg. + Rename ptw32_delete_thread_entry to ptw32_delete_thread. + Rename "us" to "thread". + (pthread_exit): Call ptw32_exit with added thread arg. + + * create.c (ptw32_start_call): Insert missing ")". + Add "us" arg to ptw32_exit() call. + (pthread_create): Modify to use new thread allocation scheme. + + * private.c: Added detailed explanation of the new thread + allocation scheme. + (ptw32_new_thread): Totally rewritten to use + new thread allocation scheme. + (ptw32_delete_thread): Ditto. + (ptw32_find_thread): Obsolete. + +Mon Jul 27 17:46:37 1998 Ross Johnson + + * create.c (pthread_create): Start of rewrite. Not completed yet. + + * private.c (ptw32_new_thread_entry): Start of rewrite. Not + complete. + + * implement.h (ptw32_threads_thread): Rename, remove thread + member, add win32handle and ptstatus members. + (ptw32_t): Add. + + * pthread.h: pthread_t is no longer mapped directly to a Win32 + HANDLE type. This is so we can let the Win32 thread terminate and + reuse the HANDLE while pthreads holds it's own thread ID until + the last waiting join exits. + +Mon Jul 27 00:20:37 1998 Ross Johnson + + * private.c (ptw32_delete_thread_entry): Destroy the thread + entry attribute object before deleting the thread entry itself. + + * attr.c (pthread_attr_init): Initialise cancel_pending = FALSE. + (pthread_attr_setdetachstate): Rename "detached" to "detachedstate". + (pthread_attr_getdetachstate): Ditto. + + * exit.c (ptw32_exit): Fix incorrect check for detachedstate. + + * implement.h (ptw32_call_t): Remove env member. + +Sun Jul 26 13:06:12 1998 Ross Johnson + + * implement.h (ptw32_new_thread_entry): Fix prototype. + (ptw32_find_thread_entry): Ditto. + (ptw32_delete_thread_entry): Ditto. + (ptw32_exit): Add prototype. + + * exit.c (ptw32_exit): New function. Called from pthread_exit() + and ptw32_start_call() to exit the thread. It allows an extra + argument which is the return code passed to _endthreadex(). + (ptw32_exit): Move thread entry delete call from ptw32_vacuum() + into here. Add more explanation of thread entry deletion. + (ptw32_exit): Clarify comment. + + * create.c (ptw32_start_call): Change pthread_exit() call to + ptw32_exit() call. + + * exit.c (ptw32_vacuum): Add thread entry deletion code + moved from ptw32_start_call(). See next item. + (pthread_exit): Remove longjmp(). Add mutex lock around thread table + manipulation code. This routine now calls _enthreadex(). + + * create.c (ptw32_start_call): Remove setjmp() call and move + cleanup code out. Call pthread_exit(NULL) to terminate the thread. + +1998-07-26 Ben Elliston + + * tsd.c (pthread_getspecific): Update comments. + + * mutex.c (pthread_mutexattr_setpshared): Not supported; remove. + (pthread_mutexattr_getpshared): Likewise. + + * pthread.h (pthread_mutexattr_setpshared): Remove prototype. + (pthread_mutexattr_getpshared): Likewise. + +Sun Jul 26 00:09:59 1998 Ross Johnson + + * sync.c: Rename all instances of ptw32_count_mutex to + ptw32_table_mutex. + + * implement.h: Rename ptw32_count_mutex to + ptw32_table_mutex. + + * global.c: Rename ptw32_count_mutex to + ptw32_table_mutex. + + * create.c (pthread_create): Add critical sections. + (ptw32_start_call): Rename ptw32_count_mutex to + ptw32_table_mutex. + + * cancel.c (pthread_setcancelstate): Fix indirection bug and rename + "this" to "us". + + * signal.c (pthread_sigmask): Rename "this" to "us" and fix some + minor syntax errors. Declare "us" and initialise it. + + * sync.c (pthread_detach): Rename "this" to "target". + + * pthread.h: Converting PTHREAD_* defines to alias the (const int) + values in global.c. + + * global.c: Started converting PTHREAD_* defines to (const int) as + a part of making the eventual pthreads DLL binary compatible + through version changes. + + * condvar.c (cond_wait): Add cancelation point. This applies the + point to both pthread_cond_wait() and pthread_cond_timedwait(). + + * exit.c (pthread_exit): Rename "this" to "us". + + * implement.h: Add comment. + + * sync.c (pthread_join): I've satisfied myself that pthread_detach() + does set the detached attribute in the thread entry attributes + to PTHREAD_CREATE_DETACHED. "if" conditions were changed to test + that attribute instead of a separate flag. + + * create.c (pthread_create): Rename "this" to "us". + (pthread_create): cancelstate and canceltype are not attributes + so the copy to thread entry attribute storage was removed. + Only the thread itself can change it's cancelstate or canceltype, + ie. the thread must exist already. + + * private.c (ptw32_delete_thread_entry): Mutex locks removed. + Mutexes must be applied at the caller level. + (ptw32_new_thread_entry): Ditto. + (ptw32_new_thread_entry): Init cancelstate, canceltype, and + cancel_pending to default values. + (ptw32_new_thread_entry): Rename "this" to "new". + (ptw32_find_thread_entry): Rename "this" to "entry". + (ptw32_delete_thread_entry): Rename "thread_entry" to "entry". + + * create.c (ptw32_start_call): Mutexes changed to + ptw32_count_mutex. All access to the threads table entries is + under the one mutex. Otherwise chaos reigns. + +Sat Jul 25 23:16:51 1998 Ross Johnson + + * implement.h (ptw32_threads_thread): Move cancelstate and + canceltype members out of pthread_attr_t into here. + + * fork.c (fork): Add comment. + +1998-07-25 Ben Elliston + + * fork.c (fork): Autoconfiscate. + +Sat Jul 25 00:00:13 1998 Ross Johnson + + * create.c (ptw32_start_call): Set thread priority. Ensure our + thread entry is removed from the thread table but only if + pthread_detach() was called and there are no waiting joins. + (pthread_create): Set detach flag in thread entry if the + thread is created PTHREAD_CREATE_DETACHED. + + * pthread.h (pthread_attr_t): Rename member "detachedstate". + + * attr.c (pthread_attr_init): Rename attr members. + + * exit.c (pthread_exit): Fix indirection mistake. + + * implement.h (PTW32_THREADS_TABLE_INDEX): Add. + + * exit.c (ptw32_vacuum): Fix incorrect args to + ptw32_handler_pop_all() calls. + Make thread entry removal conditional. + + * sync.c (pthread_join): Add multiple join and async detach handling. + + * implement.h (PTW32_THREADS_TABLE_INDEX): Add. + + * global.c (ptw32_threads_mutex_table): Add. + + * implement.h (ptw32_once_flag): Remove. + (ptw32_once_lock): Ditto. + (ptw32_threads_mutex_table): Add. + + * global.c (ptw32_once_flag): Remove. + (ptw32_once_lock): Ditto. + + * sync.c (pthread_join): Fix tests involving new return value + from ptw32_find_thread_entry(). + (pthread_detach): Ditto. + + * private.c (ptw32_find_thread_entry): Failure return code + changed from -1 to NULL. + +Fri Jul 24 23:09:33 1998 Ross Johnson + + * create.c (pthread_create): Change . to -> in sigmask memcpy() args. + + * pthread.h: (pthread_cancel): Add function prototype. + (pthread_testcancel): Ditto. + +1998-07-24 Ben Elliston + + * pthread.h (pthread_condattr_t): Rename dummy structure member. + (pthread_mutexattr_t): Likewise. + +Fri Jul 24 21:13:55 1998 Ross Johnson + + * cancel.c (pthread_cancel): Implement. + (pthread_testcancel): Implement. + + * exit.c (pthread_exit): Add comment explaining the longjmp(). + + * implement.h (ptw32_threads_thread_t): New member cancelthread. + (PTW32_YES): Define. + (PTW32_NO): Define. + (RND_SIZEOF): Remove. + + * create.c (pthread_create): Rename cancelability to cancelstate. + + * pthread.h (pthread_attr_t): Rename cancelability to cancelstate. + (PTHREAD_CANCELED): Define. + +1998-07-24 Ben Elliston + + * pthread.h (SIG_BLOCK): Define if not already defined. + (SIG_UNBLOCK): Likewise. + (SIG_SETMASK): Likewise. + (pthread_attr_t): Add signal mask member. + (pthread_sigmask): Add function prototype. + + * signal.c (pthread_sigmask): Implement. + + * create.c: #include to get a prototype for memcpy(). + (pthread_create): New threads inherit their creator's signal + mask. Copy the signal mask to the new thread structure if we know + about signals. + +Fri Jul 24 16:33:17 1998 Ross Johnson + + * fork.c (pthread_atfork): Add all the necessary push calls. + Local implementation semantics: + If we get an ENOMEM at any time then ALL handlers + (including those from previous pthread_atfork() calls) will be + popped off each of the three atfork stacks before we return. + (fork): Add all the necessary pop calls. Add the thread cancellation + and join calls to the child fork. + Add #includes. + + * implement.h: (ptw32_handler_push): Fix return type and stack arg + type in prototype. + (ptw32_handler_pop): Fix stack arg type in prototype. + (ptw32_handler_pop_all): Fix stack arg type in prototype. + + * cleanup.c (ptw32_handler_push): Change return type to int and + return ENOMEM if malloc() fails. + + * sync.c (pthread_detach): Use equality test, not assignment. + + * create.c (ptw32_start_call): Add call to Win32 CloseHandle() + if thread is detached. + +1998-07-24 Ben Elliston + + * sync.c (pthread_detach): Close the Win32 thread handle to + emulate detached (or daemon) threads. + +Fri Jul 24 03:00:25 1998 Ross Johnson + + * sync.c (pthread_join): Save valueptr arg in joinvalueptr for + pthread_exit() to use. + + * private.c (ptw32_new_thread_entry): Initialise joinvalueptr to + NULL. + + * create.c (ptw32_start_call): Rewrite to facilitate joins. + pthread_exit() will do a longjmp() back to here. Does appropriate + cleanup and exit/return from the thread. + (pthread_create): _beginthreadex() now passes a pointer to our + thread table entry instead of just the call member of that entry. + + * implement.h (ptw32_threads_thread): New member + void ** joinvalueptr. + (ptw32_call_t): New member jmpbuf env. + + * exit.c (pthread_exit): Major rewrite to handle joins and handing + value pointer to joining thread. Uses longjmp() back to + ptw32_start_call(). + + * create.c (pthread_create): Ensure values of new attribute members + are copied to the thread attribute object. + + * attr.c (pthread_attr_destroy): Fix merge conflicts. + (pthread_attr_getdetachstate): Fix merge conflicts. + (pthread_attr_setdetachstate): Fix merge conflicts. + + * pthread.h: Fix merge conflicts. + + * sync.c (pthread_join): Fix merge conflicts. + +Fri Jul 24 00:21:21 1998 Ross Johnson + + * sync.c (pthread_join): Add check for valid and joinable + thread. + (pthread_detach): Implement. After checking for a valid and joinable + thread, it's still a no-op. + + * private.c (ptw32_find_thread_entry): Bug prevented returning + an error value in some cases. + + * attr.c (pthread_attr_setdetachedstate): Implement. + (pthread_attr_getdetachedstate): Implement. + + * implement.h: Move more hidden definitions into here from + pthread.h. + +1998-07-24 Ben Elliston + + * pthread.h (PTHREAD_CREATE_JOINABLE): Define. + (PTHREAD_CREATE_DETACHED): Likewise. + (pthread_attr_t): Add new structure member `detached'. + (pthread_attr_getdetachstate): Add function prototype. + (pthread_attr_setdetachstate): Likewise. + + * sync.c (pthread_join): Return if the target thread is detached. + + * attr.c (pthread_attr_init): Initialise cancelability and + canceltype structure members. + (pthread_attr_getdetachstate): Implement. + (pthread_attr_setdetachstate): Likewise. + + * implement.h (PTW32_CANCEL_DEFAULTS): Remove. Bit fields + proved to be too cumbersome. Set the defaults in attr.c using the + public PTHREAD_CANCEL_* constants. + + * cancel.c: New file. + + * pthread.h (sched_param): Define this type. + (pthread_attr_getschedparam): Add function prototype. + (pthread_attr_setschedparam): Likewise. + (pthread_setcancelstate): Likewise. + (pthread_setcanceltype): Likewise. + (sched_get_priority_min): Likewise. + (sched_get_priority_max): Likewise. + (pthread_mutexattr_setprotocol): Remove; not supported. + (pthread_mutexattr_getprotocol): Likewise. + (pthread_mutexattr_setprioceiling): Likewise. + (pthread_mutexattr_getprioceiling): Likewise. + (pthread_attr_t): Add canceltype member. Update comments. + (SCHED_OTHER): Define this scheduling policy constant. + (SCHED_FIFO): Likewise. + (SCHED_RR): Likewise. + (SCHED_MIN): Define the lowest possible value for this constant. + (SCHED_MAX): Likewise, the maximum possible value. + (PTHREAD_CANCEL_ASYNCHRONOUS): Redefine. + (PTHREAD_CANCEL_DEFERRED): Likewise. + + * sched.c: New file. + (pthread_setschedparam): Implement. + (pthread_getschedparam): Implement. + (sched_get_priority_max): Validate policy argument. + (sched_get_priority_min): Likewise. + + * mutex.c (pthread_mutexattr_setprotocol): Remove; not supported. + (pthread_mutexattr_getprotocol): Likewise. + (pthread_mutexattr_setprioceiling): Likewise. + (pthread_mutexattr_getprioceiling): Likewise. + +Fri Jul 24 00:21:21 1998 Ross Johnson + + * create.c (pthread_create): Arg to ptw32_new_thread_entry() + changed. See next entry. Move mutex locks out. Changes made yesterday + and today allow us to start the new thread running rather than + temporarily suspended. + + * private.c (ptw32_new_thread_entry): ptw32_thread_table + was changed back to a table of thread structures rather than pointers. + As such we're trading storage for increaded speed. This routine + was modified to work with the new table. Mutex lock put in around + global data accesses. + (ptw32_find_thread_entry): Ditto + (ptw32_delete_thread_entry): Ditto + +Thu Jul 23 23:25:30 1998 Ross Johnson + + * global.c: New. Global data objects declared here. These moved from + pthread.h. + + * pthread.h: Move implementation hidden definitions into + implement.h. + + * implement.h: Move implementation hidden definitions from + pthread.h. Add constants to index into the different handler stacks. + + * cleanup.c (ptw32_handler_push): Simplify args. Restructure. + (ptw32_handler_pop): Simplify args. Restructure. + (ptw32_handler_pop_all): Simplify args. Restructure. + +Wed Jul 22 00:16:22 1998 Ross Johnson + + * attr.c, implement.h, pthread.h, ChangeLog: Resolve CVS merge + conflicts. + + * private.c (ptw32_find_thread_entry): Changes to return type + to support leaner ptw32_threads_table[] which now only stores + ptw32_thread_thread_t *. + (ptw32_new_thread_entry): Internal changes. + (ptw32_delete_thread_entry): Internal changes to avoid contention. + Calling routines changed accordingly. + + * pthread.h: Modified cleanup macros to use new generic push and pop. + Added destructor and atfork stacks to ptw32_threads_thread_t. + + * cleanup.c (ptw32_handler_push, ptw32_handler_pop, + ptw32_handler_pop_all): Renamed cleanup push and pop routines + and made generic to handle destructors and atfork handlers as + well. + + * create.c (ptw32_start_call): New function is a wrapper for + all new threads. It allows us to do some cleanup when the thread + returns, ie. that is otherwise only done if the thread is cancelled. + + * exit.c (ptw32_vacuum): New function contains code from + pthread_exit() that we need in the new ptw32_start_call() + as well. + + * implement.h: Various additions and minor changes. + + * pthread.h: Various additions and minor changes. + Change cleanup handler macros to use generic handler push and pop + functions. + + * attr.c: Minor mods to all functions. + (is_attr): Implemented missing function. + + * create.c (pthread_create): More clean up. + + * private.c (ptw32_find_thread_entry): Implement. + (ptw32_delete_thread_entry): Implement. + (ptw32_new_thread_entry): Implement. + These functions manipulate the implementations internal thread + table and are part of general code cleanup and modularisation. + They replace ptw32_getthreadindex() which was removed. + + * exit.c (pthread_exit): Changed to use the new code above. + + * pthread.h: Add cancelability constants. Update comments. + +1998-07-22 Ben Elliston + + * attr.c (pthread_setstacksize): Update test of attr argument. + (pthread_getstacksize): Likewise. + (pthread_setstackaddr): Likewise. + (pthread_getstackaddr): Likewise. + (pthread_attr_init): No need to allocate any storage. + (pthread_attr_destroy): No need to free any storage. + + * mutex.c (is_attr): Not likely to be needed; remove. + (remove_attr): Likewise. + (insert_attr): Likewise. + + * implement.h (ptw32_mutexattr_t): Moved to a public definition + in pthread.h. There was little gain in hiding these details. + (ptw32_condattr_t): Likewise. + (ptw32_attr_t): Likewise. + + * pthread.h (pthread_atfork): Add function prototype. + (pthread_attr_t): Moved here from implement.h. + + * fork.c (pthread_atfork): Preliminary implementation. + (ptw32_fork): Likewise. + +Wed Jul 22 00:16:22 1998 Ross Johnson + + * cleanup.c (ptw32_cleanup_push): Implement. + (ptw32_cleanup_pop): Implement. + (ptw32_do_cancellation): Implement. + These are private to the implementation. The real cleanup functions + are macros. See below. + + * pthread.h (pthread_cleanup_push): Implement as a macro. + (pthread_cleanup_pop): Implement as a macro. + Because these are macros which start and end a block, the POSIX scoping + requirement is observed. See the comment in the file. + + * exit.c (pthread_exit): Refine the code. + + * create.c (pthread_create): Code cleanup. + + * implement.h (RND_SIZEOF): Add RND_SIZEOF(T) to round sizeof(T) + up to multiple of DWORD. + Add function prototypes. + + * private.c (ptw32_getthreadindex): "*thread" should have been + "thread". Detect empty slot fail condition. + +1998-07-20 Ben Elliston + + * misc.c (pthread_once): Implement. Don't use a per-application + flag and mutex--make `pthread_once_t' contain these elements in + their structure. The earlier version had incorrect semantics. + + * pthread.h (ptw32_once_flag): Add new variable. Remove. + (ptw32_once_lock): Add new mutex lock to ensure integrity of + access to ptw32_once_flag. Remove. + (pthread_once): Add function prototype. + (pthread_once_t): Define this type. + +Mon Jul 20 02:31:05 1998 Ross Johnson + + * private.c (ptw32_getthreadindex): Implement. + + * pthread.h: Add application static data dependent on + _PTHREADS_BUILD_DLL define. This is needed to avoid allocating + non-sharable static data within the pthread DLL. + + * implement.h: Add ptw32_cleanup_stack_t, ptw32_cleanup_node_t + and PTW32_HASH_INDEX. + + * exit.c (pthread_exit): Begin work on cleanup and de-allocate + thread-private storage. + + * create.c (pthread_create): Add thread to thread table. + Keep a thread-private copy of the attributes with default values + filled in when necessary. Same for the cleanup stack. Make + pthread_create C run-time library friendly by using _beginthreadex() + instead of CreateThread(). Fix error returns. + +Sun Jul 19 16:26:23 1998 Ross Johnson + + * implement.h: Rename pthreads_thread_count to ptw32_threads_count. + Create ptw32_threads_thread_t struct to keep thread specific data. + + * create.c: Rename pthreads_thread_count to ptw32_threads_count. + (pthread_create): Handle errors from CreateThread(). + +1998-07-19 Ben Elliston + + * condvar.c (pthread_cond_wait): Generalise. Moved from here .. + (cond_wait): To here. + (pthread_cond_timedwait): Implement; use generalised cond_wait(). + + * pthread.h (pthread_key_t): Define this type. + (pthread_key_create): Add function prototype. + (pthread_setspecific): Likewise. + (pthread_getspecific): Likwise. + (pthread_key_delete): Likewise. + + * tsd.c (pthread_key_create): Implement. + (pthread_setspecific): Likewise. + (pthread_getspecific): Likewise. + (pthread_key_delete): Likewise. + + * mutex.c (pthread_mutex_trylock): Return ENOSYS if this function + is called on a Win32 platform which is not Windows NT. + +1998-07-18 Ben Elliston + + * condvar.c (pthread_condattr_init): Do not attempt to malloc any + storage; none is needed now that condattr_t is an empty struct. + (pthread_condattr_destory): Likewise; do not free storage. + (pthread_condattr_setpshared): No longer supported; return ENOSYS. + (pthread_condattr_getpshared): Likewise. + (pthread_cond_init): Implement with help from Douglas Schmidt. + Remember to initialise the cv's internal mutex. + (pthread_cond_wait): Likewise. + (pthread_cond_signal): Likewise. + (pthread_cond_broadcast): Likewise. + (pthread_cond_timedwait): Preliminary implementation, but I need + to see some API documentation for `WaitForMultipleObject'. + (pthread_destory): Implement. + + * pthread.h (pthread_cond_init): Add function protoype. + (pthread_cond_broadcast): Likewise. + (pthread_cond_signal): Likewise. + (pthread_cond_timedwait): Likewise. + (pthread_cond_wait): Likewise. + (pthread_cond_destroy): Likewise. + (pthread_cond_t): Define this type. Fix for u_int. Do not assume + that the mutex contained withing the pthread_cond_t structure will + be a critical section. Use our new POSIX type! + + * implement.h (ptw32_condattr_t): Remove shared attribute. + +1998-07-17 Ben Elliston + + * pthread.h (PTHREADS_PROCESS_PRIVATE): Remove. + (PTHREAD_PROCESS_SHARED): Likewise. No support for mutexes shared + across processes for now. + (pthread_mutex_t): Use a Win32 CRITICAL_SECTION type for better + performance. + + * implement.h (ptw32_mutexattr_t): Remove shared attribute. + + * mutex.c (pthread_mutexattr_setpshared): This optional function + is no longer supported, since we want to implement POSIX mutex + variables using the much more efficient Win32 critical section + primitives. Critical section objects in Win32 cannot be shared + between processes. + (pthread_mutexattr_getpshared): Likewise. + (pthread_mutexattr_init): No need to malloc any storage; the + attributes structure is now empty. + (pthread_mutexattr_destroy): This is now a nop. + (pthread_mutex_init): Use InitializeCriticalSection(). + (pthread_mutex_destroy): Use DeleteCriticalSection(). + (pthread_mutex_lock): Use EnterCriticalSection(). + (pthread_mutex_trylock): Use TryEnterCriticalSection(). This is + not supported by Windows 9x, but trylock is a hack anyway, IMHO. + (pthread_mutex_unlock): Use LeaveCriticalSection(). + +1998-07-14 Ben Elliston + + * attr.c (pthread_attr_setstacksize): Implement. + (pthread_attr_getstacksize): Likewise. + (pthread_attr_setstackaddr): Likewise. + (pthread_attr_getstackaddr): Likewise. + (pthread_attr_init): Likewise. + (pthread_attr_destroy): Likewise. + + * condvar.c (pthread_condattr_init): Add `_cond' to function name. + + * mutex.c (pthread_mutex_lock): Add `_mutex' to function name. + (pthread_mutex_trylock): Likewise. + (pthread_mutex_unlock): Likewise. + + * pthread.h (pthread_condattr_setpshared): Fix typo. + (pthread_attr_init): Add function prototype. + (pthread_attr_destroy): Likewise. + (pthread_attr_setstacksize): Likewise. + (pthread_attr_getstacksize): Likewise. + (pthread_attr_setstackaddr): Likewise. + (pthread_attr_getstackaddr): Likewise. + +Mon Jul 13 01:09:55 1998 Ross Johnson + + * implement.h: Wrap in #ifndef _IMPLEMENT_H + + * create.c (pthread_create): Map stacksize attr to Win32. + + * mutex.c: Include implement.h + +1998-07-13 Ben Elliston + + * condvar.c (pthread_condattr_init): Implement. + (pthread_condattr_destroy): Likewise. + (pthread_condattr_setpshared): Likewise. + (pthread_condattr_getpshared): Likewise. + + * implement.h (PTHREAD_THREADS_MAX): Remove trailing semicolon. + (PTHREAD_STACK_MIN): Specify; needs confirming. + (ptw32_attr_t): Define this type. + (ptw32_condattr_t): Likewise. + + * pthread.h (pthread_mutex_t): Define this type. + (pthread_condattr_t): Likewise. + (pthread_mutex_destroy): Add function prototype. + (pthread_lock): Likewise. + (pthread_trylock): Likewise. + (pthread_unlock): Likewise. + (pthread_condattr_init): Likewise. + (pthread_condattr_destroy): Likewise. + (pthread_condattr_setpshared): Likewise. + (pthread_condattr_getpshared): Likewise. + + * mutex.c (pthread_mutex_init): Implement. + (pthread_mutex_destroy): Likewise. + (pthread_lock): Likewise. + (pthread_trylock): Likewise. + (pthread_unlock): Likewise. + +1998-07-12 Ben Elliston + + * implement.h (ptw32_mutexattr_t): Define this implementation + internal type. Application programmers only see a mutex attribute + object as a void pointer. + + * pthread.h (pthread_mutexattr_t): Define this type. + (pthread_mutexattr_init): Add function prototype. + (pthread_mutexattr_destroy): Likewise. + (pthread_mutexattr_setpshared): Likewise. + (pthread_mutexattr_getpshared): Likewise. + (pthread_mutexattr_setprotocol): Likewise. + (pthread_mutexattr_getprotocol): Likewise. + (pthread_mutexattr_setprioceiling): Likewise. + (pthread_mutexattr_getprioceiling): Likewise. + (PTHREAD_PROCESS_PRIVATE): Define. + (PTHREAD_PROCESS_SHARED): Define. + + * mutex.c (pthread_mutexattr_init): Implement. + (pthread_mutexattr_destroy): Implement. + (pthread_mutexattr_setprotocol): Implement. + (pthread_mutexattr_getprotocol): Likewise. + (pthread_mutexattr_setprioceiling): Likewise. + (pthread_mutexattr_getprioceiling): Likewise. + (pthread_mutexattr_setpshared): Likewise. + (pthread_mutexattr_getpshared): Likewise. + (insert_attr): New function; very preliminary implementation! + (is_attr): Likewise. + (remove_attr): Likewise. + +Sat Jul 11 14:48:54 1998 Ross Johnson + + * implement.h: Preliminary implementation specific defines. + + * create.c (pthread_create): Preliminary implementation. + +1998-07-11 Ben Elliston + + * sync.c (pthread_join): Implement. + + * misc.c (pthread_equal): Likewise. + + * pthread.h (pthread_join): Add function prototype. + (pthread_equal): Likewise. + +1998-07-10 Ben Elliston + + * misc.c (pthread_self): Implement. + + * exit.c (pthread_exit): Implement. + + * pthread.h (pthread_exit): Add function prototype. + (pthread_self): Likewise. + (pthread_t): Define this type. + +1998-07-09 Ben Elliston + + * create.c (pthread_create): A dummy stub right now. + + * pthread.h (pthread_create): Add function prototype. diff --git a/w32-pthreads/FAQ b/w32-pthreads/FAQ new file mode 100644 index 000000000..cb1786c5a --- /dev/null +++ b/w32-pthreads/FAQ @@ -0,0 +1,451 @@ + ========================================= + PTHREADS-WIN32 Frequently Asked Questions + ========================================= + +INDEX +----- + +Q 1 What is it? + +Q 2 Which of the several dll versions do I use? + or, + What are all these pthread*.dll and pthread*.lib files? + +Q 3 What is the library naming convention? + +Q 4 Cleanup code default style or: it used to work when I built + the library myself, but now it doesn't - why? + +Q 5 Why is the default library version now less exception-friendly? + +Q 6 Should I use Cygwin or Mingw32 as a development environment? + +Q 7 Now that pthreads-win32 builds under Mingw32, why do I get + memory access violations (segfaults)? + +Q 8 How do I use pthread.dll for Win32 (Visual C++ 5.0) + +Q 9 Cancelation doesn't work for me, why? + +Q 10 How do I generate pthreadGCE.dll and libpthreadw32.a for use + with Mingw32? + +Q 11 Why isn't pthread_t defined as a scalar (e.g. pointer or int) + like it is for other POSIX threads implementations? + +============================================================================= + +Q 1 What is it? +--- + +Pthreads-win32 is an Open Source Software implementation of the +Threads component of the POSIX 1003.1c 1995 Standard for Microsoft's +Win32 environment. Some functions from POSIX 1003.1b are also +supported including semaphores. Other related functions include +the set of read-write lock functions. The library also supports +some of the functionality of the Open Group's Single Unix +specification, version 2, namely mutex types. + +See the file "ANNOUNCE" for more information including standards +conformance details and list of supported routines. + + +------------------------------------------------------------------------------ + +Q 2 Which of the several dll versions do I use? +--- or, + What are all these pthread*.dll and pthread*.lib files? + +Simply, you only use one of them, but you need to choose carefully. + +The most important choice you need to make is whether to use a +version that uses exceptions internally, or not (there are versions +of the library that use exceptions as part of the thread +cancelation and cleanup implementation, and one that uses +setjmp/longjmp instead). + +There is some contension amongst POSIX threads experts as +to how POSIX threads cancelation and exit should work +with languages that include exceptions and handlers, e.g. +C++ and even C (Microsoft's Structured Exceptions). + +The issue is: should cancelation of a thread in, say, +a C++ application cause object destructors and C++ exception +handlers to be invoked as the stack unwinds during thread +exit, or not? + +There seems to be more opinion in favour of using the +standard C version of the library (no EH) with C++ applications +since this appears to be the assumption commercial pthreads +implementations make. Therefore, if you use an EH version +of pthreads-win32 then you may be under the illusion that +your application will be portable, when in fact it is likely to +behave very differently linked with other pthreads libraries. + +Now you may be asking: why have you kept the EH versions of +the library? + +There are a couple of reasons: +- there is division amongst the experts and so the code may + be needed in the future. (Yes, it's in the repository and we + can get it out anytime in the future, but ...) +- pthreads-win32 is one of the few implementations, and possibly + the only freely available one, that has EH versions. It may be + useful to people who want to play with or study application + behaviour under these conditions. + + +------------------------------------------------------------------------------ + +Q 3 What is the library naming convention? +--- + +Because the library is being built using various exception +handling schemes and compilers - and because the library +may not work reliably if these are mixed in an application, +each different version of the library has it's own name. + +Note 1: the incompatibility is really between EH implementations +of the different compilers. It should be possible to use the +standard C version from either compiler with C++ applications +built with a different compiler. If you use an EH version of +the library, then you must use the same compiler for the +application. This is another complication and dependency that +can be avoided by using only the standard C library version. + +Note 2: if you use a standard C pthread*.dll with a C++ +application, then any functions that you define that are +intended to be called via pthread_cleanup_push() must be +__cdecl. + +Note 3: the intention is to also name either the VC or GC +version (it should be arbitrary) as pthread.dll, including +pthread.lib and libpthread.a as appropriate. + +In general: + pthread[VG]{SE,CE,C}.dll + pthread[VG]{SE,CE,C}.lib + +where: + [VG] indicates the compiler + V - MS VC + G - GNU C + + {SE,CE,C} indicates the exception handling scheme + SE - Structured EH + CE - C++ EH + C - no exceptions - uses setjmp/longjmp + +For example: + pthreadVSE.dll (MSVC/SEH) + pthreadGCE.dll (GNUC/C++ EH) + pthreadGC.dll (GNUC/not dependent on exceptions) + +The GNU library archive file names have changed to: + + libpthreadGCE.a + libpthreadGC.a + + +------------------------------------------------------------------------------ + +Q 4 Cleanup code default style or: it used to work when I built +--- the library myself, but now it doesn't - why? + +Up to and including snapshot 2001-07-12, if not defined, the cleanup +style was determined automatically from the compiler used, and one +of the following was defined accordingly: + + __CLEANUP_SEH MSVC only + __CLEANUP_CXX C++, including MSVC++, GNU G++ + __CLEANUP_C C, including GNU GCC, not MSVC + +These defines determine the style of cleanup (see pthread.h) and, +most importantly, the way that cancelation and thread exit (via +pthread_exit) is performed (see the routine ptw32_throw() in private.c). + +In short, the exceptions versions of the library throw an exception +when a thread is canceled or exits (via pthread_exit()), which is +caught by a handler in the thread startup routine, so that the +the correct stack unwinding occurs regardless of where the thread +is when it's canceled or exits via pthread_exit(). + +After snapshot 2001-07-12, unless your build explicitly defines (e.g. +via a compiler option) __CLEANUP_SEH, __CLEANUP_CXX, or __CLEANUP_C, then +the build now ALWAYS defaults to __CLEANUP_C style cleanup. This style +uses setjmp/longjmp in the cancelation and pthread_exit implementations, +and therefore won't do stack unwinding even when linked to applications +that have it (e.g. C++ apps). This is for consistency with most/all +commercial Unix POSIX threads implementations. + +Although it was not clearly documented before, it is still necessary to +build your application using the same __CLEANUP_* define as was +used for the version of the library that you link with, so that the +correct parts of pthread.h are included. That is, the possible +defines require the following library versions: + + __CLEANUP_SEH pthreadVSE.dll + __CLEANUP_CXX pthreadVCE.dll or pthreadGCE.dll + __CLEANUP_C pthreadVC.dll or pthreadGC.dll + +THE POINT OF ALL THIS IS: if you have not been defining one of these +explicitly, then the defaults have been set according to the compiler +and language you are using, as described at the top of this +section. + +THIS NOW CHANGES, as has been explained above. For example: + +If you were building your application with MSVC++ i.e. using C++ +exceptions (rather than SEH) and not explicitly defining one of +__CLEANUP_*, then __CLEANUP_C++ was defined for you in pthread.h. +You should have been linking with pthreadVCE.dll, which does +stack unwinding. + +If you now build your application as you had before, pthread.h will now +set __CLEANUP_C as the default style, and you will need to link +with pthreadVC.dll. Stack unwinding will now NOT occur when a +thread is canceled, nor when the thread calls pthread_exit(). + +Your application will now most likely behave differently to previous +versions, and in non-obvious ways. Most likely is that local +objects may not be destroyed or cleaned up after a thread +is canceled. + +If you want the same behaviour as before, then you must now define +__CLEANUP_C++ explicitly using a compiler option and link with +pthreadVCE.dll as you did before. + + +------------------------------------------------------------------------------ + +Q 5 Why is the default library version now less exception-friendly? +--- + +Because most commercial Unix POSIX threads implementations don't allow you to +choose to have stack unwinding. (Compaq's TRU64 Unix is possibly an exception.) + +Therefore, providing it in pthread-win32 as a default could be dangerous +and non-portable. We still provide the choice but you must now consciously +make it. + +WHY NOT REMOVE THE EXCEPTIONS VERSIONS OF THE LIBRARY ALTOGETHER? +There are a few reasons: +- because there are well respected POSIX threads people who believe + that POSIX threads implementations should be exceptions-aware and + do the expected thing in that context. (There are equally respected + people who believe it should not be easily accessible, if it's there + at all.) +- because pthreads-win32 is one of the few implementations that has + the choice, perhaps the only freely available one, and so offers + a laboratory to people who may want to explore the effects; +- although the code will always be around somewhere for anyone who + wants it, once it's removed from the current version it will not be + nearly as visible to people who may have a use for it. + + +------------------------------------------------------------------------------ + +Q 6 Should I use Cygwin or Mingw32 as a development environment? +--- + +Important: see Q7 also. + +Use Mingw32 with the MSVCRT library to build applications that use +the pthreads DLL. + +Cygwin's own internal support for POSIX threads is growing. +Consult that project's documentation for more information. + +------------------------------------------------------------------------------ + +Q 7 Now that pthreads-win32 builds under Mingw32, why do I get +--- memory access violations (segfaults)? + +The latest Mingw32 package has thread-safe exception handling (see Q10). +Also, see Q6 above. + +------------------------------------------------------------------------------ + +Q 8 How do I use pthread.dll for Win32 (Visual C++ 5.0) +--- + +> +> I'm a "rookie" when it comes to your pthread implementation. I'm currently +> desperately trying to install the prebuilt .dll file into my MSVC compiler. +> Could you please provide me with explicit instructions on how to do this (or +> direct me to a resource(s) where I can acquire such information)? +> +> Thank you, +> + +You should have a .dll, .lib, .def, and three .h files. It is recommended +that you use pthreadVC.dll, rather than pthreadVCE.dll or pthreadVSE.dll +(see Q2 above). + +The .dll can go in any directory listed in your PATH environment +variable, so putting it into C:\WINDOWS should work. + +The .lib file can go in any directory listed in your LIB environment +variable. + +The .h files can go in any directory listed in your INCLUDE +environment variable. + +Or you might prefer to put the .lib and .h files into a new directory +and add its path to LIB and INCLUDE. You can probably do this easiest +by editing the file:- + +C:\Program Files\DevStudio\vc\bin\vcvars32.bat + +The .def file isn't used by anything in the pre-compiled version but +is included for information. + +Cheers. +Ross + +------------------------------------------------------------------------------ + +Q 9 Cancelation doesn't work for me, why? +--- + +> I'm investigating a problem regarding thread cancelation. The thread I want +> to cancel has PTHREAD_CANCEL_ASYNCHRONOUS, however, this piece of code +> blocks on the join(): +> +> if ((retv = Pthread_cancel( recvThread )) == 0) +> { +> retv = Pthread_join( recvThread, 0 ); +> } +> +> Pthread_* are just macro's; they call pthread_*. +> +> The thread recvThread seems to block on a select() call. It doesn't get +> cancelled. +> +> Two questions: +> +> 1) is this normal behaviour? +> +> 2) if not, how does the cancel mechanism work? I'm not very familliar to +> win32 programming, so I don't really understand how the *Event() family of +> calls work. + +The answer to your first question is, normal POSIX behaviour would +be to asynchronously cancel the thread. However, even that doesn't +guarantee cancelation as the standard only says it should be +cancelled as soon as possible. + +Snapshot 99-11-02 or earlier only partially supports asynchronous cancellation. +Snapshots since then simulate async cancelation by poking the address of +a cancelation routine into the PC of the threads context. This requires +the thread to be resumed in some way for the cancelation to actually +proceed. This is not true async cancelation, but it is as close as we've +been able to get to it. + +If the thread you're trying to cancel is blocked (for instance, it could be +waiting for data from the network), it will only get cancelled when it unblocks +(when the data arrives). For true pre-emptive cancelation in these cases, +pthreads-win32 from snapshot 2004-05-16 can automatically recognise and use the +QueueUserAPCEx package by Panagiotis E. Hadjidoukas. This package is available +from the pthreads-win32 ftp site and is included in the pthreads-win32 +self-unpacking zip from 2004-05-16 onwards. + +Using deferred cancelation would normally be the way to go, however, +even though the POSIX threads standard lists a number of C library +functions that are defined as deferred cancelation points, there is +no hookup between those which are provided by Windows and the +pthreads-win32 library. + +Incidently, it's worth noting for code portability that the older POSIX +threads standards cancelation point lists didn't include "select" because +(as I read in Butenhof) it wasn't part of POSIX. However, it does appear in +the SUSV3. + +Effectively, the only mandatory cancelation points that pthreads-win32 +recognises are those the library implements itself, ie. + + pthread_testcancel + pthread_cond_wait + pthread_cond_timedwait + pthread_join + sem_wait + sem_timedwait + pthread_delay_np + +The following routines from the non-mandatory list in SUSV3 are +cancelation points in pthreads-win32: + + pthread_rwlock_wrlock + pthread_rwlock_timedwrlock + +The following routines from the non-mandatory list in SUSV3 are not +cancelation points in pthreads-win32: + + pthread_rwlock_rdlock + pthread_rwlock_timedrdlock + +Pthreads-win32 also provides two functions that allow you to create +cancelation points within your application, but only for cases where +a thread is going to block on a Win32 handle. These are: + + pthreadCancelableWait(HANDLE waitHandle) /* Infinite wait */ + + pthreadCancelableTimedWait(HANDLE waitHandle, DWORD timeout) + +------------------------------------------------------------------------------ + + +Q 10 How do I create thread-safe applications using +---- pthreadGCE.dll, libpthreadw32.a and Mingw32? + +This should not be a problem with recent versions of MinGW32. + +For early versions, see Thomas Pfaff's email at: +http://sources.redhat.com/ml/pthreads-win32/2002/msg00000.html +------------------------------------------------------------------------------ + +Q 11 Why isn't pthread_t defined as a scalar (e.g. pointer or int) + like it is for other POSIX threads implementations? +---- + +Originally pthread_t was defined as a pointer (to the opaque pthread_t_ +struct) and later it was changed to a struct containing the original +pointer plus a sequence counter. This is allowed under both the original +POSIX Threads Standard and the current Single Unix Specification. + +When pthread_t is a simple pointer to a struct some very difficult to +debug problems arise from the process of freeing and later allocing +thread structs because new pthread_t handles can acquire the identity of +previously detached threads. The change to a struct was made, along with +some changes to their internal managment, in order to guarantee (for +practical applications) that the pthread_t handle will be unique over the +life of the running process. + +Where application code attempts to compare one pthread_t against another +directly, a compiler error will be emitted because structs can't be +compared at that level. This should signal a potentially serious problem +in the code design, which would go undetected if pthread_t was a scalar. + +The POSIX Threading API provides a function named pthread_equal() to +compare pthread_t thread handles. + +Other pthreads implementations, such as Sun's, use an int as the handle +but do guarantee uniqueness within the process scope. Win32 scalar typed +thread handles also guarantee uniqueness in system scope. It wasn't clear +how well the internal management of these handles would scale as the +number of threads and the fragmentation of the sequence numbering +increased for applications where thousands or millions of threads are +created and detached over time. The current management of threads within +pthreads-win32 using structs for pthread_t, and reusing without ever +freeing them, reduces the management time overheads to a constant, which +could be important given that pthreads-win32 threads are built on top of +Win32 threads and will therefore include that management overhead on top +of their own. The cost is that the memory resources used for thread +handles will remain at the peak level until the process exits. + +While it may be inconvenient for developers to be forced away from making +assumptions about the internals of pthread_t, the advantage for the +future development of pthread-win32, as well as those applications that +use it and other pthread implementations, is that the library is free to +change pthread_t internals and management as better methods arise. + diff --git a/w32-pthreads/GNUmakefile b/w32-pthreads/GNUmakefile new file mode 100644 index 000000000..e489f002e --- /dev/null +++ b/w32-pthreads/GNUmakefile @@ -0,0 +1,593 @@ +# +# -------------------------------------------------------------------------- +# +# Pthreads-win32 - POSIX Threads Library for Win32 +# Copyright(C) 1998 John E. Bossom +# Copyright(C) 1999,2005 Pthreads-win32 contributors +# +# Contact Email: rpj@callisto.canberra.edu.au +# +# The current list of contributors is contained +# in the file CONTRIBUTORS included with the source +# code distribution. The list can also be seen at the +# following World Wide Web location: +# http://sources.redhat.com/pthreads-win32/contributors.html +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2 of the License, or (at your option) any later version. +# +# This library 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library in the file COPYING.LIB; +# if not, write to the Free Software Foundation, Inc., +# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA +# + +DLL_VER = 2 +DLL_VERD= $(DLL_VER)d + +DEVROOT = C:\PTHREADS + +DLLDEST = $(DEVROOT)\DLL +LIBDEST = $(DEVROOT)\DLL + +# If Running MsysDTK +RM = rm -f +MV = mv -f +CP = cp -f + +# If not. +#RM = erase +#MV = rename +#CP = copy + +# For cross compiling use e.g. +# make CROSS=x86_64-w64-mingw32- clean GC-inlined +CROSS = + +AR = $(CROSS)ar +DLLTOOL = $(CROSS)dlltool +CC = $(CROSS)gcc +CXX = $(CROSS)g++ +RANLIB = $(CROSS)ranlib +RC = $(CROSS)windres + +OPT = $(CLEANUP) -O3 # -finline-functions -findirect-inlining +XOPT = + +RCFLAGS = --include-dir=. +# Uncomment this if config.h defines RETAIN_WSALASTERROR +#LFLAGS = -lws2_32 + +# ---------------------------------------------------------------------- +# The library can be built with some alternative behaviour to +# facilitate development of applications on Win32 that will be ported +# to other POSIX systems. Nothing definable here will make the library +# non-compliant, but applications that make assumptions that POSIX +# does not garrantee may fail or misbehave under some settings. +# +# PTW32_THREAD_ID_REUSE_INCREMENT +# Purpose: +# POSIX says that applications should assume that thread IDs can be +# recycled. However, Solaris and some other systems use a [very large] +# sequence number as the thread ID, which provides virtual uniqueness. +# Pthreads-win32 provides pseudo-unique IDs when the default increment +# (1) is used, but pthread_t is not a scalar type like Solaris's. +# +# Usage: +# Set to any value in the range: 0 <= value <= 2^wordsize +# +# Examples: +# Set to 0 to emulate non recycle-unique behaviour like Linux or *BSD. +# Set to 1 for recycle-unique thread IDs (this is the default). +# Set to some other +ve value to emulate smaller word size types +# (i.e. will wrap sooner). +# +#PTW32_FLAGS = "-DPTW32_THREAD_ID_REUSE_INCREMENT=0" +# +# ---------------------------------------------------------------------- + +GC_CFLAGS = $(PTW32_FLAGS) +GCE_CFLAGS = $(PTW32_FLAGS) -mthreads + +## Mingw +MAKE ?= make +CFLAGS = $(OPT) $(XOPT) -I. -DHAVE_PTW32_CONFIG_H -Wall + +DLL_INLINED_OBJS = \ + pthread.o \ + version.o + +# Agregate modules for inlinability +DLL_OBJS = \ + attr.o \ + barrier.o \ + cancel.o \ + cleanup.o \ + condvar.o \ + create.o \ + dll.o \ + errno.o \ + exit.o \ + fork.o \ + global.o \ + misc.o \ + mutex.o \ + nonportable.o \ + private.o \ + rwlock.o \ + sched.o \ + semaphore.o \ + signal.o \ + spin.o \ + sync.o \ + tsd.o \ + version.o + +# Separate modules for minimum size statically linked images +SMALL_STATIC_OBJS = \ + pthread_attr_init.o \ + pthread_attr_destroy.o \ + pthread_attr_getdetachstate.o \ + pthread_attr_setdetachstate.o \ + pthread_attr_getstackaddr.o \ + pthread_attr_setstackaddr.o \ + pthread_attr_getstacksize.o \ + pthread_attr_setstacksize.o \ + pthread_attr_getscope.o \ + pthread_attr_setscope.o \ + pthread_attr_setschedpolicy.o \ + pthread_attr_getschedpolicy.o \ + pthread_attr_setschedparam.o \ + pthread_attr_getschedparam.o \ + pthread_attr_setinheritsched.o \ + pthread_attr_getinheritsched.o \ + pthread_barrier_init.o \ + pthread_barrier_destroy.o \ + pthread_barrier_wait.o \ + pthread_barrierattr_init.o \ + pthread_barrierattr_destroy.o \ + pthread_barrierattr_setpshared.o \ + pthread_barrierattr_getpshared.o \ + pthread_setcancelstate.o \ + pthread_setcanceltype.o \ + pthread_testcancel.o \ + pthread_cancel.o \ + cleanup.o \ + pthread_condattr_destroy.o \ + pthread_condattr_getpshared.o \ + pthread_condattr_init.o \ + pthread_condattr_setpshared.o \ + pthread_cond_destroy.o \ + pthread_cond_init.o \ + pthread_cond_signal.o \ + pthread_cond_wait.o \ + create.o \ + dll.o \ + autostatic.o \ + errno.o \ + pthread_exit.o \ + fork.o \ + global.o \ + pthread_mutex_init.o \ + pthread_mutex_destroy.o \ + pthread_mutexattr_init.o \ + pthread_mutexattr_destroy.o \ + pthread_mutexattr_getpshared.o \ + pthread_mutexattr_setpshared.o \ + pthread_mutexattr_settype.o \ + pthread_mutexattr_gettype.o \ + pthread_mutexattr_setrobust.o \ + pthread_mutexattr_getrobust.o \ + pthread_mutex_lock.o \ + pthread_mutex_timedlock.o \ + pthread_mutex_unlock.o \ + pthread_mutex_trylock.o \ + pthread_mutex_consistent.o \ + pthread_mutexattr_setkind_np.o \ + pthread_mutexattr_getkind_np.o \ + pthread_getw32threadhandle_np.o \ + pthread_getunique_np.o \ + pthread_delay_np.o \ + pthread_num_processors_np.o \ + pthread_win32_attach_detach_np.o \ + pthread_equal.o \ + pthread_getconcurrency.o \ + pthread_once.o \ + pthread_self.o \ + pthread_setconcurrency.o \ + pthread_rwlock_init.o \ + pthread_rwlock_destroy.o \ + pthread_rwlockattr_init.o \ + pthread_rwlockattr_destroy.o \ + pthread_rwlockattr_getpshared.o \ + pthread_rwlockattr_setpshared.o \ + pthread_rwlock_rdlock.o \ + pthread_rwlock_wrlock.o \ + pthread_rwlock_unlock.o \ + pthread_rwlock_tryrdlock.o \ + pthread_rwlock_trywrlock.o \ + pthread_setschedparam.o \ + pthread_getschedparam.o \ + pthread_timechange_handler_np.o \ + ptw32_is_attr.o \ + ptw32_cond_check_need_init.o \ + ptw32_MCS_lock.o \ + ptw32_mutex_check_need_init.o \ + ptw32_processInitialize.o \ + ptw32_processTerminate.o \ + ptw32_threadStart.o \ + ptw32_threadDestroy.o \ + ptw32_tkAssocCreate.o \ + ptw32_tkAssocDestroy.o \ + ptw32_callUserDestroyRoutines.o \ + ptw32_timespec.o \ + ptw32_throw.o \ + ptw32_getprocessors.o \ + ptw32_calloc.o \ + ptw32_new.o \ + ptw32_reuse.o \ + ptw32_semwait.o \ + ptw32_relmillisecs.o \ + ptw32_rwlock_check_need_init.o \ + sched_get_priority_max.o \ + sched_get_priority_min.o \ + sched_setscheduler.o \ + sched_getscheduler.o \ + sched_yield.o \ + sem_init.o \ + sem_destroy.o \ + sem_trywait.o \ + sem_timedwait.o \ + sem_wait.o \ + sem_post.o \ + sem_post_multiple.o \ + sem_getvalue.o \ + sem_open.o \ + sem_close.o \ + sem_unlink.o \ + signal.o \ + pthread_kill.o \ + ptw32_spinlock_check_need_init.o \ + pthread_spin_init.o \ + pthread_spin_destroy.o \ + pthread_spin_lock.o \ + pthread_spin_unlock.o \ + pthread_spin_trylock.o \ + pthread_detach.o \ + pthread_join.o \ + pthread_key_create.o \ + pthread_key_delete.o \ + pthread_setspecific.o \ + pthread_getspecific.o \ + w32_CancelableWait.o \ + version.o + +INCL = \ + config.h \ + implement.h \ + semaphore.h \ + pthread.h \ + need_errno.h + +ATTR_SRCS = \ + pthread_attr_init.c \ + pthread_attr_destroy.c \ + pthread_attr_getdetachstate.c \ + pthread_attr_setdetachstate.c \ + pthread_attr_getstackaddr.c \ + pthread_attr_setstackaddr.c \ + pthread_attr_getstacksize.c \ + pthread_attr_setstacksize.c \ + pthread_attr_getscope.c \ + pthread_attr_setscope.c + +BARRIER_SRCS = \ + pthread_barrier_init.c \ + pthread_barrier_destroy.c \ + pthread_barrier_wait.c \ + pthread_barrierattr_init.c \ + pthread_barrierattr_destroy.c \ + pthread_barrierattr_setpshared.c \ + pthread_barrierattr_getpshared.c + +CANCEL_SRCS = \ + pthread_setcancelstate.c \ + pthread_setcanceltype.c \ + pthread_testcancel.c \ + pthread_cancel.c + +CONDVAR_SRCS = \ + ptw32_cond_check_need_init.c \ + pthread_condattr_destroy.c \ + pthread_condattr_getpshared.c \ + pthread_condattr_init.c \ + pthread_condattr_setpshared.c \ + pthread_cond_destroy.c \ + pthread_cond_init.c \ + pthread_cond_signal.c \ + pthread_cond_wait.c + +EXIT_SRCS = \ + pthread_exit.c + +MISC_SRCS = \ + pthread_equal.c \ + pthread_getconcurrency.c \ + pthread_kill.c \ + pthread_once.c \ + pthread_self.c \ + pthread_setconcurrency.c \ + ptw32_calloc.c \ + ptw32_MCS_lock.c \ + ptw32_new.c \ + ptw32_reuse.c \ + w32_CancelableWait.c + +MUTEX_SRCS = \ + ptw32_mutex_check_need_init.c \ + pthread_mutex_init.c \ + pthread_mutex_destroy.c \ + pthread_mutexattr_init.c \ + pthread_mutexattr_destroy.c \ + pthread_mutexattr_getpshared.c \ + pthread_mutexattr_setpshared.c \ + pthread_mutexattr_settype.c \ + pthread_mutexattr_gettype.c \ + pthread_mutexattr_setrobust.c \ + pthread_mutexattr_getrobust.c \ + pthread_mutex_lock.c \ + pthread_mutex_timedlock.c \ + pthread_mutex_unlock.c \ + pthread_mutex_trylock.c \ + pthread_mutex_consistent.c + +NONPORTABLE_SRCS = \ + pthread_mutexattr_setkind_np.c \ + pthread_mutexattr_getkind_np.c \ + pthread_getw32threadhandle_np.c \ + pthread_getunique_np.c \ + pthread_delay_np.c \ + pthread_num_processors_np.c \ + pthread_win32_attach_detach_np.c \ + pthread_timechange_handler_np.c + +PRIVATE_SRCS = \ + ptw32_is_attr.c \ + ptw32_processInitialize.c \ + ptw32_processTerminate.c \ + ptw32_threadStart.c \ + ptw32_threadDestroy.c \ + ptw32_tkAssocCreate.c \ + ptw32_tkAssocDestroy.c \ + ptw32_callUserDestroyRoutines.c \ + ptw32_semwait.c \ + ptw32_relmillisecs.c \ + ptw32_timespec.c \ + ptw32_throw.c \ + ptw32_getprocessors.c + +RWLOCK_SRCS = \ + ptw32_rwlock_check_need_init.c \ + ptw32_rwlock_cancelwrwait.c \ + pthread_rwlock_init.c \ + pthread_rwlock_destroy.c \ + pthread_rwlockattr_init.c \ + pthread_rwlockattr_destroy.c \ + pthread_rwlockattr_getpshared.c \ + pthread_rwlockattr_setpshared.c \ + pthread_rwlock_rdlock.c \ + pthread_rwlock_timedrdlock.c \ + pthread_rwlock_wrlock.c \ + pthread_rwlock_timedwrlock.c \ + pthread_rwlock_unlock.c \ + pthread_rwlock_tryrdlock.c \ + pthread_rwlock_trywrlock.c + +SCHED_SRCS = \ + pthread_attr_setschedpolicy.c \ + pthread_attr_getschedpolicy.c \ + pthread_attr_setschedparam.c \ + pthread_attr_getschedparam.c \ + pthread_attr_setinheritsched.c \ + pthread_attr_getinheritsched.c \ + pthread_setschedparam.c \ + pthread_getschedparam.c \ + sched_get_priority_max.c \ + sched_get_priority_min.c \ + sched_setscheduler.c \ + sched_getscheduler.c \ + sched_yield.c + +SEMAPHORE_SRCS = \ + sem_init.c \ + sem_destroy.c \ + sem_trywait.c \ + sem_timedwait.c \ + sem_wait.c \ + sem_post.c \ + sem_post_multiple.c \ + sem_getvalue.c \ + sem_open.c \ + sem_close.c \ + sem_unlink.c + +SPIN_SRCS = \ + ptw32_spinlock_check_need_init.c \ + pthread_spin_init.c \ + pthread_spin_destroy.c \ + pthread_spin_lock.c \ + pthread_spin_unlock.c \ + pthread_spin_trylock.c + +SYNC_SRCS = \ + pthread_detach.c \ + pthread_join.c + +TSD_SRCS = \ + pthread_key_create.c \ + pthread_key_delete.c \ + pthread_setspecific.c \ + pthread_getspecific.c + + +GCE_DLL = pthreadGCE$(DLL_VER).dll +GCED_DLL= pthreadGCE$(DLL_VERD).dll +GCE_LIB = libpthreadGCE$(DLL_VER).a +GCED_LIB= libpthreadGCE$(DLL_VERD).a +GCE_INLINED_STAMP = pthreadGCE$(DLL_VER).stamp +GCED_INLINED_STAMP = pthreadGCE$(DLL_VERD).stamp +GCE_STATIC_STAMP = libpthreadGCE$(DLL_VER).stamp +GCED_STATIC_STAMP = libpthreadGCE$(DLL_VERD).stamp + +GC_DLL = pthreadGC$(DLL_VER).dll +GCD_DLL = pthreadGC$(DLL_VERD).dll +GC_LIB = libpthreadGC$(DLL_VER).a +GCD_LIB = libpthreadGC$(DLL_VERD).a +GC_INLINED_STAMP = pthreadGC$(DLL_VER).stamp +GCD_INLINED_STAMP = pthreadGC$(DLL_VERD).stamp +GC_STATIC_STAMP = libpthreadGC$(DLL_VER).stamp +GCD_STATIC_STAMP = libpthreadGC$(DLL_VERD).stamp + +PTHREAD_DEF = pthread.def + +help: + @ echo "Run one of the following command lines:" + @ echo "make clean GC (to build the GNU C dll with C cleanup code)" + @ echo "make clean GCE (to build the GNU C dll with C++ exception handling)" + @ echo "make clean GC-inlined (to build the GNU C inlined dll with C cleanup code)" + @ echo "make clean GCE-inlined (to build the GNU C inlined dll with C++ exception handling)" + @ echo "make clean GC-static (to build the GNU C inlined static lib with C cleanup code)" + @ echo "make clean GC-debug (to build the GNU C debug dll with C cleanup code)" + @ echo "make clean GCE-debug (to build the GNU C debug dll with C++ exception handling)" + @ echo "make clean GC-inlined-debug (to build the GNU C inlined debug dll with C cleanup code)" + @ echo "make clean GCE-inlined-debug (to build the GNU C inlined debug dll with C++ exception handling)" + @ echo "make clean GC-static-debug (to build the GNU C inlined static debug lib with C cleanup code)" + +all: + @ $(MAKE) clean GCE + @ $(MAKE) clean GC + +GC: + $(MAKE) CLEANUP=-D__CLEANUP_C XC_FLAGS="$(GC_CFLAGS)" OBJ="$(DLL_OBJS)" $(GC_DLL) + +GC-debug: + $(MAKE) CLEANUP=-D__CLEANUP_C XC_FLAGS="$(GC_CFLAGS)" OBJ="$(DLL_OBJS)" DLL_VER=$(DLL_VERD) OPT="-D__CLEANUP_C -g -O0" $(GCD_DLL) + +GCE: + $(MAKE) CC=$(CXX) CLEANUP=-D__CLEANUP_CXX XC_FLAGS="$(GCE_CFLAGS)" OBJ="$(DLL_OBJS)" $(GCE_DLL) + +GCE-debug: + $(MAKE) CC=$(CXX) CLEANUP=-D__CLEANUP_CXX XC_FLAGS="$(GCE_CFLAGS)" OBJ="$(DLL_OBJS)" DLL_VER=$(DLL_VERD) OPT="-D__CLEANUP_CXX -g -O0" $(GCED_DLL) + +GC-inlined: + $(MAKE) XOPT="-DPTW32_BUILD_INLINED" CLEANUP=-D__CLEANUP_C XC_FLAGS="$(GC_CFLAGS)" OBJ="$(DLL_INLINED_OBJS)" $(GC_INLINED_STAMP) + +GC-inlined-debug: + $(MAKE) XOPT="-DPTW32_BUILD_INLINED" CLEANUP=-D__CLEANUP_C XC_FLAGS="$(GC_CFLAGS)" OBJ="$(DLL_INLINED_OBJS)" DLL_VER=$(DLL_VERD) OPT="-D__CLEANUP_C -g -O0" $(GCD_INLINED_STAMP) + +GCE-inlined: + $(MAKE) CC=$(CXX) XOPT="-DPTW32_BUILD_INLINED" CLEANUP=-D__CLEANUP_CXX XC_FLAGS="$(GCE_CFLAGS)" OBJ="$(DLL_INLINED_OBJS)" $(GCE_INLINED_STAMP) + +GCE-inlined-debug: + $(MAKE) CC=$(CXX) XOPT="-DPTW32_BUILD_INLINED" CLEANUP=-D__CLEANUP_CXX XC_FLAGS="$(GCE_CFLAGS)" OBJ="$(DLL_INLINED_OBJS)" DLL_VER=$(DLL_VERD) OPT="-D__CLEANUP_CXX -g -O0" $(GCED_INLINED_STAMP) + +GC-static: + $(MAKE) XOPT="-DPTW32_BUILD_INLINED -DPTW32_STATIC_LIB" CLEANUP=-D__CLEANUP_C XC_FLAGS="$(GC_CFLAGS)" OBJ="$(DLL_INLINED_OBJS)" $(GC_STATIC_STAMP) + +GC-static-debug: + $(MAKE) XOPT="-DPTW32_BUILD_INLINED -DPTW32_STATIC_LIB" CLEANUP=-D__CLEANUP_C XC_FLAGS="$(GC_CFLAGS)" OBJ="$(DLL_INLINED_OBJS)" DLL_VER=$(DLL_VERD) OPT="-D__CLEANUP_C -g -O0" $(GCD_STATIC_STAMP) + +tests: + @ cd tests + @ $(MAKE) auto + +%.pre: %.c + $(CC) -E -o $@ $(CFLAGS) $^ + +%.s: %.c + $(CC) -c $(CFLAGS) -DPTW32_BUILD_INLINED -Wa,-ahl $^ > $@ + +%.o: %.rc + $(RC) $(RCFLAGS) $(CLEANUP) -o $@ -i $< + +.SUFFIXES: .dll .rc .c .o + +.c.o:; $(CC) -c -o $@ $(CFLAGS) $(XC_FLAGS) $< + + +$(GC_DLL) $(GCD_DLL): $(DLL_OBJS) + $(CC) $(OPT) -shared -o $(GC_DLL) $(DLL_OBJS) $(LFLAGS) + $(DLLTOOL) -z pthread.def $(DLL_OBJS) + $(DLLTOOL) -k --dllname $@ --output-lib $(GC_LIB) --def $(PTHREAD_DEF) + +$(GCE_DLL): $(DLL_OBJS) + $(CC) $(OPT) -mthreads -shared -o $(GCE_DLL) $(DLL_OBJS) $(LFLAGS) + $(DLLTOOL) -z pthread.def $(DLL_OBJS) + $(DLLTOOL) -k --dllname $@ --output-lib $(GCE_LIB) --def $(PTHREAD_DEF) + +$(GC_INLINED_STAMP) $(GCD_INLINED_STAMP): $(DLL_INLINED_OBJS) + $(CC) $(OPT) $(XOPT) -shared -o $(GC_DLL) $(DLL_INLINED_OBJS) $(LFLAGS) + $(DLLTOOL) -z pthread.def $(DLL_INLINED_OBJS) + $(DLLTOOL) -k --dllname $(GC_DLL) --output-lib $(GC_LIB) --def $(PTHREAD_DEF) + echo touched > $(GC_INLINED_STAMP) + +$(GCE_INLINED_STAMP) $(GCED_INLINED_STAMP): $(DLL_INLINED_OBJS) + $(CC) $(OPT) $(XOPT) -mthreads -shared -o $(GCE_DLL) $(DLL_INLINED_OBJS) $(LFLAGS) + $(DLLTOOL) -z pthread.def $(DLL_INLINED_OBJS) + $(DLLTOOL) -k --dllname $(GCE_DLL) --output-lib $(GCE_LIB) --def $(PTHREAD_DEF) + echo touched > $(GCE_INLINED_STAMP) + +$(GC_STATIC_STAMP) $(GCD_STATIC_STAMP): $(DLL_INLINED_OBJS) + $(RM) $(GC_LIB) + $(AR) -rv $(GC_LIB) $(DLL_INLINED_OBJS) + $(RANLIB) $(GC_LIB) + echo touched > $(GC_STATIC_STAMP) + +clean: + -$(RM) *~ + -$(RM) *.i + -$(RM) *.s + -$(RM) *.o + -$(RM) *.obj + -$(RM) *.exe + -$(RM) $(PTHREAD_DEF) + +realclean: clean + -$(RM) $(GC_LIB) + -$(RM) $(GCE_LIB) + -$(RM) $(GC_DLL) + -$(RM) $(GCE_DLL) + -$(RM) $(GC_INLINED_STAMP) + -$(RM) $(GCE_INLINED_STAMP) + -$(RM) $(GC_STATIC_STAMP) + -$(RM) $(GCD_LIB) + -$(RM) $(GCED_LIB) + -$(RM) $(GCD_DLL) + -$(RM) $(GCED_DLL) + -$(RM) $(GCD_INLINED_STAMP) + -$(RM) $(GCED_INLINED_STAMP) + -$(RM) $(GCD_STATIC_STAMP) + +attr.o: attr.c $(ATTR_SRCS) $(INCL) +barrier.o: barrier.c $(BARRIER_SRCS) $(INCL) +cancel.o: cancel.c $(CANCEL_SRCS) $(INCL) +condvar.o: condvar.c $(CONDVAR_SRCS) $(INCL) +exit.o: exit.c $(EXIT_SRCS) $(INCL) +misc.o: misc.c $(MISC_SRCS) $(INCL) +mutex.o: mutex.c $(MUTEX_SRCS) $(INCL) +nonportable.o: nonportable.c $(NONPORTABLE_SRCS) $(INCL) +private.o: private.c $(PRIVATE_SRCS) $(INCL) +rwlock.o: rwlock.c $(RWLOCK_SRCS) $(INCL) +sched.o: sched.c $(SCHED_SRCS) $(INCL) +semaphore.o: semaphore.c $(SEMAPHORE_SRCS) $(INCL) +spin.o: spin.c $(SPIN_SRCS) $(INCL) +sync.o: sync.c $(SYNC_SRCS) $(INCL) +tsd.o: tsd.c $(TSD_SRCS) $(INCL) +version.o: version.rc $(INCL) diff --git a/w32-pthreads/MAINTAINERS b/w32-pthreads/MAINTAINERS new file mode 100644 index 000000000..d253c1f69 --- /dev/null +++ b/w32-pthreads/MAINTAINERS @@ -0,0 +1,4 @@ +CVS Repository maintainers + +Ross Johnson rpj@ise.canberra.edu.au +Ben Elliston bje@cygnus.com diff --git a/w32-pthreads/Makefile b/w32-pthreads/Makefile new file mode 100644 index 000000000..472969cf9 --- /dev/null +++ b/w32-pthreads/Makefile @@ -0,0 +1,514 @@ +# This makefile is compatible with MS nmake and can be used as a +# replacement for buildlib.bat. I've changed the target from an ordinary dll +# (/LD) to a debugging dll (/LDd). +# +# The variables $DLLDEST and $LIBDEST hold the destination directories for the +# dll and the lib, respectively. Probably all that needs to change is $DEVROOT. + + +# DLL_VER: +# See pthread.h and README - This number is computed as 'current - age' +DLL_VER = 2 +DLL_VERD= $(DLL_VER)d + +DEVROOT = C:\pthreads + +DLLDEST = $(DEVROOT)\dll +LIBDEST = $(DEVROOT)\lib +HDRDEST = $(DEVROOT)\include + +DLLS = pthreadVCE$(DLL_VER).dll pthreadVSE$(DLL_VER).dll pthreadVC$(DLL_VER).dll \ + pthreadVCE$(DLL_VERD).dll pthreadVSE$(DLL_VERD).dll pthreadVC$(DLL_VERD).dll +INLINED_STAMPS = pthreadVCE$(DLL_VER).stamp pthreadVSE$(DLL_VER).stamp pthreadVC$(DLL_VER).stamp \ + pthreadVCE$(DLL_VERD).stamp pthreadVSE$(DLL_VERD).stamp pthreadVC$(DLL_VERD).stamp +STATIC_STAMPS = pthreadVCE$(DLL_VER).static pthreadVSE$(DLL_VER).static pthreadVC$(DLL_VER).static \ + pthreadVCE$(DLL_VERD).static pthreadVSE$(DLL_VERD).static pthreadVC$(DLL_VERD).static + +CC = cl +CPPFLAGS = /I. /DHAVE_PTW32_CONFIG_H +XCFLAGS = /W3 /MD /nologo +CFLAGS = /O2 /Ob2 $(XCFLAGS) +CFLAGSD = /Z7 $(XCFLAGS) + +# Uncomment this if config.h defines RETAIN_WSALASTERROR +#XLIBS = wsock32.lib + +# Default cleanup style +CLEANUP = __CLEANUP_C + +# C++ Exceptions +VCEFLAGS = /EHsc /TP $(CPPFLAGS) $(CFLAGS) +VCEFLAGSD = /EHsc /TP $(CPPFLAGS) $(CFLAGSD) +#Structured Exceptions +VSEFLAGS = $(CPPFLAGS) $(CFLAGS) +VSEFLAGSD = $(CPPFLAGS) $(CFLAGSD) +#C cleanup code +VCFLAGS = $(CPPFLAGS) $(CFLAGS) +VCFLAGSD = $(CPPFLAGS) $(CFLAGSD) + +DLL_INLINED_OBJS = \ + pthread.obj \ + version.res + +# Aggregate modules for inlinability +DLL_OBJS = \ + attr.obj \ + barrier.obj \ + cancel.obj \ + cleanup.obj \ + condvar.obj \ + create.obj \ + dll.obj \ + autostatic.obj \ + errno.obj \ + exit.obj \ + fork.obj \ + global.obj \ + misc.obj \ + mutex.obj \ + nonportable.obj \ + private.obj \ + rwlock.obj \ + sched.obj \ + semaphore.obj \ + signal.obj \ + spin.obj \ + sync.obj \ + tsd.obj \ + version.res + +# Separate modules for minimising the size of statically linked images +SMALL_STATIC_OBJS = \ + pthread_attr_init.obj \ + pthread_attr_destroy.obj \ + pthread_attr_getdetachstate.obj \ + pthread_attr_setdetachstate.obj \ + pthread_attr_getstackaddr.obj \ + pthread_attr_setstackaddr.obj \ + pthread_attr_getstacksize.obj \ + pthread_attr_setstacksize.obj \ + pthread_attr_getscope.obj \ + pthread_attr_setscope.obj \ + pthread_attr_setschedpolicy.obj \ + pthread_attr_getschedpolicy.obj \ + pthread_attr_setschedparam.obj \ + pthread_attr_getschedparam.obj \ + pthread_attr_setinheritsched.obj \ + pthread_attr_getinheritsched.obj \ + pthread_barrier_init.obj \ + pthread_barrier_destroy.obj \ + pthread_barrier_wait.obj \ + pthread_barrierattr_init.obj \ + pthread_barrierattr_destroy.obj \ + pthread_barrierattr_setpshared.obj \ + pthread_barrierattr_getpshared.obj \ + pthread_setcancelstate.obj \ + pthread_setcanceltype.obj \ + pthread_testcancel.obj \ + pthread_cancel.obj \ + cleanup.obj \ + pthread_condattr_destroy.obj \ + pthread_condattr_getpshared.obj \ + pthread_condattr_init.obj \ + pthread_condattr_setpshared.obj \ + pthread_cond_destroy.obj \ + pthread_cond_init.obj \ + pthread_cond_signal.obj \ + pthread_cond_wait.obj \ + create.obj \ + dll.obj \ + autostatic.obj \ + errno.obj \ + pthread_exit.obj \ + fork.obj \ + global.obj \ + pthread_mutex_init.obj \ + pthread_mutex_destroy.obj \ + pthread_mutexattr_init.obj \ + pthread_mutexattr_destroy.obj \ + pthread_mutexattr_getpshared.obj \ + pthread_mutexattr_setpshared.obj \ + pthread_mutexattr_settype.obj \ + pthread_mutexattr_gettype.obj \ + pthread_mutexattr_setrobust.obj \ + pthread_mutexattr_getrobust.obj \ + pthread_mutex_lock.obj \ + pthread_mutex_timedlock.obj \ + pthread_mutex_unlock.obj \ + pthread_mutex_trylock.obj \ + pthread_mutex_consistent.obj \ + pthread_mutexattr_setkind_np.obj \ + pthread_mutexattr_getkind_np.obj \ + pthread_getw32threadhandle_np.obj \ + pthread_getunique_np.obj \ + pthread_delay_np.obj \ + pthread_num_processors_np.obj \ + pthread_win32_attach_detach_np.obj \ + pthread_equal.obj \ + pthread_getconcurrency.obj \ + pthread_once.obj \ + pthread_self.obj \ + pthread_setconcurrency.obj \ + pthread_rwlock_init.obj \ + pthread_rwlock_destroy.obj \ + pthread_rwlockattr_init.obj \ + pthread_rwlockattr_destroy.obj \ + pthread_rwlockattr_getpshared.obj \ + pthread_rwlockattr_setpshared.obj \ + pthread_rwlock_rdlock.obj \ + pthread_rwlock_wrlock.obj \ + pthread_rwlock_unlock.obj \ + pthread_rwlock_tryrdlock.obj \ + pthread_rwlock_trywrlock.obj \ + pthread_setschedparam.obj \ + pthread_getschedparam.obj \ + pthread_timechange_handler_np.obj \ + ptw32_is_attr.obj \ + ptw32_processInitialize.obj \ + ptw32_processTerminate.obj \ + ptw32_threadStart.obj \ + ptw32_threadDestroy.obj \ + ptw32_tkAssocCreate.obj \ + ptw32_tkAssocDestroy.obj \ + ptw32_callUserDestroyRoutines.obj \ + ptw32_timespec.obj \ + ptw32_throw.obj \ + ptw32_getprocessors.obj \ + ptw32_calloc.obj \ + ptw32_new.obj \ + ptw32_reuse.obj \ + ptw32_rwlock_check_need_init.obj \ + ptw32_cond_check_need_init.obj \ + ptw32_mutex_check_need_init.obj \ + ptw32_semwait.obj \ + ptw32_relmillisecs.obj \ + ptw32_MCS_lock.obj \ + sched_get_priority_max.obj \ + sched_get_priority_min.obj \ + sched_setscheduler.obj \ + sched_getscheduler.obj \ + sched_yield.obj \ + sem_init.obj \ + sem_destroy.obj \ + sem_trywait.obj \ + sem_timedwait.obj \ + sem_wait.obj \ + sem_post.obj \ + sem_post_multiple.obj \ + sem_getvalue.obj \ + sem_open.obj \ + sem_close.obj \ + sem_unlink.obj \ + signal.obj \ + pthread_kill.obj \ + ptw32_spinlock_check_need_init.obj \ + pthread_spin_init.obj \ + pthread_spin_destroy.obj \ + pthread_spin_lock.obj \ + pthread_spin_unlock.obj \ + pthread_spin_trylock.obj \ + pthread_detach.obj \ + pthread_join.obj \ + pthread_key_create.obj \ + pthread_key_delete.obj \ + pthread_setspecific.obj \ + pthread_getspecific.obj \ + w32_CancelableWait.obj \ + version.res + +INCL = config.h implement.h semaphore.h pthread.h need_errno.h + +ATTR_SRCS = \ + pthread_attr_init.c \ + pthread_attr_destroy.c \ + pthread_attr_getdetachstate.c \ + pthread_attr_setdetachstate.c \ + pthread_attr_getstackaddr.c \ + pthread_attr_setstackaddr.c \ + pthread_attr_getstacksize.c \ + pthread_attr_setstacksize.c \ + pthread_attr_getscope.c \ + pthread_attr_setscope.c + +BARRIER_SRCS = \ + pthread_barrier_init.c \ + pthread_barrier_destroy.c \ + pthread_barrier_wait.c \ + pthread_barrierattr_init.c \ + pthread_barrierattr_destroy.c \ + pthread_barrierattr_setpshared.c \ + pthread_barrierattr_getpshared.c + +CANCEL_SRCS = \ + pthread_setcancelstate.c \ + pthread_setcanceltype.c \ + pthread_testcancel.c \ + pthread_cancel.c + +CONDVAR_SRCS = \ + ptw32_cond_check_need_init.c \ + pthread_condattr_destroy.c \ + pthread_condattr_getpshared.c \ + pthread_condattr_init.c \ + pthread_condattr_setpshared.c \ + pthread_cond_destroy.c \ + pthread_cond_init.c \ + pthread_cond_signal.c \ + pthread_cond_wait.c + +EXIT_SRCS = \ + pthread_exit.c + +MISC_SRCS = \ + pthread_equal.c \ + pthread_getconcurrency.c \ + pthread_kill.c \ + pthread_once.c \ + pthread_self.c \ + pthread_setconcurrency.c \ + ptw32_calloc.c \ + ptw32_MCS_lock.c \ + ptw32_new.c \ + ptw32_reuse.c \ + ptw32_relmillisecs.c \ + w32_CancelableWait.c + +MUTEX_SRCS = \ + ptw32_mutex_check_need_init.c \ + pthread_mutex_init.c \ + pthread_mutex_destroy.c \ + pthread_mutexattr_init.c \ + pthread_mutexattr_destroy.c \ + pthread_mutexattr_getpshared.c \ + pthread_mutexattr_setpshared.c \ + pthread_mutexattr_settype.c \ + pthread_mutexattr_gettype.c \ + pthread_mutexattr_setrobust.c \ + pthread_mutexattr_getrobust.c \ + pthread_mutex_lock.c \ + pthread_mutex_timedlock.c \ + pthread_mutex_unlock.c \ + pthread_mutex_trylock.c \ + pthread_mutex_consistent.c + +NONPORTABLE_SRCS = \ + pthread_mutexattr_setkind_np.c \ + pthread_mutexattr_getkind_np.c \ + pthread_getw32threadhandle_np.c \ + pthread_getunique_np.c \ + pthread_delay_np.c \ + pthread_num_processors_np.c \ + pthread_win32_attach_detach_np.c \ + pthread_timechange_handler_np.c + +PRIVATE_SRCS = \ + ptw32_is_attr.c \ + ptw32_processInitialize.c \ + ptw32_processTerminate.c \ + ptw32_threadStart.c \ + ptw32_threadDestroy.c \ + ptw32_tkAssocCreate.c \ + ptw32_tkAssocDestroy.c \ + ptw32_callUserDestroyRoutines.c \ + ptw32_semwait.c \ + ptw32_timespec.c \ + ptw32_throw.c \ + ptw32_getprocessors.c + +RWLOCK_SRCS = \ + ptw32_rwlock_check_need_init.c \ + ptw32_rwlock_cancelwrwait.c \ + pthread_rwlock_init.c \ + pthread_rwlock_destroy.c \ + pthread_rwlockattr_init.c \ + pthread_rwlockattr_destroy.c \ + pthread_rwlockattr_getpshared.c \ + pthread_rwlockattr_setpshared.c \ + pthread_rwlock_rdlock.c \ + pthread_rwlock_timedrdlock.c \ + pthread_rwlock_wrlock.c \ + pthread_rwlock_timedwrlock.c \ + pthread_rwlock_unlock.c \ + pthread_rwlock_tryrdlock.c \ + pthread_rwlock_trywrlock.c + +SCHED_SRCS = \ + pthread_attr_setschedpolicy.c \ + pthread_attr_getschedpolicy.c \ + pthread_attr_setschedparam.c \ + pthread_attr_getschedparam.c \ + pthread_attr_setinheritsched.c \ + pthread_attr_getinheritsched.c \ + pthread_setschedparam.c \ + pthread_getschedparam.c \ + sched_get_priority_max.c \ + sched_get_priority_min.c \ + sched_setscheduler.c \ + sched_getscheduler.c \ + sched_yield.c + +SEMAPHORE_SRCS = \ + sem_init.c \ + sem_destroy.c \ + sem_trywait.c \ + sem_timedwait.c \ + sem_wait.c \ + sem_post.c \ + sem_post_multiple.c \ + sem_getvalue.c \ + sem_open.c \ + sem_close.c \ + sem_unlink.c + +SPIN_SRCS = \ + ptw32_spinlock_check_need_init.c \ + pthread_spin_init.c \ + pthread_spin_destroy.c \ + pthread_spin_lock.c \ + pthread_spin_unlock.c \ + pthread_spin_trylock.c + +SYNC_SRCS = \ + pthread_detach.c \ + pthread_join.c + +TSD_SRCS = \ + pthread_key_create.c \ + pthread_key_delete.c \ + pthread_setspecific.c \ + pthread_getspecific.c + + +help: + @ echo Run one of the following command lines: + @ echo nmake clean VCE (to build the MSVC dll with C++ exception handling) + @ echo nmake clean VSE (to build the MSVC dll with structured exception handling) + @ echo nmake clean VC (to build the MSVC dll with C cleanup code) + @ echo nmake clean VCE-inlined (to build the MSVC inlined dll with C++ exception handling) + @ echo nmake clean VSE-inlined (to build the MSVC inlined dll with structured exception handling) + @ echo nmake clean VC-inlined (to build the MSVC inlined dll with C cleanup code) + @ echo nmake clean VC-static (to build the MSVC static lib with C cleanup code) + @ echo nmake clean VCE-debug (to build the debug MSVC dll with C++ exception handling) + @ echo nmake clean VSE-debug (to build the debug MSVC dll with structured exception handling) + @ echo nmake clean VC-debug (to build the debug MSVC dll with C cleanup code) + @ echo nmake clean VCE-inlined-debug (to build the debug MSVC inlined dll with C++ exception handling) + @ echo nmake clean VSE-inlined-debug (to build the debug MSVC inlined dll with structured exception handling) + @ echo nmake clean VC-inlined-debug (to build the debug MSVC inlined dll with C cleanup code) + @ echo nmake clean VC-static-debug (to build the debug MSVC static lib with C cleanup code) + +all: + @ $(MAKE) /E clean VCE-inlined + @ $(MAKE) /E clean VSE-inlined + @ $(MAKE) /E clean VC-inlined + @ $(MAKE) /E clean VCE-inlined-debug + @ $(MAKE) /E clean VSE-inlined-debug + @ $(MAKE) /E clean VC-inlined-debug + +VCE: + @ $(MAKE) /E /nologo EHFLAGS="$(VCEFLAGS)" CLEANUP=__CLEANUP_CXX pthreadVCE$(DLL_VER).dll + +VCE-debug: + @ $(MAKE) /E /nologo EHFLAGS="$(VCEFLAGSD)" CLEANUP=__CLEANUP_CXX pthreadVCE$(DLL_VERD).dll + +VSE: + @ $(MAKE) /E /nologo EHFLAGS="$(VSEFLAGS)" CLEANUP=__CLEANUP_SEH pthreadVSE$(DLL_VER).dll + +VSE-debug: + @ $(MAKE) /E /nologo EHFLAGS="$(VSEFLAGSD)" CLEANUP=__CLEANUP_SEH pthreadVSE$(DLL_VERD).dll + +VC: + @ $(MAKE) /E /nologo EHFLAGS="$(VCFLAGS)" CLEANUP=__CLEANUP_C pthreadVC$(DLL_VER).dll + +VC-debug: + @ $(MAKE) /E /nologo EHFLAGS="$(VCFLAGSD)" CLEANUP=__CLEANUP_C pthreadVC$(DLL_VERD).dll + +# +# The so-called inlined DLL is just a single translation unit with +# inlining optimisation turned on. +# +VCE-inlined: + @ $(MAKE) /E /nologo EHFLAGS="$(VCEFLAGS) /DPTW32_BUILD_INLINED" CLEANUP=__CLEANUP_CXX pthreadVCE$(DLL_VER).stamp + +VCE-inlined-debug: + @ $(MAKE) /E /nologo EHFLAGS="$(VCEFLAGSD) /DPTW32_BUILD_INLINED" CLEANUP=__CLEANUP_CXX pthreadVCE$(DLL_VERD).stamp + +VSE-inlined: + @ $(MAKE) /E /nologo EHFLAGS="$(VSEFLAGS) /DPTW32_BUILD_INLINED" CLEANUP=__CLEANUP_SEH pthreadVSE$(DLL_VER).stamp + +VSE-inlined-debug: + @ $(MAKE) /E /nologo EHFLAGS="$(VSEFLAGSD) /DPTW32_BUILD_INLINED" CLEANUP=__CLEANUP_SEH pthreadVSE$(DLL_VERD).stamp + +VC-inlined: + @ $(MAKE) /E /nologo EHFLAGS="$(VCFLAGS) /DPTW32_BUILD_INLINED" CLEANUP=__CLEANUP_C pthreadVC$(DLL_VER).stamp + +VC-inlined-debug: + @ $(MAKE) /E /nologo EHFLAGS="$(VCFLAGSD) /DPTW32_BUILD_INLINED" CLEANUP=__CLEANUP_C pthreadVC$(DLL_VERD).stamp + +VC-static: + @ $(MAKE) /E /nologo EHFLAGS="$(VCFLAGS) /DPTW32_BUILD_INLINED /DPTW32_STATIC_LIB" CLEANUP=__CLEANUP_C pthreadVC$(DLL_VER).static + +VC-static-debug: + @ $(MAKE) /E /nologo EHFLAGS="$(VCFLAGSD) /DPTW32_BUILD_INLINED /DPTW32_STATIC_LIB" CLEANUP=__CLEANUP_C pthreadVC$(DLL_VERD).static + +realclean: clean + if exist pthread*.dll del pthread*.dll + if exist pthread*.lib del pthread*.lib + if exist *.manifest del *.manifest + if exist *.stamp del *.stamp + +clean: + if exist *.obj del *.obj + if exist *.def del *.def + if exist *.ilk del *.ilk + if exist *.pdb del *.pdb + if exist *.exp del *.exp + if exist *.map del *.map + if exist *.o del *.o + if exist *.i del *.i + if exist *.res del *.res + + +install: + copy pthread*.dll $(DLLDEST) + copy pthread*.lib $(LIBDEST) + copy pthread.h $(HDRDEST) + copy sched.h $(HDRDEST) + copy semaphore.h $(HDRDEST) + +$(DLLS): $(DLL_OBJS) + $(CC) /LDd /Zi /nologo $(DLL_OBJS) /link /implib:$*.lib $(XLIBS) /out:$@ + +$(INLINED_STAMPS): $(DLL_INLINED_OBJS) + $(CC) /LDd /Zi /nologo $(DLL_INLINED_OBJS) /link /implib:$*.lib $(XLIBS) /out:$*.dll + +$(STATIC_STAMPS): $(DLL_INLINED_OBJS) + if exist $*.lib del $*.lib + lib $(DLL_INLINED_OBJS) /out:$*.lib + +.c.obj: + $(CC) $(EHFLAGS) /D$(CLEANUP) -c $< + +# TARGET_CPU is an environment variable set by Visual Studio Command Prompt +# as provided by the SDK +.rc.res: + rc /dPTW32_ARCH$(TARGET_CPU) /dPTW32_RC_MSC /d$(CLEANUP) $< + +.c.i: + $(CC) /P /O2 /Ob1 $(VCFLAGS) $< + +attr.obj: attr.c $(ATTR_SRCS) $(INCL) +barrier.obj: barrier.c $(BARRIER_SRCS) $(INCL) +cancel.obj: cancel.c $(CANCEL_SRCS) $(INCL) +condvar.obj: condvar.c $(CONDVAR_SRCS) $(INCL) +exit.obj: exit.c $(EXIT_SRCS) $(INCL) +misc.obj: misc.c $(MISC_SRCS) $(INCL) +mutex.obj: mutex.c $(MUTEX_SRCS) $(INCL) +nonportable.obj: nonportable.c $(NONPORTABLE_SRCS) $(INCL) +private.obj: private.c $(PRIVATE_SRCS) $(INCL) +rwlock.obj: rwlock.c $(RWLOCK_SRCS) $(INCL) +sched.obj: sched.c $(SCHED_SRCS) $(INCL) +semaphore.obj: semaphore.c $(SEMAPHORE_SRCS) $(INCL) +spin.obj: spin.c $(SPIN_SRCS) $(INCL) +sync.obj: sync.c $(SYNC_SRCS) $(INCL) +tsd.obj: tsd.c $(TSD_SRCS) $(INCL) +version.res: version.rc $(INCL) diff --git a/w32-pthreads/NEWS b/w32-pthreads/NEWS new file mode 100644 index 000000000..d1b789635 --- /dev/null +++ b/w32-pthreads/NEWS @@ -0,0 +1,1241 @@ +RELEASE 2.9.0 +------------- +(2012-05-25) + +General +------- +New bug fixes in this release since 2.8.0 have NOT been applied to the +1.x.x series. + +Some changes post 2011-02-26 in CVS may not be compatible with pre +Windows 2000 systems. + +Use of other than the "C" version of the library is now discouraged. +That is, the "C++" version fails some tests and does not provide any +additional functionality. + +Testing and verification +------------------------ +This version has been tested on SMP architecture (Intel x64 Hex Core) +by completing the included test suite, stress and bench tests. + +New Features +------------ +DLL properties now properly includes the target architecture, i.e. +right-click on the file pthreadVC2.dll in explorer and choose the Detail +tab will show the compiler and architecture in the description field, e.g. +"MS C x64" or "MS C x86". +- Ross Johnson + +(MSC and GNU builds) The statically linked library now automatically +initialises and cleans up on program start/exit, i.e. statically linked +applications need not call the routines pthread_win32_process_attach_np() +and pthread_win32_process_detach_np() explicitly. The per-thread routine +pthread_win32_thread_detach_np() is also called at program exit to cleanup +POSIX resources acquired by the primary Windows native thread, if I (RJ) +understand the process correctly. Other Windows native threads that call +POSIX API routines may need to call the thread detach routine on thread +exit if the application depends on reclaimed POSIX resources or running +POSIX TSD (TLS) destructors. +See README.NONPORTABLE for descriptions of these routines. +- Ramiro Polla + +Robust mutexes are implemented within the PROCESS_PRIVATE scope. NOTE that +pthread_mutex_* functions may return different error codes for robust +mutexes than they otherwise do in normal usage, e.g. pthread_mutex_unlock +is required to check ownership for all mutex types when the mutex is +robust, whereas this does not occur for the "normal" non-robust mutex type. +- Ross Johnson + +pthread_getunique_np is implemented for source level compatibility +with some other implementations. This routine returns a 64 bit +sequence number that is uniquely associated with a thread. It can be +used by applications to order or hash POSIX thread handles. +- Ross Johnson + +Bug fixes +--------- +Many more changes for 64 bit systems. +- Kai Tietz + +Various modifications and fixes to build and test for WinCE. +- Marcel Ruff, Sinan Kaya + +Fix pthread_cond_destroy() - should not be a cancellation point. Other +minor build problems fixed. +- Romano Paolo Tenca + +Remove potential deadlock condition from pthread_cond_destroy(). +- Eric Berge + +Various modifications to build and test for Win64. +- Kip Streithorst + +Various fixes to the QueueUserAPCEx async cancellation helper DLL +(this is a separate download) and pthreads code cleanups. +- Sebastian Gottschalk + +Removed potential NULL pointer reference. +- Robert Kindred + +Removed the requirement that applications restrict the number of threads +calling pthread_barrier_wait to just the barrier count. Also reduced the +contention between barrier_wait and barrier_destroy. This change will have +slowed barriers down slightly but halves the number of semaphores consumed +per barrier to one. +- Ross Johnson + +Fixed a handle leak in sched_[gs]etscheduler. +- Mark Pizzolato + +Removed all of the POSIX re-entrant function compatibility macros from pthread.h. +Some were simply not semanticly correct. +- Igor Lubashev + +Threads no longer attempt to pass uncaught exceptions out of thread scope (C++ +and SEH builds only). Uncaught exceptions now cause the thread to exit with +the return code PTHREAD_CANCELED. +- Ross Johnson + +Lots of casting fixes particularly for x64, Interlocked fixes and reworking +for x64. +- Daniel Richard G., John Kamp + +Other changes +------------- +Dependence on the winsock library is now discretionary via +#define RETAIN_WSALASTERROR in config.h. It is undefined by default unless +WINCE is defined (because RJ is unsure of the dependency there). +- Ramiro Polla + +Several static POSIX mutexes used for internal management were replaced by +MCS queue-based locks to reduce resource consumption, in particular use of Win32 +objects. +- Ross Johnson + +For security, the QuserEx.dll if used must now be installed in the Windows System +folder. +- Ross Johnson + +New tests +--------- +robust[1-5].c - Robust mutexes +sequence1.c - per-thread unique sequence numbers + +Modified tests and benchtests +----------------------------- +All mutex*.c tests wherever appropriate have been modified to also test +robust mutexes under the same conditions. +Added robust mutex benchtests to benchtest*.c wherever appropriate. + + +RELEASE 2.8.0 +------------- +(2006-12-22) + +General +------- +New bug fixes in this release since 2.7.0 have not been applied to the +version 1.x.x series. It is probably time to drop version 1. + +Testing and verification +------------------------ +This release has not yet been tested on SMP architechtures. All tests pass +on a uni-processor system. + +Bug fixes +--------- +Sem_destroy could return EBUSY even though no threads were waiting on the +semaphore. Other races around invalidating semaphore structs (internally) +have been removed as well. + +New tests +--------- +semaphore5.c - tests the bug fix referred to above. + + +RELEASE 2.7.0 +------------- +(2005-06-04) + +General +------- +All new features in this release have been back-ported in release 1.11.0, +including the incorporation of MCS locks in pthread_once, however, versions +1 and 2 remain incompatible even though they are now identical in +performance and functionality. + +Testing and verification +------------------------ +This release has been tested (passed the test suite) on both uni-processor +and multi-processor systems. +- Tim Theisen + +Bug fixes +--------- +Pthread_once has been re-implemented to remove priority boosting and other +complexity to improve robustness. Races for Win32 handles that are not +recycle-unique have been removed. The general form of pthread_once is now +the same as that suggested earlier by Alexander Terekhov, but instead of the +'named mutex', a queue-based lock has been implemented which has the required +properties of dynamic self initialisation and destruction. This lock is also +efficient. The ABI is unaffected in as much as the size of pthread_once_t has +not changed and PTHREAD_ONCE_INIT has not changed, however, applications that +peek inside pthread_once_t, which is supposed to be opaque, will break. +- Vladimir Kliatchko + +New features +------------ +* Support for Mingw cross development tools added to GNUmakefile. +Mingw cross tools allow building the libraries on Linux. +- Mikael Magnusson + + +RELEASE 2.6.0 +------------- +(2005-05-19) + +General +------- +All of the bug fixes and new features in this release have been +back-ported in release 1.10.0. + +Testing and verification +------------------------ +This release has been tested (passed the test suite) on both uni-processor +and multi-processor systems. Thanks to Tim Theisen at TomoTherapy for +exhaustively running the MP tests and for providing crutial observations +and data when faults are detected. + +Bugs fixed +---------- + +* pthread_detach() now reclaims remaining thread resources if called after +the target thread has terminated. Previously, this routine did nothing in +this case. + +New tests +--------- + +* detach1.c - tests that pthread_detach properly invalidates the target +thread, which indicates that the thread resources have been reclaimed. + + +RELEASE 2.5.0 +------------- +(2005-05-09) + +General +------- + +The package now includes a reference documentation set consisting of +HTML formatted Unix-style manual pages that have been edited for +consistency with Pthreads-w32. The set can also be read online at: +http://sources.redhat.com/pthreads-win32/manual/index.html + +Thanks again to Tim Theisen for running the test suite pre-release +on an MP system. + +All of the bug fixes and new features in this release have been +back-ported in release 1.9.0. + +Bugs fixed +---------- + +* Thread Specific Data (TSD) key management has been ammended to +eliminate a source of (what was effectively) resource leakage (a HANDLE +plus memory for each key destruct routine/thread association). This was +not a true leak because these resources were eventually reclaimed when +pthread_key_delete was run AND each thread referencing the key had exited. +The problem was that these two conditions are often not met until very +late, and often not until the process is about to exit. + +The ammended implementation avoids the need for the problematic HANDLE +and reclaims the memory as soon as either the key is deleted OR the +thread exits, whichever is first. + +Thanks to Richard Hughes at Aculab for identifying and locating the leak. + +* TSD key destructors are now processed up to PTHREAD_DESTRUCTOR_ITERATIONS +times instead of just once. PTHREAD_DESTRUCTOR_ITERATIONS has been +defined in pthread.h for some time but not used. + +* Fix a semaphore accounting race between sem_post/sem_post_multiple +and sem_wait cancellation. This is the same issue as with +sem_timedwait that was fixed in the last release. + +* sem_init, sem_post, and sem_post_multiple now check that the +semaphore count never exceeds _POSIX_SEM_VALUE_MAX. + +* Although sigwait() is nothing more than a no-op, it should at least +be a cancellation point to be consistent with the standard. + +New tests +--------- + +* stress1.c - attempts to expose problems in condition variable +and semaphore timed wait logic. This test was inspired by Stephan +Mueller's sample test code used to identify the sem_timedwait bug +from the last release. It's not a part of the regular test suite +because it can take awhile to run. To run it: +nmake clean VC-stress + +* tsd2.c - tests that key destructors are re-run if the tsd key value is +not NULL after the destructor routine has run. Also tests that +pthread_setspecific() and pthread_getspecific() are callable from +destructors. + + +RELEASE 2.4.0 +------------- +(2005-04-26) + +General +------- + +There is now no plan to release a version 3.0.0 to fix problems in +pthread_once(). Other possible implementations of pthread_once +will still be investigated for a possible future release in an attempt +to reduce the current implementation's complexity. + +All of the bug fixes and new features in this release have been +back-ported for release 1.8.0. + +Bugs fixed +---------- + +* Fixed pthread_once race (failures on an MP system). Thanks to +Tim Theisen for running exhaustive pre-release testing on his MP system +using a range of compilers: + VC++ 6 + VC++ 7.1 + Intel C++ version 8.0 +All tests passed. +Some minor speed improvements were also done. + +* Fix integer overrun error in pthread_mutex_timedlock() - missed when +sem_timedwait() was fixed in release 2.2.0. This routine no longer returns +ENOTSUP when NEED_SEM is defined - it is supported (NEED_SEM is only +required for WinCE versions prior to 3.0). + +* Fix timeout bug in sem_timedwait(). +- Thanks to Stephan Mueller for reporting, providing diagnostic output +and test code. + +* Fix several problems in the NEED_SEM conditionally included code. +NEED_SEM included code is provided for systems that don't implement W32 +semaphores, such as WinCE prior to version 3.0. An alternate implementation +of POSIX semaphores is built using W32 events for these systems when +NEED_SEM is defined. This code has been completely rewritten in this +release to reuse most of the default POSIX semaphore code, and particularly, +to implement all of the sem_* routines supported by pthreads-win32. Tim +Theisen also run the test suite over the NEED_SEM code on his MP system. All +tests passed. + +* The library now builds without errors for the Borland Builder 5.5 compiler. + +New features +------------ + +* pthread_mutex_timedlock() and all sem_* routines provided by +pthreads-win32 are now implemented for WinCE versions prior to 3.0. Those +versions did not implement W32 semaphores. Define NEED_SEM in config.h when +building the library for these systems. + +Known issues in this release +---------------------------- + +* pthread_once is too complicated - but it works as far as testing can +determine.. + +* The Borland version of the dll fails some of the tests with a memory read +exception. The cause is not yet known but a compiler bug has not been ruled +out. + + +RELEASE 2.3.0 +------------- +(2005-04-12) + +General +------- + +Release 1.7.0 is a backport of features and bug fixes new in +this release. See earlier notes under Release 2.0.0/General. + +Bugs fixed +---------- + +* Fixed pthread_once potential for post once_routine cancellation +hanging due to starvation. See comments in pthread_once.c. +Momentary priority boosting is used to ensure that, after a +once_routine is cancelled, the thread that will run the +once_routine is not starved by higher priority waiting threads at +critical times. Priority boosting occurs only AFTER a once_routine +cancellation, and is applied only to that once_control. The +once_routine is run at the thread's normal base priority. + +New tests +--------- + +* once4.c: Aggressively tests pthread_once() under realtime +conditions using threads with varying priorities. Windows' +random priority boosting does not occur for threads with realtime +priority levels. + + +RELEASE 2.2.0 +------------- +(2005-04-04) + +General +------- + +* Added makefile targets to build static link versions of the library. +Both MinGW and MSVC. Please note that this does not imply any change +to the LGPL licensing, which still imposes psecific conditions on +distributing software that has been statically linked with this library. + +* There is a known bug in pthread_once(). Cancellation of the init_routine +exposes a potential starvation (i.e. deadlock) problem if a waiting thread +has a higher priority than the initting thread. This problem will be fixed +in version 3.0.0 of the library. + +Bugs fixed +---------- + +* Fix integer overrun error in sem_timedwait(). +Kevin Lussier + +* Fix preprocessor directives for static linking. +Dimitar Panayotov + + +RELEASE 2.1.0 +------------- +(2005-03-16) + +Bugs fixed +---------- + +* Reverse change to pthread_setcancelstate() in 2.0.0. + + +RELEASE 2.0.0 +------------- +(2005-03-16) + +General +------- + +This release represents an ABI change and the DLL version naming has +incremented from 1 to 2, e.g. pthreadVC2.dll. + +Version 1.4.0 back-ports the new functionality included in this +release. Please distribute DLLs built from that version with updates +to applications built on pthreads-win32 version 1.x.x. + +The package naming has changed, replacing the snapshot date with +the version number + descriptive information. E.g. this +release is "pthreads-w32-2-0-0-release". + +Bugs fixed +---------- + +* pthread_setcancelstate() no longer checks for a pending +async cancel event if the library is using alertable async +cancel. See the README file (Prerequisites section) for info +on adding alertable async cancelation. + +New features +------------ + +* pthread_once() now supports init_routine cancellability. + +New tests +--------- + +* Agressively test pthread_once() init_routine cancellability. + + +SNAPSHOT 2005-03-08 +------------------- +Version 1.3.0 + +Bug reports (fixed) +------------------- + +* Implicitly created threads leave Win32 handles behind after exiting. +- Dmitrii Semii + +* pthread_once() starvation problem. +- Gottlob Frege + +New tests +--------- + +* More intense testing of pthread_once(). + + +SNAPSHOT 2005-01-25 +------------------- +Version 1.2.0 + +Bug fixes +--------- + +* Attempted acquisition of a recursive mutex could cause waiting threads +to not be woken when the mutex was released. +- Ralf Kubis + +* Various package omissions have been fixed. + + +SNAPSHOT 2005-01-03 +------------------- +Version 1.1.0 + +Bug fixes +--------- + +* Unlocking recursive or errorcheck mutexes would sometimes +unexpectedly return an EPERM error (bug introduced in +snapshot-2004-11-03). +- Konstantin Voronkov + + +SNAPSHOT 2004-11-22 +------------------- +Version 1.0.0 + +This snapshot primarily fixes the condvar bug introduced in +snapshot-2004-11-03. DLL versioning has also been included to allow +applications to runtime check the Microsoft compatible DLL version +information, and to extend the DLL naming system for ABI and major +(non-backward compatible) API changes. See the README file for details. + +Bug fixes +--------- + +* Condition variables no longer deadlock (bug introduced in +snapshot-2004-11-03). +- Alexander Kotliarov and Nicolas at saintmac + +* DLL naming extended to avoid 'DLL hell' in the future, and to +accommodate the ABI change introduced in snapshot-2004-11-03. Snapshot +2004-11-03 will be removed from FTP sites. + +New features +------------ + +* A Microsoft-style version resource has been added to the DLL for +applications that wish to check DLL compatibility at runtime. + +* Pthreads-win32 DLL naming has been extended to allow incompatible DLL +versions to co-exist in the same filesystem. See the README file for details, +but briefly: while the version information inside the DLL will change with +each release from now on, the DLL version names will only change if the new +DLL is not backward compatible with older applications. + +The versioning scheme has been borrowed from GNU Libtool, and the DLL +naming scheme is from Cygwin. Provided the Libtool-style numbering rules are +honoured, the Cygwin DLL naming scheme automatcally ensures that DLL name +changes are minimal and that applications will not load an incompatible +pthreads-win32 DLL. + +Those who use the pre-built DLLs will find that the DLL/LIB names have a new +suffix (1) in this snapshot. E.g. pthreadVC1.dll etc. + +* The POSIX thread ID reuse uniqueness feature introduced in the last snapshot +has been kept as default, but the behaviour can now be controlled when the DLL +is built to effectively switch it off. This makes the library much more +sensitive to applications that assume that POSIX thread IDs are unique, i.e. +are not strictly compliant with POSIX. See the PTW32_THREAD_ID_REUSE_INCREMENT +macro comments in config.h for details. + +Other changes +------------- +Certain POSIX macros have changed. + +These changes are intended to conform to the Single Unix Specification version 3, +which states that, if set to 0 (zero) or not defined, then applications may use +sysconf() to determine their values at runtime. Pthreads-win32 does not +implement sysconf(). + +The following macros are no longer undefined, but defined and set to -1 +(not implemented): + + _POSIX_THREAD_ATTR_STACKADDR + _POSIX_THREAD_PRIO_INHERIT + _POSIX_THREAD_PRIO_PROTECT + _POSIX_THREAD_PROCESS_SHARED + +The following macros are defined and set to 200112L (implemented): + + _POSIX_THREADS + _POSIX_THREAD_SAFE_FUNCTIONS + _POSIX_THREAD_ATTR_STACKSIZE + _POSIX_THREAD_PRIORITY_SCHEDULING + _POSIX_SEMAPHORES + _POSIX_READER_WRITER_LOCKS + _POSIX_SPIN_LOCKS + _POSIX_BARRIERS + +The following macros are defined and set to appropriate values: + + _POSIX_THREAD_THREADS_MAX + _POSIX_SEM_VALUE_MAX + _POSIX_SEM_NSEMS_MAX + PTHREAD_DESTRUCTOR_ITERATIONS + PTHREAD_KEYS_MAX + PTHREAD_STACK_MIN + PTHREAD_THREADS_MAX + + +SNAPSHOT 2004-11-03 +------------------- + +DLLs produced from this snapshot cannot be used with older applications without +recompiling the application, due to a change to pthread_t to provide unique POSIX +thread IDs. + +Although this snapshot passes the extended test suite, many of the changes are +fairly major, and some applications may show different behaviour than previously, +so adopt with care. Hopefully, any changed behaviour will be due to the library +being better at it's job, not worse. + +Bug fixes +--------- + +* pthread_create() no longer accepts NULL as the thread reference arg. +A segfault (memory access fault) will result, and no thread will be +created. + +* pthread_barrier_wait() no longer acts as a cancelation point. + +* Fix potential race condition in pthread_once() +- Tristan Savatier + +* Changes to pthread_cond_destroy() exposed some coding weaknesses in several +test suite mini-apps because pthread_cond_destroy() now returns EBUSY if the CV +is still in use. + +New features +------------ + +* Added for compatibility: +PTHREAD_RECURSIVE_MUTEX_INITIALIZER, +PTHREAD_ERRORCHECK_MUTEX_INITIALIZER, +PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP, +PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP + +* Initial support for Digital Mars compiler +- Anuj Goyal + +* Faster Mutexes. These have been been rewritten following a model provided by +Alexander Terekhov that reduces kernel space checks, and eliminates some additional +critical sections used to manage a race between timedlock expiration and unlock. +Please be aware that the new mutexes do not enforce strict absolute FIFO scheduling +of mutexes, however any out-of-order lock acquisition should be very rare. + +* Faster semaphores. Following a similar model to mutexes above, these have been +rewritten to use preliminary users space checks. + +* sem_getvalue() now returns the number of waiters. + +* The POSIX thread ID now has much stronger uniqueness characteristics. The library +garrantees not to reuse the same thread ID for at least 2^(wordsize) thread +destruction/creation cycles. + +New tests +--------- + +* semaphore4.c: Tests cancelation of the new sem_wait(). + +* semaphore4t.c: Likewise for sem_timedwait(). + +* rwlock8.c: Tests and times the slow execution paths of r/w locks, and the CVs, +mutexes, and semaphores that they're built on. + + +SNAPSHOT 2004-05-16 +------------------- + +Attempt to add Watcom to the list of compilers that can build the library. +This failed in the end due to it's non-thread-aware errno. The library +builds but the test suite fails. See README.Watcom for more details. + +Bug fixes +--------- +* Bug and memory leak in sem_init() +- Alex Blanco + +* ptw32_getprocessors() now returns CPU count of 1 for WinCE. +- James Ewing + +* pthread_cond_wait() could be canceled at a point where it should not +be cancelable. Fixed. +- Alexander Terekhov + +* sem_timedwait() had an incorrect timeout calculation. +- Philippe Di Cristo + +* Fix a memory leak left behind after threads are destroyed. +- P. van Bruggen + +New features +------------ +* Ported to AMD64. +- Makoto Kato + +* True pre-emptive asynchronous cancelation of threads. This is optional +and requires that Panagiotis E. Hadjidoukas's QueueUserAPCEx package be +installed. This package is included in the pthreads-win32 self-unpacking +Zip archive starting from this snapshot. See the README.txt file inside +the package for installation details. + +Note: If you don't use async cancelation in your application, or don't need +to cancel threads that are blocked on system resources such as network I/O, +then the default non-preemptive async cancelation is probably good enough. +However, pthreads-win32 auto-detects the availability of these components +at run-time, so you don't need to rebuild the library from source if you +change your mind later. + +All of the advice available in books and elsewhere on the undesirability +of using async cancelation in any application still stands, but this +feature is a welcome addition with respect to the library's conformance to +the POSIX standard. + +SNAPSHOT 2003-09-18 +------------------- + +Cleanup of thread priority management. In particular, setting of thread +priority now attempts to map invalid Win32 values within the range returned +by sched_get_priority_min/max() to useful values. See README.NONPORTABLE +under "Thread priority". + +Bug fixes +--------- +* pthread_getschedparam() now returns the priority given by the most recent +call to pthread_setschedparam() or established by pthread_create(), as +required by the standard. Previously, pthread_getschedparam() incorrectly +returned the running thread priority at the time of the call, which may have +been adjusted or temporarily promoted/demoted. + +* sched_get_priority_min() and sched_get_priority_max() now return -1 on error +and set errno. Previously, they incorrectly returned the error value directly. + + +SNAPSHOT 2003-09-04 +------------------- + +Bug fixes +--------- +* ptw32_cancelableWait() now allows cancelation of waiting implicit POSIX +threads. + +New test +-------- +* cancel8.c tests cancelation of Win32 threads waiting at a POSIX cancelation +point. + + +SNAPSHOT 2003-09-03 +------------------- + +Bug fixes +--------- +* pthread_self() would free the newly created implicit POSIX thread handle if +DuplicateHandle failed instead of recycle it (very unlikely). + +* pthread_exit() was neither freeing nor recycling the POSIX thread struct +for implicit POSIX threads. + +New feature - Cancelation of/by Win32 (non-POSIX) threads +--------------------------------------------------------- +Since John Bossom's original implementation, the library has allowed non-POSIX +initialised threads (Win32 threads) to call pthreads-win32 routines and +therefore interact with POSIX threads. This is done by creating an on-the-fly +POSIX thread ID for the Win32 thread that, once created, allows fully +reciprical interaction. This did not extend to thread cancelation (async or +deferred). Now it does. + +Any thread can be canceled by any other thread (Win32 or POSIX) if the former +thread's POSIX pthread_t value is known. It's TSD destructors and POSIX +cleanup handlers will be run before the thread exits with an exit code of +PTHREAD_CANCELED (retrieved with GetExitCodeThread()). + +This allows a Win32 thread to, for example, call POSIX CV routines in the same way +that POSIX threads would/should, with pthread_cond_wait() cancelability and +cleanup handlers (pthread_cond_wait() is a POSIX cancelation point). + +By adding cancelation, Win32 threads should now be able to call all POSIX +threads routines that make sense including semaphores, mutexes, condition +variables, read/write locks, barriers, spinlocks, tsd, cleanup push/pop, +cancelation, pthread_exit, scheduling, etc. + +Note that these on-the-fly 'implicit' POSIX thread IDs are initialised as detached +(not joinable) with deferred cancelation type. The POSIX thread ID will be created +automatically by any POSIX routines that need a POSIX handle (unless the routine +needs a pthread_t as a parameter of course). A Win32 thread can discover it's own +POSIX thread ID by calling pthread_self(), which will create the handle if +necessary and return the pthread_t value. + +New tests +--------- +Test the above new feature. + + +SNAPSHOT 2003-08-19 +------------------- + +This snapshot fixes some accidental corruption to new test case sources. +There are no changes to the library source code. + + +SNAPSHOT 2003-08-15 +------------------- + +Bug fixes +--------- + +* pthread.dsp now uses correct compile flags (/MD). +- Viv + +* pthread_win32_process_detach_np() fixed memory leak. +- Steven Reddie + +* pthread_mutex_destroy() fixed incorrect return code. +- Nicolas Barry + +* pthread_spin_destroy() fixed memory leak. +- Piet van Bruggen + +* Various changes to tighten arg checking, and to work with later versions of +MinGW32 and MsysDTK. + +* pthread_getschedparam() etc, fixed dangerous thread validity checking. +- Nicolas Barry + +* POSIX thread handles are now reused and their memory is not freed on thread exit. +This allows for stronger thread validity checking. + +New standard routine +-------------------- + +* pthread_kill() added to provide thread validity checking to applications. +It does not accept any non zero values for the signal arg. + +New test cases +-------------- + +* New test cases to confirm validity checking, pthread_kill(), and thread reuse. + + +SNAPSHOT 2003-05-10 +------------------- + +Bug fixes +--------- + +* pthread_mutex_trylock() now returns correct error values. +pthread_mutex_destroy() will no longer destroy a recursively locked mutex. +pthread_mutex_lock() is no longer inadvertantly behaving as a cancelation point. +- Thomas Pfaff + +* pthread_mutex_timedlock() no longer occasionally sets incorrect mutex +ownership, causing deadlocks in some applications. +- Robert Strycek and Alexander Terekhov + + +SNAPSHOT 2002-11-04 +------------------- + +Bug fixes +--------- + +* sem_getvalue() now returns the correct value under Win NT and WinCE. +- Rob Fanner + +* sem_timedwait() now uses tighter checks for unreasonable +abstime values - that would result in unexpected timeout values. + +* ptw32_cond_wait_cleanup() no longer mysteriously consumes +CV signals but may produce more spurious wakeups. It is believed +that the sem_timedwait() call is consuming a CV signal that it +shouldn't. +- Alexander Terekhov + +* Fixed a memory leak in ptw32_threadDestroy() for implicit threads. + +* Fixed potential for deadlock in pthread_cond_destroy(). +A deadlock could occur for statically declared CVs (PTHREAD_COND_INITIALIZER), +when one thread is attempting to destroy the condition variable while another +is attempting to dynamically initialize it. +- Michael Johnson + + +SNAPSHOT 2002-03-02 +------------------- + +Cleanup code default style. (IMPORTANT) +---------------------------------------------------------------------- +Previously, if not defined, the cleanup style was determined automatically +from the compiler/language, and one of the following was defined accordingly: + + __CLEANUP_SEH MSVC only + __CLEANUP_CXX C++, including MSVC++, GNU G++ + __CLEANUP_C C, including GNU GCC, not MSVC + +These defines determine the style of cleanup (see pthread.h) and, +most importantly, the way that cancelation and thread exit (via +pthread_exit) is performed (see the routine ptw32_throw() in private.c). + +In short, the exceptions versions of the library throw an exception +when a thread is canceled or exits (via pthread_exit()), which is +caught by a handler in the thread startup routine, so that the +the correct stack unwinding occurs regardless of where the thread +is when it's canceled or exits via pthread_exit(). + +In this and future snapshots, unless the build explicitly defines (e.g. +via a compiler option) __CLEANUP_SEH, __CLEANUP_CXX, or __CLEANUP_C, then +the build NOW always defaults to __CLEANUP_C style cleanup. This style +uses setjmp/longjmp in the cancelation and pthread_exit implementations, +and therefore won't do stack unwinding even when linked to applications +that have it (e.g. C++ apps). This is for consistency with most +current commercial Unix POSIX threads implementations. Compaq's TRU64 +may be an exception (no pun intended) and possible future trend. + +Although it was not clearly documented before, it is still necessary to +build your application using the same __CLEANUP_* define as was +used for the version of the library that you link with, so that the +correct parts of pthread.h are included. That is, the possible +defines require the following library versions: + + __CLEANUP_SEH pthreadVSE.dll + __CLEANUP_CXX pthreadVCE.dll or pthreadGCE.dll + __CLEANUP_C pthreadVC.dll or pthreadGC.dll + +E.g. regardless of whether your app is C or C++, if you link with +pthreadVC.lib or libpthreadGC.a, then you must define __CLEANUP_C. + + +THE POINT OF ALL THIS IS: if you have not been defining one of these +explicitly, then the defaults as described at the top of this +section were being used. + +THIS NOW CHANGES, as has been explained above, but to try to make this +clearer here's an example: + +If you were building your application with MSVC++ i.e. using C++ +exceptions and not explicitly defining one of __CLEANUP_*, then +__CLEANUP_C++ was automatically defined for you in pthread.h. +You should have been linking with pthreadVCE.dll, which does +stack unwinding. + +If you now build your application as you had before, pthread.h will now +automatically set __CLEANUP_C as the default style, and you will need to +link with pthreadVC.dll. Stack unwinding will now NOT occur when a thread +is canceled, or the thread calls pthread_exit(). + +Your application will now most likely behave differently to previous +versions, and in non-obvious ways. Most likely is that locally +instantiated objects may not be destroyed or cleaned up after a thread +is canceled. + +If you want the same behaviour as before, then you must now define +__CLEANUP_C++ explicitly using a compiler option and link with +pthreadVCE.dll as you did before. + + +WHY ARE WE MAKING THE DEFAULT STYLE LESS EXCEPTION-FRIENDLY? +Because no commercial Unix POSIX threads implementation allows you to +choose to have stack unwinding. Therefore, providing it in pthread-win32 +as a default is dangerous. We still provide the choice but unless +you consciously choose to do otherwise, your pthreads applications will +now run or crash in similar ways irrespective of the threads platform +you use. Or at least this is the hope. + + +WHY NOT REMOVE THE EXCEPTIONS VERSIONS OF THE LIBRARY ALTOGETHER? +There are a few reasons: +- because there are well respected POSIX threads people who believe + that POSIX threads implementations should be exceptions aware and + do the expected thing in that context. (There are equally respected + people who believe it should not be easily accessible, if it's there + at all, for unconditional conformity to other implementations.) +- because pthreads-win32 is one of the few implementations that has + the choice, perhaps the only freely available one, and so offers + a laboratory to people who may want to explore the effects; +- although the code will always be around somewhere for anyone who + wants it, once it's removed from the current version it will not be + nearly as visible to people who may have a use for it. + + +Source module splitting +----------------------- +In order to enable smaller image sizes to be generated +for applications that link statically with the library, +most routines have been separated out into individual +source code files. + +This is being done in such a way as to be backward compatible. +The old source files are reused to congregate the individual +routine files into larger translation units (via a bunch of +# includes) so that the compiler can still optimise wherever +possible, e.g. through inlining, which can only be done +within the same translation unit. + +It is also possible to build the entire library by compiling +the single file named "pthread.c", which just #includes all +the secondary congregation source files. The compiler +may be able to use this to do more inlining of routines. + +Although the GNU compiler is able to produce libraries with +the necessary separation (the -ffunction-segments switch), +AFAIK, the MSVC and other compilers don't have this feature. + +Finally, since I use makefiles and command-line compilation, +I don't know what havoc this reorganisation may wreak amongst +IDE project file users. You should be able to continue +using your existing project files without modification. + + +New non-portable functions +-------------------------- +pthread_num_processors_np(): + Returns the number of processors in the system that are + available to the process, as determined from the processor + affinity mask. + +pthread_timechange_handler_np(): + To improve tolerance against operator or time service initiated + system clock changes. + + This routine can be called by an application when it + receives a WM_TIMECHANGE message from the system. At present + it broadcasts all condition variables so that waiting threads + can wake up and re-evaluate their conditions and restart + their timed waits if required. + - Suggested by Alexander Terekhov + + +Platform dependence +------------------- +As Win95 doesn't provide one, the library now contains +it's own InterlockedCompareExchange() routine, which is used +whenever Windows doesn't provide it. InterlockedCompareExchange() +is used to implement spinlocks and barriers, and also in mutexes. +This routine relies on the CMPXCHG machine instruction which +is not available on i386 CPUs. This library (from snapshot +20010712 onwards) is therefore no longer supported on i386 +processor platforms. + + +New standard routines +--------------------- +For source code portability only - rwlocks cannot be process shared yet. + + pthread_rwlockattr_init() + pthread_rwlockattr_destroy() + pthread_rwlockattr_setpshared() + pthread_rwlockattr_getpshared() + +As defined in the new POSIX standard, and the Single Unix Spec version 3: + + sem_timedwait() + pthread_mutex_timedlock() - Alexander Terekhov and Thomas Pfaff + pthread_rwlock_timedrdlock() - adapted from pthread_rwlock_rdlock() + pthread_rwlock_timedwrlock() - adapted from pthread_rwlock_wrlock() + + +pthread.h no longer includes windows.h +-------------------------------------- +[Not yet for G++] + +This was done to prevent conflicts. + +HANDLE, DWORD, and NULL are temporarily defined within pthread.h if +they are not already. + + +pthread.h, sched.h and semaphore.h now use dllexport/dllimport +-------------------------------------------------------------- +Not only to avoid the need for the pthread.def file, but to +improve performance. Apparently, declaring functions with dllimport +generates a direct call to the function and avoids the overhead +of a stub function call. + +Bug fixes +--------- +* Fixed potential NULL pointer dereferences in pthread_mutexattr_init, +pthread_mutexattr_getpshared, pthread_barrierattr_init, +pthread_barrierattr_getpshared, and pthread_condattr_getpshared. +- Scott McCaskill + +* Removed potential race condition in pthread_mutex_trylock and +pthread_mutex_lock; +- Alexander Terekhov + +* The behaviour of pthread_mutex_trylock in relation to +recursive mutexes was inconsistent with commercial implementations. +Trylock would return EBUSY if the lock was owned already by the +calling thread regardless of mutex type. Trylock now increments the +recursion count and returns 0 for RECURSIVE mutexes, and will +return EDEADLK rather than EBUSY for ERRORCHECK mutexes. This is +consistent with Solaris. +- Thomas Pfaff + +* Found a fix for the library and workaround for applications for +the known bug #2, i.e. where __CLEANUP_CXX or __CLEANUP_SEH is defined. +See the "Known Bugs in this snapshot" section below. + +This could be made transparent to applications by replacing the macros that +define the current C++ and SEH versions of pthread_cleanup_push/pop +with the C version, but AFAIK cleanup handlers would not then run in the +correct sequence with destructors and exception cleanup handlers when +an exception occurs. + +* Cancelation once started in a thread cannot now be inadvertantly +double canceled. That is, once a thread begins it's cancelation run, +cancelation is disabled and a subsequent cancel request will +return an error (ESRCH). + +* errno: An incorrect compiler directive caused a local version +of errno to be used instead of the Win32 errno. Both instances are +thread-safe but applications checking errno after a pthreads-win32 +call would be wrong. Fixing this also fixed a bad compiler +option in the testsuite (/MT should have been /MD) which is +needed to link with the correct library MSVCRT.LIB. + + +SNAPSHOT 2001-07-12 +------------------- + +To be added + + +SNAPSHOT 2001-07-03 +------------------- + +To be added + + +SNAPSHOT 2000-08-13 +------------------- + +New: +- Renamed DLL and LIB files: + pthreadVSE.dll (MS VC++/Structured EH) + pthreadVSE.lib + pthreadVCE.dll (MS VC++/C++ EH) + pthreadVCE.lib + pthreadGCE.dll (GNU G++/C++ EH) + libpthreadw32.a + + Both your application and the pthread dll should use the + same exception handling scheme. + +Bugs fixed: +- MSVC++ C++ exception handling. + +Some new tests have been added. + + +SNAPSHOT 2000-08-10 +------------------- + +New: +- asynchronous cancelation on X86 (Jason Nye) +- Makefile compatible with MS nmake to replace + buildlib.bat +- GNUmakefile for Mingw32 +- tests/Makefile for MS nmake replaces runall.bat +- tests/GNUmakefile for Mingw32 + +Bugs fixed: +- kernel32 load/free problem +- attempt to hide internel exceptions from application + exception handlers (__try/__except and try/catch blocks) +- Win32 thread handle leakage bug + (David Baggett/Paul Redondo/Eyal Lebedinsky) + +Some new tests have been added. + + +SNAPSHOT 1999-11-02 +------------------- + +Bugs fixed: +- ctime_r macro had an incorrect argument (Erik Hensema), +- threads were not being created + PTHREAD_CANCEL_DEFERRED. This should have + had little effect as deferred is the only + supported type. (Ross Johnson). + +Some compatibility improvements added, eg. +- pthread_setcancelstate accepts NULL pointer + for the previous value argument. Ditto for + pthread_setcanceltype. This is compatible + with Solaris but should not affect + standard applications (Erik Hensema) + +Some new tests have been added. + + +SNAPSHOT 1999-10-17 +------------------- + +Bug fix - Cancelation of threads waiting on condition variables +now works properly (Lorin Hochstein and Peter Slacik) + + +SNAPSHOT 1999-08-12 +------------------- + +Fixed exception stack cleanup if calling pthread_exit() +- (Lorin Hochstein and John Bossom). + +Fixed bugs in condition variables - (Peter Slacik): + - additional contention checks + - properly adjust number of waiting threads after timed + condvar timeout. + + +SNAPSHOT 1999-05-30 +------------------- + +Some minor bugs have been fixed. See the ChangeLog file for details. + +Some more POSIX 1b functions are now included but ony return an +error (ENOSYS) if called. They are: + + sem_open + sem_close + sem_unlink + sem_getvalue + + +SNAPSHOT 1999-04-07 +------------------- + +Some POSIX 1b functions which were internally supported are now +available as exported functions: + + sem_init + sem_destroy + sem_wait + sem_trywait + sem_post + sched_yield + sched_get_priority_min + sched_get_priority_max + +Some minor bugs have been fixed. See the ChangeLog file for details. + + +SNAPSHOT 1999-03-16 +------------------- + +Initial release. + diff --git a/w32-pthreads/Nmakefile b/w32-pthreads/Nmakefile new file mode 100644 index 000000000..d9e5bf1bc --- /dev/null +++ b/w32-pthreads/Nmakefile @@ -0,0 +1,24 @@ +/* + * nmake file for uwin pthread library + */ + +VERSION = - +CCFLAGS = -V -g $(CC.DLL) +HAVE_PTW32_CONFIG_H == 1 +_MT == 1 +_timeb == timeb +_ftime == ftime +_errno == _ast_errno + +$(INCLUDEDIR) :INSTALLDIR: pthread.h sched.h + +pthread $(VERSION) :LIBRARY: attr.c barrier.c cancel.c cleanup.c condvar.c \ + create.c dll.c exit.c fork.c global.c misc.c mutex.c private.c \ + rwlock.c sched.c semaphore.c spin.c sync.c tsd.c nonportable.c + +:: ANNOUNCE CONTRIBUTORS COPYING.LIB ChangeLog FAQ GNUmakefile MAINTAINERS \ + Makefile Makefile.in Makefile.vc NEWS PROGRESS README README.WinCE \ + TODO WinCE-PORT install-sh errno.c tests tests.mk acconfig.h \ + config.guess config.h.in config.sub configure configure.in signal.c \ + README.CV README.NONPORTABLE pthread.dsp pthread.dsw + diff --git a/w32-pthreads/Nmakefile.tests b/w32-pthreads/Nmakefile.tests new file mode 100644 index 000000000..203560b6c --- /dev/null +++ b/w32-pthreads/Nmakefile.tests @@ -0,0 +1,260 @@ +/* for running tests */ +CCFLAGS = -g +_MT == 1 +_timeb == timeb +_ftime == ftime + +.SOURCE: tests +/* +:PACKAGE: pthread +*/ + +set keepgoing + +":test:" : .MAKE .OPERATOR + local I + $(<:D:B:S=.pass) : .IMPLICIT $(>:D:B:S=.pass) + for I $(<) $(>) + $(I:D:B:S=.pass) : .VIRTUAL .FORCE $(I) + $(>) + end +sizes:: sizes.c +loadfree:: loadfree.c +mutex1:: mutex1.c +mutex1e:: mutex1e.c +mutex1n:: mutex1n.c +mutex1r:: mutex1r.c +mutex2:: mutex2.c +mutex2r:: mutex2r.c +mutex2e:: mutex2e.c +exit1:: exit1.c +condvar1:: condvar1.c +condvar1_1:: condvar1_1.c +condvar1_2:: condvar1_2.c +self1:: self1.c +condvar2:: condvar2.c +condvar2_1:: condvar2_1.c +condvar3_1:: condvar3_1.c +condvar3_2:: condvar3_2.c +condvar3_3:: condvar3_3.c +create1.:: create1.c +create2.:: create2.c +cancel1:: cancel1.c +cancel2:: cancel2.c +mutex3:: mutex3.c +mutex3r:: mutex3r.c +mutex3e:: mutex3e.c +mutex4:: mutex4.c +mutex5:: mutex5.c +mutex6:: mutex6.c +mutex6e:: mutex6e.c +mutex6n:: mutex6n.c +mutex6r:: mutex6r.c +mutex7:: mutex7.c +mutex6s:: mutex6s.c +mutex6rs:: mutex6rs.c +mutex6es:: mutex6es.c +mutex7e:: mutex7e.c +mutex7n:: mutex7n.c +mutex7r:: mutex7r.c +mutex8:: mutex8.c +mutex8e:: mutex8e.c +mutex8n:: mutex8n.c +mutex8r:: mutex8r.c +equal1:: equal1.c +exit2:: exit2.c +exit3:: exit3.c +exit4:: exit4.c +exit5:: exit5.c +join0:: join0.c +join1:: join1.c +join2:: join2.c +join3:: join3.c +kill1:: kill1.c +count1:: count1.c +once1:: once1.c +tsd1:: tsd1.c +self2:: self2.c +eyal1:: eyal1.c +condvar3:: condvar3.c +condvar4:: condvar4.c +condvar5:: condvar5.c +condvar6:: condvar6.c +condvar7:: condvar7.c +condvar8:: condvar8.c +condvar9:: condvar9.c +errno1:: errno1.c +reuse1.:: reuse1.c +reuse2.:: reuse2.c +rwlock1:: rwlock1.c +rwlock2:: rwlock2.c +rwlock3:: rwlock3.c +rwlock4:: rwlock4.c +rwlock5:: rwlock5.c +rwlock6:: rwlock6.c +rwlock7:: rwlock7.c +rwlock8:: rwlock8.c +rwlock2_t:: rwlock2_t.c +rwlock3_t:: rwlock3_t.c +rwlock4_t:: rwlock4_t.c +rwlock5_t:: rwlock5_t.c +rwlock6_t:: rwlock6_t.c +rwlock6_t2:: rwlock6_t2.c +semaphore1:: semaphore1.c +semaphore2:: semaphore2.c +semaphore3:: semaphore3.c +context1:: context1.c +cancel3:: cancel3.c +cancel4:: cancel4.c +cancel5:: cancel5.c +cancel6a:: cancel6a.c +cancel6d:: cancel6d.c +cancel7:: cancel7.c +cleanup0:: cleanup0.c +cleanup1:: cleanup1.c +cleanup2:: cleanup2.c +cleanup3:: cleanup3.c +priority1:: priority1.c +priority2:: priority2.c +inherit1:: inherit1.c +spin1:: spin1.c +spin2:: spin2.c +spin3:: spin3.c +spin4:: spin4.c +barrier1:: barrier1.c +barrier2:: barrier2.c +barrier3:: barrier3.c +barrier4:: barrier4.c +barrier5:: barrier5.c +exception1:: exception1.c +exception2:: exception2.c +exception3:: exception3.c +benchtest1:: benchtest1.c +benchtest2:: benchtest2.c +benchtest3:: benchtest3.c +benchtest4:: benchtest4.c +benchtest5:: benchtest5.c +valid1:: valid1.c +valid2:: valid2.c +cancel9:: cancel9.c + +sizes: :test: sizes +loadfree: :test: +mutex5 :test: loadfree +mutex1 :test: loadfree +mutex1n :test: loadfree +mutex1r :test: loadfree +mutex1e :test: loadfree +semaphore1 :test: loadfree +semaphore2 :test: loadfree +semaphore3 :test: loadfree +mutex2 :test: loadfree +mutex2r :test: loadfree +mutex2e :test: loadfree +exit1 :test: loadfree +condvar1 :test: loadfree +kill1 :test: loadfree +condvar1_1 :test: condvar1 +condvar1_2 :test: join2 +self1 :test: loadfree +condvar2 :test: condvar1 +condvar2_1 :test: condvar2 +create1 :test: mutex2 +create2 :test: create1 +reuse1 :test: create2 +reuse2 :test: reuse1 +cancel1 :test: create1 +cancel2 :test: cancel1 +mutex3 :test: create1 +mutex3r :test: create1 +mutex3e :test: create1 +mutex4 :test: mutex3 +mutex6 :test: mutex4 +mutex6n :test: mutex4 +mutex6e :test: mutex4 +mutex6r :test: mutex4 +mutex6s :test: mutex6 +mutex6rs :test: mutex6r +mutex6es :test: mutex6e +mutex7 :test: mutex6 +mutex7n :test: mutex6n +mutex7e :test: mutex6e +mutex7r :test: mutex6r +mutex8 :test: mutex7 +mutex8n :test: mutex7n +mutex8e :test: mutex7e +mutex8r :test: mutex7r +equal1 :test: create1 +exit2 :test: create1 +exit3 :test: create1 +exit4 :test: kill1 +exit5 :test: exit4 +join0 :test: create1 +join1 :test: create1 +join2 :test: create1 +join3 :test: join2 +count1 :test: join1 +once1 :test: create1 +tsd1 :test: join1 +self2 :test: create1 +eyal1 :test: tsd1 +condvar3 :test: create1 +condvar3_1 :test: condvar3 +condvar3_2 :test: condvar3_1 +condvar3_3 :test: condvar3_2 +condvar4 :test: create1 +condvar5 :test: condvar4 +condvar6 :test: condvar5 +condvar7 :test: condvar6 cleanup1 +condvar8 :test: condvar7 +condvar9 :test: condvar8 +errno1 :test: mutex3 +rwlock1 :test: condvar6 +rwlock2 :test: rwlock1 +rwlock3 :test: rwlock2 +rwlock4 :test: rwlock3 +rwlock5 :test: rwlock4 +rwlock6 :test: rwlock5 +rwlock7 :test: rwlock6 +rwlock8 :test: rwlock7 +rwlock2_t :test: rwlock2 +rwlock3_t :test: rwlock2_t +rwlock4_t :test: rwlock3_t +rwlock5_t :test: rwlock4_t +rwlock6_t :test: rwlock5_t +rwlock6_t2 :test: rwlock6_t +context1 :test: cancel2 +cancel3 :test: context1 +cancel4 :test: cancel3 +cancel5 :test: cancel3 +cancel6a :test: cancel3 +cancel6d :test: cancel3 +cancel7 :test: kill1 +cleanup0 :test: cancel5 +cleanup1 :test: cleanup0 +cleanup2 :test: cleanup1 +cleanup3 :test: cleanup2 +priority1 :test: join1 +priority2 :test: priority1 +inherit1 :test: join1 +spin1 :test: +spin2 :test: spin1.c +spin3 :test: spin2.c +spin4 :test: spin3.c +barrier1 :test: +barrier2 :test: barrier1.c +barrier3 :test: barrier2.c +barrier4 :test: barrier3.c +barrier5 :test: barrier4.c +benchtest1 :test: mutex3 +benchtest2 :test: benchtest1 +benchtest3 :test: benchtest2 +benchtest4 :test: benchtest3 +benchtest5 :test: benchtest4 +exception1 :test: cancel4 +exception2 :test: exception1 +exception3 :test: exception2 +exit4 :test: exit3 +valid1 :test: join1 +valid2 :test: valid1 +cancel9 :test: cancel8 diff --git a/w32-pthreads/PROGRESS b/w32-pthreads/PROGRESS new file mode 100644 index 000000000..9abf0bca4 --- /dev/null +++ b/w32-pthreads/PROGRESS @@ -0,0 +1,4 @@ +Please see the ANNOUNCE file "Level of Standards Conformance" +or the web page: + +http://sources.redhat.com/pthreads-win32/conformance.html diff --git a/w32-pthreads/README b/w32-pthreads/README new file mode 100644 index 000000000..545360bfa --- /dev/null +++ b/w32-pthreads/README @@ -0,0 +1,601 @@ +PTHREADS-WIN32 +============== + +Pthreads-win32 is free software, distributed under the GNU Lesser +General Public License (LGPL). See the file 'COPYING.LIB' for terms +and conditions. Also see the file 'COPYING' for information +specific to pthreads-win32, copyrights and the LGPL. + + +What is it? +----------- + +Pthreads-win32 is an Open Source Software implementation of the +Threads component of the POSIX 1003.1c 1995 Standard (or later) +for Microsoft's Win32 environment. Some functions from POSIX +1003.1b are also supported including semaphores. Other related +functions include the set of read-write lock functions. The +library also supports some of the functionality of the Open +Group's Single Unix specification, version 2, namely mutex types, +plus some common and pthreads-win32 specific non-portable +routines (see README.NONPORTABLE). + +See the file "ANNOUNCE" for more information including standards +conformance details and the list of supported and unsupported +routines. + + +Prerequisites +------------- +MSVC or GNU C (MinGW32 MSys development kit) + To build from source. + +QueueUserAPCEx by Panagiotis E. Hadjidoukas + To support any thread cancelation in C++ library builds or + to support cancelation of blocked threads in any build. + This library is not required otherwise. + + For true async cancelation of threads (including blocked threads). + This is a DLL and Windows driver that provides pre-emptive APC + by forcing threads into an alertable state when the APC is queued. + Both the DLL and driver are provided with the pthreads-win32.exe + self-unpacking ZIP, and on the pthreads-win32 FTP site (in source + and pre-built forms). Currently this is a separate LGPL package to + pthreads-win32. See the README in the QueueUserAPCEx folder for + installation instructions. + + Pthreads-win32 will automatically detect if the QueueUserAPCEx DLL + QuserEx.DLL is available and whether the driver AlertDrv.sys is + loaded. If it is not available, pthreads-win32 will simulate async + cancelation, which means that it can async cancel only threads that + are runnable. The simulated async cancellation cannot cancel blocked + threads. + + [FOR SECURITY] To be found Quserex.dll MUST be installed in the + Windows System Folder. This is not an unreasonable constraint given a + driver must also be installed and loaded at system startup. + + +Library naming +-------------- + +Because the library is being built using various exception +handling schemes and compilers - and because the library +may not work reliably if these are mixed in an application, +each different version of the library has it's own name. + +Note 1: the incompatibility is really between EH implementations +of the different compilers. It should be possible to use the +standard C version from either compiler with C++ applications +built with a different compiler. If you use an EH version of +the library, then you must use the same compiler for the +application. This is another complication and dependency that +can be avoided by using only the standard C library version. + +Note 2: if you use a standard C pthread*.dll with a C++ +application, then any functions that you define that are +intended to be called via pthread_cleanup_push() must be +__cdecl. + +Note 3: the intention was to also name either the VC or GC +version (it should be arbitrary) as pthread.dll, including +pthread.lib and libpthread.a as appropriate. This is no longer +likely to happen. + +Note 4: the compatibility number was added so that applications +can differentiate between binary incompatible versions of the +libs and dlls. + +In general: + pthread[VG]{SE,CE,C}[c].dll + pthread[VG]{SE,CE,C}[c].lib + +where: + [VG] indicates the compiler + V - MS VC, or + G - GNU C + + {SE,CE,C} indicates the exception handling scheme + SE - Structured EH, or + CE - C++ EH, or + C - no exceptions - uses setjmp/longjmp + + c - DLL compatibility number indicating ABI and API + compatibility with applications built against + a snapshot with the same compatibility number. + See 'Version numbering' below. + +The name may also be suffixed by a 'd' to indicate a debugging version +of the library. E.g. pthreadVC2d.lib. Debugging versions contain +additional information for debugging (symbols etc) and are often not +optimised in any way (compiled with optimisation turned off). + +Examples: + pthreadVSE.dll (MSVC/SEH) + pthreadGCE.dll (GNUC/C++ EH) + pthreadGC.dll (GNUC/not dependent on exceptions) + pthreadVC1.dll (MSVC/not dependent on exceptions - not binary + compatible with pthreadVC.dll) + pthreadVC2.dll (MSVC/not dependent on exceptions - not binary + compatible with pthreadVC1.dll or pthreadVC.dll) + +The GNU library archive file names have correspondingly changed to: + + libpthreadGCEc.a + libpthreadGCc.a + + +Versioning numbering +-------------------- + +Version numbering is separate from the snapshot dating system, and +is the canonical version identification system embedded within the +DLL using the Microsoft version resource system. The versioning +system chosen follows the GNU Libtool system. See +http://www.gnu.org/software/libtool/manual.html section 6.2. + +See the resource file 'version.rc'. + +Microsoft version numbers use 4 integers: + + 0.0.0.0 + +Pthreads-win32 uses the first 3 following the Libtool convention. +The fourth is commonly used for the build number, but will be reserved +for future use. + + current.revision.age.0 + +The numbers are changed as follows: + +1. If the library source code has changed at all since the last update, + then increment revision (`c:r:a' becomes `c:r+1:a'). +2. If any interfaces have been added, removed, or changed since the last + update, increment current, and set revision to 0. +3. If any interfaces have been added since the last public release, then + increment age. +4. If any interfaces have been removed or changed since the last public + release, then set age to 0. + + +DLL compatibility numbering is an attempt to ensure that applications +always load a compatible pthreads-win32 DLL by using a DLL naming system +that is consistent with the version numbering system. It also allows +older and newer DLLs to coexist in the same filesystem so that older +applications can continue to be used. For pre .NET Windows systems, +this inevitably requires incompatible versions of the same DLLs to have +different names. + +Pthreads-win32 has adopted the Cygwin convention of appending a single +integer number to the DLL name. The number used is based on the library +version number and is computed as 'current' - 'age'. + +(See http://home.att.net/~perlspinr/libversioning.html for a nicely +detailed explanation.) + +Using this method, DLL name/s will only change when the DLL's +backwards compatibility changes. Note that the addition of new +'interfaces' will not of itself change the DLL's compatibility for older +applications. + + +Which of the several dll versions to use? +----------------------------------------- +or, +--- +What are all these pthread*.dll and pthread*.lib files? +------------------------------------------------------- + +Simple, use either pthreadGCv.* if you use GCC, or pthreadVCv.* if you +use MSVC - where 'v' is the DLL versioning (compatibility) number. + +Otherwise, you need to choose carefully and know WHY. + +The most important choice you need to make is whether to use a +version that uses exceptions internally, or not. There are versions +of the library that use exceptions as part of the thread +cancelation and exit implementation. The default version uses +setjmp/longjmp. + +There is some contension amongst POSIX threads experts as +to how POSIX threads cancelation and exit should work +with languages that use exceptions, e.g. C++ and even C +(Microsoft's Structured Exceptions). + +The issue is: should cancelation of a thread in, say, +a C++ application cause object destructors and C++ exception +handlers to be invoked as the stack unwinds during thread +exit, or not? + +There seems to be more opinion in favour of using the +standard C version of the library (no EH) with C++ applications +for the reason that this appears to be the assumption commercial +pthreads implementations make. Therefore, if you use an EH version +of pthreads-win32 then you may be under the illusion that +your application will be portable, when in fact it is likely to +behave differently when linked with other pthreads libraries. + +Now you may be asking: then why have you kept the EH versions of +the library? + +There are a couple of reasons: +- there is division amongst the experts and so the code may + be needed in the future. Yes, it's in the repository and we + can get it out anytime in the future, but it would be difficult + to find. +- pthreads-win32 is one of the few implementations, and possibly + the only freely available one, that has EH versions. It may be + useful to people who want to play with or study application + behaviour under these conditions. + +Notes: + +[If you use either pthreadVCE or pthreadGCE] + +1. [See also the discussion in the FAQ file - Q2, Q4, and Q5] + +If your application contains catch(...) blocks in your POSIX +threads then you will need to replace the "catch(...)" with the macro +"PtW32Catch", eg. + + #ifdef PtW32Catch + PtW32Catch { + ... + } + #else + catch(...) { + ... + } + #endif + +Otherwise neither pthreads cancelation nor pthread_exit() will work +reliably when using versions of the library that use C++ exceptions +for cancelation and thread exit. + +This is due to what is believed to be a C++ compliance error in VC++ +whereby you may not have multiple handlers for the same exception in +the same try/catch block. GNU G++ doesn't have this restriction. + + +Other name changes +------------------ + +All snapshots prior to and including snapshot 2000-08-13 +used "_pthread_" as the prefix to library internal +functions, and "_PTHREAD_" to many library internal +macros. These have now been changed to "ptw32_" and "PTW32_" +respectively so as to not conflict with the ANSI standard's +reservation of identifiers beginning with "_" and "__" for +use by compiler implementations only. + +If you have written any applications and you are linking +statically with the pthreads-win32 library then you may have +included a call to _pthread_processInitialize. You will +now have to change that to ptw32_processInitialize. + + +Cleanup code default style +-------------------------- + +Previously, if not defined, the cleanup style was determined automatically +from the compiler used, and one of the following was defined accordingly: + + __CLEANUP_SEH MSVC only + __CLEANUP_CXX C++, including MSVC++, GNU G++ + __CLEANUP_C C, including GNU GCC, not MSVC + +These defines determine the style of cleanup (see pthread.h) and, +most importantly, the way that cancelation and thread exit (via +pthread_exit) is performed (see the routine ptw32_throw()). + +In short, the exceptions versions of the library throw an exception +when a thread is canceled, or exits via pthread_exit(). This exception is +caught by a handler in the thread startup routine, so that the +the correct stack unwinding occurs regardless of where the thread +is when it's canceled or exits via pthread_exit(). + +In this snapshot, unless the build explicitly defines (e.g. via a +compiler option) __CLEANUP_SEH, __CLEANUP_CXX, or __CLEANUP_C, then +the build NOW always defaults to __CLEANUP_C style cleanup. This style +uses setjmp/longjmp in the cancelation and pthread_exit implementations, +and therefore won't do stack unwinding even when linked to applications +that have it (e.g. C++ apps). This is for consistency with most/all +commercial Unix POSIX threads implementations. + +Although it was not clearly documented before, it is still necessary to +build your application using the same __CLEANUP_* define as was +used for the version of the library that you link with, so that the +correct parts of pthread.h are included. That is, the possible +defines require the following library versions: + + __CLEANUP_SEH pthreadVSE.dll + __CLEANUP_CXX pthreadVCE.dll or pthreadGCE.dll + __CLEANUP_C pthreadVC.dll or pthreadGC.dll + +It is recommended that you let pthread.h use it's default __CLEANUP_C +for both library and application builds. That is, don't define any of +the above, and then link with pthreadVC.lib (MSVC or MSVC++) and +libpthreadGC.a (MinGW GCC or G++). The reason is explained below, but +another reason is that the prebuilt pthreadVCE.dll is currently broken. +Versions built with MSVC++ later than version 6 may not be broken, but I +can't verify this yet. + +WHY ARE WE MAKING THE DEFAULT STYLE LESS EXCEPTION-FRIENDLY? +Because no commercial Unix POSIX threads implementation allows you to +choose to have stack unwinding. Therefore, providing it in pthread-win32 +as a default is dangerous. We still provide the choice but unless +you consciously choose to do otherwise, your pthreads applications will +now run or crash in similar ways irrespective of the pthreads platform +you use. Or at least this is the hope. + + +Building under VC++ using C++ EH, Structured EH, or just C +---------------------------------------------------------- + +From the source directory run nmake without any arguments to list +help information. E.g. + +$ nmake + +Microsoft (R) Program Maintenance Utility Version 6.00.8168.0 +Copyright (C) Microsoft Corp 1988-1998. All rights reserved. + +Run one of the following command lines: +nmake clean VCE (to build the MSVC dll with C++ exception handling) +nmake clean VSE (to build the MSVC dll with structured exception handling) +nmake clean VC (to build the MSVC dll with C cleanup code) +nmake clean VCE-inlined (to build the MSVC inlined dll with C++ exception handling) +nmake clean VSE-inlined (to build the MSVC inlined dll with structured exception handling) +nmake clean VC-inlined (to build the MSVC inlined dll with C cleanup code) +nmake clean VC-static (to build the MSVC static lib with C cleanup code) +nmake clean VCE-debug (to build the debug MSVC dll with C++ exception handling) +nmake clean VSE-debug (to build the debug MSVC dll with structured exception handling) +nmake clean VC-debug (to build the debug MSVC dll with C cleanup code) +nmake clean VCE-inlined-debug (to build the debug MSVC inlined dll with C++ exception handling) +nmake clean VSE-inlined-debug (to build the debug MSVC inlined dll with structured exception handling) +nmake clean VC-inlined-debug (to build the debug MSVC inlined dll with C cleanup code) +nmake clean VC-static-debug (to build the debug MSVC static lib with C cleanup code) + + +The pre-built dlls are normally built using the *-inlined targets. + +You can run the testsuite by changing to the "tests" directory and +running nmake. E.g.: + +$ cd tests +$ nmake + +Microsoft (R) Program Maintenance Utility Version 6.00.8168.0 +Copyright (C) Microsoft Corp 1988-1998. All rights reserved. + +Run one of the following command lines: +nmake clean VC (to test using VC dll with VC (no EH) applications) +nmake clean VCX (to test using VC dll with VC++ (EH) applications) +nmake clean VCE (to test using the VCE dll with VC++ EH applications) +nmake clean VSE (to test using VSE dll with VC (SEH) applications) +nmake clean VC-bench (to benchtest using VC dll with C bench app) +nmake clean VCX-bench (to benchtest using VC dll with C++ bench app) +nmake clean VCE-bench (to benchtest using VCE dll with C++ bench app) +nmake clean VSE-bench (to benchtest using VSE dll with SEH bench app) +nmake clean VC-static (to test using VC static lib with VC (no EH) applications) + + +Building under Mingw32 +---------------------- + +The dll can be built easily with recent versions of Mingw32. +(The distributed versions are built using Mingw32 and MsysDTK +from www.mingw32.org.) + +From the source directory, run make for help information. E.g.: + +$ make +Run one of the following command lines: +make clean GC (to build the GNU C dll with C cleanup code) +make clean GCE (to build the GNU C dll with C++ exception handling) +make clean GC-inlined (to build the GNU C inlined dll with C cleanup code) +make clean GCE-inlined (to build the GNU C inlined dll with C++ exception handling) +make clean GC-static (to build the GNU C inlined static lib with C cleanup code) +make clean GC-debug (to build the GNU C debug dll with C cleanup code) +make clean GCE-debug (to build the GNU C debug dll with C++ exception handling) +make clean GC-inlined-debug (to build the GNU C inlined debug dll with C cleanup code) +make clean GCE-inlined-debug (to build the GNU C inlined debug dll with C++ exception handling) +make clean GC-static-debug (to build the GNU C inlined static debug lib with C cleanup code) + + +The pre-built dlls are normally built using the *-inlined targets. + +You can run the testsuite by changing to the "tests" directory and +running make for help information. E.g.: + +$ cd tests +$ make +Run one of the following command lines: +make clean GC (to test using GC dll with C (no EH) applications) +make clean GCX (to test using GC dll with C++ (EH) applications) +make clean GCE (to test using GCE dll with C++ (EH) applications) +make clean GC-bench (to benchtest using GNU C dll with C cleanup code) +make clean GCE-bench (to benchtest using GNU C dll with C++ exception handling) +make clean GC-static (to test using GC static lib with C (no EH) applications) + + +Building under Linux using the Mingw32 cross development tools +-------------------------------------------------------------- + +You can build the library without leaving Linux by using the Mingw32 cross +development toolchain. See http://www.libsdl.org/extras/win32/cross/ for +tools and info. The GNUmakefile contains some support for this, for example: + +make CROSS=i386-mingw32msvc- clean GC-inlined + +will build pthreadGCn.dll and libpthreadGCn.a (n=version#), provided your +cross-tools/bin directory is in your PATH (or use the cross-make.sh script +at the URL above). + + +Building the library as a statically linkable library +----------------------------------------------------- + +General: PTW32_STATIC_LIB must be defined for both the library build and the +application build. The makefiles supplied and used by the following 'make' +command lines will define this for you. + +MSVC (creates pthreadVCn.lib as a static link lib): + +nmake clean VC-static + + +MinGW32 (creates libpthreadGCn.a as a static link lib): + +make clean GC-static + + +Define PTW32_STATIC_LIB when building your application. Also, your +application must call a two non-portable routines to initialise the +some state on startup and cleanup before exit. One other routine needs +to be called to cleanup after any Win32 threads have called POSIX API +routines. See README.NONPORTABLE or the html reference manual pages for +details on these routines: + +BOOL pthread_win32_process_attach_np (void); +BOOL pthread_win32_process_detach_np (void); +BOOL pthread_win32_thread_attach_np (void); // Currently a no-op +BOOL pthread_win32_thread_detach_np (void); + + +The tests makefiles have the same targets but only check that the +static library is statically linkable. They don't run the full +testsuite. To run the full testsuite, build the dlls and run the +dll test targets. + + +Building the library under Cygwin +--------------------------------- + +Cygwin is implementing it's own POSIX threads routines and these +will be the ones to use if you develop using Cygwin. + + +Ready to run binaries +--------------------- + +For convenience, the following ready-to-run files can be downloaded +from the FTP site (see under "Availability" below): + + pthread.h + semaphore.h + sched.h + pthreadVC.dll - built with MSVC compiler using C setjmp/longjmp + pthreadVC.lib + pthreadVCE.dll - built with MSVC++ compiler using C++ EH + pthreadVCE.lib + pthreadVSE.dll - built with MSVC compiler using SEH + pthreadVSE.lib + pthreadGC.dll - built with Mingw32 GCC + libpthreadGC.a - derived from pthreadGC.dll + pthreadGCE.dll - built with Mingw32 G++ + libpthreadGCE.a - derived from pthreadGCE.dll + +As of August 2003 pthreads-win32 pthreadG* versions are built and tested +using the MinGW + MsysDTK environment current as of that date or later. +The following file MAY be needed for older MinGW environments. + + gcc.dll - needed to build and run applications that use + pthreadGCE.dll. + + +Building applications with GNU compilers +---------------------------------------- + +If you're using pthreadGC.dll: + +With the three header files, pthreadGC.dll and libpthreadGC.a in the +same directory as your application myapp.c, you could compile, link +and run myapp.c under Mingw32 as follows: + + gcc -o myapp.exe myapp.c -I. -L. -lpthreadGC + myapp + +Or put pthreadGC.dll in an appropriate directory in your PATH, +put libpthreadGC.a in your system lib directory, and +put the three header files in your system include directory, +then use: + + gcc -o myapp.exe myapp.c -lpthreadGC + myapp + + +If you're using pthreadGCE.dll: + +With the three header files, pthreadGCE.dll, gcc.dll and libpthreadGCE.a +in the same directory as your application myapp.c, you could compile, +link and run myapp.c under Mingw32 as follows: + + gcc -x c++ -o myapp.exe myapp.c -I. -L. -lpthreadGCE + myapp + +Or put pthreadGCE.dll and gcc.dll in an appropriate directory in +your PATH, put libpthreadGCE.a in your system lib directory, and +put the three header files in your system include directory, +then use: + + gcc -x c++ -o myapp.exe myapp.c -lpthreadGCE + myapp + + +Availability +------------ + +The complete source code in either unbundled, self-extracting +Zip file, or tar/gzipped format can be found at: + + ftp://sources.redhat.com/pub/pthreads-win32 + +The pre-built DLL, export libraries and matching pthread.h can +be found at: + + ftp://sources.redhat.com/pub/pthreads-win32/dll-latest + +Home page: + + http://sources.redhat.com/pthreads-win32/ + + +Mailing list +------------ + +There is a mailing list for discussing pthreads on Win32. +To join, send email to: + + pthreads-win32-subscribe@sources.redhat.com + +Unsubscribe by sending mail to: + + pthreads-win32-unsubscribe@sources.redhat.com + + +Acknowledgements +---------------- + +See the ANNOUNCE file for acknowledgements. +See the 'CONTRIBUTORS' file for the list of contributors. + +As much as possible, the ChangeLog file attributes +contributions and patches that have been incorporated +in the library to the individuals responsible. + +Finally, thanks to all those who work on and contribute to the +POSIX and Single Unix Specification standards. The maturity of an +industry can be measured by it's open standards. + +---- +Ross Johnson + + + + + + + + + diff --git a/w32-pthreads/README.Borland b/w32-pthreads/README.Borland new file mode 100644 index 000000000..a130d2bd2 --- /dev/null +++ b/w32-pthreads/README.Borland @@ -0,0 +1,57 @@ +In ptw32_InterlockedCompareExchange.c, I've added a section for +Borland's compiler; it's identical to that for the MS compiler except +that it uses /* ... */ comments instead of ; comments. + +[RPJ: need to define HAVE_TASM32 in config.h to use the above.] + + +The other file is a makefile suitable for use with Borland's compiler +(run "make -fBmakefile" in the directory). It builds a single version +of the library, pthreadBC.dll and the corresponding pthreadBC.lib +import library, which is comparable to the pthreadVC version; I can't +personally see any demand for the versions that include structured or +C++ exception cancellation handling so I haven't attempted to build +those versions of the library. (I imagine a static version might be +of use to some, but we can't legally use that on my commercial +projects so I can't try that out, unfortunately.) + +[RPJ: Added tests\Bmakefile as well.] + +Borland C++ doesn't define the ENOSYS constant used by pthreads-win32; +rather than make more extensive patches to the pthreads-win32 source I +have a mostly-arbitrary constant for it in the makefile. However this +doesn't make it visible to the application using the library, so if +anyone actually wants to use this constant in their apps (why?) +someone might like to make a seperate NEED_BCC_something define to add +this stuff. + +The makefile also #defines EDEADLK as EDEADLOCK, _timeb as timeb, and +_ftime as ftime, to deal with the minor differences between the two +RTLs' naming conventions, and sets the compiler flags as required to +get a normal compile of the library. + +[RPJ: Moved errno values and _timeb etc to pthread.h, so apps will also +use them.] + +(While I'm on the subject, the reason Borland users should recompile +the library, rather than using the impdef/implib technique suggested +previously on the mailing list, is that a) the errno constants are +different, so the results returned by the pthread_* functions can be +meaningless, and b) the errno variable/pseudo-variable itself is +different in the MS & BCC runtimes, so you can't access the +pthreadVC's errno from a Borland C++-compiled host application +correctly - I imagine there are other potential problems from the RTL +mismatch too.) + +[RPJ: Make sure you use the same RTL in both dll and application builds. +The dll and tests Bmakefiles use cw32mti.lib. Having some trouble with +memory read exceptions running the test suite using BCC55.] + +Best regards, +Will + +-- +Will Bryant +Systems Architect, eCOSM Limited +Cell +64 21 655 443, office +64 3 365 4176 +http://www.ecosm.com/ diff --git a/w32-pthreads/README.CV b/w32-pthreads/README.CV new file mode 100644 index 000000000..698728b95 --- /dev/null +++ b/w32-pthreads/README.CV @@ -0,0 +1,3036 @@ +README.CV -- Condition Variables +-------------------------------- + +The original implementation of condition variables in +pthreads-win32 was based on a discussion paper: + +"Strategies for Implementing POSIX Condition Variables +on Win32": http://www.cs.wustl.edu/~schmidt/win32-cv-1.html + +The changes suggested below were made on Feb 6 2001. This +file is included in the package for the benefit of anyone +interested in understanding the pthreads-win32 implementation +of condition variables and the (sometimes subtle) issues that +it attempts to resolve. + +Thanks go to the individuals whose names appear throughout +the following text. + +Ross Johnson + +-------------------------------------------------------------------- + +fyi.. (more detailed problem description/demos + possible fix/patch) + +regards, +alexander. + + +Alexander Terekhov +31.01.2001 17:43 + +To: ace-bugs@cs.wustl.edu +cc: +From: Alexander Terekhov/Germany/IBM@IBMDE +Subject: Implementation of POSIX CVs: spur.wakeups/lost + signals/deadlocks/unfairness + + + + ACE VERSION: + + 5.1.12 (pthread-win32 snapshot 2000-12-29) + + HOST MACHINE and OPERATING SYSTEM: + + IBM IntelliStation Z Pro, 2 x XEON 1GHz, Win2K + + TARGET MACHINE and OPERATING SYSTEM, if different from HOST: + COMPILER NAME AND VERSION (AND PATCHLEVEL): + + Microsoft Visual C++ 6.0 + + AREA/CLASS/EXAMPLE AFFECTED: + + Implementation of POSIX condition variables - OS.cpp/.h + + DOES THE PROBLEM AFFECT: + + EXECUTION? YES! + + SYNOPSIS: + + a) spurious wakeups (minor problem) + b) lost signals + c) broadcast deadlock + d) unfairness (minor problem) + + DESCRIPTION: + + Please see attached copy of discussion thread + from comp.programming.threads for more details on + some reported problems. (i've also posted a "fyi" + message to ace-users a week or two ago but + unfortunately did not get any response so far). + + It seems that current implementation suffers from + two essential problems: + + 1) cond.waiters_count does not accurately reflect + number of waiters blocked on semaphore - w/o + proper synchronisation that could result (in the + time window when counter is not accurate) + in spurious wakeups organised by subsequent + _signals and _broadcasts. + + 2) Always having (with no e.g. copy_and_clear/..) + the same queue in use (semaphore+counter) + neither signal nor broadcast provide 'atomic' + behaviour with respect to other threads/subsequent + calls to signal/broadcast/wait. + + Each problem and combination of both could produce + various nasty things: + + a) spurious wakeups (minor problem) + + it is possible that waiter(s) which was already + unblocked even so is still counted as blocked + waiter. signal and broadcast will release + semaphore which will produce a spurious wakeup + for a 'real' waiter coming later. + + b) lost signals + + signalling thread ends up consuming its own + signal. please see demo/discussion below. + + c) broadcast deadlock + + last_waiter processing code does not correctly + handle the case with multiple threads + waiting for the end of broadcast. + please see demo/discussion below. + + d) unfairness (minor problem) + + without SignalObjectAndWait some waiter(s) + may end up consuming broadcasted signals + multiple times (spurious wakeups) because waiter + thread(s) can be preempted before they call + semaphore wait (but after count++ and mtx.unlock). + + REPEAT BY: + + See below... run problem demos programs (tennis.cpp and + tennisb.cpp) number of times concurrently (on multiprocessor) + and in multiple sessions or just add a couple of "Sleep"s + as described in the attached copy of discussion thread + from comp.programming.threads + + SAMPLE FIX/WORKAROUND: + + See attached patch to pthread-win32.. well, I can not + claim that it is completely bug free but at least my + test and tests provided by pthreads-win32 seem to work. + Perhaps that will help. + + regards, + alexander. + + +>> Forum: comp.programming.threads +>> Thread: pthread_cond_* implementation questions +. +. +. +David Schwartz wrote: + +> terekhov@my-deja.com wrote: +> +>> BTW, could you please also share your view on other perceived +>> "problems" such as nested broadcast deadlock, spurious wakeups +>> and (the latest one) lost signals?? +> +>I'm not sure what you mean. The standard allows an implementation +>to do almost whatever it likes. In fact, you could implement +>pthread_cond_wait by releasing the mutex, sleeping a random +>amount of time, and then reacquiring the mutex. Of course, +>this would be a pretty poor implementation, but any code that +>didn't work under that implementation wouldn't be strictly +>compliant. + +The implementation you suggested is indeed correct +one (yes, now I see it :). However it requires from +signal/broadcast nothing more than to "{ return 0; }" +That is not the case for pthread-win32 and ACE +implementations. I do think that these implementations +(basically the same implementation) have some serious +problems with wait/signal/broadcast calls. I am looking +for help to clarify whether these problems are real +or not. I think that I can demonstrate what I mean +using one or two small sample programs. +. +. +. +========== +tennis.cpp +========== + +#include "ace/Synch.h" +#include "ace/Thread.h" + +enum GAME_STATE { + + START_GAME, + PLAYER_A, // Player A playes the ball + PLAYER_B, // Player B playes the ball + GAME_OVER, + ONE_PLAYER_GONE, + BOTH_PLAYERS_GONE + +}; + +enum GAME_STATE eGameState; +ACE_Mutex* pmtxGameStateLock; +ACE_Condition< ACE_Mutex >* pcndGameStateChange; + +void* + playerA( + void* pParm + ) +{ + + // For access to game state variable + pmtxGameStateLock->acquire(); + + // Play loop + while ( eGameState < GAME_OVER ) { + + // Play the ball + cout << endl << "PLAYER-A" << endl; + + // Now its PLAYER-B's turn + eGameState = PLAYER_B; + + // Signal to PLAYER-B that now it is his turn + pcndGameStateChange->signal(); + + // Wait until PLAYER-B finishes playing the ball + do { + + pcndGameStateChange->wait(); + + if ( PLAYER_B == eGameState ) + cout << endl << "----PLAYER-A: SPURIOUS WAKEUP!!!" << endl; + + } while ( PLAYER_B == eGameState ); + + } + + // PLAYER-A gone + eGameState = (GAME_STATE)(eGameState+1); + cout << endl << "PLAYER-A GONE" << endl; + + // No more access to state variable needed + pmtxGameStateLock->release(); + + // Signal PLAYER-A gone event + pcndGameStateChange->broadcast(); + + return 0; + +} + +void* + playerB( + void* pParm + ) +{ + + // For access to game state variable + pmtxGameStateLock->acquire(); + + // Play loop + while ( eGameState < GAME_OVER ) { + + // Play the ball + cout << endl << "PLAYER-B" << endl; + + // Now its PLAYER-A's turn + eGameState = PLAYER_A; + + // Signal to PLAYER-A that now it is his turn + pcndGameStateChange->signal(); + + // Wait until PLAYER-A finishes playing the ball + do { + + pcndGameStateChange->wait(); + + if ( PLAYER_A == eGameState ) + cout << endl << "----PLAYER-B: SPURIOUS WAKEUP!!!" << endl; + + } while ( PLAYER_A == eGameState ); + + } + + // PLAYER-B gone + eGameState = (GAME_STATE)(eGameState+1); + cout << endl << "PLAYER-B GONE" << endl; + + // No more access to state variable needed + pmtxGameStateLock->release(); + + // Signal PLAYER-B gone event + pcndGameStateChange->broadcast(); + + return 0; + +} + + +int +main (int, ACE_TCHAR *[]) +{ + + pmtxGameStateLock = new ACE_Mutex(); + pcndGameStateChange = new ACE_Condition< ACE_Mutex >( *pmtxGameStateLock +); + + // Set initial state + eGameState = START_GAME; + + // Create players + ACE_Thread::spawn( playerA ); + ACE_Thread::spawn( playerB ); + + // Give them 5 sec. to play + Sleep( 5000 );//sleep( 5 ); + + // Set game over state + pmtxGameStateLock->acquire(); + eGameState = GAME_OVER; + + // Let them know + pcndGameStateChange->broadcast(); + + // Wait for players to stop + do { + + pcndGameStateChange->wait(); + + } while ( eGameState < BOTH_PLAYERS_GONE ); + + // Cleanup + cout << endl << "GAME OVER" << endl; + pmtxGameStateLock->release(); + delete pcndGameStateChange; + delete pmtxGameStateLock; + + return 0; + +} + +=========== +tennisb.cpp +=========== +#include "ace/Synch.h" +#include "ace/Thread.h" + +enum GAME_STATE { + + START_GAME, + PLAYER_A, // Player A playes the ball + PLAYER_B, // Player B playes the ball + GAME_OVER, + ONE_PLAYER_GONE, + BOTH_PLAYERS_GONE + +}; + +enum GAME_STATE eGameState; +ACE_Mutex* pmtxGameStateLock; +ACE_Condition< ACE_Mutex >* pcndGameStateChange; + +void* + playerA( + void* pParm + ) +{ + + // For access to game state variable + pmtxGameStateLock->acquire(); + + // Play loop + while ( eGameState < GAME_OVER ) { + + // Play the ball + cout << endl << "PLAYER-A" << endl; + + // Now its PLAYER-B's turn + eGameState = PLAYER_B; + + // Signal to PLAYER-B that now it is his turn + pcndGameStateChange->broadcast(); + + // Wait until PLAYER-B finishes playing the ball + do { + + pcndGameStateChange->wait(); + + if ( PLAYER_B == eGameState ) + cout << endl << "----PLAYER-A: SPURIOUS WAKEUP!!!" << endl; + + } while ( PLAYER_B == eGameState ); + + } + + // PLAYER-A gone + eGameState = (GAME_STATE)(eGameState+1); + cout << endl << "PLAYER-A GONE" << endl; + + // No more access to state variable needed + pmtxGameStateLock->release(); + + // Signal PLAYER-A gone event + pcndGameStateChange->broadcast(); + + return 0; + +} + +void* + playerB( + void* pParm + ) +{ + + // For access to game state variable + pmtxGameStateLock->acquire(); + + // Play loop + while ( eGameState < GAME_OVER ) { + + // Play the ball + cout << endl << "PLAYER-B" << endl; + + // Now its PLAYER-A's turn + eGameState = PLAYER_A; + + // Signal to PLAYER-A that now it is his turn + pcndGameStateChange->broadcast(); + + // Wait until PLAYER-A finishes playing the ball + do { + + pcndGameStateChange->wait(); + + if ( PLAYER_A == eGameState ) + cout << endl << "----PLAYER-B: SPURIOUS WAKEUP!!!" << endl; + + } while ( PLAYER_A == eGameState ); + + } + + // PLAYER-B gone + eGameState = (GAME_STATE)(eGameState+1); + cout << endl << "PLAYER-B GONE" << endl; + + // No more access to state variable needed + pmtxGameStateLock->release(); + + // Signal PLAYER-B gone event + pcndGameStateChange->broadcast(); + + return 0; + +} + + +int +main (int, ACE_TCHAR *[]) +{ + + pmtxGameStateLock = new ACE_Mutex(); + pcndGameStateChange = new ACE_Condition< ACE_Mutex >( *pmtxGameStateLock +); + + // Set initial state + eGameState = START_GAME; + + // Create players + ACE_Thread::spawn( playerA ); + ACE_Thread::spawn( playerB ); + + // Give them 5 sec. to play + Sleep( 5000 );//sleep( 5 ); + + // Make some noise + pmtxGameStateLock->acquire(); + cout << endl << "---Noise ON..." << endl; + pmtxGameStateLock->release(); + for ( int i = 0; i < 100000; i++ ) + pcndGameStateChange->broadcast(); + cout << endl << "---Noise OFF" << endl; + + // Set game over state + pmtxGameStateLock->acquire(); + eGameState = GAME_OVER; + cout << endl << "---Stopping the game..." << endl; + + // Let them know + pcndGameStateChange->broadcast(); + + // Wait for players to stop + do { + + pcndGameStateChange->wait(); + + } while ( eGameState < BOTH_PLAYERS_GONE ); + + // Cleanup + cout << endl << "GAME OVER" << endl; + pmtxGameStateLock->release(); + delete pcndGameStateChange; + delete pmtxGameStateLock; + + return 0; + +} +. +. +. +David Schwartz wrote: +>> > It's compliant +>> +>> That is really good. +> +>> Tomorrow (I have to go urgently now) I will try to +>> demonstrate the lost-signal "problem" of current +>> pthread-win32 and ACE-(variant w/o SingleObjectAndWait) +>> implementations: players start suddenly drop their balls :-) +>> (with no change in source code). +> +>Signals aren't lost, they're going to the main thread, +>which isn't coded correctly to handle them. Try this: +> +> // Wait for players to stop +> do { +> +> pthread_cond_wait( &cndGameStateChange,&mtxGameStateLock ); +>printf("Main thread stole a signal\n"); +> +> } while ( eGameState < BOTH_PLAYERS_GONE ); +> +>I bet everytime you thing a signal is lost, you'll see that printf. +>The signal isn't lost, it was stolen by another thread. + +well, you can probably loose your bet.. it was indeed stolen +by "another" thread but not the one you seem to think of. + +I think that what actually happens is the following: + +H:\SA\UXX\pt\PTHREADS\TESTS>tennis3.exe + +PLAYER-A + +PLAYER-B + +----PLAYER-B: SPURIOUS WAKEUP!!! + +PLAYER-A GONE + +PLAYER-B GONE + +GAME OVER + +H:\SA\UXX\pt\PTHREADS\TESTS> + +here you can see that PLAYER-B after playing his first +ball (which came via signal from PLAYER-A) just dropped +it down. What happened is that his signal to player A +was consumed as spurious wakeup by himself (player B). + +The implementation has a problem: + +================ +waiting threads: +================ + +{ /** Critical Section + + inc cond.waiters_count + +} + + /* + /* Atomic only if using Win32 SignalObjectAndWait + /* + cond.mtx.release + + /*** ^^-- A THREAD WHICH DID SIGNAL MAY ACQUIRE THE MUTEX, + /*** GO INTO WAIT ON THE SAME CONDITION AND OVERTAKE + /*** ORIGINAL WAITER(S) CONSUMING ITS OWN SIGNAL! + + cond.sem.wait + +Player-A after playing game's initial ball went into +wait (called _wait) but was pre-empted before reaching +wait semaphore. He was counted as waiter but was not +actually waiting/blocked yet. + +=============== +signal threads: +=============== + +{ /** Critical Section + + waiters_count = cond.waiters_count + +} + + if ( waiters_count != 0 ) + + sem.post 1 + + endif + +Player-B after he received signal/ball from Player A +called _signal. The _signal did see that there was +one waiter blocked on the condition (Player-A) and +released the semaphore.. (but it did not unblock +Player-A because he was not actually blocked). +Player-B thread continued its execution, called _wait, +was counted as second waiter BUT was allowed to slip +through opened semaphore gate (which was opened for +Player-B) and received his own signal. Player B remained +blocked followed by Player A. Deadlock happened which +lasted until main thread came in and said game over. + +It seems to me that the implementation fails to +correctly implement the following statement +from specification: + +http://www.opengroup.org/ +onlinepubs/007908799/xsh/pthread_cond_wait.html + +"These functions atomically release mutex and cause +the calling thread to block on the condition variable +cond; atomically here means "atomically with respect +to access by another thread to the mutex and then the +condition variable". That is, if another thread is +able to acquire the mutex after the about-to-block +thread has released it, then a subsequent call to +pthread_cond_signal() or pthread_cond_broadcast() +in that thread behaves as if it were issued after +the about-to-block thread has blocked." + +Question: Am I right? + +(I produced the program output above by simply +adding ?Sleep( 1 )?: + +================ +waiting threads: +================ + +{ /** Critical Section + + inc cond.waiters_count + +} + + /* + /* Atomic only if using Win32 SignalObjectAndWait + /* + cond.mtx.release + +Sleep( 1 ); // Win32 + + /*** ^^-- A THREAD WHICH DID SIGNAL MAY ACQUIRE THE MUTEX, + /*** GO INTO WAIT ON THE SAME CONDITION AND OVERTAKE + /*** ORIGINAL WAITER(S) CONSUMING ITS OWN SIGNAL! + + cond.sem.wait + +to the source code of pthread-win32 implementation: + +http://sources.redhat.com/cgi-bin/cvsweb.cgi/pthreads/ +condvar.c?rev=1.36&content-type=text/ +x-cvsweb-markup&cvsroot=pthreads-win32 + + + /* + * We keep the lock held just long enough to increment the count of + * waiters by one (above). + * Note that we can't keep it held across the + * call to sem_wait since that will deadlock other calls + * to pthread_cond_signal + */ + cleanup_args.mutexPtr = mutex; + cleanup_args.cv = cv; + cleanup_args.resultPtr = &result; + + pthread_cleanup_push (ptw32_cond_wait_cleanup, (void *) +&cleanup_args); + + if ((result = pthread_mutex_unlock (mutex)) == 0) + {((result +Sleep( 1 ); // @AT + + /* + * Wait to be awakened by + * pthread_cond_signal, or + * pthread_cond_broadcast, or + * a timeout + * + * Note: + * ptw32_sem_timedwait is a cancelation point, + * hence providing the + * mechanism for making pthread_cond_wait a cancelation + * point. We use the cleanup mechanism to ensure we + * re-lock the mutex and decrement the waiters count + * if we are canceled. + */ + if (ptw32_sem_timedwait (&(cv->sema), abstime) == -1) { + result = errno; + } + } + + pthread_cleanup_pop (1); /* Always cleanup */ + + +BTW, on my system (2 CPUs) I can manage to get +signals lost even without any source code modification +if I run the tennis program many times in different +shell sessions. +. +. +. +David Schwartz wrote: +>terekhov@my-deja.com wrote: +> +>> well, it might be that the program is in fact buggy. +>> but you did not show me any bug. +> +>You're right. I was close but not dead on. I was correct, however, +>that the code is buggy because it uses 'pthread_cond_signal' even +>though not any thread waiting on the condition variable can do the +>job. I was wrong in which thread could be waiting on the cv but +>unable to do the job. + +Okay, lets change 'pthread_cond_signal' to 'pthread_cond_broadcast' +but also add some noise from main() right before declaring the game +to be over (I need it in order to demonstrate another problem of +pthread-win32/ACE implementations - broadcast deadlock)... +. +. +. +It is my understanding of POSIX conditions, +that on correct implementation added noise +in form of unnecessary broadcasts from main, +should not break the tennis program. The +only 'side effect' of added noise on correct +implementation would be 'spurious wakeups' of +players (in fact they are not spurious, +players just see them as spurious) unblocked, +not by another player but by main before +another player had a chance to acquire the +mutex and change the game state variable: +. +. +. + +PLAYER-B + +PLAYER-A + +---Noise ON... + +PLAYER-B + +PLAYER-A + +. +. +. + +PLAYER-B + +PLAYER-A + +----PLAYER-A: SPURIOUS WAKEUP!!! + +PLAYER-B + +PLAYER-A + +---Noise OFF + +PLAYER-B + +---Stopping the game... + +PLAYER-A GONE + +PLAYER-B GONE + +GAME OVER + +H:\SA\UXX\pt\PTHREADS\TESTS> + +On pthread-win32/ACE implementations the +program could stall: + +. +. +. + +PLAYER-A + +PLAYER-B + +PLAYER-A + +PLAYER-B + +PLAYER-A + +PLAYER-B + +PLAYER-A + +PLAYER-B + +---Noise ON... + +PLAYER-A + +---Noise OFF +^C +H:\SA\UXX\pt\PTHREADS\TESTS> + + +The implementation has problems: + +================ +waiting threads: +================ + +{ /** Critical Section + + inc cond.waiters_count + +} + + /* + /* Atomic only if using Win32 SignalObjectAndWait + /* + cond.mtx.release + cond.sem.wait + + /*** ^^-- WAITER CAN BE PREEMPTED AFTER BEING UNBLOCKED... + +{ /** Critical Section + + dec cond.waiters_count + + /*** ^^- ...AND BEFORE DECREMENTING THE COUNT (1) + + last_waiter = ( cond.was_broadcast && + cond.waiters_count == 0 ) + + if ( last_waiter ) + + cond.was_broadcast = FALSE + + endif + +} + + if ( last_waiter ) + + /* + /* Atomic only if using Win32 SignalObjectAndWait + /* + cond.auto_reset_event_or_sem.post /* Event for Win32 + cond.mtx.acquire + + /*** ^^-- ...AND BEFORE CALL TO mtx.acquire (2) + + /*** ^^-- NESTED BROADCASTS RESULT IN A DEADLOCK + + + else + + cond.mtx.acquire + + /*** ^^-- ...AND BEFORE CALL TO mtx.acquire (3) + + endif + + +================== +broadcast threads: +================== + +{ /** Critical Section + + waiters_count = cond.waiters_count + + if ( waiters_count != 0 ) + + cond.was_broadcast = TRUE + + endif + +} + +if ( waiters_count != 0 ) + + cond.sem.post waiters_count + + /*** ^^^^^--- SPURIOUS WAKEUPS DUE TO (1) + + cond.auto_reset_event_or_sem.wait /* Event for Win32 + + /*** ^^^^^--- DEADLOCK FOR FURTHER BROADCASTS IF THEY + HAPPEN TO GO INTO WAIT WHILE PREVIOUS + BROADCAST IS STILL IN PROGRESS/WAITING + +endif + +a) cond.waiters_count does not accurately reflect +number of waiters blocked on semaphore - that could +result (in the time window when counter is not accurate) +in spurios wakeups organised by subsequent _signals +and _broadcasts. From standard compliance point of view +that is OK but that could be a real problem from +performance/efficiency point of view. + +b) If subsequent broadcast happen to go into wait on +cond.auto_reset_event_or_sem before previous +broadcast was unblocked from cond.auto_reset_event_or_sem +by its last waiter, one of two blocked threads will +remain blocked because last_waiter processing code +fails to unblock both threads. + +In the situation with tennisb.c the Player-B was put +in a deadlock by noise (broadcast) coming from main +thread. And since Player-B holds the game state +mutex when it calls broadcast, the whole program +stalled: Player-A was deadlocked on mutex and +main thread after finishing with producing the noise +was deadlocked on mutex too (needed to declare the +game over) + +(I produced the program output above by simply +adding ?Sleep( 1 )?: + +================== +broadcast threads: +================== + +{ /** Critical Section + + waiters_count = cond.waiters_count + + if ( waiters_count != 0 ) + + cond.was_broadcast = TRUE + + endif + +} + +if ( waiters_count != 0 ) + +Sleep( 1 ); //Win32 + + cond.sem.post waiters_count + + /*** ^^^^^--- SPURIOUS WAKEUPS DUE TO (1) + + cond.auto_reset_event_or_sem.wait /* Event for Win32 + + /*** ^^^^^--- DEADLOCK FOR FURTHER BROADCASTS IF THEY + HAPPEN TO GO INTO WAIT WHILE PREVIOUS + BROADCAST IS STILL IN PROGRESS/WAITING + +endif + +to the source code of pthread-win32 implementation: + +http://sources.redhat.com/cgi-bin/cvsweb.cgi/pthreads/ +condvar.c?rev=1.36&content-type=text/ +x-cvsweb-markup&cvsroot=pthreads-win32 + + if (wereWaiters) + {(wereWaiters)sroot=pthreads-win32eb.cgi/pthreads/Yem...m + /* + * Wake up all waiters + */ + +Sleep( 1 ); //@AT + +#ifdef NEED_SEM + + result = (ptw32_increase_semaphore( &cv->sema, cv->waiters ) + ? 0 + : EINVAL); + +#else /* NEED_SEM */ + + result = (ReleaseSemaphore( cv->sema, cv->waiters, NULL ) + ? 0 + : EINVAL); + +#endif /* NEED_SEM */ + + } + + (void) pthread_mutex_unlock(&(cv->waitersLock)); + + if (wereWaiters && result == 0) + {(wereWaiters + /* + * Wait for all the awakened threads to acquire their part of + * the counting semaphore + */ + + if (WaitForSingleObject (cv->waitersDone, INFINITE) + == WAIT_OBJECT_0) + { + result = 0; + } + else + { + result = EINVAL; + } + + } + + return (result); + +} + +BTW, on my system (2 CPUs) I can manage to get +the program stalled even without any source code +modification if I run the tennisb program many +times in different shell sessions. + +=================== +pthread-win32 patch +=================== +struct pthread_cond_t_ { + long nWaitersBlocked; /* Number of threads blocked +*/ + long nWaitersUnblocked; /* Number of threads unblocked +*/ + long nWaitersToUnblock; /* Number of threads to unblock +*/ + sem_t semBlockQueue; /* Queue up threads waiting for the +*/ + /* condition to become signalled +*/ + sem_t semBlockLock; /* Semaphore that guards access to +*/ + /* | waiters blocked count/block queue +*/ + /* +-> Mandatory Sync.LEVEL-1 +*/ + pthread_mutex_t mtxUnblockLock; /* Mutex that guards access to +*/ + /* | waiters (to)unblock(ed) counts +*/ + /* +-> Optional* Sync.LEVEL-2 +*/ +}; /* Opt*) for _timedwait and +cancellation*/ + +int +pthread_cond_init (pthread_cond_t * cond, const pthread_condattr_t * attr) + int result = EAGAIN; + pthread_cond_t cv = NULL; + + if (cond == NULL) + {(cond + return EINVAL; + } + + if ((attr != NULL && *attr != NULL) && + ((*attr)->pshared == PTHREAD_PROCESS_SHARED)) + { + /* + * Creating condition variable that can be shared between + * processes. + */ + result = ENOSYS; + + goto FAIL0; + } + + cv = (pthread_cond_t) calloc (1, sizeof (*cv)); + + if (cv == NULL) + {(cv + result = ENOMEM; + goto FAIL0; + } + + cv->nWaitersBlocked = 0; + cv->nWaitersUnblocked = 0; + cv->nWaitersToUnblock = 0; + + if (sem_init (&(cv->semBlockLock), 0, 1) != 0) + {(sem_init + goto FAIL0; + } + + if (sem_init (&(cv->semBlockQueue), 0, 0) != 0) + {(sem_init + goto FAIL1; + } + + if (pthread_mutex_init (&(cv->mtxUnblockLock), 0) != 0) + {(pthread_mutex_init + goto FAIL2; + } + + + result = 0; + + goto DONE; + + /* + * ------------- + * Failed... + * ------------- + */ +FAIL2: + (void) sem_destroy (&(cv->semBlockQueue)); + +FAIL1: + (void) sem_destroy (&(cv->semBlockLock)); + +FAIL0: +DONE: + *cond = cv; + + return (result); + +} /* pthread_cond_init */ + +int +pthread_cond_destroy (pthread_cond_t * cond) +{ + int result = 0; + pthread_cond_t cv; + + /* + * Assuming any race condition here is harmless. + */ + if (cond == NULL + || *cond == NULL) + { + return EINVAL; + } + + if (*cond != (pthread_cond_t) PTW32_OBJECT_AUTO_INIT) + {(*cond + cv = *cond; + + /* + * Synchronize access to waiters blocked count (LEVEL-1) + */ + if (sem_wait(&(cv->semBlockLock)) != 0) + {(sem_wait(&(cv->semBlockLock)) + return errno; + } + + /* + * Synchronize access to waiters (to)unblock(ed) counts (LEVEL-2) + */ + if ((result = pthread_mutex_lock(&(cv->mtxUnblockLock))) != 0) + {((result + (void) sem_post(&(cv->semBlockLock)); + return result; + } + + /* + * Check whether cv is still busy (still has waiters blocked) + */ + if (cv->nWaitersBlocked - cv->nWaitersUnblocked > 0) + {(cv->nWaitersBlocked + (void) sem_post(&(cv->semBlockLock)); + (void) pthread_mutex_unlock(&(cv->mtxUnblockLock)); + return EBUSY; + } + + /* + * Now it is safe to destroy + */ + (void) sem_destroy (&(cv->semBlockLock)); + (void) sem_destroy (&(cv->semBlockQueue)); + (void) pthread_mutex_unlock (&(cv->mtxUnblockLock)); + (void) pthread_mutex_destroy (&(cv->mtxUnblockLock)); + + free(cv); + *cond = NULL; + } + else + { + /* + * See notes in ptw32_cond_check_need_init() above also. + */ + EnterCriticalSection(&ptw32_cond_test_init_lock); + + /* + * Check again. + */ + if (*cond == (pthread_cond_t) PTW32_OBJECT_AUTO_INIT) + {(*cond + /* + * This is all we need to do to destroy a statically + * initialised cond that has not yet been used (initialised). + * If we get to here, another thread + * waiting to initialise this cond will get an EINVAL. + */ + *cond = NULL; + } + else + { + /* + * The cv has been initialised while we were waiting + * so assume it's in use. + */ + result = EBUSY; + } + + LeaveCriticalSection(&ptw32_cond_test_init_lock); + } + + return (result); +} + +/* + * Arguments for cond_wait_cleanup, since we can only pass a + * single void * to it. + */ +typedef struct { + pthread_mutex_t * mutexPtr; + pthread_cond_t cv; + int * resultPtr; +} ptw32_cond_wait_cleanup_args_t; + +static void +ptw32_cond_wait_cleanup(void * args) +{ + ptw32_cond_wait_cleanup_args_t * cleanup_args = +(ptw32_cond_wait_cleanup_args_t *) args; + pthread_cond_t cv = cleanup_args->cv; + int * resultPtr = cleanup_args->resultPtr; + int eLastSignal; /* enum: 1=yes 0=no -1=cancelled/timedout w/o signal(s) +*/ + int result; + + /* + * Whether we got here as a result of signal/broadcast or because of + * timeout on wait or thread cancellation we indicate that we are no + * longer waiting. The waiter is responsible for adjusting waiters + * (to)unblock(ed) counts (protected by unblock lock). + * Unblock lock/Sync.LEVEL-2 supports _timedwait and cancellation. + */ + if ((result = pthread_mutex_lock(&(cv->mtxUnblockLock))) != 0) + {((result + *resultPtr = result; + return; + } + + cv->nWaitersUnblocked++; + + eLastSignal = (cv->nWaitersToUnblock == 0) ? + -1 : (--cv->nWaitersToUnblock == 0); + + /* + * No more LEVEL-2 access to waiters (to)unblock(ed) counts needed + */ + if ((result = pthread_mutex_unlock(&(cv->mtxUnblockLock))) != 0) + {((result + *resultPtr = result; + return; + } + + /* + * If last signal... + */ + if (eLastSignal == 1) + {(eLastSignal + /* + * ...it means that we have end of 'atomic' signal/broadcast + */ + if (sem_post(&(cv->semBlockLock)) != 0) + {(sem_post(&(cv->semBlockLock)) + *resultPtr = errno; + return; + } + } + /* + * If not last signal and not timed out/cancelled wait w/o signal... + */ + else if (eLastSignal == 0) + { + /* + * ...it means that next waiter can go through semaphore + */ + if (sem_post(&(cv->semBlockQueue)) != 0) + {(sem_post(&(cv->semBlockQueue)) + *resultPtr = errno; + return; + } + } + + /* + * XSH: Upon successful return, the mutex has been locked and is owned + * by the calling thread + */ + if ((result = pthread_mutex_lock(cleanup_args->mutexPtr)) != 0) + {((result + *resultPtr = result; + } + +} /* ptw32_cond_wait_cleanup */ + +static int +ptw32_cond_timedwait (pthread_cond_t * cond, + pthread_mutex_t * mutex, + const struct timespec *abstime) +{ + int result = 0; + pthread_cond_t cv; + ptw32_cond_wait_cleanup_args_t cleanup_args; + + if (cond == NULL || *cond == NULL) + {(cond + return EINVAL; + } + + /* + * We do a quick check to see if we need to do more work + * to initialise a static condition variable. We check + * again inside the guarded section of ptw32_cond_check_need_init() + * to avoid race conditions. + */ + if (*cond == (pthread_cond_t) PTW32_OBJECT_AUTO_INIT) + {(*cond + result = ptw32_cond_check_need_init(cond); + } + + if (result != 0 && result != EBUSY) + {(result + return result; + } + + cv = *cond; + + /* + * Synchronize access to waiters blocked count (LEVEL-1) + */ + if (sem_wait(&(cv->semBlockLock)) != 0) + {(sem_wait(&(cv->semBlockLock)) + return errno; + } + + cv->nWaitersBlocked++; + + /* + * Thats it. Counted means waiting, no more access needed + */ + if (sem_post(&(cv->semBlockLock)) != 0) + {(sem_post(&(cv->semBlockLock)) + return errno; + } + + /* + * Setup this waiter cleanup handler + */ + cleanup_args.mutexPtr = mutex; + cleanup_args.cv = cv; + cleanup_args.resultPtr = &result; + + pthread_cleanup_push (ptw32_cond_wait_cleanup, (void *) &cleanup_args); + + /* + * Now we can release 'mutex' and... + */ + if ((result = pthread_mutex_unlock (mutex)) == 0) + {((result + + /* + * ...wait to be awakened by + * pthread_cond_signal, or + * pthread_cond_broadcast, or + * timeout, or + * thread cancellation + * + * Note: + * + * ptw32_sem_timedwait is a cancellation point, + * hence providing the mechanism for making + * pthread_cond_wait a cancellation point. + * We use the cleanup mechanism to ensure we + * re-lock the mutex and adjust (to)unblock(ed) waiters + * counts if we are cancelled, timed out or signalled. + */ + if (ptw32_sem_timedwait (&(cv->semBlockQueue), abstime) != 0) + {(ptw32_sem_timedwait + result = errno; + } + } + + /* + * Always cleanup + */ + pthread_cleanup_pop (1); + + + /* + * "result" can be modified by the cleanup handler. + */ + return (result); + +} /* ptw32_cond_timedwait */ + + +static int +ptw32_cond_unblock (pthread_cond_t * cond, + int unblockAll) +{ + int result; + pthread_cond_t cv; + + if (cond == NULL || *cond == NULL) + {(cond + return EINVAL; + } + + cv = *cond; + + /* + * No-op if the CV is static and hasn't been initialised yet. + * Assuming that any race condition is harmless. + */ + if (cv == (pthread_cond_t) PTW32_OBJECT_AUTO_INIT) + {(cv + return 0; + } + + /* + * Synchronize access to waiters blocked count (LEVEL-1) + */ + if (sem_wait(&(cv->semBlockLock)) != 0) + {(sem_wait(&(cv->semBlockLock)) + return errno; + } + + /* + * Synchronize access to waiters (to)unblock(ed) counts (LEVEL-2) + * This sync.level supports _timedwait and cancellation + */ + if ((result = pthread_mutex_lock(&(cv->mtxUnblockLock))) != 0) + {((result + return result; + } + + /* + * Adjust waiters blocked and unblocked counts (collect garbage) + */ + if (cv->nWaitersUnblocked != 0) + {(cv->nWaitersUnblocked + cv->nWaitersBlocked -= cv->nWaitersUnblocked; + cv->nWaitersUnblocked = 0; + } + + /* + * If (after adjustment) there are still some waiters blocked counted... + */ + if ( cv->nWaitersBlocked > 0) + {( + /* + * We will unblock first waiter and leave semBlockLock/LEVEL-1 locked + * LEVEL-1 access is left disabled until last signal/unblock +completes + */ + cv->nWaitersToUnblock = (unblockAll) ? cv->nWaitersBlocked : 1; + + /* + * No more LEVEL-2 access to waiters (to)unblock(ed) counts needed + * This sync.level supports _timedwait and cancellation + */ + if ((result = pthread_mutex_unlock(&(cv->mtxUnblockLock))) != 0) + {((result + return result; + } + + + /* + * Now, with LEVEL-2 lock released let first waiter go through +semaphore + */ + if (sem_post(&(cv->semBlockQueue)) != 0) + {(sem_post(&(cv->semBlockQueue)) + return errno; + } + } + /* + * No waiter blocked - no more LEVEL-1 access to blocked count needed... + */ + else if (sem_post(&(cv->semBlockLock)) != 0) + { + return errno; + } + /* + * ...and no more LEVEL-2 access to waiters (to)unblock(ed) counts needed +too + * This sync.level supports _timedwait and cancellation + */ + else + { + result = pthread_mutex_unlock(&(cv->mtxUnblockLock)); + } + + return(result); + +} /* ptw32_cond_unblock */ + +int +pthread_cond_wait (pthread_cond_t * cond, + pthread_mutex_t * mutex) +{ + /* The NULL abstime arg means INFINITE waiting. */ + return(ptw32_cond_timedwait(cond, mutex, NULL)); +} /* pthread_cond_wait */ + + +int +pthread_cond_timedwait (pthread_cond_t * cond, + pthread_mutex_t * mutex, + const struct timespec *abstime) +{ + if (abstime == NULL) + {(abstime + return EINVAL; + } + + return(ptw32_cond_timedwait(cond, mutex, abstime)); +} /* pthread_cond_timedwait */ + + +int +pthread_cond_signal (pthread_cond_t * cond) +{ + /* The '0'(FALSE) unblockAll arg means unblock ONE waiter. */ + return(ptw32_cond_unblock(cond, 0)); +} /* pthread_cond_signal */ + +int +pthread_cond_broadcast (pthread_cond_t * cond) +{ + /* The '1'(TRUE) unblockAll arg means unblock ALL waiters. */ + return(ptw32_cond_unblock(cond, 1)); +} /* pthread_cond_broadcast */ + + + + +TEREKHOV@de.ibm.com on 17.01.2001 01:00:57 + +Please respond to TEREKHOV@de.ibm.com + +To: pthreads-win32@sourceware.cygnus.com +cc: schmidt@uci.edu +Subject: win32 conditions: sem+counter+event = broadcast_deadlock + + spur.wakeup/unfairness/incorrectness ?? + + + + + + + +Hi, + +Problem 1: broadcast_deadlock + +It seems that current implementation does not provide "atomic" +broadcasts. That may lead to "nested" broadcasts... and it seems +that nested case is not handled correctly -> producing a broadcast +DEADLOCK as a result. + +Scenario: + +N (>1) waiting threads W1..N are blocked (in _wait) on condition's +semaphore. + +Thread B1 calls pthread_cond_broadcast, which results in "releasing" N +W threads via incrementing semaphore counter by N (stored in +cv->waiters) BUT cv->waiters counter does not change!! The caller +thread B1 remains blocked on cv->waitersDone event (auto-reset!!) BUT +condition is not protected from starting another broadcast (when called +on another thread) while still waiting for the "old" broadcast to +complete on thread B1. + +M (>=0, waiters counter. + +L (N-M) "late" waiter W threads are a) still blocked/not returned from +their semaphore wait call or b) were preempted after sem_wait but before +lock( &cv->waitersLock ) or c) are blocked on cv->waitersLock. + +cv->waiters is still > 0 (= L). + +Another thread B2 (or some W thread from M group) calls +pthread_cond_broadcast and gains access to counter... neither a) nor b) +prevent thread B2 in pthread_cond_broadcast from gaining access to +counter and starting another broadcast ( for c) - it depends on +cv->waitersLock scheduling rules: FIFO=OK, PRTY=PROBLEM,... ) + +That call to pthread_cond_broadcast (on thread B2) will result in +incrementing semaphore by cv->waiters (=L) which is INCORRECT (all +W1..N were in fact already released by thread B1) and waiting on +_auto-reset_ event cv->waitersDone which is DEADLY WRONG (produces a +deadlock)... + +All late W1..L threads now have a chance to complete their _wait call. +Last W_L thread sets an auto-reselt event cv->waitersDone which will +release either B1 or B2 leaving one of B threads in a deadlock. + +Problem 2: spur.wakeup/unfairness/incorrectness + +It seems that: + +a) because of the same problem with counter which does not reflect the +actual number of NOT RELEASED waiters, the signal call may increment +a semaphore counter w/o having a waiter blocked on it. That will result +in (best case) spurious wake ups - performance degradation due to +unnecessary context switches and predicate re-checks and (in worth case) +unfairness/incorrectness problem - see b) + +b) neither signal nor broadcast prevent other threads - "new waiters" +(and in the case of signal, the caller thread as well) from going into +_wait and overtaking "old" waiters (already released but still not returned +from sem_wait on condition's semaphore). Win semaphore just [API DOC]: +"Maintains a count between zero and some maximum value, limiting the number +of threads that are simultaneously accessing a shared resource." Calling +ReleaseSemaphore does not imply (at least not documented) that on return +from ReleaseSemaphore all waiters will in fact become released (returned +from their Wait... call) and/or that new waiters calling Wait... afterwards +will become less importance. It is NOT documented to be an atomic release +of +waiters... And even if it would be there is still a problem with a thread +being preempted after Wait on semaphore and before Wait on cv->waitersLock +and scheduling rules for cv->waitersLock itself +(??WaitForMultipleObjects??) +That may result in unfairness/incorrectness problem as described +for SetEvent impl. in "Strategies for Implementing POSIX Condition +Variables +on Win32": http://www.cs.wustl.edu/~schmidt/win32-cv-1.html + +Unfairness -- The semantics of the POSIX pthread_cond_broadcast function is +to wake up all threads currently blocked in wait calls on the condition +variable. The awakened threads then compete for the external_mutex. To +ensure +fairness, all of these threads should be released from their +pthread_cond_wait calls and allowed to recheck their condition expressions +before other threads can successfully complete a wait on the condition +variable. + +Unfortunately, the SetEvent implementation above does not guarantee that +all +threads sleeping on the condition variable when cond_broadcast is called +will +acquire the external_mutex and check their condition expressions. Although +the Pthreads specification does not mandate this degree of fairness, the +lack of fairness can cause starvation. + +To illustrate the unfairness problem, imagine there are 2 threads, C1 and +C2, +that are blocked in pthread_cond_wait on condition variable not_empty_ that +is guarding a thread-safe message queue. Another thread, P1 then places two +messages onto the queue and calls pthread_cond_broadcast. If C1 returns +from +pthread_cond_wait, dequeues and processes the message, and immediately +waits +again then it and only it may end up acquiring both messages. Thus, C2 will +never get a chance to dequeue a message and run. + +The following illustrates the sequence of events: + +1. Thread C1 attempts to dequeue and waits on CV non_empty_ +2. Thread C2 attempts to dequeue and waits on CV non_empty_ +3. Thread P1 enqueues 2 messages and broadcasts to CV not_empty_ +4. Thread P1 exits +5. Thread C1 wakes up from CV not_empty_, dequeues a message and runs +6. Thread C1 waits again on CV not_empty_, immediately dequeues the 2nd + message and runs +7. Thread C1 exits +8. Thread C2 is the only thread left and blocks forever since + not_empty_ will never be signaled + +Depending on the algorithm being implemented, this lack of fairness may +yield +concurrent programs that have subtle bugs. Of course, application +developers +should not rely on the fairness semantics of pthread_cond_broadcast. +However, +there are many cases where fair implementations of condition variables can +simplify application code. + +Incorrectness -- A variation on the unfairness problem described above +occurs +when a third consumer thread, C3, is allowed to slip through even though it +was not waiting on condition variable not_empty_ when a broadcast occurred. + +To illustrate this, we will use the same scenario as above: 2 threads, C1 +and +C2, are blocked dequeuing messages from the message queue. Another thread, +P1 +then places two messages onto the queue and calls pthread_cond_broadcast. +C1 +returns from pthread_cond_wait, dequeues and processes the message. At this +time, C3 acquires the external_mutex, calls pthread_cond_wait and waits on +the events in WaitForMultipleObjects. Since C2 has not had a chance to run +yet, the BROADCAST event is still signaled. C3 then returns from +WaitForMultipleObjects, and dequeues and processes the message in the +queue. +Thus, C2 will never get a chance to dequeue a message and run. + +The following illustrates the sequence of events: + +1. Thread C1 attempts to dequeue and waits on CV non_empty_ +2. Thread C2 attempts to dequeue and waits on CV non_empty_ +3. Thread P1 enqueues 2 messages and broadcasts to CV not_empty_ +4. Thread P1 exits +5. Thread C1 wakes up from CV not_empty_, dequeues a message and runs +6. Thread C1 exits +7. Thread C3 waits on CV not_empty_, immediately dequeues the 2nd + message and runs +8. Thread C3 exits +9. Thread C2 is the only thread left and blocks forever since + not_empty_ will never be signaled + +In the above case, a thread that was not waiting on the condition variable +when a broadcast occurred was allowed to proceed. This leads to incorrect +semantics for a condition variable. + + +COMMENTS??? + +regards, +alexander. + +----------------------------------------------------------------------------- + +Subject: RE: FYI/comp.programming.threads/Re: pthread_cond_* + implementation questions +Date: Wed, 21 Feb 2001 11:54:47 +0100 +From: TEREKHOV@de.ibm.com +To: lthomas@arbitrade.com +CC: rpj@ise.canberra.edu.au, Thomas Pfaff , + Nanbor Wang + +Hi Louis, + +generation number 8.. + +had some time to revisit timeouts/spurious wakeup problem.. +found some bugs (in 7.b/c/d) and something to improve +(7a - using IPC semaphores but it should speedup Win32 +version as well). + +regards, +alexander. + +---------- Algorithm 8a / IMPL_SEM,UNBLOCK_STRATEGY == UNBLOCK_ALL ------ +given: +semBlockLock - bin.semaphore +semBlockQueue - semaphore +mtxExternal - mutex or CS +mtxUnblockLock - mutex or CS +nWaitersGone - int +nWaitersBlocked - int +nWaitersToUnblock - int + +wait( timeout ) { + + [auto: register int result ] // error checking omitted + [auto: register int nSignalsWasLeft ] + [auto: register int nWaitersWasGone ] + + sem_wait( semBlockLock ); + nWaitersBlocked++; + sem_post( semBlockLock ); + + unlock( mtxExternal ); + bTimedOut = sem_wait( semBlockQueue,timeout ); + + lock( mtxUnblockLock ); + if ( 0 != (nSignalsWasLeft = nWaitersToUnblock) ) { + if ( bTimeout ) { // timeout (or canceled) + if ( 0 != nWaitersBlocked ) { + nWaitersBlocked--; + } + else { + nWaitersGone++; // count spurious wakeups + } + } + if ( 0 == --nWaitersToUnblock ) { + if ( 0 != nWaitersBlocked ) { + sem_post( semBlockLock ); // open the gate + nSignalsWasLeft = 0; // do not open the gate below +again + } + else if ( 0 != (nWaitersWasGone = nWaitersGone) ) { + nWaitersGone = 0; + } + } + } + else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious +semaphore :-) + sem_wait( semBlockLock ); + nWaitersBlocked -= nWaitersGone; // something is going on here - +test of timeouts? :-) + sem_post( semBlockLock ); + nWaitersGone = 0; + } + unlock( mtxUnblockLock ); + + if ( 1 == nSignalsWasLeft ) { + if ( 0 != nWaitersWasGone ) { + // sem_adjust( -nWaitersWasGone ); + while ( nWaitersWasGone-- ) { + sem_wait( semBlockLock ); // better now than spurious +later + } + } + sem_post( semBlockLock ); // open the gate + } + + lock( mtxExternal ); + + return ( bTimedOut ) ? ETIMEOUT : 0; +} + +signal(bAll) { + + [auto: register int result ] + [auto: register int nSignalsToIssue] + + lock( mtxUnblockLock ); + + if ( 0 != nWaitersToUnblock ) { // the gate is closed!!! + if ( 0 == nWaitersBlocked ) { // NO-OP + return unlock( mtxUnblockLock ); + } + if (bAll) { + nWaitersToUnblock += nSignalsToIssue=nWaitersBlocked; + nWaitersBlocked = 0; + } + else { + nSignalsToIssue = 1; + nWaitersToUnblock++; + nWaitersBlocked--; + } + } + else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION! + sem_wait( semBlockLock ); // close the gate + if ( 0 != nWaitersGone ) { + nWaitersBlocked -= nWaitersGone; + nWaitersGone = 0; + } + if (bAll) { + nSignalsToIssue = nWaitersToUnblock = nWaitersBlocked; + nWaitersBlocked = 0; + } + else { + nSignalsToIssue = nWaitersToUnblock = 1; + nWaitersBlocked--; + } + } + else { // NO-OP + return unlock( mtxUnblockLock ); + } + + unlock( mtxUnblockLock ); + sem_post( semBlockQueue,nSignalsToIssue ); + return result; +} + +---------- Algorithm 8b / IMPL_SEM,UNBLOCK_STRATEGY == UNBLOCK_ONEBYONE +------ +given: +semBlockLock - bin.semaphore +semBlockQueue - bin.semaphore +mtxExternal - mutex or CS +mtxUnblockLock - mutex or CS +nWaitersGone - int +nWaitersBlocked - int +nWaitersToUnblock - int + +wait( timeout ) { + + [auto: register int result ] // error checking omitted + [auto: register int nWaitersWasGone ] + [auto: register int nSignalsWasLeft ] + + sem_wait( semBlockLock ); + nWaitersBlocked++; + sem_post( semBlockLock ); + + unlock( mtxExternal ); + bTimedOut = sem_wait( semBlockQueue,timeout ); + + lock( mtxUnblockLock ); + if ( 0 != (nSignalsWasLeft = nWaitersToUnblock) ) { + if ( bTimeout ) { // timeout (or canceled) + if ( 0 != nWaitersBlocked ) { + nWaitersBlocked--; + nSignalsWasLeft = 0; // do not unblock next waiter +below (already unblocked) + } + else { + nWaitersGone = 1; // spurious wakeup pending!! + } + } + if ( 0 == --nWaitersToUnblock && + if ( 0 != nWaitersBlocked ) { + sem_post( semBlockLock ); // open the gate + nSignalsWasLeft = 0; // do not open the gate below +again + } + else if ( 0 != (nWaitersWasGone = nWaitersGone) ) { + nWaitersGone = 0; + } + } + } + else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious +semaphore :-) + sem_wait( semBlockLock ); + nWaitersBlocked -= nWaitersGone; // something is going on here - +test of timeouts? :-) + sem_post( semBlockLock ); + nWaitersGone = 0; + } + unlock( mtxUnblockLock ); + + if ( 1 == nSignalsWasLeft ) { + if ( 0 != nWaitersWasGone ) { + // sem_adjust( -1 ); + sem_wait( semBlockQueue ); // better now than spurious +later + } + sem_post( semBlockLock ); // open the gate + } + else if ( 0 != nSignalsWasLeft ) { + sem_post( semBlockQueue ); // unblock next waiter + } + + lock( mtxExternal ); + + return ( bTimedOut ) ? ETIMEOUT : 0; +} + +signal(bAll) { + + [auto: register int result ] + + lock( mtxUnblockLock ); + + if ( 0 != nWaitersToUnblock ) { // the gate is closed!!! + if ( 0 == nWaitersBlocked ) { // NO-OP + return unlock( mtxUnblockLock ); + } + if (bAll) { + nWaitersToUnblock += nWaitersBlocked; + nWaitersBlocked = 0; + } + else { + nWaitersToUnblock++; + nWaitersBlocked--; + } + unlock( mtxUnblockLock ); + } + else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION! + sem_wait( semBlockLock ); // close the gate + if ( 0 != nWaitersGone ) { + nWaitersBlocked -= nWaitersGone; + nWaitersGone = 0; + } + if (bAll) { + nWaitersToUnblock = nWaitersBlocked; + nWaitersBlocked = 0; + } + else { + nWaitersToUnblock = 1; + nWaitersBlocked--; + } + unlock( mtxUnblockLock ); + sem_post( semBlockQueue ); + } + else { // NO-OP + unlock( mtxUnblockLock ); + } + + return result; +} + +---------- Algorithm 8c / IMPL_EVENT,UNBLOCK_STRATEGY == UNBLOCK_ONEBYONE +--------- +given: +hevBlockLock - auto-reset event +hevBlockQueue - auto-reset event +mtxExternal - mutex or CS +mtxUnblockLock - mutex or CS +nWaitersGone - int +nWaitersBlocked - int +nWaitersToUnblock - int + +wait( timeout ) { + + [auto: register int result ] // error checking omitted + [auto: register int nSignalsWasLeft ] + [auto: register int nWaitersWasGone ] + + wait( hevBlockLock,INFINITE ); + nWaitersBlocked++; + set_event( hevBlockLock ); + + unlock( mtxExternal ); + bTimedOut = wait( hevBlockQueue,timeout ); + + lock( mtxUnblockLock ); + if ( 0 != (SignalsWasLeft = nWaitersToUnblock) ) { + if ( bTimeout ) { // timeout (or canceled) + if ( 0 != nWaitersBlocked ) { + nWaitersBlocked--; + nSignalsWasLeft = 0; // do not unblock next waiter +below (already unblocked) + } + else { + nWaitersGone = 1; // spurious wakeup pending!! + } + } + if ( 0 == --nWaitersToUnblock ) + if ( 0 != nWaitersBlocked ) { + set_event( hevBlockLock ); // open the gate + nSignalsWasLeft = 0; // do not open the gate below +again + } + else if ( 0 != (nWaitersWasGone = nWaitersGone) ) { + nWaitersGone = 0; + } + } + } + else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious +event :-) + wait( hevBlockLock,INFINITE ); + nWaitersBlocked -= nWaitersGone; // something is going on here - +test of timeouts? :-) + set_event( hevBlockLock ); + nWaitersGone = 0; + } + unlock( mtxUnblockLock ); + + if ( 1 == nSignalsWasLeft ) { + if ( 0 != nWaitersWasGone ) { + reset_event( hevBlockQueue ); // better now than spurious +later + } + set_event( hevBlockLock ); // open the gate + } + else if ( 0 != nSignalsWasLeft ) { + set_event( hevBlockQueue ); // unblock next waiter + } + + lock( mtxExternal ); + + return ( bTimedOut ) ? ETIMEOUT : 0; +} + +signal(bAll) { + + [auto: register int result ] + + lock( mtxUnblockLock ); + + if ( 0 != nWaitersToUnblock ) { // the gate is closed!!! + if ( 0 == nWaitersBlocked ) { // NO-OP + return unlock( mtxUnblockLock ); + } + if (bAll) { + nWaitersToUnblock += nWaitersBlocked; + nWaitersBlocked = 0; + } + else { + nWaitersToUnblock++; + nWaitersBlocked--; + } + unlock( mtxUnblockLock ); + } + else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION! + wait( hevBlockLock,INFINITE ); // close the gate + if ( 0 != nWaitersGone ) { + nWaitersBlocked -= nWaitersGone; + nWaitersGone = 0; + } + if (bAll) { + nWaitersToUnblock = nWaitersBlocked; + nWaitersBlocked = 0; + } + else { + nWaitersToUnblock = 1; + nWaitersBlocked--; + } + unlock( mtxUnblockLock ); + set_event( hevBlockQueue ); + } + else { // NO-OP + unlock( mtxUnblockLock ); + } + + return result; +} + +---------- Algorithm 8d / IMPL_EVENT,UNBLOCK_STRATEGY == UNBLOCK_ALL ------ +given: +hevBlockLock - auto-reset event +hevBlockQueueS - auto-reset event // for signals +hevBlockQueueB - manual-reset even // for broadcasts +mtxExternal - mutex or CS +mtxUnblockLock - mutex or CS +eBroadcast - int // 0: no broadcast, 1: broadcast, 2: +broadcast after signal(s) +nWaitersGone - int +nWaitersBlocked - int +nWaitersToUnblock - int + +wait( timeout ) { + + [auto: register int result ] // error checking omitted + [auto: register int eWasBroadcast ] + [auto: register int nSignalsWasLeft ] + [auto: register int nWaitersWasGone ] + + wait( hevBlockLock,INFINITE ); + nWaitersBlocked++; + set_event( hevBlockLock ); + + unlock( mtxExternal ); + bTimedOut = waitformultiple( hevBlockQueueS,hevBlockQueueB,timeout,ONE ); + + lock( mtxUnblockLock ); + if ( 0 != (SignalsWasLeft = nWaitersToUnblock) ) { + if ( bTimeout ) { // timeout (or canceled) + if ( 0 != nWaitersBlocked ) { + nWaitersBlocked--; + nSignalsWasLeft = 0; // do not unblock next waiter +below (already unblocked) + } + else if ( 1 != eBroadcast ) { + nWaitersGone = 1; + } + } + if ( 0 == --nWaitersToUnblock ) { + if ( 0 != nWaitersBlocked ) { + set_event( hevBlockLock ); // open the gate + nSignalsWasLeft = 0; // do not open the gate below +again + } + else { + if ( 0 != (eWasBroadcast = eBroadcast) ) { + eBroadcast = 0; + } + if ( 0 != (nWaitersWasGone = nWaitersGone ) { + nWaitersGone = 0; + } + } + } + else if ( 0 != eBroadcast ) { + nSignalsWasLeft = 0; // do not unblock next waiter +below (already unblocked) + } + } + else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious +event :-) + wait( hevBlockLock,INFINITE ); + nWaitersBlocked -= nWaitersGone; // something is going on here - +test of timeouts? :-) + set_event( hevBlockLock ); + nWaitersGone = 0; + } + unlock( mtxUnblockLock ); + + if ( 1 == nSignalsWasLeft ) { + if ( 0 != eWasBroadcast ) { + reset_event( hevBlockQueueB ); + } + if ( 0 != nWaitersWasGone ) { + reset_event( hevBlockQueueS ); // better now than spurious +later + } + set_event( hevBlockLock ); // open the gate + } + else if ( 0 != nSignalsWasLeft ) { + set_event( hevBlockQueueS ); // unblock next waiter + } + + lock( mtxExternal ); + + return ( bTimedOut ) ? ETIMEOUT : 0; +} + +signal(bAll) { + + [auto: register int result ] + [auto: register HANDLE hevBlockQueue ] + + lock( mtxUnblockLock ); + + if ( 0 != nWaitersToUnblock ) { // the gate is closed!!! + if ( 0 == nWaitersBlocked ) { // NO-OP + return unlock( mtxUnblockLock ); + } + if (bAll) { + nWaitersToUnblock += nWaitersBlocked; + nWaitersBlocked = 0; + eBroadcast = 2; + hevBlockQueue = hevBlockQueueB; + } + else { + nWaitersToUnblock++; + nWaitersBlocked--; + return unlock( mtxUnblockLock ); + } + } + else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION! + wait( hevBlockLock,INFINITE ); // close the gate + if ( 0 != nWaitersGone ) { + nWaitersBlocked -= nWaitersGone; + nWaitersGone = 0; + } + if (bAll) { + nWaitersToUnblock = nWaitersBlocked; + nWaitersBlocked = 0; + eBroadcast = 1; + hevBlockQueue = hevBlockQueueB; + } + else { + nWaitersToUnblock = 1; + nWaitersBlocked--; + hevBlockQueue = hevBlockQueueS; + } + } + else { // NO-OP + return unlock( mtxUnblockLock ); + } + + unlock( mtxUnblockLock ); + set_event( hevBlockQueue ); + return result; +} +---------------------- Forwarded by Alexander Terekhov/Germany/IBM on +02/21/2001 09:13 AM --------------------------- + +Alexander Terekhov +02/20/2001 04:33 PM + +To: Louis Thomas +cc: + +From: Alexander Terekhov/Germany/IBM@IBMDE +Subject: RE: FYI/comp.programming.threads/Re: pthread_cond_* implementatio + n questions +Importance: Normal + +>Sorry, gotta take a break and work on something else for a while. +>Real work +>calls, unfortunately. I'll get back to you in two or three days. + +ok. no problem. here is some more stuff for pauses you might have +in between :) + +---------- Algorithm 7d / IMPL_EVENT,UNBLOCK_STRATEGY == UNBLOCK_ALL ------ +given: +hevBlockLock - auto-reset event +hevBlockQueueS - auto-reset event // for signals +hevBlockQueueB - manual-reset even // for broadcasts +mtxExternal - mutex or CS +mtxUnblockLock - mutex or CS +bBroadcast - int +nWaitersGone - int +nWaitersBlocked - int +nWaitersToUnblock - int + +wait( timeout ) { + + [auto: register int result ] // error checking omitted + [auto: register int bWasBroadcast ] + [auto: register int nSignalsWasLeft ] + + wait( hevBlockLock,INFINITE ); + nWaitersBlocked++; + set_event( hevBlockLock ); + + unlock( mtxExternal ); + bTimedOut = waitformultiple( hevBlockQueueS,hevBlockQueueB,timeout,ONE ); + + lock( mtxUnblockLock ); + if ( 0 != (SignalsWasLeft = nWaitersToUnblock) ) { + if ( bTimeout ) { // timeout (or canceled) + if ( 0 != nWaitersBlocked ) { + nWaitersBlocked--; + nSignalsWasLeft = 0; // do not unblock next waiter +below (already unblocked) + } + else if ( !bBroadcast ) { + wait( hevBlockQueueS,INFINITE ); // better now than spurious +later + } + } + if ( 0 == --nWaitersToUnblock ) { + if ( 0 != nWaitersBlocked ) { + if ( bBroadcast ) { + reset_event( hevBlockQueueB ); + bBroadcast = false; + } + set_event( hevBlockLock ); // open the gate + nSignalsWasLeft = 0; // do not open the gate below +again + } + else if ( false != (bWasBroadcast = bBroadcast) ) { + bBroadcast = false; + } + } + else { + bWasBroadcast = bBroadcast; + } + } + else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or spurious +event :-) + wait( hevBlockLock,INFINITE ); + nWaitersBlocked -= nWaitersGone; // something is going on here - +test of timeouts? :-) + set_event( hevBlockLock ); + nWaitersGone = 0; + } + unlock( mtxUnblockLock ); + + if ( 1 == nSignalsWasLeft ) { + if ( bWasBroadcast ) { + reset_event( hevBlockQueueB ); + } + set_event( hevBlockLock ); // open the gate + } + else if ( 0 != nSignalsWasLeft && !bWasBroadcast ) { + set_event( hevBlockQueueS ); // unblock next waiter + } + + lock( mtxExternal ); + + return ( bTimedOut ) ? ETIMEOUT : 0; +} + +signal(bAll) { + + [auto: register int result ] + [auto: register HANDLE hevBlockQueue ] + + lock( mtxUnblockLock ); + + if ( 0 != nWaitersToUnblock ) { // the gate is closed!!! + if ( 0 == nWaitersBlocked ) { // NO-OP + return unlock( mtxUnblockLock ); + } + if (bAll) { + nWaitersToUnblock += nWaitersBlocked; + nWaitersBlocked = 0; + bBroadcast = true; + hevBlockQueue = hevBlockQueueB; + } + else { + nWaitersToUnblock++; + nWaitersBlocked--; + return unlock( mtxUnblockLock ); + } + } + else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION! + wait( hevBlockLock,INFINITE ); // close the gate + if ( 0 != nWaitersGone ) { + nWaitersBlocked -= nWaitersGone; + nWaitersGone = 0; + } + if (bAll) { + nWaitersToUnblock = nWaitersBlocked; + nWaitersBlocked = 0; + bBroadcast = true; + hevBlockQueue = hevBlockQueueB; + } + else { + nWaitersToUnblock = 1; + nWaitersBlocked--; + hevBlockQueue = hevBlockQueueS; + } + } + else { // NO-OP + return unlock( mtxUnblockLock ); + } + + unlock( mtxUnblockLock ); + set_event( hevBlockQueue ); + return result; +} + + +---------------------------------------------------------------------------- + +Subject: RE: FYI/comp.programming.threads/Re: pthread_cond_* implementatio + n questions +Date: Mon, 26 Feb 2001 22:20:12 -0600 +From: Louis Thomas +To: "'TEREKHOV@de.ibm.com'" +CC: rpj@ise.canberra.edu.au, Thomas Pfaff , + Nanbor Wang + + +Sorry all. Busy week. + +> this insures the fairness +> which POSIX does not (e.g. two subsequent broadcasts - the gate does +insure +> that first wave waiters will start the race for the mutex before waiters +> from the second wave - Linux pthreads process/unblock both waves +> concurrently...) + +I'm not sure how we are any more fair about this than Linux. We certainly +don't guarantee that the threads released by the first broadcast will get +the external mutex before the threads of the second wave. In fact, it is +possible that those threads will never get the external mutex if there is +enough contention for it. + +> e.g. i was thinking about implementation with a pool of +> N semaphores/counters [...] + +I considered that too. The problem is as you mentioned in a). You really +need to assign threads to semaphores once you know how you want to wake them +up, not when they first begin waiting which is the only time you can assign +them. + +> well, i am not quite sure that i've fully understood your scenario, + +Hmm. Well, it think it's an important example, so I'll try again. First, we +have thread A which we KNOW is waiting on a condition. As soon as it becomes +unblocked for any reason, we will know because it will set a flag. Since the +flag is not set, we are 100% confident that thread A is waiting on the +condition. We have another thread, thread B, which has acquired the mutex +and is about to wait on the condition. Thus it is pretty clear that at any +point, either just A is waiting, or A and B are waiting. Now thread C comes +along. C is about to do a broadcast on the condition. A broadcast is +guaranteed to unblock all threads currently waiting on a condition, right? +Again, we said that either just A is waiting, or A and B are both waiting. +So, when C does its broadcast, depending upon whether B has started waiting +or not, thread C will unblock A or unblock A and B. Either way, C must +unblock A, right? + +Now, you said anything that happens is correct so long as a) "a signal is +not lost between unlocking the mutex and waiting on the condition" and b) "a +thread must not steal a signal it sent", correct? Requirement b) is easy to +satisfy: in this scenario, thread C will never wait on the condition, so it +won't steal any signals. Requirement a) is not hard either. The only way we +could fail to meet requirement a) in this scenario is if thread B was +started waiting but didn't wake up because a signal was lost. This will not +happen. + +Now, here is what happens. Assume thread C beats thread B. Thread C looks to +see how many threads are waiting on the condition. Thread C sees just one +thread, thread A, waiting. It does a broadcast waking up just one thread +because just one thread is waiting. Next, before A can become unblocked, +thread B begins waiting. Now there are two threads waiting, but only one +will be unblocked. Suppose B wins. B will become unblocked. A will not +become unblocked, because C only unblocked one thread (sema_post cond, 1). +So at the end, B finishes and A remains blocked. + +We have met both of your requirements, so by your rules, this is an +acceptable outcome. However, I think that the spec says this is an +unacceptable outcome! We know for certain that A was waiting and that C did +a broadcast, but A did not become unblocked! Yet, the spec says that a +broadcast wakes up all waiting threads. This did not happen. Do you agree +that this shows your rules are not strict enough? + +> and what about N2? :) this one does allow almost everything. + +Don't get me started about rule #2. I'll NEVER advocate an algorithm that +uses rule 2 as an excuse to suck! + +> but it is done (decrement)under mutex protection - this is not a subject +> of a race condition. + +You are correct. My mistake. + +> i would remove "_bTimedOut=false".. after all, it was a real timeout.. + +I disagree. A thread that can't successfully retract its waiter status can't +really have timed out. If a thread can't return without executing extra code +to deal with the fact that someone tried to unblock it, I think it is a poor +idea to pretend we +didn't realize someone was trying to signal us. After all, a signal is more +important than a time out. + +> when nSignaled != 0, it is possible to update nWaiters (--) and do not +> touch nGone + +I realize this, but I was thinking that writing it the other ways saves +another if statement. + +> adjust only if nGone != 0 and save one cache memory write - probably much +slower than 'if' + +Hmm. You are probably right. + +> well, in a strange (e.g. timeout test) program you may (theoretically) +> have an overflow of nWaiters/nGone counters (with waiters repeatedly +timing +> out and no signals at all). + +Also true. Not only that, but you also have the possibility that one could +overflow the number of waiters as well! However, considering the limit you +have chosen for nWaitersGone, I suppose it is unlikely that anyone would be +able to get INT_MAX/2 threads waiting on a single condition. :) + +Analysis of 8a: + +It looks correct to me. + +What are IPC semaphores? + +In the line where you state, "else if ( nWaitersBlocked > nWaitersGone ) { +// HARMLESS RACE CONDITION!" there is no race condition for nWaitersGone +because nWaitersGone is never modified without holding mtxUnblockLock. You +are correct that there is a harmless race on nWaitersBlocked, which can +increase and make the condition become true just after we check it. If this +happens, we interpret it as the wait starting after the signal. + +I like your optimization of this. You could improve Alg. 6 as follows: +---------- Algorithm 6b ---------- +signal(bAll) { + _nSig=0 + lock counters + // this is safe because nWaiting can only be decremented by a thread that + // owns counters and nGone can only be changed by a thread that owns +counters. + if (nWaiting>nGone) { + if (0==nSignaled) { + sema_wait gate // close gate if not already closed + } + if (nGone>0) { + nWaiting-=nGone + nGone=0 + } + _nSig=bAll?nWaiting:1 + nSignaled+=_nSig + nWaiting-=_nSig + } + unlock counters + if (0!=_nSig) { + sema_post queue, _nSig + } +} +---------- ---------- ---------- +I guess this wouldn't apply to Alg 8a because nWaitersGone changes meanings +depending upon whether the gate is open or closed. + +In the loop "while ( nWaitersWasGone-- ) {" you do a sema_wait on +semBlockLock. Perhaps waiting on semBlockQueue would be a better idea. + +What have you gained by making the last thread to be signaled do the waits +for all the timed out threads, besides added complexity? It took me a long +time to figure out what your objective was with this, to realize you were +using nWaitersGone to mean two different things, and to verify that you +hadn't introduced any bug by doing this. Even now I'm not 100% sure. + +What has all this playing about with nWaitersGone really gained us besides a +lot of complexity (it is much harder to verify that this solution is +correct), execution overhead (we now have a lot more if statements to +evaluate), and space overhead (more space for the extra code, and another +integer in our data)? We did manage to save a lock/unlock pair in an +uncommon case (when a time out occurs) at the above mentioned expenses in +the common cases. + +As for 8b, c, and d, they look ok though I haven't studied them thoroughly. +What would you use them for? + + Later, + -Louis! :) + +----------------------------------------------------------------------------- + +Subject: RE: FYI/comp.programming.threads/Re: pthread_cond_* implementatio + n questions +Date: Tue, 27 Feb 2001 15:51:28 +0100 +From: TEREKHOV@de.ibm.com +To: Louis Thomas +CC: rpj@ise.canberra.edu.au, Thomas Pfaff , + Nanbor Wang + +Hi Louis, + +>> that first wave waiters will start the race for the mutex before waiters +>> from the second wave - Linux pthreads process/unblock both waves +>> concurrently...) +> +>I'm not sure how we are any more fair about this than Linux. We certainly +>don't guarantee that the threads released by the first broadcast will get +>the external mutex before the threads of the second wave. In fact, it is +>possible that those threads will never get the external mutex if there is +>enough contention for it. + +correct. but gate is nevertheless more fair than Linux because of the +barrier it establishes between two races (1st and 2nd wave waiters) for +the mutex which under 'normal' circumstances (e.g. all threads of equal +priorities,..) will 'probably' result in fair behaviour with respect to +mutex ownership. + +>> well, i am not quite sure that i've fully understood your scenario, +> +>Hmm. Well, it think it's an important example, so I'll try again. ... + +ok. now i seem to understand this example. well, now it seems to me +that the only meaningful rule is just: + +a) "a signal is not lost between unlocking the mutex and waiting on the +condition" + +and that the rule + +b) "a thread must not steal a signal it sent" + +is not needed at all because a thread which violates b) also violates a). + +i'll try to explain.. + +i think that the most important thing is how POSIX defines waiter's +visibility: + +"if another thread is able to acquire the mutex after the about-to-block +thread +has released it, then a subsequent call to pthread_cond_signal() or +pthread_cond_broadcast() in that thread behaves as if it were issued after +the about-to-block thread has blocked. " + +my understanding is the following: + +1) there is no guarantees whatsoever with respect to whether +signal/broadcast +will actually unblock any 'waiter' if it is done w/o acquiring the mutex +first +(note that a thread may release it before signal/broadcast - it does not +matter). + +2) it is guaranteed that waiters become 'visible' - eligible for unblock as +soon +as signalling thread acquires the mutex (but not before!!) + +so.. + +>So, when C does its broadcast, depending upon whether B has started +waiting +>or not, thread C will unblock A or unblock A and B. Either way, C must +>unblock A, right? + +right. but only if C did acquire the mutex prior to broadcast (it may +release it before broadcast as well). + +implementation will violate waiters visibility rule (signal will become +lost) +if C will not unblock A. + +>Now, here is what happens. Assume thread C beats thread B. Thread C looks +to +>see how many threads are waiting on the condition. Thread C sees just one +>thread, thread A, waiting. It does a broadcast waking up just one thread +>because just one thread is waiting. Next, before A can become unblocked, +>thread B begins waiting. Now there are two threads waiting, but only one +>will be unblocked. Suppose B wins. B will become unblocked. A will not +>become unblocked, because C only unblocked one thread (sema_post cond, 1). +>So at the end, B finishes and A remains blocked. + +thread C did acquire the mutex ("Thread C sees just one thread, thread A, +waiting"). beginning from that moment it is guaranteed that subsequent +broadcast will unblock A. Otherwise we will have a lost signal with respect +to A. I do think that it does not matter whether the signal was physically +(completely) lost or was just stolen by another thread (B) - in both cases +it was simply lost with respect to A. + +>..Do you agree that this shows your rules are not strict enough? + +probably the opposite.. :-) i think that it shows that the only meaningful +rule is + +a) "a signal is not lost between unlocking the mutex and waiting on the +condition" + +with clarification of waiters visibility as defined by POSIX above. + +>> i would remove "_bTimedOut=false".. after all, it was a real timeout.. +> +>I disagree. A thread that can't successfully retract its waiter status +can't +>really have timed out. If a thread can't return without executing extra +code +>to deal with the fact that someone tried to unblock it, I think it is a +poor +>idea to pretend we +>didn't realize someone was trying to signal us. After all, a signal is +more +>important than a time out. + +a) POSIX does allow timed out thread to consume a signal (cancelled is +not). +b) ETIMEDOUT status just says that: "The time specified by abstime to +pthread_cond_timedwait() has passed." +c) it seem to me that hiding timeouts would violate "The +pthread_cond_timedwait() +function is the same as pthread_cond_wait() except that an error is +returned if +the absolute time specified by abstime passes (that is, system time equals +or +exceeds abstime) before the condition cond is signaled or broadcasted" +because +the abs. time did really pass before cond was signaled (waiter was +released via semaphore). however, if it really matters, i could imaging +that we +can save an abs. time of signal/broadcast and compare it with timeout after +unblock to find out whether it was a 'real' timeout or not. absent this +check +i do think that hiding timeouts would result in technical violation of +specification.. but i think that this check is not important and we can +simply +trust timeout error code provided by wait since we are not trying to make +'hard' realtime implementation. + +>What are IPC semaphores? + + +int semctl(int, int, int, ...); +int semget(key_t, int, int); +int semop(int, struct sembuf *, size_t); + +they support adjustment of semaphore counter (semvalue) +in one single call - imaging Win32 ReleaseSemaphore( hsem,-N ) + +>In the line where you state, "else if ( nWaitersBlocked > nWaitersGone ) { +>// HARMLESS RACE CONDITION!" there is no race condition for nWaitersGone +>because nWaitersGone is never modified without holding mtxUnblockLock. You +>are correct that there is a harmless race on nWaitersBlocked, which can +>increase and make the condition become true just after we check it. If +this +>happens, we interpret it as the wait starting after the signal. + +well, the reason why i've asked on comp.programming.threads whether this +race +condition is harmless or not is that in order to be harmless it should not +violate the waiters visibility rule (see above). Fortunately, we increment +the counter under protection of external mutex.. so that any (signalling) +thread which will acquire the mutex next, should see the updated counter +(in signal) according to POSIX memory visibility rules and mutexes +(memory barriers). But i am not so sure how it actually works on +Win32/INTEL +which does not explicitly define any memory visibility rules :( + +>I like your optimization of this. You could improve Alg. 6 as follows: +>---------- Algorithm 6b ---------- +>signal(bAll) { +> _nSig=0 +> lock counters +> // this is safe because nWaiting can only be decremented by a thread +that +> // owns counters and nGone can only be changed by a thread that owns +>counters. +> if (nWaiting>nGone) { +> if (0==nSignaled) { +> sema_wait gate // close gate if not already closed +> } +> if (nGone>0) { +> nWaiting-=nGone +> nGone=0 +> } +> _nSig=bAll?nWaiting:1 +> nSignaled+=_nSig +> nWaiting-=_nSig +> } +> unlock counters +> if (0!=_nSig) { +> sema_post queue, _nSig +> } +>} +>---------- ---------- ---------- +>I guess this wouldn't apply to Alg 8a because nWaitersGone changes +meanings +>depending upon whether the gate is open or closed. + +agree. + +>In the loop "while ( nWaitersWasGone-- ) {" you do a sema_wait on +>semBlockLock. Perhaps waiting on semBlockQueue would be a better idea. + +you are correct. my mistake. + +>What have you gained by making the last thread to be signaled do the waits +>for all the timed out threads, besides added complexity? It took me a long +>time to figure out what your objective was with this, to realize you were +>using nWaitersGone to mean two different things, and to verify that you +>hadn't introduced any bug by doing this. Even now I'm not 100% sure. +> +>What has all this playing about with nWaitersGone really gained us besides +a +>lot of complexity (it is much harder to verify that this solution is +>correct), execution overhead (we now have a lot more if statements to +>evaluate), and space overhead (more space for the extra code, and another +>integer in our data)? We did manage to save a lock/unlock pair in an +>uncommon case (when a time out occurs) at the above mentioned expenses in +>the common cases. + +well, please consider the following: + +1) with multiple waiters unblocked (but some timed out) the trick with +counter +seem to ensure potentially higher level of concurrency by not delaying +most of unblocked waiters for semaphore cleanup - only the last one +will be delayed but all others would already contend/acquire/release +the external mutex - the critical section protected by mtxUnblockLock is +made smaller (increment + couple of IFs is faster than system/kernel call) +which i think is good in general. however, you are right, this is done +at expense of 'normal' waiters.. + +2) some semaphore APIs (e.g. POSIX IPC sems) do allow to adjust the +semaphore counter in one call => less system/kernel calls.. imagine: + +if ( 1 == nSignalsWasLeft ) { + if ( 0 != nWaitersWasGone ) { + ReleaseSemaphore( semBlockQueue,-nWaitersWasGone ); // better now +than spurious later + } + sem_post( semBlockLock ); // open the gate + } + +3) even on win32 a single thread doing multiple cleanup calls (to wait) +will probably result in faster execution (because of processor caching) +than multiple threads each doing a single call to wait. + +>As for 8b, c, and d, they look ok though I haven't studied them +thoroughly. +>What would you use them for? + +8b) for semaphores which do not allow to unblock multiple waiters +in a single call to post/release (e.g. POSIX realtime semaphores - +) + +8c/8d) for WinCE prior to 3.0 (WinCE 3.0 does have semaphores) + +ok. so, which one is the 'final' algorithm(s) which we should use in +pthreads-win32?? + +regards, +alexander. + +---------------------------------------------------------------------------- + +Louis Thomas on 02/27/2001 05:20:12 AM + +Please respond to Louis Thomas + +To: Alexander Terekhov/Germany/IBM@IBMDE +cc: rpj@ise.canberra.edu.au, Thomas Pfaff , Nanbor Wang + +Subject: RE: FYI/comp.programming.threads/Re: pthread_cond_* implementatio + n questions + +Sorry all. Busy week. + +> this insures the fairness +> which POSIX does not (e.g. two subsequent broadcasts - the gate does +insure +> that first wave waiters will start the race for the mutex before waiters +> from the second wave - Linux pthreads process/unblock both waves +> concurrently...) + +I'm not sure how we are any more fair about this than Linux. We certainly +don't guarantee that the threads released by the first broadcast will get +the external mutex before the threads of the second wave. In fact, it is +possible that those threads will never get the external mutex if there is +enough contention for it. + +> e.g. i was thinking about implementation with a pool of +> N semaphores/counters [...] + +I considered that too. The problem is as you mentioned in a). You really +need to assign threads to semaphores once you know how you want to wake +them +up, not when they first begin waiting which is the only time you can assign +them. + +> well, i am not quite sure that i've fully understood your scenario, + +Hmm. Well, it think it's an important example, so I'll try again. First, we +have thread A which we KNOW is waiting on a condition. As soon as it +becomes +unblocked for any reason, we will know because it will set a flag. Since +the +flag is not set, we are 100% confident that thread A is waiting on the +condition. We have another thread, thread B, which has acquired the mutex +and is about to wait on the condition. Thus it is pretty clear that at any +point, either just A is waiting, or A and B are waiting. Now thread C comes +along. C is about to do a broadcast on the condition. A broadcast is +guaranteed to unblock all threads currently waiting on a condition, right? +Again, we said that either just A is waiting, or A and B are both waiting. +So, when C does its broadcast, depending upon whether B has started waiting +or not, thread C will unblock A or unblock A and B. Either way, C must +unblock A, right? + +Now, you said anything that happens is correct so long as a) "a signal is +not lost between unlocking the mutex and waiting on the condition" and b) +"a +thread must not steal a signal it sent", correct? Requirement b) is easy to +satisfy: in this scenario, thread C will never wait on the condition, so it +won't steal any signals. Requirement a) is not hard either. The only way +we +could fail to meet requirement a) in this scenario is if thread B was +started waiting but didn't wake up because a signal was lost. This will not +happen. + +Now, here is what happens. Assume thread C beats thread B. Thread C looks +to +see how many threads are waiting on the condition. Thread C sees just one +thread, thread A, waiting. It does a broadcast waking up just one thread +because just one thread is waiting. Next, before A can become unblocked, +thread B begins waiting. Now there are two threads waiting, but only one +will be unblocked. Suppose B wins. B will become unblocked. A will not +become unblocked, because C only unblocked one thread (sema_post cond, 1). +So at the end, B finishes and A remains blocked. + +We have met both of your requirements, so by your rules, this is an +acceptable outcome. However, I think that the spec says this is an +unacceptable outcome! We know for certain that A was waiting and that C did +a broadcast, but A did not become unblocked! Yet, the spec says that a +broadcast wakes up all waiting threads. This did not happen. Do you agree +that this shows your rules are not strict enough? + +> and what about N2? :) this one does allow almost everything. + +Don't get me started about rule #2. I'll NEVER advocate an algorithm that +uses rule 2 as an excuse to suck! + +> but it is done (decrement)under mutex protection - this is not a subject +> of a race condition. + +You are correct. My mistake. + +> i would remove "_bTimedOut=false".. after all, it was a real timeout.. + +I disagree. A thread that can't successfully retract its waiter status +can't +really have timed out. If a thread can't return without executing extra +code +to deal with the fact that someone tried to unblock it, I think it is a +poor +idea to pretend we +didn't realize someone was trying to signal us. After all, a signal is more +important than a time out. + +> when nSignaled != 0, it is possible to update nWaiters (--) and do not +> touch nGone + +I realize this, but I was thinking that writing it the other ways saves +another if statement. + +> adjust only if nGone != 0 and save one cache memory write - probably much +slower than 'if' + +Hmm. You are probably right. + +> well, in a strange (e.g. timeout test) program you may (theoretically) +> have an overflow of nWaiters/nGone counters (with waiters repeatedly +timing +> out and no signals at all). + +Also true. Not only that, but you also have the possibility that one could +overflow the number of waiters as well! However, considering the limit you +have chosen for nWaitersGone, I suppose it is unlikely that anyone would be +able to get INT_MAX/2 threads waiting on a single condition. :) + +Analysis of 8a: + +It looks correct to me. + +What are IPC semaphores? + +In the line where you state, "else if ( nWaitersBlocked > nWaitersGone ) { +// HARMLESS RACE CONDITION!" there is no race condition for nWaitersGone +because nWaitersGone is never modified without holding mtxUnblockLock. You +are correct that there is a harmless race on nWaitersBlocked, which can +increase and make the condition become true just after we check it. If this +happens, we interpret it as the wait starting after the signal. + +I like your optimization of this. You could improve Alg. 6 as follows: +---------- Algorithm 6b ---------- +signal(bAll) { + _nSig=0 + lock counters + // this is safe because nWaiting can only be decremented by a thread that + // owns counters and nGone can only be changed by a thread that owns +counters. + if (nWaiting>nGone) { + if (0==nSignaled) { + sema_wait gate // close gate if not already closed + } + if (nGone>0) { + nWaiting-=nGone + nGone=0 + } + _nSig=bAll?nWaiting:1 + nSignaled+=_nSig + nWaiting-=_nSig + } + unlock counters + if (0!=_nSig) { + sema_post queue, _nSig + } +} +---------- ---------- ---------- +I guess this wouldn't apply to Alg 8a because nWaitersGone changes meanings +depending upon whether the gate is open or closed. + +In the loop "while ( nWaitersWasGone-- ) {" you do a sema_wait on +semBlockLock. Perhaps waiting on semBlockQueue would be a better idea. + +What have you gained by making the last thread to be signaled do the waits +for all the timed out threads, besides added complexity? It took me a long +time to figure out what your objective was with this, to realize you were +using nWaitersGone to mean two different things, and to verify that you +hadn't introduced any bug by doing this. Even now I'm not 100% sure. + +What has all this playing about with nWaitersGone really gained us besides +a +lot of complexity (it is much harder to verify that this solution is +correct), execution overhead (we now have a lot more if statements to +evaluate), and space overhead (more space for the extra code, and another +integer in our data)? We did manage to save a lock/unlock pair in an +uncommon case (when a time out occurs) at the above mentioned expenses in +the common cases. + +As for 8b, c, and d, they look ok though I haven't studied them thoroughly. +What would you use them for? + + Later, + -Louis! :) + diff --git a/w32-pthreads/README.NONPORTABLE b/w32-pthreads/README.NONPORTABLE new file mode 100644 index 000000000..9bdc445c7 --- /dev/null +++ b/w32-pthreads/README.NONPORTABLE @@ -0,0 +1,783 @@ +This file documents non-portable functions and other issues. + +Non-portable functions included in pthreads-win32 +------------------------------------------------- + +BOOL +pthread_win32_test_features_np(int mask) + + This routine allows an application to check which + run-time auto-detected features are available within + the library. + + The possible features are: + + PTW32_SYSTEM_INTERLOCKED_COMPARE_EXCHANGE + Return TRUE if the native version of + InterlockedCompareExchange() is being used. + This feature is not meaningful in recent + library versions as MSVC builds only support + system implemented ICE. Note that all Mingw + builds use inlined asm versions of all the + Interlocked routines. + PTW32_ALERTABLE_ASYNC_CANCEL + Return TRUE is the QueueUserAPCEx package + QUSEREX.DLL is available and the AlertDrv.sys + driver is loaded into Windows, providing + alertable (pre-emptive) asyncronous threads + cancelation. If this feature returns FALSE + then the default async cancel scheme is in + use, which cannot cancel blocked threads. + + Features may be Or'ed into the mask parameter, in which case + the routine returns TRUE if any of the Or'ed features would + return TRUE. At this stage it doesn't make sense to Or features + but it may some day. + + +void * +pthread_timechange_handler_np(void *) + + To improve tolerance against operator or time service + initiated system clock changes. + + This routine can be called by an application when it + receives a WM_TIMECHANGE message from the system. At + present it broadcasts all condition variables so that + waiting threads can wake up and re-evaluate their + conditions and restart their timed waits if required. + + It has the same return type and argument type as a + thread routine so that it may be called directly + through pthread_create(), i.e. as a separate thread. + + Parameters + + Although a parameter must be supplied, it is ignored. + The value NULL can be used. + + Return values + + It can return an error EAGAIN to indicate that not + all condition variables were broadcast for some reason. + Otherwise, 0 is returned. + + If run as a thread, the return value is returned + through pthread_join(). + + The return value should be cast to an integer. + + +HANDLE +pthread_getw32threadhandle_np(pthread_t thread); + + Returns the win32 thread handle that the POSIX + thread "thread" is running as. + + Applications can use the win32 handle to set + win32 specific attributes of the thread. + +DWORD +pthread_getw32threadid_np (pthread_t thread) + + Returns the Windows native thread ID that the POSIX + thread "thread" is running as. + + Only valid when the library is built where + ! (defined(__MINGW64__) || defined(__MINGW32__)) || defined (__MSVCRT__) || defined (__DMC__) + and otherwise returns 0. + + +int +pthread_mutexattr_setkind_np(pthread_mutexattr_t * attr, int kind) + +int +pthread_mutexattr_getkind_np(pthread_mutexattr_t * attr, int *kind) + + These two routines are included for Linux compatibility + and are direct equivalents to the standard routines + pthread_mutexattr_settype + pthread_mutexattr_gettype + + pthread_mutexattr_setkind_np accepts the following + mutex kinds: + PTHREAD_MUTEX_FAST_NP + PTHREAD_MUTEX_ERRORCHECK_NP + PTHREAD_MUTEX_RECURSIVE_NP + + These are really just equivalent to (respectively): + PTHREAD_MUTEX_NORMAL + PTHREAD_MUTEX_ERRORCHECK + PTHREAD_MUTEX_RECURSIVE + +int +pthread_delay_np (const struct timespec *interval); + + This routine causes a thread to delay execution for a specific period of time. + This period ends at the current time plus the specified interval. The routine + will not return before the end of the period is reached, but may return an + arbitrary amount of time after the period has gone by. This can be due to + system load, thread priorities, and system timer granularity. + + Specifying an interval of zero (0) seconds and zero (0) nanoseconds is + allowed and can be used to force the thread to give up the processor or to + deliver a pending cancelation request. + + This routine is a cancelation point. + + The timespec structure contains the following two fields: + + tv_sec is an integer number of seconds. + tv_nsec is an integer number of nanoseconds. + + Return Values + + If an error condition occurs, this routine returns an integer value + indicating the type of error. Possible return values are as follows: + + 0 Successful completion. + [EINVAL] The value specified by interval is invalid. + +int +pthread_num_processors_np (void) + + This routine (found on HPUX systems) returns the number of processors + in the system. This implementation actually returns the number of + processors available to the process, which can be a lower number + than the system's number, depending on the process's affinity mask. + +BOOL +pthread_win32_process_attach_np (void); + +BOOL +pthread_win32_process_detach_np (void); + +BOOL +pthread_win32_thread_attach_np (void); + +BOOL +pthread_win32_thread_detach_np (void); + + These functions contain the code normally run via dllMain + when the library is used as a dll but which need to be + called explicitly by an application when the library + is statically linked. As of version 2.9.0 of the library, static + builds using either MSC or GCC will call pthread_win32_process_* + automatically at application startup and exit respectively. + + Otherwise, you will need to call pthread_win32_process_attach_np() + before you can call any pthread routines when statically linking. + You should call pthread_win32_process_detach_np() before + exiting your application to clean up. + + pthread_win32_thread_attach_np() is currently a no-op, but + pthread_win32_thread_detach_np() is needed to clean up + the implicit pthread handle that is allocated to a Win32 thread if + it calls any pthreads routines. Call this routine when the + Win32 thread exits. + + Threads created through pthread_create() do not need to call + pthread_win32_thread_detach_np(). + + These functions invariably return TRUE except for + pthread_win32_process_attach_np() which will return FALSE + if pthreads-win32 initialisation fails. + +int +pthreadCancelableWait (HANDLE waitHandle); + +int +pthreadCancelableTimedWait (HANDLE waitHandle, DWORD timeout); + + These two functions provide hooks into the pthread_cancel + mechanism that will allow you to wait on a Windows handle + and make it a cancellation point. Both functions block + until either the given w32 handle is signaled, or + pthread_cancel has been called. It is implemented using + WaitForMultipleObjects on 'waitHandle' and a manually + reset w32 event used to implement pthread_cancel. + + +Non-portable issues +------------------- + +Thread priority + + POSIX defines a single contiguous range of numbers that determine a + thread's priority. Win32 defines priority classes and priority + levels relative to these classes. Classes are simply priority base + levels that the defined priority levels are relative to such that, + changing a process's priority class will change the priority of all + of it's threads, while the threads retain the same relativity to each + other. + + A Win32 system defines a single contiguous monotonic range of values + that define system priority levels, just like POSIX. However, Win32 + restricts individual threads to a subset of this range on a + per-process basis. + + The following table shows the base priority levels for combinations + of priority class and priority value in Win32. + + Process Priority Class Thread Priority Level + ----------------------------------------------------------------- + 1 IDLE_PRIORITY_CLASS THREAD_PRIORITY_IDLE + 1 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_IDLE + 1 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_IDLE + 1 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_IDLE + 1 HIGH_PRIORITY_CLASS THREAD_PRIORITY_IDLE + 2 IDLE_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + 3 IDLE_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + 4 IDLE_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + 4 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + 5 IDLE_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + 5 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + 5 Background NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + 6 IDLE_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + 6 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + 6 Background NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + 7 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + 7 Background NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + 7 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + 8 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + 8 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + 8 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + 8 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + 9 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + 9 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + 9 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + 10 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + 10 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + 11 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + 11 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + 11 HIGH_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + 12 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + 12 HIGH_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + 13 HIGH_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + 14 HIGH_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + 15 HIGH_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + 15 HIGH_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + 15 IDLE_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + 15 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + 15 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + 15 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + 16 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_IDLE + 17 REALTIME_PRIORITY_CLASS -7 + 18 REALTIME_PRIORITY_CLASS -6 + 19 REALTIME_PRIORITY_CLASS -5 + 20 REALTIME_PRIORITY_CLASS -4 + 21 REALTIME_PRIORITY_CLASS -3 + 22 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + 23 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + 24 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + 25 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + 26 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + 27 REALTIME_PRIORITY_CLASS 3 + 28 REALTIME_PRIORITY_CLASS 4 + 29 REALTIME_PRIORITY_CLASS 5 + 30 REALTIME_PRIORITY_CLASS 6 + 31 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + + Windows NT: Values -7, -6, -5, -4, -3, 3, 4, 5, and 6 are not supported. + + + As you can see, the real priority levels available to any individual + Win32 thread are non-contiguous. + + An application using pthreads-win32 should not make assumptions about + the numbers used to represent thread priority levels, except that they + are monotonic between the values returned by sched_get_priority_min() + and sched_get_priority_max(). E.g. Windows 95, 98, NT, 2000, XP make + available a non-contiguous range of numbers between -15 and 15, while + at least one version of WinCE (3.0) defines the minimum priority + (THREAD_PRIORITY_LOWEST) as 5, and the maximum priority + (THREAD_PRIORITY_HIGHEST) as 1. + + Internally, pthreads-win32 maps any priority levels between + THREAD_PRIORITY_IDLE and THREAD_PRIORITY_LOWEST to THREAD_PRIORITY_LOWEST, + or between THREAD_PRIORITY_TIME_CRITICAL and THREAD_PRIORITY_HIGHEST to + THREAD_PRIORITY_HIGHEST. Currently, this also applies to + REALTIME_PRIORITY_CLASSi even if levels -7, -6, -5, -4, -3, 3, 4, 5, and 6 + are supported. + + If it wishes, a Win32 application using pthreads-win32 can use the Win32 + defined priority macros THREAD_PRIORITY_IDLE through + THREAD_PRIORITY_TIME_CRITICAL. + + +The opacity of the pthread_t datatype +------------------------------------- +and possible solutions for portable null/compare/hash, etc +---------------------------------------------------------- + +Because pthread_t is an opague datatype an implementation is permitted to define +pthread_t in any way it wishes. That includes defining some bits, if it is +scalar, or members, if it is an aggregate, to store information that may be +extra to the unique identifying value of the ID. As a result, pthread_t values +may not be directly comparable. + +If you want your code to be portable you must adhere to the following contraints: + +1) Don't assume it is a scalar data type, e.g. an integer or pointer value. There +are several other implementations where pthread_t is also a struct. See our FAQ +Question 11 for our reasons for defining pthread_t as a struct. + +2) You must not compare them using relational or equality operators. You must use +the API function pthread_equal() to test for equality. + +3) Never attempt to reference individual members. + + +The problem + +Certain applications would like to be able to access only the 'pure' pthread_t +id values, primarily to use as keys into data structures to manage threads or +thread-related data, but this is not possible in a maximally portable and +standards compliant way for current POSIX threads implementations. + +For implementations that define pthread_t as a scalar, programmers often employ +direct relational and equality operators on pthread_t. This code will break when +ported to an implementation that defines pthread_t as an aggregate type. + +For implementations that define pthread_t as an aggregate, e.g. a struct, +programmers can use memcmp etc., but then face the prospect that the struct may +include alignment padding bytes or bits as well as extra implementation-specific +members that are not part of the unique identifying value. + +[While this is not currently the case for pthreads-win32, opacity also +means that an implementation is free to change the definition, which should +generally only require that applications be recompiled and relinked, not +rewritten.] + + +Doesn't the compiler take care of padding? + +The C89 and later standards only effectively guarrantee element-by-element +equivalence following an assignment or pass by value of a struct or union, +therefore undefined areas of any two otherwise equivalent pthread_t instances +can still compare differently, e.g. attempting to compare two such pthread_t +variables byte-by-byte, e.g. memcmp(&t1, &t2, sizeof(pthread_t) may give an +incorrect result. In practice I'm reasonably confident that compilers routinely +also copy the padding bytes, mainly because assignment of unions would be far +too complicated otherwise. But it just isn't guarranteed by the standard. + +Illustration: + +We have two thread IDs t1 and t2 + +pthread_t t1, t2; + +In an application we create the threads and intend to store the thread IDs in an +ordered data structure (linked list, tree, etc) so we need to be able to compare +them in order to insert them initially and also to traverse. + +Suppose pthread_t contains undefined padding bits and our compiler copies our +pthread_t [struct] element-by-element, then for the assignment: + +pthread_t temp = t1; + +temp and t1 will be equivalent and correct but a byte-for-byte comparison such as +memcmp(&temp, &t1, sizeof(pthread_t)) == 0 may not return true as we expect because +the undefined bits may not have the same values in the two variable instances. + +Similarly if passing by value under the same conditions. + +If, on the other hand, the undefined bits are at least constant through every +assignment and pass-by-value then the byte-for-byte comparison +memcmp(&temp, &t1, sizeof(pthread_t)) == 0 will always return the expected result. +How can we force the behaviour we need? + + +Solutions + +Adding new functions to the standard API or as non-portable extentions is +the only reliable and portable way to provide the necessary operations. +Remember also that POSIX is not tied to the C language. The most common +functions that have been suggested are: + +pthread_null() +pthread_compare() +pthread_hash() + +A single more general purpose function could also be defined as a +basis for at least the last two of the above functions. + +First we need to list the freedoms and constraints with restpect +to pthread_t so that we can be sure our solution is compatible with the +standard. + +What is known or may be deduced from the standard: +1) pthread_t must be able to be passed by value, so it must be a single object. +2) from (1) it must be copyable so cannot embed thread-state information, locks +or other volatile objects required to manage the thread it associates with. +3) pthread_t may carry additional information, e.g. for debugging or to manage +itself. +4) there is an implicit requirement that the size of pthread_t is determinable +at compile-time and size-invariant, because it must be able to copy the object +(i.e. through assignment and pass-by-value). Such copies must be genuine +duplicates, not merely a copy of a pointer to a common instance such as +would be the case if pthread_t were defined as an array. + + +Suppose we define the following function: + +/* This function shall return it's argument */ +pthread_t* pthread_normalize(pthread_t* thread); + +For scalar or aggregate pthread_t types this function would simply zero any bits +within the pthread_t that don't uniquely identify the thread, including padding, +such that client code can return consistent results from operations done on the +result. If the additional bits are a pointer to an associate structure then +this function would ensure that the memory used to store that associate +structure does not leak. After normalization the following compare would be +valid and repeatable: + +memcmp(pthread_normalize(&t1),pthread_normalize(&t2),sizeof(pthread_t)) + +Note 1: such comparisons are intended merely to order and sort pthread_t values +and allow them to index various data structures. They are not intended to reveal +anything about the relationships between threads, like startup order. + +Note 2: the normalized pthread_t is also a valid pthread_t that uniquely +identifies the same thread. + +Advantages: +1) In most existing implementations this function would reduce to a no-op that +emits no additional instructions, i.e after in-lining or optimisation, or if +defined as a macro: +#define pthread_normalise(tptr) (tptr) + +2) This single function allows an application to portably derive +application-level versions of any of the other required functions. + +3) It is a generic function that could enable unanticipated uses. + +Disadvantages: +1) Less efficient than dedicated compare or hash functions for implementations +that include significant extra non-id elements in pthread_t. + +2) Still need to be concerned about padding if copying normalized pthread_t. +See the later section on defining pthread_t to neutralise padding issues. + +Generally a pthread_t may need to be normalized every time it is used, +which could have a significant impact. However, this is a design decision +for the implementor in a competitive environment. An implementation is free +to define a pthread_t in a way that minimises or eliminates padding or +renders this function a no-op. + +Hazards: +1) Pass-by-reference directly modifies 'thread' so the application must +synchronise access or ensure that the pointer refers to a copy. The alternative +of pass-by-value/return-by-value was considered but then this requires two copy +operations, disadvantaging implementations where this function is not a no-op +in terms of speed of execution. This function is intended to be used in high +frequency situations and needs to be efficient, or at least not unnecessarily +inefficient. The alternative also sits awkwardly with functions like memcmp. + +2) [Non-compliant] code that uses relational and equality operators on +arithmetic or pointer style pthread_t types would need to be rewritten, but it +should be rewritten anyway. + + +C implementation of null/compare/hash functions using pthread_normalize(): + +/* In pthread.h */ +pthread_t* pthread_normalize(pthread_t* thread); + +/* In user code */ +/* User-level bitclear function - clear bits in loc corresponding to mask */ +void* bitclear (void* loc, void* mask, size_t count); + +typedef unsigned int hash_t; + +/* User-level hash function */ +hash_t hash(void* ptr, size_t count); + +/* + * User-level pthr_null function - modifies the origin thread handle. + * The concept of a null pthread_t is highly implementation dependent + * and this design may be far from the mark. For example, in an + * implementation "null" may mean setting a special value inside one + * element of pthread_t to mean "INVALID". However, if that value was zero and + * formed part of the id component then we may get away with this design. + */ +pthread_t* pthr_null(pthread_t* tp) +{ + /* + * This should have the same effect as memset(tp, 0, sizeof(pthread_t)) + * We're just showing that we can do it. + */ + void* p = (void*) pthread_normalize(tp); + return (pthread_t*) bitclear(p, p, sizeof(pthread_t)); +} + +/* + * Safe user-level pthr_compare function - modifies temporary thread handle copies + */ +int pthr_compare_safe(pthread_t thread1, pthread_t thread2) +{ + return memcmp(pthread_normalize(&thread1), pthread_normalize(&thread2), sizeof(pthread_t)); +} + +/* + * Fast user-level pthr_compare function - modifies origin thread handles + */ +int pthr_compare_fast(pthread_t* thread1, pthread_t* thread2) +{ + return memcmp(pthread_normalize(&thread1), pthread_normalize(&thread2), sizeof(pthread_t)); +} + +/* + * Safe user-level pthr_hash function - modifies temporary thread handle copy + */ +hash_t pthr_hash_safe(pthread_t thread) +{ + return hash((void *) pthread_normalize(&thread), sizeof(pthread_t)); +} + +/* + * Fast user-level pthr_hash function - modifies origin thread handle + */ +hash_t pthr_hash_fast(pthread_t thread) +{ + return hash((void *) pthread_normalize(&thread), sizeof(pthread_t)); +} + +/* User-level bitclear function - modifies the origin array */ +void* bitclear(void* loc, void* mask, size_t count) +{ + int i; + for (i=0; i < count; i++) { + (unsigned char) *loc++ &= ~((unsigned char) *mask++); + } +} + +/* Donald Knuth hash */ +hash_t hash(void* str, size_t count) +{ + hash_t hash = (hash_t) count; + unsigned int i = 0; + + for(i = 0; i < len; str++, i++) + { + hash = ((hash << 5) ^ (hash >> 27)) ^ (*str); + } + return hash; +} + +/* Example of advantage point (3) - split a thread handle into its id and non-id values */ +pthread_t id = thread, non-id = thread; +bitclear((void*) &non-id, (void*) pthread_normalize(&id), sizeof(pthread_t)); + + +A pthread_t type change proposal to neutralise the effects of padding + +Even if pthread_nornalize() is available, padding is still a problem because +the standard only garrantees element-by-element equivalence through +copy operations (assignment and pass-by-value). So padding bit values can +still change randomly after calls to pthread_normalize(). + +[I suspect that most compilers take the easy path and always byte-copy anyway, +partly because it becomes too complex to do (e.g. unions that contain sub-aggregates) +but also because programmers can easily design their aggregates to minimise and +often eliminate padding]. + +How can we eliminate the problem of padding bytes in structs? Could +defining pthread_t as a union rather than a struct provide a solution? + +In fact, the Linux pthread.h defines most of it's pthread_*_t objects (but not +pthread_t itself) as unions, possibly for this and/or other reasons. We'll +borrow some element naming from there but the ideas themselves are well known +- the __align element used to force alignment of the union comes from K&R's +storage allocator example. + +/* Essentially our current pthread_t renamed */ +typedef struct { + struct thread_state_t * __p; + long __x; /* sequence counter */ +} thread_id_t; + +Ensuring that the last element in the above struct is a long ensures that the +overall struct size is a multiple of sizeof(long), so there should be no trailing +padding in this struct or the union we define below. +(Later we'll see that we can handle internal but not trailing padding.) + +/* New pthread_t */ +typedef union { + char __size[sizeof(thread_id_t)]; /* array as the first element */ + thread_id_t __tid; + long __align; /* Ensure that the union starts on long boundary */ +} pthread_t; + +This guarrantees that, during an assignment or pass-by-value, the compiler copies +every byte in our thread_id_t because the compiler guarrantees that the __size +array, which we have ensured is the equal-largest element in the union, retains +equivalence. + +This means that pthread_t values stored, assigned and passed by value will at least +carry the value of any undefined padding bytes along and therefore ensure that +those values remain consistent. Our comparisons will return consistent results and +our hashes of [zero initialised] pthread_t values will also return consistent +results. + +We have also removed the need for a pthread_null() function; we can initialise +at declaration time or easily create our own const pthread_t to use in assignments +later: + +const pthread_t null_tid = {0}; /* braces are required */ + +pthread_t t; +... +t = null_tid; + + +Note that we don't have to explicitly make use of the __size array at all. It's +there just to force the compiler behaviour we want. + + +Partial solutions without a pthread_normalize function + + +An application-level pthread_null and pthread_compare proposal +(and pthread_hash proposal by extention) + +In order to deal with the problem of scalar/aggregate pthread_t type disparity in +portable code I suggest using an old-fashioned union, e.g.: + +Contraints: +- there is no padding, or padding values are preserved through assignment and + pass-by-value (see above); +- there are no extra non-id values in the pthread_t. + + +Example 1: A null initialiser for pthread_t variables... + +typedef union { + unsigned char b[sizeof(pthread_t)]; + pthread_t t; +} init_t; + +const init_t initial = {0}; + +pthread_t tid = initial.t; /* init tid to all zeroes */ + + +Example 2: A comparison function for pthread_t values + +typedef union { + unsigned char b[sizeof(pthread_t)]; + pthread_t t; +} pthcmp_t; + +int pthcmp(pthread_t left, pthread_t right) +{ + /* + * Compare two pthread handles in a way that imposes a repeatable but arbitrary + * ordering on them. + * I.e. given the same set of pthread_t handles the ordering should be the same + * each time but the order has no particular meaning other than that. E.g. + * the ordering does not imply the thread start sequence, or any other + * relationship between threads. + * + * Return values are: + * 1 : left is greater than right + * 0 : left is equal to right + * -1 : left is less than right + */ + int i; + pthcmp_t L, R; + L.t = left; + R.t = right; + for (i = 0; i < sizeof(pthread_t); i++) + { + if (L.b[i] > R.b[i]) + return 1; + else if (L.b[i] < R.b[i]) + return -1; + } + return 0; +} + +It has been pointed out that the C99 standard allows for the possibility that +integer types also may include padding bits, which could invalidate the above +method. This addition to C99 was specifically included after it was pointed +out that there was one, presumably not particularly well known, architecture +that included a padding bit in it's 32 bit integer type. See section 6.2.6.2 +of both the standard and the rationale, specifically the paragraph starting at +line 16 on page 43 of the rationale. + + +An aside + +Certain compilers, e.g. gcc and one of the IBM compilers, include a feature +extention: provided the union contains a member of the same type as the +object then the object may be cast to the union itself. + +We could use this feature to speed up the pthrcmp() function from example 2 +above by casting rather than assigning the pthread_t arguments to the union, e.g.: + +int pthcmp(pthread_t left, pthread_t right) +{ + /* + * Compare two pthread handles in a way that imposes a repeatable but arbitrary + * ordering on them. + * I.e. given the same set of pthread_t handles the ordering should be the same + * each time but the order has no particular meaning other than that. E.g. + * the ordering does not imply the thread start sequence, or any other + * relationship between threads. + * + * Return values are: + * 1 : left is greater than right + * 0 : left is equal to right + * -1 : left is less than right + */ + int i; + for (i = 0; i < sizeof(pthread_t); i++) + { + if (((pthcmp_t)left).b[i] > ((pthcmp_t)right).b[i]) + return 1; + else if (((pthcmp_t)left).b[i] < ((pthcmp_t)right).b[i]) + return -1; + } + return 0; +} + + +Result thus far + +We can't remove undefined bits if they are there in pthread_t already, but we have +attempted to render them inert for comparison and hashing functions by making them +consistent through assignment, copy and pass-by-value. + +Note: Hashing pthread_t values requires that all pthread_t variables be initialised +to the same value (usually all zeros) before being assigned a proper thread ID, i.e. +to ensure that any padding bits are zero, or at least the same value for all +pthread_t. Since all pthread_t values are generated by the library in the first +instance this need not be an application-level operation. + + +Conclusion + +I've attempted to resolve the multiple issues of type opacity and the possible +presence of undefined bits and bytes in pthread_t values, which prevent +applications from comparing or hashing pthread handles. + +Two complimentary partial solutions have been proposed, one an application-level +scheme to handle both scalar and aggregate pthread_t types equally, plus a +definition of pthread_t itself that neutralises padding bits and bytes by +coercing semantics out of the compiler to eliminate variations in the values of +padding bits. + +I have not provided any solution to the problem of handling extra values embedded +in pthread_t, e.g. debugging or trap information that an implementation is entitled +to include. Therefore none of this replaces the portability and flexibility of API +functions but what functions are needed? The threads standard is unlikely to +include that can be implemented by a combination of existing features and more +generic functions (several references in the threads rationale suggest this. +Therefore I propose that the following function could replace the several functions +that have been suggested in conversations: + +pthread_t * pthread_normalize(pthread_t * handle); + +For most existing pthreads implementations this function, or macro, would reduce to +a no-op with zero call overhead. diff --git a/w32-pthreads/README.Watcom b/w32-pthreads/README.Watcom new file mode 100644 index 000000000..2974928a3 --- /dev/null +++ b/w32-pthreads/README.Watcom @@ -0,0 +1,62 @@ +Watcom compiler notes +===================== + +Status +------ +Not yet usable. Although the library builds under Watcom it +substantially fails the test suite. + +There is a working Wmakefile for wmake for the library build. + +invoke as any of: +wmake -f Wmakefile clean WC +wmake -f Wmakefile clean WC-inlined +wmake -f Wmakefile clean WCE +wmake -f Wmakefile clean WCE-inlined + +These build pthreadWC.dll and pthreadWCE.dll. + +There is a working Wmakefile for wmake for the test suite. + +invoke as any of: +wmake -f Wmakefile clean WC +wmake -f Wmakefile clean WCX +wmake -f Wmakefile clean WCE +wmake -f Wmakefile clean WC-bench +wmake -f Wmakefile clean WCX-bench +wmake -f Wmakefile clean WCE-bench + + +Current known problems +---------------------- + +Library build: +The Watcom compiler uses a different default call convention to MS C or GNU C and so +applications are not compatible with pthreadVC.dll etc using pre 2003-10-14 versions +of pthread.h, sched.h, or semaphore.h. The cdecl attribute can be used on exposed +function prototypes to force compatibility with MS C built DLLs. + +However, there appear to be other incompatibilities. Errno.h, for example, defines +different values for the standard C and POSIX errors to those defined by the MS C +errno.h. It may be that references to Watcom's threads compatible 'errno' do set +and return translated numbers consistently, but I have not verified this. + +Watcom defines errno as a dereferenced pointer returned by the function +_get_errno_ptr(). This is similar to both the MS and GNU C environments for +multithreaded use. However, the Watcom version appears to have a number of problems: + +- different threads return the same pointer value. Compare with the MS and GNU C +versions which correctly return different values (since each thread must maintain +a thread specific errno value). + +- an errno value set within the DLL appears as zero in the application even though +both share the same thread. + +Therefore applications built using the Watcom compiler may need to use +a Watcom built version of the library (pthreadWC.dll). If this is the case, then +the cdecl function attribute should not be required. + +Application builds: +The test suite fails with the Watcom compiler. + +Test semaphore1.c fails for pthreadWC.dll because errno returns 0 instead of EAGAIN. diff --git a/w32-pthreads/README.WinCE b/w32-pthreads/README.WinCE new file mode 100644 index 000000000..a2cd8c213 --- /dev/null +++ b/w32-pthreads/README.WinCE @@ -0,0 +1,6 @@ +WinCE port +---------- +(See the file WinCE-PORT for a detailed explanation.) + +Make sure you define "WINCE" amongst your compiler flags (eg. -DWINCE). +The config.h file will define all the necessary defines for you. diff --git a/w32-pthreads/TODO b/w32-pthreads/TODO new file mode 100644 index 000000000..fa9efc46e --- /dev/null +++ b/w32-pthreads/TODO @@ -0,0 +1,7 @@ + Things that aren't done yet + --------------------------- + +1. Implement PTHREAD_PROCESS_SHARED for semaphores, mutexes, + condition variables, read/write locks, barriers. + + diff --git a/w32-pthreads/WinCE-PORT b/w32-pthreads/WinCE-PORT new file mode 100644 index 000000000..7bcfdea6c --- /dev/null +++ b/w32-pthreads/WinCE-PORT @@ -0,0 +1,222 @@ +NOTE: The comments in this file relate to the original WinCE port +done by Tristan Savatier. The semaphore routines have been +completely rewritten since (2005-04-25), having been progressively +broken more and more by changes to the library. All of the semaphore +routines implemented for W9x/WNT/2000 and up should now also work for +WinCE. Also, pthread_mutex_timedlock should now work. + +Additional WinCE updates have been applied since this as well. Check the +ChangeLog file and search for WINCE for example. (2007-01-07) + +[RPJ] + +---- + +Some interesting news: + +I have been able to port pthread-win32 to Windows-CE, +which uses a subset of the WIN32 API. + +Since we intend to keep using pthread-win32 for our +Commercial WinCE developments, I would be very interested +if WinCE support could be added to the main source tree +of pthread-win32. Also, I would like to be credited +for this port :-) + +Now, here is the story... + +The port was performed and tested on a Casio "Cassiopeia" +PalmSize PC, which runs a MIP processor. The OS in the +Casio is WinCE version 2.11, but I used VC++ 6.0 with +the WinCE SDK for version 2.01. + +I used pthread-win32 to port a heavily multithreaded +commercial application (real-time MPEG video player) +from Linux to WinCE. I consider the changes that +I have done to be quite well tested. + +Overall the modifications that we had to do are minor. + +The WinCE port were based on pthread-win32-snap-1999-05-30, +but I am certain that they can be integrated very easiely +to more recent versions of the source. + +I have attached the modified source code: +pthread-win32-snap-1999-05-30-WinCE. + +All the changes do not affect the code compiled on non-WinCE +environment, provided that the macros used for WinCE compilation +are not used, of course! + +Overall description of the WinCE port: +------------------------------------- + +Most of the changes had to be made in areas where +pthread-win32 was relying on some standard-C librairies +(e.g. _ftime, calloc, errno), which are not available +on WinCE. We have changed the code to use native Win32 +API instead (or in some cases we made wrappers). + +The Win32 Semaphores are not available, +so we had to re-implement Semaphores using mutexes +and events. + +Limitations / known problems of the WinCE port: +---------------------------------------------- + +Not all the semaphore routines have been ported +(semaphores are defined by Posix but are not part +pf pthread). I have just done enough to make +pthread routines (that rely internally on semaphores) +work, like signal conditions. + +I noticed that the Win32 threads work slightly +differently on WinCE. This may have some impact +on some tricky parts of pthread-win32, but I have +not really investigated. For example, on WinCE, +the process is killed if the main thread falls off +the bottom (or calls pthread_exit), regardless +of the existence of any other detached thread. +Microsoft manual indicates that this behavior is +deffirent from that of Windows Threads for other +Win32 platforms. + + +Detailed descriptions of the changes and rationals: + +------------------------------------ +- use a new macro NEED_ERRNO. + +If defined, the code in errno.c that defines a reentrant errno +is compiled, regardless of _MT and _REENTRANT. + +Rational: On WinCE, there is no support for , or +any other standard C library, i.e. even if _MT or _REENTRANT +is defined, errno is not provided by any library. NEED_ERRNO +must be set to compile for WinCE. + +------------------------------------ +- In implement.h, change #include to #include "semaphore.h". + +Rational: semaphore.h is provided in pthread-win32 and should not +be searched in the systems standard include. would not compile. +This change does not seem to create problems on "classic" win32 +(e.g. win95). + +------------------------------------ +- use a new macro NEED_CALLOC. + +If defined, some code in misc.c will provide a replacement +for calloc, which is not available on Win32. + + +------------------------------------ +- use a new macro NEED_CREATETHREAD. + +If defined, implement.h defines the macro _beginthreadex +and _endthreadex. + +Rational: On WinCE, the wrappers _beginthreadex and _endthreadex +do not exist. The native Win32 routines must be used. + +------------------------------------ +- in misc.c: + +#ifdef NEED_DUPLICATEHANDLE + /* DuplicateHandle does not exist on WinCE */ + self->threadH = GetCurrentThread(); +#else + if( !DuplicateHandle( + GetCurrentProcess(), + GetCurrentThread(), + GetCurrentProcess(), + &self->threadH, + 0, + FALSE, + DUPLICATE_SAME_ACCESS ) ) + { + free( self ); + return (NULL); + } +#endif + +Rational: On WinCE, DuplicateHandle does not exist. I could not understand +why DuplicateHandle must be used. It seems to me that getting the current +thread handle with GetCurrentThread() is sufficient, and it seems to work +perfectly fine, so maybe DuplicateHandle was just plain useless to begin with ? + +------------------------------------ +- In private.c, added some code at the beginning of ptw32_processInitialize +to detect the case of multiple calls to ptw32_processInitialize. + +Rational: In order to debug pthread-win32, it is easier to compile +it as a regular library (it is not possible to debug DLL's on winCE). +In that case, the application must call ptw32_rocessInitialize() +explicitely, to initialize pthread-win32. It is safer in this circumstance +to handle the case where ptw32_processInitialize() is called on +an already initialized library: + +int +ptw32_processInitialize (void) +{ + if (ptw32_processInitialized) { + /* + * ignore if already initialized. this is useful for + * programs that uses a non-dll pthread + * library. such programs must call ptw32_processInitialize() explicitely, + * since this initialization routine is automatically called only when + * the dll is loaded. + */ + return TRUE; + } + ptw32_processInitialized = TRUE; + [...] +} + +------------------------------------ +- in private.c, if macro NEED_FTIME is defined, add routines to +convert timespec_to_filetime and filetime_to_timespec, and modified +code that was using _ftime() to use Win32 API instead. + +Rational: _ftime is not available on WinCE. It is necessary to use +the native Win32 time API instead. + +Note: the routine timespec_to_filetime is provided as a convenience and a mean +to test that filetime_to_timespec works, but it is not used by the library. + +------------------------------------ +- in semaphore.c, if macro NEED_SEM is defined, add code for the routines +_increase_semaphore and _decrease_semaphore, and modify significantly +the implementation of the semaphores so that it does not use CreateSemaphore. + +Rational: CreateSemaphore is not available on WinCE. I had to re-implement +semaphores using mutexes and Events. + +Note: Only the semaphore routines that are used by pthread are implemented +(i.e. signal conditions rely on a subset of the semaphores routines, and +this subset works). Some other semaphore routines (e.g. sem_trywait) are +not yet supported on my WinCE port (and since I don't need them, I am not +planning to do anything about them). + +------------------------------------ +- in tsd.c, changed the code that defines TLS_OUT_OF_INDEXES + +/* TLS_OUT_OF_INDEXES not defined on WinCE */ +#ifndef TLS_OUT_OF_INDEXES +#define TLS_OUT_OF_INDEXES 0xffffffff +#endif + +Rational: TLS_OUT_OF_INDEXES is not defined in any standard include file +on WinCE. + +------------------------------------ +- added file need_errno.h + +Rational: On WinCE, there is no errno.h file. need_errno.h is just a +copy of windows version of errno.h, with minor modifications due to the fact +that some of the error codes are defined by the WinCE socket library. +In pthread.h, if NEED_ERRNO is defined, the file need_errno.h is +included (instead of ). + + +-- eof diff --git a/w32-pthreads/attr.c b/w32-pthreads/attr.c new file mode 100644 index 000000000..a9d55f4a4 --- /dev/null +++ b/w32-pthreads/attr.c @@ -0,0 +1,53 @@ +/* + * attr.c + * + * Description: + * This translation unit agregates operations on thread attribute objects. + * It is used for inline optimisation. + * + * The included modules are used separately when static executable sizes + * must be minimised. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +#include "pthread_attr_init.c" +#include "pthread_attr_destroy.c" +#include "pthread_attr_getdetachstate.c" +#include "pthread_attr_setdetachstate.c" +#include "pthread_attr_getstackaddr.c" +#include "pthread_attr_setstackaddr.c" +#include "pthread_attr_getstacksize.c" +#include "pthread_attr_setstacksize.c" +#include "pthread_attr_getscope.c" +#include "pthread_attr_setscope.c" diff --git a/w32-pthreads/autostatic.c b/w32-pthreads/autostatic.c new file mode 100644 index 000000000..092aff2ae --- /dev/null +++ b/w32-pthreads/autostatic.c @@ -0,0 +1,69 @@ +/* + * autostatic.c + * + * Description: + * This translation unit implements static auto-init and auto-exit logic. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#if defined(PTW32_STATIC_LIB) + +#if defined(__MINGW64__) || defined(__MINGW32__) || defined(_MSC_VER) + +#include "pthread.h" +#include "implement.h" + +static void on_process_init(void) +{ + pthread_win32_process_attach_np (); +} + +static void on_process_exit(void) +{ + pthread_win32_thread_detach_np (); + pthread_win32_process_detach_np (); +} + +#if defined(__MINGW64__) || defined(__MINGW32__) +# define attribute_section(a) __attribute__((section(a))) +#elif defined(_MSC_VER) +# define attribute_section(a) __pragma(section(a,long,read)); __declspec(allocate(a)) +#endif + +attribute_section(".ctors") void *gcc_ctor = on_process_init; +attribute_section(".dtors") void *gcc_dtor = on_process_exit; + +attribute_section(".CRT$XCU") void *msc_ctor = on_process_init; +attribute_section(".CRT$XPU") void *msc_dtor = on_process_exit; + +#endif /* defined(__MINGW64__) || defined(__MINGW32__) || defined(_MSC_VER) */ + +#endif /* PTW32_STATIC_LIB */ diff --git a/w32-pthreads/barrier.c b/w32-pthreads/barrier.c new file mode 100644 index 000000000..41b950cd1 --- /dev/null +++ b/w32-pthreads/barrier.c @@ -0,0 +1,47 @@ +/* + * barrier.c + * + * Description: + * This translation unit implements barrier primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +#include "pthread_barrier_init.c" +#include "pthread_barrier_destroy.c" +#include "pthread_barrier_wait.c" +#include "pthread_barrierattr_init.c" +#include "pthread_barrierattr_destroy.c" +#include "pthread_barrierattr_getpshared.c" +#include "pthread_barrierattr_setpshared.c" diff --git a/w32-pthreads/builddmc.bat b/w32-pthreads/builddmc.bat new file mode 100644 index 000000000..bf813d816 --- /dev/null +++ b/w32-pthreads/builddmc.bat @@ -0,0 +1,9 @@ +; Build the pthreads library with the Digital Mars Compiler +; +set DMCDIR=c:\dm + +; RELEASE +%DMCDIR%\bin\dmc -D_WIN32_WINNT -D_MT -DHAVE_PTW32_CONFIG_H -I.;c:\dm\include -o+all -WD pthread.c user32.lib+kernel32.lib+wsock32.lib -L/impl -L/NODEBUG -L/SU:WINDOWS + +; DEBUG +%DMCDIR%\bin\dmc -g -D_WIN32_WINNT -D_MT -DHAVE_PTW32_CONFIG_H -I.;c:\dm\include -o+all -WD pthread.c user32.lib+kernel32.lib+wsock32.lib -L/impl -L/SU:WINDOWS diff --git a/w32-pthreads/cancel.c b/w32-pthreads/cancel.c new file mode 100644 index 000000000..1bd14ebe6 --- /dev/null +++ b/w32-pthreads/cancel.c @@ -0,0 +1,44 @@ +/* + * cancel.c + * + * Description: + * POSIX thread functions related to thread cancellation. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +#include "pthread_setcancelstate.c" +#include "pthread_setcanceltype.c" +#include "pthread_testcancel.c" +#include "pthread_cancel.c" diff --git a/w32-pthreads/cleanup.c b/w32-pthreads/cleanup.c new file mode 100644 index 000000000..381d1e87c --- /dev/null +++ b/w32-pthreads/cleanup.c @@ -0,0 +1,148 @@ +/* + * cleanup.c + * + * Description: + * This translation unit implements routines associated + * with cleaning up threads. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +/* + * The functions ptw32_pop_cleanup and ptw32_push_cleanup + * are implemented here for applications written in C with no + * SEH or C++ destructor support. + */ + +ptw32_cleanup_t * +ptw32_pop_cleanup (int execute) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function pops the most recently pushed cleanup + * handler. If execute is nonzero, then the cleanup handler + * is executed if non-null. + * + * PARAMETERS + * execute + * if nonzero, execute the cleanup handler + * + * + * DESCRIPTION + * This function pops the most recently pushed cleanup + * handler. If execute is nonzero, then the cleanup handler + * is executed if non-null. + * NOTE: specify 'execute' as nonzero to avoid duplication + * of common cleanup code. + * + * RESULTS + * N/A + * + * ------------------------------------------------------ + */ +{ + ptw32_cleanup_t *cleanup; + + cleanup = (ptw32_cleanup_t *) pthread_getspecific (ptw32_cleanupKey); + + if (cleanup != NULL) + { + if (execute && (cleanup->routine != NULL)) + { + + (*cleanup->routine) (cleanup->arg); + + } + + pthread_setspecific (ptw32_cleanupKey, (void *) cleanup->prev); + + } + + return (cleanup); + +} /* ptw32_pop_cleanup */ + + +void +ptw32_push_cleanup (ptw32_cleanup_t * cleanup, + ptw32_cleanup_callback_t routine, void *arg) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function pushes a new cleanup handler onto the thread's stack + * of cleanup handlers. Each cleanup handler pushed onto the stack is + * popped and invoked with the argument 'arg' when + * a) the thread exits by calling 'pthread_exit', + * b) when the thread acts on a cancellation request, + * c) or when the thread calls pthread_cleanup_pop with a nonzero + * 'execute' argument + * + * PARAMETERS + * cleanup + * a pointer to an instance of pthread_cleanup_t, + * + * routine + * pointer to a cleanup handler, + * + * arg + * parameter to be passed to the cleanup handler + * + * + * DESCRIPTION + * This function pushes a new cleanup handler onto the thread's stack + * of cleanup handlers. Each cleanup handler pushed onto the stack is + * popped and invoked with the argument 'arg' when + * a) the thread exits by calling 'pthread_exit', + * b) when the thread acts on a cancellation request, + * c) or when the thrad calls pthread_cleanup_pop with a nonzero + * 'execute' argument + * NOTE: pthread_push_cleanup, ptw32_pop_cleanup must be paired + * in the same lexical scope. + * + * RESULTS + * pthread_cleanup_t * + * pointer to the previous cleanup + * + * ------------------------------------------------------ + */ +{ + cleanup->routine = routine; + cleanup->arg = arg; + + cleanup->prev = (ptw32_cleanup_t *) pthread_getspecific (ptw32_cleanupKey); + + pthread_setspecific (ptw32_cleanupKey, (void *) cleanup); + +} /* ptw32_push_cleanup */ diff --git a/w32-pthreads/condvar.c b/w32-pthreads/condvar.c new file mode 100644 index 000000000..704f4d793 --- /dev/null +++ b/w32-pthreads/condvar.c @@ -0,0 +1,50 @@ +/* + * condvar.c + * + * Description: + * This translation unit implements condition variables and their primitives. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + */ + +#include "pthread.h" +#include "implement.h" + +#include "ptw32_cond_check_need_init.c" +#include "pthread_condattr_init.c" +#include "pthread_condattr_destroy.c" +#include "pthread_condattr_getpshared.c" +#include "pthread_condattr_setpshared.c" +#include "pthread_cond_init.c" +#include "pthread_cond_destroy.c" +#include "pthread_cond_wait.c" +#include "pthread_cond_signal.c" diff --git a/w32-pthreads/config.h b/w32-pthreads/config.h new file mode 100644 index 000000000..e231724e3 --- /dev/null +++ b/w32-pthreads/config.h @@ -0,0 +1,153 @@ +/* config.h */ + +#ifndef PTW32_CONFIG_H +#define PTW32_CONFIG_H + +/********************************************************************* + * Defaults: see target specific redefinitions below. + *********************************************************************/ + +/* We're building the pthreads-win32 library */ +#define PTW32_BUILD + +/* Do we know about the C type sigset_t? */ +#undef HAVE_SIGSET_T + +/* Define if you have the header file. */ +#undef HAVE_SIGNAL_H + +/* Define if you have the Borland TASM32 or compatible assembler. */ +#undef HAVE_TASM32 + +/* Define if you don't have Win32 DuplicateHandle. (eg. WinCE) */ +#undef NEED_DUPLICATEHANDLE + +/* Define if you don't have Win32 _beginthreadex. (eg. WinCE) */ +#undef NEED_CREATETHREAD + +/* Define if you don't have Win32 errno. (eg. WinCE) */ +#undef NEED_ERRNO + +/* Define if you don't have Win32 calloc. (eg. WinCE) */ +#undef NEED_CALLOC + +/* Define if you don't have Win32 ftime. (eg. WinCE) */ +#undef NEED_FTIME + +/* Define if you don't have Win32 semaphores. (eg. WinCE 2.1 or earlier) */ +#undef NEED_SEM + +/* Define if you need to convert string parameters to unicode. (eg. WinCE) */ +#undef NEED_UNICODE_CONSTS + +/* Define if your C (not C++) compiler supports "inline" functions. */ +#undef HAVE_C_INLINE + +/* Do we know about type mode_t? */ +#undef HAVE_MODE_T + +/* + * Define if GCC has atomic builtins, i.e. __sync_* intrinsics + * __sync_lock_* is implemented in mingw32 gcc 4.5.2 at least + * so this define does not turn those on or off. If you get an + * error from __sync_lock* then consider upgrading your gcc. + */ +#undef HAVE_GCC_ATOMIC_BUILTINS + +/* Define if you have the timespec struct */ +#undef HAVE_STRUCT_TIMESPEC + +/* Define if you don't have the GetProcessAffinityMask() */ +#undef NEED_PROCESS_AFFINITY_MASK + +/* Define if your version of Windows TLSGetValue() clears WSALastError + * and calling SetLastError() isn't enough restore it. You'll also need to + * link against wsock32.lib (or libwsock32.a for MinGW). + */ +#undef RETAIN_WSALASTERROR + +/* +# ---------------------------------------------------------------------- +# The library can be built with some alternative behaviour to better +# facilitate development of applications on Win32 that will be ported +# to other POSIX systems. +# +# Nothing described here will make the library non-compliant and strictly +# compliant applications will not be affected in any way, but +# applications that make assumptions that POSIX does not guarantee are +# not strictly compliant and may fail or misbehave with some settings. +# +# PTW32_THREAD_ID_REUSE_INCREMENT +# Purpose: +# POSIX says that applications should assume that thread IDs can be +# recycled. However, Solaris (and some other systems) use a [very large] +# sequence number as the thread ID, which provides virtual uniqueness. +# This provides a very high but finite level of safety for applications +# that are not meticulous in tracking thread lifecycles e.g. applications +# that call functions which target detached threads without some form of +# thread exit synchronisation. +# +# Usage: +# Set to any value in the range: 0 <= value < 2^wordsize. +# Set to 0 to emulate reusable thread ID behaviour like Linux or *BSD. +# Set to 1 for unique thread IDs like Solaris (this is the default). +# Set to some factor of 2^wordsize to emulate smaller word size types +# (i.e. will wrap sooner). This might be useful to emulate some embedded +# systems. +# +# define PTW32_THREAD_ID_REUSE_INCREMENT 0 +# +# ---------------------------------------------------------------------- + */ +#undef PTW32_THREAD_ID_REUSE_INCREMENT + + +/********************************************************************* + * Target specific groups + * + * If you find that these are incorrect or incomplete please report it + * to the pthreads-win32 maintainer. Thanks. + *********************************************************************/ +#if defined(WINCE) +#define NEED_DUPLICATEHANDLE +#define NEED_CREATETHREAD +#define NEED_ERRNO +#define NEED_CALLOC +#define NEED_FTIME +/* #define NEED_SEM */ +#define NEED_UNICODE_CONSTS +#define NEED_PROCESS_AFFINITY_MASK +/* This may not be needed */ +#define RETAIN_WSALASTERROR +#endif + +#if defined(_UWIN) +#define HAVE_MODE_T +#define HAVE_STRUCT_TIMESPEC +#endif + +#if defined(__GNUC__) +#define HAVE_C_INLINE +#endif + +#if defined(__MINGW64__) +#define HAVE_MODE_T +#define HAVE_STRUCT_TIMESPEC +#elif defined(__MINGW32__) +#define HAVE_MODE_T +#endif + +#if defined(__BORLANDC__) +#endif + +#if defined(__WATCOMC__) +#endif + +#if defined(__DMC__) +#define HAVE_SIGNAL_H +#define HAVE_C_INLINE +#endif + + + +#endif diff --git a/w32-pthreads/context.h b/w32-pthreads/context.h new file mode 100644 index 000000000..3d4511f5b --- /dev/null +++ b/w32-pthreads/context.h @@ -0,0 +1,74 @@ +/* + * context.h + * + * Description: + * POSIX thread macros related to thread cancellation. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#ifndef PTW32_CONTEXT_H +#define PTW32_CONTEXT_H + +#undef PTW32_PROGCTR + +#if defined(_M_IX86) || (defined(_X86_) && !defined(__amd64__)) +#define PTW32_PROGCTR(Context) ((Context).Eip) +#endif + +#if defined (_M_IA64) || defined(_IA64) +#define PTW32_PROGCTR(Context) ((Context).StIIP) +#endif + +#if defined(_MIPS_) || defined(MIPS) +#define PTW32_PROGCTR(Context) ((Context).Fir) +#endif + +#if defined(_ALPHA_) +#define PTW32_PROGCTR(Context) ((Context).Fir) +#endif + +#if defined(_PPC_) +#define PTW32_PROGCTR(Context) ((Context).Iar) +#endif + +#if defined(_AMD64_) || defined(__amd64__) +#define PTW32_PROGCTR(Context) ((Context).Rip) +#endif + +#if defined(_ARM_) || defined(ARM) +#define PTW32_PROGCTR(Context) ((Context).Pc) +#endif + +#if !defined(PTW32_PROGCTR) +#error Module contains CPU-specific code; modify and recompile. +#endif + +#endif diff --git a/w32-pthreads/create.c b/w32-pthreads/create.c new file mode 100644 index 000000000..8b036cc2e --- /dev/null +++ b/w32-pthreads/create.c @@ -0,0 +1,308 @@ +/* + * create.c + * + * Description: + * This translation unit implements routines associated with spawning a new + * thread. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#if ! defined(_UWIN) && ! defined(WINCE) +#include +#endif + +int +pthread_create (pthread_t * tid, + const pthread_attr_t * attr, + void *(PTW32_CDECL *start) (void *), void *arg) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function creates a thread running the start function, + * passing it the parameter value, 'arg'. The 'attr' + * argument specifies optional creation attributes. + * The identity of the new thread is returned + * via 'tid', which should not be NULL. + * + * PARAMETERS + * tid + * pointer to an instance of pthread_t + * + * attr + * optional pointer to an instance of pthread_attr_t + * + * start + * pointer to the starting routine for the new thread + * + * arg + * optional parameter passed to 'start' + * + * + * DESCRIPTION + * This function creates a thread running the start function, + * passing it the parameter value, 'arg'. The 'attr' + * argument specifies optional creation attributes. + * The identity of the new thread is returned + * via 'tid', which should not be the NULL pointer. + * + * RESULTS + * 0 successfully created thread, + * EINVAL attr invalid, + * EAGAIN insufficient resources. + * + * ------------------------------------------------------ + */ +{ + pthread_t thread; + ptw32_thread_t * tp; + register pthread_attr_t a; + HANDLE threadH = 0; + int result = EAGAIN; + int run = PTW32_TRUE; + ThreadParms *parms = NULL; + unsigned int stackSize; + int priority; + pthread_t self; + + /* + * Before doing anything, check that tid can be stored through + * without invoking a memory protection error (segfault). + * Make sure that the assignment below can't be optimised out by the compiler. + * This is assured by conditionally assigning *tid again at the end. + */ + tid->x = 0; + + if (attr != NULL) + { + a = *attr; + } + else + { + a = NULL; + } + + if ((thread = ptw32_new ()).p == NULL) + { + goto FAIL0; + } + + tp = (ptw32_thread_t *) thread.p; + + priority = tp->sched_priority; + + if ((parms = (ThreadParms *) malloc (sizeof (*parms))) == NULL) + { + goto FAIL0; + } + + parms->tid = thread; + parms->start = start; + parms->arg = arg; + +#if defined(HAVE_SIGSET_T) + + /* + * Threads inherit their initial sigmask from their creator thread. + */ + self = pthread_self(); + tp->sigmask = ((ptw32_thread_t *)self.p)->sigmask; + +#endif /* HAVE_SIGSET_T */ + + + if (a != NULL) + { + stackSize = (unsigned int)a->stacksize; + tp->detachState = a->detachstate; + priority = a->param.sched_priority; + +#if (THREAD_PRIORITY_LOWEST > THREAD_PRIORITY_NORMAL) + /* WinCE */ +#else + /* Everything else */ + + /* + * Thread priority must be set to a valid system level + * without altering the value set by pthread_attr_setschedparam(). + */ + + /* + * PTHREAD_EXPLICIT_SCHED is the default because Win32 threads + * don't inherit their creator's priority. They are started with + * THREAD_PRIORITY_NORMAL (win32 value). The result of not supplying + * an 'attr' arg to pthread_create() is equivalent to defaulting to + * PTHREAD_EXPLICIT_SCHED and priority THREAD_PRIORITY_NORMAL. + */ + if (PTHREAD_INHERIT_SCHED == a->inheritsched) + { + /* + * If the thread that called pthread_create() is a Win32 thread + * then the inherited priority could be the result of a temporary + * system adjustment. This is not the case for POSIX threads. + */ +#if ! defined(HAVE_SIGSET_T) + self = pthread_self (); +#endif + priority = ((ptw32_thread_t *) self.p)->sched_priority; + } + +#endif + + } + else + { + /* + * Default stackSize + */ + stackSize = PTHREAD_STACK_MIN; + } + + tp->state = run ? PThreadStateInitial : PThreadStateSuspended; + + tp->keys = NULL; + + /* + * Threads must be started in suspended mode and resumed if necessary + * after _beginthreadex returns us the handle. Otherwise we set up a + * race condition between the creating and the created threads. + * Note that we also retain a local copy of the handle for use + * by us in case thread.p->threadH gets NULLed later but before we've + * finished with it here. + */ + +#if ! (defined (__MINGW64__) || defined(__MINGW32__)) || defined (__MSVCRT__) || defined (__DMC__) + + tp->threadH = + threadH = + (HANDLE) _beginthreadex ((void *) NULL, /* No security info */ + stackSize, /* default stack size */ + ptw32_threadStart, + parms, + (unsigned) + CREATE_SUSPENDED, + (unsigned *) &(tp->thread)); + + if (threadH != 0) + { + if (a != NULL) + { + (void) ptw32_setthreadpriority (thread, SCHED_OTHER, priority); + } + + if (run) + { + ResumeThread (threadH); + } + } + +#else + + { + ptw32_mcs_local_node_t stateLock; + + /* + * This lock will force pthread_threadStart() to wait until we have + * the thread handle and have set the priority. + */ + ptw32_mcs_lock_acquire(&tp->stateLock, &stateLock); + + tp->threadH = + threadH = + (HANDLE) _beginthread (ptw32_threadStart, stackSize, /* default stack size */ + parms); + + /* + * Make the return code match _beginthreadex's. + */ + if (threadH == (HANDLE) - 1L) + { + tp->threadH = threadH = 0; + } + else + { + if (!run) + { + /* + * beginthread does not allow for create flags, so we do it now. + * Note that beginthread itself creates the thread in SUSPENDED + * mode, and then calls ResumeThread to start it. + */ + SuspendThread (threadH); + } + + if (a != NULL) + { + (void) ptw32_setthreadpriority (thread, SCHED_OTHER, priority); + } + } + + ptw32_mcs_lock_release (&stateLock); + } +#endif + + result = (threadH != 0) ? 0 : EAGAIN; + + /* + * Fall Through Intentionally + */ + + /* + * ------------ + * Failure Code + * ------------ + */ + +FAIL0: + if (result != 0) + { + + ptw32_threadDestroy (thread); + tp = NULL; + + if (parms != NULL) + { + free (parms); + } + } + else + { + *tid = thread; + } + +#if defined(_UWIN) + if (result == 0) + pthread_count++; +#endif + return (result); + +} /* pthread_create */ diff --git a/w32-pthreads/dll.c b/w32-pthreads/dll.c new file mode 100644 index 000000000..05e01bee7 --- /dev/null +++ b/w32-pthreads/dll.c @@ -0,0 +1,92 @@ +/* + * dll.c + * + * Description: + * This translation unit implements DLL initialisation. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#if !defined(PTW32_STATIC_LIB) + +#include "pthread.h" +#include "implement.h" + +#if defined(_MSC_VER) +/* + * lpvReserved yields an unreferenced formal parameter; + * ignore it + */ +#pragma warning( disable : 4100 ) +#endif + +#if defined(__cplusplus) +/* + * Dear c++: Please don't mangle this name. -thanks + */ +extern "C" +#endif /* __cplusplus */ + BOOL WINAPI +DllMain (HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpvReserved) +{ + BOOL result = PTW32_TRUE; + + switch (fdwReason) + { + + case DLL_PROCESS_ATTACH: + result = pthread_win32_process_attach_np (); + break; + + case DLL_THREAD_ATTACH: + /* + * A thread is being created + */ + result = pthread_win32_thread_attach_np (); + break; + + case DLL_THREAD_DETACH: + /* + * A thread is exiting cleanly + */ + result = pthread_win32_thread_detach_np (); + break; + + case DLL_PROCESS_DETACH: + (void) pthread_win32_thread_detach_np (); + result = pthread_win32_process_detach_np (); + break; + } + + return (result); + +} /* DllMain */ + +#endif /* PTW32_STATIC_LIB */ diff --git a/w32-pthreads/errno.c b/w32-pthreads/errno.c new file mode 100644 index 000000000..78aa920a5 --- /dev/null +++ b/w32-pthreads/errno.c @@ -0,0 +1,94 @@ +/* + * errno.c + * + * Description: + * This translation unit implements routines associated with spawning a new + * thread. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#if defined(NEED_ERRNO) + +#include "pthread.h" +#include "implement.h" + +static int reallyBad = ENOMEM; + +/* + * Re-entrant errno. + * + * Each thread has it's own errno variable in pthread_t. + * + * The benefit of using the pthread_t structure + * instead of another TSD key is TSD keys are limited + * on Win32 to 64 per process. Secondly, to implement + * it properly without using pthread_t you'd need + * to dynamically allocate an int on starting the thread + * and store it manually into TLS and then ensure that you free + * it on thread termination. We get all that for free + * by simply storing the errno on the pthread_t structure. + * + * MSVC and Mingw32 already have their own thread-safe errno. + * + * #if defined( _REENTRANT ) || defined( _MT ) + * #define errno *_errno() + * + * int *_errno( void ); + * #else + * extern int errno; + * #endif + * + */ + +int * +_errno (void) +{ + pthread_t self; + int *result; + + if ((self = pthread_self ()).p == NULL) + { + /* + * Yikes! unable to allocate a thread! + * Throw an exception? return an error? + */ + result = &reallyBad; + } + else + { + result = (int *)(&self.p->exitStatus); + } + + return (result); + +} /* _errno */ + +#endif /* (NEED_ERRNO) */ diff --git a/w32-pthreads/exit.c b/w32-pthreads/exit.c new file mode 100644 index 000000000..94369d007 --- /dev/null +++ b/w32-pthreads/exit.c @@ -0,0 +1,44 @@ +/* + * exit.c + * + * Description: + * This translation unit implements routines associated with exiting from + * a thread. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#if ! defined(_UWIN) && ! defined(WINCE) +# include +#endif + +#include "pthread_exit.c" diff --git a/w32-pthreads/fork.c b/w32-pthreads/fork.c new file mode 100644 index 000000000..8a29550ca --- /dev/null +++ b/w32-pthreads/fork.c @@ -0,0 +1,39 @@ +/* + * fork.c + * + * Description: + * Implementation of fork() for POSIX threads. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + + +#include "pthread.h" +#include "implement.h" diff --git a/w32-pthreads/global.c b/w32-pthreads/global.c new file mode 100644 index 000000000..f1e9b3f66 --- /dev/null +++ b/w32-pthreads/global.c @@ -0,0 +1,107 @@ +/* + * global.c + * + * Description: + * This translation unit instantiates data associated with the implementation + * as a whole. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int ptw32_processInitialized = PTW32_FALSE; +ptw32_thread_t * ptw32_threadReuseTop = PTW32_THREAD_REUSE_EMPTY; +ptw32_thread_t * ptw32_threadReuseBottom = PTW32_THREAD_REUSE_EMPTY; +pthread_key_t ptw32_selfThreadKey = NULL; +pthread_key_t ptw32_cleanupKey = NULL; +pthread_cond_t ptw32_cond_list_head = NULL; +pthread_cond_t ptw32_cond_list_tail = NULL; + +int ptw32_concurrency = 0; + +/* What features have been auto-detected */ +int ptw32_features = 0; + +/* + * Global [process wide] thread sequence Number + */ +unsigned __int64 ptw32_threadSeqNumber = 0; + +/* + * Function pointer to QueueUserAPCEx if it exists, otherwise + * it will be set at runtime to a substitute routine which cannot unblock + * blocked threads. + */ +DWORD (*ptw32_register_cancelation) (PAPCFUNC, HANDLE, DWORD) = NULL; + +/* + * Global lock for managing pthread_t struct reuse. + */ +ptw32_mcs_lock_t ptw32_thread_reuse_lock = 0; + +/* + * Global lock for testing internal state of statically declared mutexes. + */ +ptw32_mcs_lock_t ptw32_mutex_test_init_lock = 0; + +/* + * Global lock for testing internal state of PTHREAD_COND_INITIALIZER + * created condition variables. + */ +ptw32_mcs_lock_t ptw32_cond_test_init_lock = 0; + +/* + * Global lock for testing internal state of PTHREAD_RWLOCK_INITIALIZER + * created read/write locks. + */ +ptw32_mcs_lock_t ptw32_rwlock_test_init_lock = 0; + +/* + * Global lock for testing internal state of PTHREAD_SPINLOCK_INITIALIZER + * created spin locks. + */ +ptw32_mcs_lock_t ptw32_spinlock_test_init_lock = 0; + +/* + * Global lock for condition variable linked list. The list exists + * to wake up CVs when a WM_TIMECHANGE message arrives. See + * w32_TimeChangeHandler.c. + */ +ptw32_mcs_lock_t ptw32_cond_list_lock = 0; + +#if defined(_UWIN) +/* + * Keep a count of the number of threads. + */ +int pthread_count = 0; +#endif diff --git a/w32-pthreads/implement.h b/w32-pthreads/implement.h new file mode 100644 index 000000000..693be26a2 --- /dev/null +++ b/w32-pthreads/implement.h @@ -0,0 +1,943 @@ +/* + * implement.h + * + * Definitions that don't need to be public. + * + * Keeps all the internals out of pthread.h + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: Ross.Johnson@homemail.com.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#if !defined(_IMPLEMENT_H) +#define _IMPLEMENT_H + +#if !defined(_WIN32_WINNT) +#define _WIN32_WINNT 0x0400 +#endif + +#include + +/* + * In case windows.h doesn't define it (e.g. WinCE perhaps) + */ +#if defined(WINCE) +typedef VOID (APIENTRY *PAPCFUNC)(DWORD dwParam); +#endif + +/* + * note: ETIMEDOUT is correctly defined in winsock.h + */ +#include + +/* + * In case ETIMEDOUT hasn't been defined above somehow. + */ +#if !defined(ETIMEDOUT) +# define ETIMEDOUT 10060 /* This is the value in winsock.h. */ +#endif + +#if !defined(malloc) +#include +#endif + +#if defined(__CLEANUP_C) +# include +#endif + +#if !defined(INT_MAX) +#include +#endif + +/* use local include files during development */ +#include "semaphore.h" +#include "sched.h" + +#if defined(HAVE_C_INLINE) || defined(__cplusplus) +#define INLINE inline +#else +#define INLINE +#endif + +#if defined(_MSC_VER) && _MSC_VER < 1300 +/* + * MSVC 6 does not use the "volatile" qualifier + */ +#define PTW32_INTERLOCKED_VOLATILE +#else +#define PTW32_INTERLOCKED_VOLATILE volatile +#endif +#define PTW32_INTERLOCKED_LONG long +#define PTW32_INTERLOCKED_SIZE size_t +#define PTW32_INTERLOCKED_PVOID PVOID +#define PTW32_INTERLOCKED_LONGPTR PTW32_INTERLOCKED_VOLATILE long* +#define PTW32_INTERLOCKED_SIZEPTR PTW32_INTERLOCKED_VOLATILE size_t* +#define PTW32_INTERLOCKED_PVOID_PTR PTW32_INTERLOCKED_VOLATILE PVOID* + +#if defined(__MINGW64__) || defined(__MINGW32__) +# include +#elif defined(__BORLANDC__) +# define int64_t ULONGLONG +#else +# define int64_t _int64 +# if defined(_MSC_VER) && _MSC_VER < 1300 + typedef long intptr_t; +# endif +#endif + +typedef enum +{ + /* + * This enumeration represents the state of the thread; + * The thread is still "alive" if the numeric value of the + * state is greater or equal "PThreadStateRunning". + */ + PThreadStateInitial = 0, /* Thread not running */ + PThreadStateRunning, /* Thread alive & kicking */ + PThreadStateSuspended, /* Thread alive but suspended */ + PThreadStateCancelPending, /* Thread alive but */ + /* has cancelation pending. */ + PThreadStateCanceling, /* Thread alive but is */ + /* in the process of terminating */ + /* due to a cancellation request */ + PThreadStateExiting, /* Thread alive but exiting */ + /* due to an exception */ + PThreadStateLast, /* All handlers have been run and now */ + /* final cleanup can be done. */ + PThreadStateReuse /* In reuse pool. */ +} +PThreadState; + +typedef struct ptw32_mcs_node_t_ ptw32_mcs_local_node_t; +typedef struct ptw32_mcs_node_t_* ptw32_mcs_lock_t; +typedef struct ptw32_robust_node_t_ ptw32_robust_node_t; +typedef struct ptw32_thread_t_ ptw32_thread_t; + + +struct ptw32_thread_t_ +{ + unsigned __int64 seqNumber; /* Process-unique thread sequence number */ + HANDLE threadH; /* Win32 thread handle - POSIX thread is invalid if threadH == 0 */ + pthread_t ptHandle; /* This thread's permanent pthread_t handle */ + ptw32_thread_t * prevReuse; /* Links threads on reuse stack */ + volatile PThreadState state; + ptw32_mcs_lock_t threadLock; /* Used for serialised access to public thread state */ + ptw32_mcs_lock_t stateLock; /* Used for async-cancel safety */ + HANDLE cancelEvent; + void *exitStatus; + void *parms; + void *keys; + void *nextAssoc; +#if defined(__CLEANUP_C) + jmp_buf start_mark; /* Jump buffer follows void* so should be aligned */ +#endif /* __CLEANUP_C */ +#if defined(HAVE_SIGSET_T) + sigset_t sigmask; +#endif /* HAVE_SIGSET_T */ + ptw32_mcs_lock_t + robustMxListLock; /* robustMxList lock */ + ptw32_robust_node_t* + robustMxList; /* List of currenty held robust mutexes */ + int ptErrno; + int detachState; + int sched_priority; /* As set, not as currently is */ + int cancelState; + int cancelType; + int implicit:1; + DWORD thread; /* Win32 thread ID */ +#if defined(_UWIN) + DWORD dummy[5]; +#endif + size_t align; /* Force alignment if this struct is packed */ +}; + + +/* + * Special value to mark attribute objects as valid. + */ +#define PTW32_ATTR_VALID ((unsigned long) 0xC4C0FFEE) + +struct pthread_attr_t_ +{ + unsigned long valid; + void *stackaddr; + size_t stacksize; + int detachstate; + struct sched_param param; + int inheritsched; + int contentionscope; +#if defined(HAVE_SIGSET_T) + sigset_t sigmask; +#endif /* HAVE_SIGSET_T */ +}; + + +/* + * ==================== + * ==================== + * Semaphores, Mutexes and Condition Variables + * ==================== + * ==================== + */ + +struct sem_t_ +{ + int value; + pthread_mutex_t lock; + HANDLE sem; +#if defined(NEED_SEM) + int leftToUnblock; +#endif +}; + +#define PTW32_OBJECT_AUTO_INIT ((void *)(size_t) -1) +#define PTW32_OBJECT_INVALID NULL + +struct pthread_mutex_t_ +{ + LONG lock_idx; /* Provides exclusive access to mutex state + via the Interlocked* mechanism. + 0: unlocked/free. + 1: locked - no other waiters. + -1: locked - with possible other waiters. + */ + int recursive_count; /* Number of unlocks a thread needs to perform + before the lock is released (recursive + mutexes only). */ + int kind; /* Mutex type. */ + pthread_t ownerThread; + HANDLE event; /* Mutex release notification to waiting + threads. */ + ptw32_robust_node_t* + robustNode; /* Extra state for robust mutexes */ +}; + +enum ptw32_robust_state_t_ +{ + PTW32_ROBUST_CONSISTENT, + PTW32_ROBUST_INCONSISTENT, + PTW32_ROBUST_NOTRECOVERABLE +}; + +typedef enum ptw32_robust_state_t_ ptw32_robust_state_t; + +/* + * Node used to manage per-thread lists of currently-held robust mutexes. + */ +struct ptw32_robust_node_t_ +{ + pthread_mutex_t mx; + ptw32_robust_state_t stateInconsistent; + ptw32_robust_node_t* prev; + ptw32_robust_node_t* next; +}; + +struct pthread_mutexattr_t_ +{ + int pshared; + int kind; + int robustness; +}; + +/* + * Possible values, other than PTW32_OBJECT_INVALID, + * for the "interlock" element in a spinlock. + * + * In this implementation, when a spinlock is initialised, + * the number of cpus available to the process is checked. + * If there is only one cpu then "interlock" is set equal to + * PTW32_SPIN_USE_MUTEX and u.mutex is an initialised mutex. + * If the number of cpus is greater than 1 then "interlock" + * is set equal to PTW32_SPIN_UNLOCKED and the number is + * stored in u.cpus. This arrangement allows the spinlock + * routines to attempt an InterlockedCompareExchange on "interlock" + * immediately and, if that fails, to try the inferior mutex. + * + * "u.cpus" isn't used for anything yet, but could be used at + * some point to optimise spinlock behaviour. + */ +#define PTW32_SPIN_INVALID (0) +#define PTW32_SPIN_UNLOCKED (1) +#define PTW32_SPIN_LOCKED (2) +#define PTW32_SPIN_USE_MUTEX (3) + +struct pthread_spinlock_t_ +{ + long interlock; /* Locking element for multi-cpus. */ + union + { + int cpus; /* No. of cpus if multi cpus, or */ + pthread_mutex_t mutex; /* mutex if single cpu. */ + } u; +}; + +/* + * MCS lock queue node - see ptw32_MCS_lock.c + */ +struct ptw32_mcs_node_t_ +{ + struct ptw32_mcs_node_t_ **lock; /* ptr to tail of queue */ + struct ptw32_mcs_node_t_ *next; /* ptr to successor in queue */ + HANDLE readyFlag; /* set after lock is released by + predecessor */ + HANDLE nextFlag; /* set after 'next' ptr is set by + successor */ +}; + + +struct pthread_barrier_t_ +{ + unsigned int nCurrentBarrierHeight; + unsigned int nInitialBarrierHeight; + int pshared; + sem_t semBarrierBreeched; + ptw32_mcs_lock_t lock; + ptw32_mcs_local_node_t proxynode; +}; + +struct pthread_barrierattr_t_ +{ + int pshared; +}; + +struct pthread_key_t_ +{ + DWORD key; + void (PTW32_CDECL *destructor) (void *); + ptw32_mcs_lock_t keyLock; + void *threads; +}; + + +typedef struct ThreadParms ThreadParms; + +struct ThreadParms +{ + pthread_t tid; + void *(PTW32_CDECL *start) (void *); + void *arg; +}; + + +struct pthread_cond_t_ +{ + long nWaitersBlocked; /* Number of threads blocked */ + long nWaitersGone; /* Number of threads timed out */ + long nWaitersToUnblock; /* Number of threads to unblock */ + sem_t semBlockQueue; /* Queue up threads waiting for the */ + /* condition to become signalled */ + sem_t semBlockLock; /* Semaphore that guards access to */ + /* | waiters blocked count/block queue */ + /* +-> Mandatory Sync.LEVEL-1 */ + pthread_mutex_t mtxUnblockLock; /* Mutex that guards access to */ + /* | waiters (to)unblock(ed) counts */ + /* +-> Optional* Sync.LEVEL-2 */ + pthread_cond_t next; /* Doubly linked list */ + pthread_cond_t prev; +}; + + +struct pthread_condattr_t_ +{ + int pshared; +}; + +#define PTW32_RWLOCK_MAGIC 0xfacade2 + +struct pthread_rwlock_t_ +{ + pthread_mutex_t mtxExclusiveAccess; + pthread_mutex_t mtxSharedAccessCompleted; + pthread_cond_t cndSharedAccessCompleted; + int nSharedAccessCount; + int nExclusiveAccessCount; + int nCompletedSharedAccessCount; + int nMagic; +}; + +struct pthread_rwlockattr_t_ +{ + int pshared; +}; + +typedef struct ThreadKeyAssoc ThreadKeyAssoc; + +struct ThreadKeyAssoc +{ + /* + * Purpose: + * This structure creates an association between a thread and a key. + * It is used to implement the implicit invocation of a user defined + * destroy routine for thread specific data registered by a user upon + * exiting a thread. + * + * Graphically, the arrangement is as follows, where: + * + * K - Key with destructor + * (head of chain is key->threads) + * T - Thread that has called pthread_setspecific(Kn) + * (head of chain is thread->keys) + * A - Association. Each association is a node at the + * intersection of two doubly-linked lists. + * + * T1 T2 T3 + * | | | + * | | | + * K1 -----+-----A-----A-----> + * | | | + * | | | + * K2 -----A-----A-----+-----> + * | | | + * | | | + * K3 -----A-----+-----A-----> + * | | | + * | | | + * V V V + * + * Access to the association is guarded by two locks: the key's + * general lock (guarding the row) and the thread's general + * lock (guarding the column). This avoids the need for a + * dedicated lock for each association, which not only consumes + * more handles but requires that the lock resources persist + * until both the key is deleted and the thread has called the + * destructor. The two-lock arrangement allows those resources + * to be freed as soon as either thread or key is concluded. + * + * To avoid deadlock, whenever both locks are required both the + * key and thread locks are acquired consistently in the order + * "key lock then thread lock". An exception to this exists + * when a thread calls the destructors, however, this is done + * carefully (but inelegantly) to avoid deadlock. + * + * An association is created when a thread first calls + * pthread_setspecific() on a key that has a specified + * destructor. + * + * An association is destroyed either immediately after the + * thread calls the key destructor function on thread exit, or + * when the key is deleted. + * + * Attributes: + * thread + * reference to the thread that owns the + * association. This is actually the pointer to the + * thread struct itself. Since the association is + * destroyed before the thread exits, this can never + * point to a different logical thread to the one that + * created the assoc, i.e. after thread struct reuse. + * + * key + * reference to the key that owns the association. + * + * nextKey + * The pthread_t->keys attribute is the head of a + * chain of associations that runs through the nextKey + * link. This chain provides the 1 to many relationship + * between a pthread_t and all pthread_key_t on which + * it called pthread_setspecific. + * + * prevKey + * Similarly. + * + * nextThread + * The pthread_key_t->threads attribute is the head of + * a chain of associations that runs through the + * nextThreads link. This chain provides the 1 to many + * relationship between a pthread_key_t and all the + * PThreads that have called pthread_setspecific for + * this pthread_key_t. + * + * prevThread + * Similarly. + * + * Notes: + * 1) As soon as either the key or the thread is no longer + * referencing the association, it can be destroyed. The + * association will be removed from both chains. + * + * 2) Under WIN32, an association is only created by + * pthread_setspecific if the user provided a + * destroyRoutine when they created the key. + * + * + */ + ptw32_thread_t * thread; + pthread_key_t key; + ThreadKeyAssoc *nextKey; + ThreadKeyAssoc *nextThread; + ThreadKeyAssoc *prevKey; + ThreadKeyAssoc *prevThread; +}; + + +#if defined(__CLEANUP_SEH) +/* + * -------------------------------------------------------------- + * MAKE_SOFTWARE_EXCEPTION + * This macro constructs a software exception code following + * the same format as the standard Win32 error codes as defined + * in WINERROR.H + * Values are 32 bit values laid out as follows: + * + * 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 + * +---+-+-+-----------------------+-------------------------------+ + * |Sev|C|R| Facility | Code | + * +---+-+-+-----------------------+-------------------------------+ + * + * Severity Values: + */ +#define SE_SUCCESS 0x00 +#define SE_INFORMATION 0x01 +#define SE_WARNING 0x02 +#define SE_ERROR 0x03 + +#define MAKE_SOFTWARE_EXCEPTION( _severity, _facility, _exception ) \ +( (DWORD) ( ( (_severity) << 30 ) | /* Severity code */ \ + ( 1 << 29 ) | /* MS=0, User=1 */ \ + ( 0 << 28 ) | /* Reserved */ \ + ( (_facility) << 16 ) | /* Facility Code */ \ + ( (_exception) << 0 ) /* Exception Code */ \ + ) ) + +/* + * We choose one specific Facility/Error code combination to + * identify our software exceptions vs. WIN32 exceptions. + * We store our actual component and error code within + * the optional information array. + */ +#define EXCEPTION_PTW32_SERVICES \ + MAKE_SOFTWARE_EXCEPTION( SE_ERROR, \ + PTW32_SERVICES_FACILITY, \ + PTW32_SERVICES_ERROR ) + +#define PTW32_SERVICES_FACILITY 0xBAD +#define PTW32_SERVICES_ERROR 0xDEED + +#endif /* __CLEANUP_SEH */ + +/* + * Services available through EXCEPTION_PTW32_SERVICES + * and also used [as parameters to ptw32_throw()] as + * generic exception selectors. + */ + +#define PTW32_EPS_EXIT (1) +#define PTW32_EPS_CANCEL (2) + + +/* Useful macros */ +#define PTW32_MAX(a,b) ((a)<(b)?(b):(a)) +#define PTW32_MIN(a,b) ((a)>(b)?(b):(a)) + + +/* Declared in pthread_cancel.c */ +extern DWORD (*ptw32_register_cancelation) (PAPCFUNC, HANDLE, DWORD); + +/* Thread Reuse stack bottom marker. Must not be NULL or any valid pointer to memory. */ +#define PTW32_THREAD_REUSE_EMPTY ((ptw32_thread_t *)(size_t) 1) + +extern int ptw32_processInitialized; +extern ptw32_thread_t * ptw32_threadReuseTop; +extern ptw32_thread_t * ptw32_threadReuseBottom; +extern pthread_key_t ptw32_selfThreadKey; +extern pthread_key_t ptw32_cleanupKey; +extern pthread_cond_t ptw32_cond_list_head; +extern pthread_cond_t ptw32_cond_list_tail; + +extern int ptw32_mutex_default_kind; + +extern unsigned __int64 ptw32_threadSeqNumber; + +extern int ptw32_concurrency; + +extern int ptw32_features; + +extern ptw32_mcs_lock_t ptw32_thread_reuse_lock; +extern ptw32_mcs_lock_t ptw32_mutex_test_init_lock; +extern ptw32_mcs_lock_t ptw32_cond_list_lock; +extern ptw32_mcs_lock_t ptw32_cond_test_init_lock; +extern ptw32_mcs_lock_t ptw32_rwlock_test_init_lock; +extern ptw32_mcs_lock_t ptw32_spinlock_test_init_lock; + +#if defined(_UWIN) +extern int pthread_count; +#endif + +#if defined(__cplusplus) +extern "C" +{ +#endif /* __cplusplus */ + +/* + * ===================== + * ===================== + * Forward Declarations + * ===================== + * ===================== + */ + + int ptw32_is_attr (const pthread_attr_t * attr); + + int ptw32_cond_check_need_init (pthread_cond_t * cond); + int ptw32_mutex_check_need_init (pthread_mutex_t * mutex); + int ptw32_rwlock_check_need_init (pthread_rwlock_t * rwlock); + + int ptw32_robust_mutex_inherit(pthread_mutex_t * mutex); + void ptw32_robust_mutex_add(pthread_mutex_t* mutex, pthread_t self); + void ptw32_robust_mutex_remove(pthread_mutex_t* mutex, ptw32_thread_t* otp); + + DWORD + ptw32_RegisterCancelation (PAPCFUNC callback, + HANDLE threadH, DWORD callback_arg); + + int ptw32_processInitialize (void); + + void ptw32_processTerminate (void); + + void ptw32_threadDestroy (pthread_t tid); + + void ptw32_pop_cleanup_all (int execute); + + pthread_t ptw32_new (void); + + pthread_t ptw32_threadReusePop (void); + + void ptw32_threadReusePush (pthread_t thread); + + int ptw32_getprocessors (int *count); + + int ptw32_setthreadpriority (pthread_t thread, int policy, int priority); + + void ptw32_rwlock_cancelwrwait (void *arg); + +#if ! (defined (__MINGW64__) || defined(__MINGW32__)) || (defined(__MSVCRT__) && ! defined(__DMC__)) + unsigned __stdcall +#else + void +#endif + ptw32_threadStart (void *vthreadParms); + + void ptw32_callUserDestroyRoutines (pthread_t thread); + + int ptw32_tkAssocCreate (ptw32_thread_t * thread, pthread_key_t key); + + void ptw32_tkAssocDestroy (ThreadKeyAssoc * assoc); + + int ptw32_semwait (sem_t * sem); + + DWORD ptw32_relmillisecs (const struct timespec * abstime); + + void ptw32_mcs_lock_acquire (ptw32_mcs_lock_t * lock, ptw32_mcs_local_node_t * node); + + int ptw32_mcs_lock_try_acquire (ptw32_mcs_lock_t * lock, ptw32_mcs_local_node_t * node); + + void ptw32_mcs_lock_release (ptw32_mcs_local_node_t * node); + + void ptw32_mcs_node_transfer (ptw32_mcs_local_node_t * new_node, ptw32_mcs_local_node_t * old_node); + +#if defined(NEED_FTIME) + void ptw32_timespec_to_filetime (const struct timespec *ts, FILETIME * ft); + void ptw32_filetime_to_timespec (const FILETIME * ft, struct timespec *ts); +#endif + +/* Declared in misc.c */ +#if defined(NEED_CALLOC) +#define calloc(n, s) ptw32_calloc(n, s) + void *ptw32_calloc (size_t n, size_t s); +#endif + +/* Declared in private.c */ +#if defined(_MSC_VER) +/* + * Ignore the warning: + * "C++ exception specification ignored except to indicate that + * the function is not __declspec(nothrow)." + */ +#pragma warning(disable:4290) +#endif + void ptw32_throw (DWORD exception) +#if defined(__CLEANUP_CXX) + throw(ptw32_exception_cancel,ptw32_exception_exit) +#endif +; + +#if defined(__cplusplus) +} +#endif /* __cplusplus */ + + +#if defined(_UWIN_) +# if defined(_MT) +# if defined(__cplusplus) +extern "C" +{ +# endif + _CRTIMP unsigned long __cdecl _beginthread (void (__cdecl *) (void *), + unsigned, void *); + _CRTIMP void __cdecl _endthread (void); + _CRTIMP unsigned long __cdecl _beginthreadex (void *, unsigned, + unsigned (__stdcall *) (void *), + void *, unsigned, unsigned *); + _CRTIMP void __cdecl _endthreadex (unsigned); +# if defined(__cplusplus) +} +# endif +# endif +#else +# include +# endif + + +/* + * Use intrinsic versions wherever possible. VC will do this + * automatically where possible and GCC define these if available: + * __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 + * __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 + * __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 + * __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 + * __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 + * + * The full set of Interlocked intrinsics in GCC are (check versions): + * type __sync_fetch_and_add (type *ptr, type value, ...) + * type __sync_fetch_and_sub (type *ptr, type value, ...) + * type __sync_fetch_and_or (type *ptr, type value, ...) + * type __sync_fetch_and_and (type *ptr, type value, ...) + * type __sync_fetch_and_xor (type *ptr, type value, ...) + * type __sync_fetch_and_nand (type *ptr, type value, ...) + * type __sync_add_and_fetch (type *ptr, type value, ...) + * type __sync_sub_and_fetch (type *ptr, type value, ...) + * type __sync_or_and_fetch (type *ptr, type value, ...) + * type __sync_and_and_fetch (type *ptr, type value, ...) + * type __sync_xor_and_fetch (type *ptr, type value, ...) + * type __sync_nand_and_fetch (type *ptr, type value, ...) + * bool __sync_bool_compare_and_swap (type *ptr, type oldval type newval, ...) + * type __sync_val_compare_and_swap (type *ptr, type oldval type newval, ...) + * __sync_synchronize (...) // Full memory barrier + * type __sync_lock_test_and_set (type *ptr, type value, ...) // Acquire barrier + * void __sync_lock_release (type *ptr, ...) // Release barrier + * + * These are all overloaded and take 1,2,4,8 byte scalar or pointer types. + * + * The above aren't available in Mingw32 as of gcc 4.5.2 so define our own. + */ +#if defined(__GNUC__) +# if defined(_WIN64) +# define PTW32_INTERLOCKED_COMPARE_EXCHANGE_64(location, value, comparand) \ + ({ \ + __typeof (value) _result; \ + __asm__ __volatile__ \ + ( \ + "lock\n\t" \ + "cmpxchgq %2,(%1)" \ + :"=a" (_result) \ + :"r" (location), "r" (value), "a" (comparand) \ + :"memory", "cc"); \ + _result; \ + }) +# define PTW32_INTERLOCKED_EXCHANGE_64(location, value) \ + ({ \ + __typeof (value) _result; \ + __asm__ __volatile__ \ + ( \ + "xchgq %0,(%1)" \ + :"=r" (_result) \ + :"r" (location), "0" (value) \ + :"memory", "cc"); \ + _result; \ + }) +# define PTW32_INTERLOCKED_EXCHANGE_ADD_64(location, value) \ + ({ \ + __typeof (value) _result; \ + __asm__ __volatile__ \ + ( \ + "lock\n\t" \ + "xaddq %0,(%1)" \ + :"=r" (_result) \ + :"r" (location), "0" (value) \ + :"memory", "cc"); \ + _result; \ + }) +# define PTW32_INTERLOCKED_INCREMENT_64(location) \ + ({ \ + PTW32_INTERLOCKED_LONG _temp = 1; \ + __asm__ __volatile__ \ + ( \ + "lock\n\t" \ + "xaddq %0,(%1)" \ + :"+r" (_temp) \ + :"r" (location) \ + :"memory", "cc"); \ + ++_temp; \ + }) +# define PTW32_INTERLOCKED_DECREMENT_64(location) \ + ({ \ + PTW32_INTERLOCKED_LONG _temp = -1; \ + __asm__ __volatile__ \ + ( \ + "lock\n\t" \ + "xaddq %2,(%1)" \ + :"+r" (_temp) \ + :"r" (location) \ + :"memory", "cc"); \ + --_temp; \ + }) +#endif +# define PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG(location, value, comparand) \ + ({ \ + __typeof (value) _result; \ + __asm__ __volatile__ \ + ( \ + "lock\n\t" \ + "cmpxchgl %2,(%1)" \ + :"=a" (_result) \ + :"r" (location), "r" (value), "a" (comparand) \ + :"memory", "cc"); \ + _result; \ + }) +# define PTW32_INTERLOCKED_EXCHANGE_LONG(location, value) \ + ({ \ + __typeof (value) _result; \ + __asm__ __volatile__ \ + ( \ + "xchgl %0,(%1)" \ + :"=r" (_result) \ + :"r" (location), "0" (value) \ + :"memory", "cc"); \ + _result; \ + }) +# define PTW32_INTERLOCKED_EXCHANGE_ADD_LONG(location, value) \ + ({ \ + __typeof (value) _result; \ + __asm__ __volatile__ \ + ( \ + "lock\n\t" \ + "xaddl %0,(%1)" \ + :"=r" (_result) \ + :"r" (location), "0" (value) \ + :"memory", "cc"); \ + _result; \ + }) +# define PTW32_INTERLOCKED_INCREMENT_LONG(location) \ + ({ \ + PTW32_INTERLOCKED_LONG _temp = 1; \ + __asm__ __volatile__ \ + ( \ + "lock\n\t" \ + "xaddl %0,(%1)" \ + :"+r" (_temp) \ + :"r" (location) \ + :"memory", "cc"); \ + ++_temp; \ + }) +# define PTW32_INTERLOCKED_DECREMENT_LONG(location) \ + ({ \ + PTW32_INTERLOCKED_LONG _temp = -1; \ + __asm__ __volatile__ \ + ( \ + "lock\n\t" \ + "xaddl %0,(%1)" \ + :"+r" (_temp) \ + :"r" (location) \ + :"memory", "cc"); \ + --_temp; \ + }) +# define PTW32_INTERLOCKED_COMPARE_EXCHANGE_PTR(location, value, comparand) \ + PTW32_INTERLOCKED_COMPARE_EXCHANGE_SIZE((PTW32_INTERLOCKED_SIZEPTR)location, \ + (PTW32_INTERLOCKED_SIZE)value, \ + (PTW32_INTERLOCKED_SIZE)comparand) +# define PTW32_INTERLOCKED_EXCHANGE_PTR(location, value) \ + PTW32_INTERLOCKED_EXCHANGE_SIZE((PTW32_INTERLOCKED_SIZEPTR)location, \ + (PTW32_INTERLOCKED_SIZE)value) +#else +# if defined(_WIN64) +# define PTW32_INTERLOCKED_COMPARE_EXCHANGE_64 InterlockedCompareExchange64 +# define PTW32_INTERLOCKED_EXCHANGE_64 InterlockedExchange64 +# define PTW32_INTERLOCKED_EXCHANGE_ADD_64 InterlockedExchangeAdd64 +# define PTW32_INTERLOCKED_INCREMENT_64 InterlockedIncrement64 +# define PTW32_INTERLOCKED_DECREMENT_64 InterlockedDecrement64 +# endif +# if defined(_MSC_VER) && _MSC_VER < 1300 && !defined(_WIN64) /* MSVC 6 */ +# define PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG(location, value, comparand) \ + ((LONG)InterlockedCompareExchange((PVOID *)(location), (PVOID)(value), (PVOID)(comparand))) +# else +# define PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG InterlockedCompareExchange +# endif +# define PTW32_INTERLOCKED_EXCHANGE_LONG InterlockedExchange +# define PTW32_INTERLOCKED_EXCHANGE_ADD_LONG InterlockedExchangeAdd +# define PTW32_INTERLOCKED_INCREMENT_LONG InterlockedIncrement +# define PTW32_INTERLOCKED_DECREMENT_LONG InterlockedDecrement +# if defined(_MSC_VER) && _MSC_VER < 1300 && !defined(_WIN64) /* MSVC 6 */ +# define PTW32_INTERLOCKED_COMPARE_EXCHANGE_PTR InterlockedCompareExchange +# define PTW32_INTERLOCKED_EXCHANGE_PTR(location, value) \ + ((PVOID)InterlockedExchange((LPLONG)(location), (LONG)(value))) +# else +# define PTW32_INTERLOCKED_COMPARE_EXCHANGE_PTR InterlockedCompareExchangePointer +# define PTW32_INTERLOCKED_EXCHANGE_PTR InterlockedExchangePointer +# endif +#endif +#if defined(_WIN64) +# define PTW32_INTERLOCKED_COMPARE_EXCHANGE_SIZE PTW32_INTERLOCKED_COMPARE_EXCHANGE_64 +# define PTW32_INTERLOCKED_EXCHANGE_SIZE PTW32_INTERLOCKED_EXCHANGE_64 +# define PTW32_INTERLOCKED_EXCHANGE_ADD_SIZE PTW32_INTERLOCKED_EXCHANGE_ADD_64 +# define PTW32_INTERLOCKED_INCREMENT_SIZE PTW32_INTERLOCKED_INCREMENT_64 +# define PTW32_INTERLOCKED_DECREMENT_SIZE PTW32_INTERLOCKED_DECREMENT_64 +#else +# define PTW32_INTERLOCKED_COMPARE_EXCHANGE_SIZE PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG +# define PTW32_INTERLOCKED_EXCHANGE_SIZE PTW32_INTERLOCKED_EXCHANGE_LONG +# define PTW32_INTERLOCKED_EXCHANGE_ADD_SIZE PTW32_INTERLOCKED_EXCHANGE_ADD_LONG +# define PTW32_INTERLOCKED_INCREMENT_SIZE PTW32_INTERLOCKED_INCREMENT_LONG +# define PTW32_INTERLOCKED_DECREMENT_SIZE PTW32_INTERLOCKED_DECREMENT_LONG +#endif + +#if defined(NEED_CREATETHREAD) + +/* + * Macro uses args so we can cast start_proc to LPTHREAD_START_ROUTINE + * in order to avoid warnings because of return type + */ + +#define _beginthreadex(security, \ + stack_size, \ + start_proc, \ + arg, \ + flags, \ + pid) \ + CreateThread(security, \ + stack_size, \ + (LPTHREAD_START_ROUTINE) start_proc, \ + arg, \ + flags, \ + pid) + +#define _endthreadex ExitThread + +#endif /* NEED_CREATETHREAD */ + + +#endif /* _IMPLEMENT_H */ diff --git a/w32-pthreads/libpthreadGC2.a b/w32-pthreads/libpthreadGC2.a new file mode 100644 index 000000000..43ff77ed9 Binary files /dev/null and b/w32-pthreads/libpthreadGC2.a differ diff --git a/w32-pthreads/libpthreadGC2.stamp b/w32-pthreads/libpthreadGC2.stamp new file mode 100644 index 000000000..16225d0f1 --- /dev/null +++ b/w32-pthreads/libpthreadGC2.stamp @@ -0,0 +1 @@ +touched diff --git a/w32-pthreads/manual/ChangeLog b/w32-pthreads/manual/ChangeLog new file mode 100644 index 000000000..071b847ef --- /dev/null +++ b/w32-pthreads/manual/ChangeLog @@ -0,0 +1,74 @@ +2011-03-26 Ross Johnson + + * pthread_nutex_init.html (robust mutexes): Added + descriptions for newly implemented interface. + * pthread_mutexattr_init.html (robust mutexes): Likewise. + * pthread_getsequence_np.html: New. + * index.html: Updated. + +2008-06-30 Ross Johnson + + * pthread_setschedparam.html: Fix "see also" links. + +2005-05-06 Ross Johnson + + * PortabilityIssues.html: Was nonPortableIssues.html. + * index.html: Updated; add table of contents at top. + * *.html: Add Pthreads-win32 header info; add link back to the + index page 'index.html'. + +2005-05-06 Ross Johnson + + * index.html: New. + * nonPortableIssues.html: New. + * pthread_attr_init.html: New. + * pthread_attr_setstackaddr.html: New. + * pthread_attr_setstacksize.html: New. + * pthread_barrierattr_init.html: New. + * pthread_barrierattr_setpshared.html: New. + * pthread_barrier_init.html: New. + * pthread_barrier_wait.html: New. + * pthreadCancelableWait.html: New. + * pthread_cancel.html: New. + * pthread_cleanup_push.html: New. + * pthread_condattr_init.html: New. + * pthread_condattr_setpshared.html: New. + * pthread_cond_init.html: New. + * pthread_create.html: New. + * pthread_delay_np.html: New. + * pthread_detach.html: New. + * pthread_equal.html: New. + * pthread_exit.html: New. + * pthread_getw32threadhandle_np.html: New. + * pthread_join.html: New. + * pthread_key_create.html: New. + * pthread_kill.html: New. + * pthread_mutexattr_init.html: New. + * pthread_mutexattr_setpshared.html: New. + * pthread_mutex_init.html: New. + * pthread_num_processors_np.html: New. + * pthread_once.html: New. + * pthread_rwlockattr_init.html: New. + * pthread_rwlockattr_setpshared.html: New. + * pthread_rwlock_init.html: New. + * pthread_rwlock_rdlock.html: New. + * pthread_rwlock_timedrdlock.html: New. + * pthread_rwlock_timedwrlock.html: New. + * pthread_rwlock_unlock.html: New. + * pthread_rwlock_wrlock.html: New. + * pthread_self.html: New. + * pthread_setcancelstate.html: New. + * pthread_setcanceltype.html: New. + * pthread_setconcurrency.html: New. + * pthread_setschedparam.html: New. + * pthread_spin_init.html: New. + * pthread_spin_lock.html: New. + * pthread_spin_unlock.html: New. + * pthread_timechange_handler_np.html: New. + * pthread_win32_attach_detach_np.html: New. + * pthread_win32_test_features_np.html: New. + * sched_get_priority_max.html: New. + * sched_getscheduler.html: New. + * sched_setscheduler.html: New. + * sched_yield.html: New. + * sem_init.html: New. diff --git a/w32-pthreads/manual/PortabilityIssues.html b/w32-pthreads/manual/PortabilityIssues.html new file mode 100644 index 000000000..376a5f00e --- /dev/null +++ b/w32-pthreads/manual/PortabilityIssues.html @@ -0,0 +1,718 @@ + + + + + PORTABILITYISSUES manual page + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

Portability issues

+

Synopsis

+

Thread priority

+

Description

+

Thread priority

+

POSIX defines a single contiguous range +of numbers that determine a thread's priority. Win32 defines priority +classes - and priority levels relative to these classes. Classes are +simply priority base levels that the defined priority levels are +relative to such that, changing a process's priority class will +change the priority of all of it's threads, while the threads retain +the same relativity to each other.

+

A Win32 system defines a single +contiguous monotonic range of values that define system priority +levels, just like POSIX. However, Win32 restricts individual threads +to a subset of this range on a per-process basis.

+

The following table shows the base +priority levels for combinations of priority class and priority value +in Win32.

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+


+

+
+

Process Priority Class

+
+

Thread Priority Level

+
+

1

+
+

IDLE_PRIORITY_CLASS

+
+

THREAD_PRIORITY_IDLE

+
+

1

+
+

BELOW_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_IDLE

+
+

1

+
+

NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_IDLE

+
+

1

+
+

ABOVE_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_IDLE

+
+

1

+
+

HIGH_PRIORITY_CLASS

+
+

THREAD_PRIORITY_IDLE

+
+

2

+
+

IDLE_PRIORITY_CLASS

+
+

THREAD_PRIORITY_LOWEST

+
+

3

+
+

IDLE_PRIORITY_CLASS

+
+

THREAD_PRIORITY_BELOW_NORMAL

+
+

4

+
+

IDLE_PRIORITY_CLASS

+
+

THREAD_PRIORITY_NORMAL

+
+

4

+
+

BELOW_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_LOWEST

+
+

5

+
+

IDLE_PRIORITY_CLASS

+
+

THREAD_PRIORITY_ABOVE_NORMAL

+
+

5

+
+

BELOW_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_BELOW_NORMAL

+
+

5

+
+

Background NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_LOWEST

+
+

6

+
+

IDLE_PRIORITY_CLASS

+
+

THREAD_PRIORITY_HIGHEST

+
+

6

+
+

BELOW_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_NORMAL

+
+

6

+
+

Background NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_BELOW_NORMAL

+
+

7

+
+

BELOW_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_ABOVE_NORMAL

+
+

7

+
+

Background NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_NORMAL

+
+

7

+
+

Foreground NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_LOWEST

+
+

8

+
+

BELOW_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_HIGHEST

+
+

8

+
+

NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_ABOVE_NORMAL

+
+

8

+
+

Foreground NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_BELOW_NORMAL

+
+

8

+
+

ABOVE_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_LOWEST

+
+

9

+
+

NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_HIGHEST

+
+

9

+
+

Foreground NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_NORMAL

+
+

9

+
+

ABOVE_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_BELOW_NORMAL

+
+

10

+
+

Foreground NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_ABOVE_NORMAL

+
+

10

+
+

ABOVE_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_NORMAL

+
+

11

+
+

Foreground NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_HIGHEST

+
+

11

+
+

ABOVE_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_ABOVE_NORMAL

+
+

11

+
+

HIGH_PRIORITY_CLASS

+
+

THREAD_PRIORITY_LOWEST

+
+

12

+
+

ABOVE_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_HIGHEST

+
+

12

+
+

HIGH_PRIORITY_CLASS

+
+

THREAD_PRIORITY_BELOW_NORMAL

+
+

13

+
+

HIGH_PRIORITY_CLASS

+
+

THREAD_PRIORITY_NORMAL

+
+

14

+
+

HIGH_PRIORITY_CLASS

+
+

THREAD_PRIORITY_ABOVE_NORMAL

+
+

15

+
+

HIGH_PRIORITY_CLASS

+
+

THREAD_PRIORITY_HIGHEST

+
+

15

+
+

HIGH_PRIORITY_CLASS

+
+

THREAD_PRIORITY_TIME_CRITICAL

+
+

15

+
+

IDLE_PRIORITY_CLASS

+
+

THREAD_PRIORITY_TIME_CRITICAL

+
+

15

+
+

BELOW_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_TIME_CRITICAL

+
+

15

+
+

NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_TIME_CRITICAL

+
+

15

+
+

ABOVE_NORMAL_PRIORITY_CLASS

+
+

THREAD_PRIORITY_TIME_CRITICAL

+
+

16

+
+

REALTIME_PRIORITY_CLASS

+
+

THREAD_PRIORITY_IDLE

+
+

17

+
+

REALTIME_PRIORITY_CLASS

+
+

-7

+
+

18

+
+

REALTIME_PRIORITY_CLASS

+
+

-6

+
+

19

+
+

REALTIME_PRIORITY_CLASS

+
+

-5

+
+

20

+
+

REALTIME_PRIORITY_CLASS

+
+

-4

+
+

21

+
+

REALTIME_PRIORITY_CLASS

+
+

-3

+
+

22

+
+

REALTIME_PRIORITY_CLASS

+
+

THREAD_PRIORITY_LOWEST

+
+

23

+
+

REALTIME_PRIORITY_CLASS

+
+

THREAD_PRIORITY_BELOW_NORMAL

+
+

24

+
+

REALTIME_PRIORITY_CLASS

+
+

THREAD_PRIORITY_NORMAL

+
+

25

+
+

REALTIME_PRIORITY_CLASS

+
+

THREAD_PRIORITY_ABOVE_NORMAL

+
+

26

+
+

REALTIME_PRIORITY_CLASS

+
+

THREAD_PRIORITY_HIGHEST

+
+

27

+
+

REALTIME_PRIORITY_CLASS

+
+

3

+
+

28

+
+

REALTIME_PRIORITY_CLASS

+
+

4

+
+

29

+
+

REALTIME_PRIORITY_CLASS

+
+

5

+
+

30

+
+

REALTIME_PRIORITY_CLASS

+
+

6

+
+

31

+
+

REALTIME_PRIORITY_CLASS

+
+

THREAD_PRIORITY_TIME_CRITICAL

+
+
+
+

Windows NT: Values -7, -6, -5, -4, -3, 3, +4, 5, and 6 are not supported.

+

As you can see, the real priority levels +available to any individual Win32 thread are non-contiguous.

+

An application using Pthreads-w32 should +not make assumptions about the numbers used to represent thread +priority levels, except that they are monotonic between the values +returned by sched_get_priority_min() and sched_get_priority_max(). +E.g. Windows 95, 98, NT, 2000, XP make available a non-contiguous +range of numbers between -15 and 15, while at least one version of +WinCE (3.0) defines the minimum priority (THREAD_PRIORITY_LOWEST) as +5, and the maximum priority (THREAD_PRIORITY_HIGHEST) as 1.

+

Internally, pthreads-win32 maps any +priority levels between THREAD_PRIORITY_IDLE and +THREAD_PRIORITY_LOWEST to THREAD_PRIORITY_LOWEST, or between +THREAD_PRIORITY_TIME_CRITICAL and THREAD_PRIORITY_HIGHEST to +THREAD_PRIORITY_HIGHEST. Currently, this also applies to +REALTIME_PRIORITY_CLASS even if levels -7, -6, -5, -4, -3, 3, 4, 5, +and 6 are supported.

+

If it wishes, a Win32 application using +pthreads-w32 can use the Win32 defined priority macros +THREAD_PRIORITY_IDLE through THREAD_PRIORITY_TIME_CRITICAL.

+

Author

+

Ross Johnson for use with Pthreads-w32.

+

See also

+



+

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/index.html b/w32-pthreads/manual/index.html new file mode 100644 index 000000000..f7b5bc919 --- /dev/null +++ b/w32-pthreads/manual/index.html @@ -0,0 +1,158 @@ + + + + + + + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - +Pthreads-w32

+

Table of Contents

+

POSIX +threads API reference
Miscellaneous +POSIX thread safe routines provided by Pthreads-w32
Non-portable +Pthreads-w32 routines
Other

+

POSIX threads API +reference

+

pthread_attr_destroy

+

pthread_attr_getdetachstate

+

pthread_attr_getinheritsched

+

pthread_attr_getschedparam

+

pthread_attr_getschedpolicy

+

pthread_attr_getscope

+

pthread_attr_getstackaddr

+

pthread_attr_getstacksize

+

pthread_attr_init

+

pthread_attr_setdetachstate

+

pthread_attr_setinheritsched

+

pthread_attr_setschedparam

+

pthread_attr_setschedpolicy

+

pthread_attr_setscope

+

pthread_attr_setstackaddr

+

pthread_attr_setstacksize

+

pthread_barrierattr_destroy

+

pthread_barrierattr_getpshared

+

pthread_barrierattr_init

+

pthread_barrierattr_setpshared

+

pthread_barrier_destroy

+

pthread_barrier_init

+

pthread_barrier_wait

+

pthread_cancel

+

pthread_cleanup_pop

+

pthread_cleanup_push

+

pthread_condattr_destroy

+

pthread_condattr_getpshared

+

pthread_condattr_init

+

pthread_condattr_setpshared

+

pthread_cond_broadcast

+

pthread_cond_destroy

+

pthread_cond_init

+

pthread_cond_signal

+

pthread_cond_timedwait

+

pthread_cond_wait

+

pthread_create

+

pthread_detach

+

pthread_equal

+

pthread_exit

+

pthread_getconcurrency

+

pthread_getschedparam

+

pthread_getunique_np

+

pthread_getspecific

+

pthread_join

+

pthread_key_create

+

pthread_key_delete

+

pthread_kill

+

pthread_mutexattr_destroy

+

pthread_mutexattr_getkind_np

+

pthread_mutexattr_getpshared

+

pthread_mutexattr_getrobust

+

pthread_mutexattr_gettype

+

pthread_mutexattr_init

+

pthread_mutexattr_setkind_np

+

pthread_mutexattr_setpshared

+

pthread_mutexattr_setrobust

+

pthread_mutexattr_settype

+

pthread_mutex_consistent

+

pthread_mutex_destroy

+

pthread_mutex_init

+

pthread_mutex_lock

+

pthread_mutex_timedlock

+

pthread_mutex_trylock

+

pthread_mutex_unlock

+

pthread_once

+

pthread_rwlockattr_destroy

+

pthread_rwlockattr_getpshared

+

pthread_rwlockattr_init

+

pthread_rwlockattr_setpshared

+

pthread_rwlock_destroy

+

pthread_rwlock_init

+

pthread_rwlock_rdlock

+

pthread_rwlock_timedrdlock

+

pthread_rwlock_timedwrlock

+

pthread_rwlock_tryrdlock

+

pthread_rwlock_trywrlock

+

pthread_rwlock_unlock

+

pthread_rwlock_wrlock

+

pthread_self

+

pthread_setcancelstate

+

pthread_setcanceltype

+

pthread_setconcurrency

+

pthread_setschedparam

+

pthread_setspecific

+

pthread_sigmask

+

pthread_spin_destroy

+

pthread_spin_init

+

pthread_spin_lock

+

pthread_spin_trylock

+

pthread_spin_unlock

+

pthread_testcancel

+

sched_get_priority_max

+

sched_get_priority_min

+

sched_getscheduler

+

sched_setscheduler

+

sched_yield

+

sem_close

+

sem_destroy

+

sem_getvalue

+

sem_init

+

sem_open

+

sem_post

+

sem_post_multiple

+

sem_timedwait

+

sem_trywait

+

sem_unlink

+

sem_wait

+

sigwait

+

Non-portable +Pthreads-w32 routines

+

pthreadCancelableTimedWait

+

pthreadCancelableWait

+

pthread_delay_np

+

pthread_getw32threadhandle_np

+

pthread_num_processors_np

+

pthread_win32_test_features_np

+

pthread_timechange_handler_np

+

pthread_win32_process_attach_np

+

pthread_win32_process_detach_np

+

pthread_win32_thread_attach_np

+

pthread_win32_thread_detach_np

+

Other

+

Portability +issues

+ + \ No newline at end of file diff --git a/w32-pthreads/manual/pthreadCancelableWait.html b/w32-pthreads/manual/pthreadCancelableWait.html new file mode 100644 index 000000000..9d7c1a458 --- /dev/null +++ b/w32-pthreads/manual/pthreadCancelableWait.html @@ -0,0 +1,86 @@ + + + + + PTHREADCANCELLABLEWAIT manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthreadCancelableTimedWait, +pthreadCancelableWait ā€“ provide cancellation hooks for user Win32 +routines

+

Synopsis

+

#include <pthread.h> +

+

int pthreadCancelableTimedWait (HANDLE waitHandle, +DWORD timeout);

+

int pthreadCancelableWait (HANDLE waitHandle);

+

Description

+

These two functions provide hooks into the pthread_cancel() +mechanism that will allow you to wait on a Windows handle and make it +a cancellation point. Both functions block until either the given +Win32 HANDLE is signalled, or pthread_cancel() +has been called. They are implemented using WaitForMultipleObjects +on waitHandle and the manually reset Win32 event handle that +is the target of pthread_cancel(). +These routines may be called from Win32 native threads but +pthread_cancel() will +require that thread's POSIX thread ID that the thread must retrieve +using pthread_self().

+

pthreadCancelableTimedWait is the timed version that will +return with the code ETIMEDOUT if the interval timeout +milliseconds elapses before waitHandle is signalled.

+

Cancellation

+

These routines allow routines that block on Win32 HANDLEs to be +cancellable via pthread_cancel().

+

Return Value

+



+

+

Errors

+

The pthreadCancelableTimedWait function returns the +following error code on error: +

+
+
+
ETIMEDOUT +
+
+

+The interval timeout milliseconds elapsed before waitHandle +was signalled.

+

Author

+

Ross Johnson for use with Pthreads-w32.

+

See also

+

pthread_cancel(), +pthread_self()

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_attr_init.html b/w32-pthreads/manual/pthread_attr_init.html new file mode 100644 index 000000000..fa5ab5811 --- /dev/null +++ b/w32-pthreads/manual/pthread_attr_init.html @@ -0,0 +1,280 @@ + + + + + PTHREAD_ATTR_INIT(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_attr_init, pthread_attr_destroy, +pthread_attr_setdetachstate, pthread_attr_getdetachstate, +pthread_attr_setschedparam, pthread_attr_getschedparam, +pthread_attr_setschedpolicy, pthread_attr_getschedpolicy, +pthread_attr_setinheritsched, pthread_attr_getinheritsched, +pthread_attr_setscope, pthread_attr_getscope - thread creation +attributes +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_attr_init(pthread_attr_t *attr); +

+

int pthread_attr_destroy(pthread_attr_t *attr); +

+

int pthread_attr_setdetachstate(pthread_attr_t *attr, +int detachstate); +

+

int pthread_attr_getdetachstate(const pthread_attr_t *attr, +int *detachstate); +

+

int pthread_attr_setschedpolicy(pthread_attr_t *attr, +int policy); +

+

int pthread_attr_getschedpolicy(const pthread_attr_t *attr, +int *policy); +

+

int pthread_attr_setschedparam(pthread_attr_t *attr, +const struct sched_param *param); +

+

int pthread_attr_getschedparam(const pthread_attr_t *attr, +struct sched_param *param); +

+

int pthread_attr_setinheritsched(pthread_attr_t *attr, +int inherit); +

+

int pthread_attr_getinheritsched(const pthread_attr_t *attr, +int *inherit); +

+

int pthread_attr_setscope(pthread_attr_t *attr, +int scope); +

+

int pthread_attr_getscope(const pthread_attr_t *attr, +int *scope); +

+

Description

+

Setting attributes for threads is achieved by filling a thread +attribute object attr of type pthread_attr_t, then +passing it as second argument to pthread_create(3) +. Passing NULL is equivalent to passing a thread attribute +object with all attributes set to their default values. +

+

pthread_attr_init initializes the thread attribute object +attr and fills it with default values for the attributes. (The +default values are listed below for each attribute.) +

+

Each attribute attrname (see below for a list of all +attributes) can be individually set using the function +pthread_attr_setattrname and retrieved using the +function pthread_attr_getattrname. +

+

pthread_attr_destroy destroys a thread attribute object, +which must not then be reused until it is reinitialized. +

+

Attribute objects are consulted only when creating a new thread. +The same attribute object can be used for creating several threads. +Modifying an attribute object after a call to pthread_create +does not change the attributes of the thread previously created. +

+

The following thread attributes are supported: +

+

detachstate

+

Control whether the thread is created in the joinable state (value +PTHREAD_CREATE_JOINABLE) or in the detached state ( +PTHREAD_CREATE_DETACHED). +

+

Default value: PTHREAD_CREATE_JOINABLE. +

+

In the joinable state, another thread can synchronize on the +thread termination and recover its termination code using +pthread_join(3) . When a +joinable thread terminates, some of the thread resources are kept +allocated, and released only when another thread performs +pthread_join(3) on that +thread. +

+

In the detached state, the thread's resources are released +immediately when it terminates. pthread_join(3) +cannot be used to synchronize on the thread termination. +

+

A thread created in the joinable state can later be put in the +detached thread using pthread_detach(3) +. +

+

schedpolicy

+

Select the scheduling policy for the thread: one of SCHED_OTHER +(regular, non-real-time scheduling), SCHED_RR (real-time, +round-robin) or SCHED_FIFO (real-time, first-in first-out). +

+

Pthreads-w32 only supports SCHED_OTHER - attempting +to set one of the other policies will return an error ENOTSUP.

+

Default value: SCHED_OTHER. +

+

Pthreads-w32 only supports SCHED_OTHER - attempting +to set one of the other policies will return an error ENOTSUP.

+

The scheduling policy of a thread can be changed after creation +with pthread_setschedparam(3) +. +

+

schedparam

+

Contain the scheduling parameters (essentially, the scheduling +priority) for the thread.

+

Pthreads-w32 supports the priority levels defined by the +Windows system it is running on. Under Windows, thread priorities are +relative to the process priority class, which must be set via the +Windows W32 API.

+

Default value: priority is 0 (Win32 level THREAD_PRIORITY_NORMAL). +

+

The scheduling priority of a thread can be changed after creation +with pthread_setschedparam(3) +. +

+

inheritsched

+

Indicate whether the scheduling policy and scheduling parameters +for the newly created thread are determined by the values of the +schedpolicy and schedparam attributes (value +PTHREAD_EXPLICIT_SCHED) or are inherited from the parent +thread (value PTHREAD_INHERIT_SCHED). +

+

Default value: PTHREAD_EXPLICIT_SCHED. +

+

scope

+

Define the scheduling contention scope for the created thread. The +only value supported in the Pthreads-w32 implementation is +PTHREAD_SCOPE_SYSTEM, meaning that the threads contend for CPU +time with all processes running on the machine. The other value +specified by the standard, PTHREAD_SCOPE_PROCESS, means that +scheduling contention occurs only between the threads of the running +process.

+

Pthreads-w32 only supports PTHREAD_SCOPE_SYSTEM.

+

Default value: PTHREAD_SCOPE_SYSTEM. +

+

Return Value

+

All functions return 0 on success and a non-zero error code on +error. On success, the pthread_attr_getattrname +functions also store the current value of the attribute attrname +in the location pointed to by their second argument. +

+

Errors

+

The pthread_attr_setdetachstate function returns the +following error codes on error: +

+
+
+
EINVAL +
+ the specified detachstate is not one of + PTHREAD_CREATE_JOINABLE or PTHREAD_CREATE_DETACHED. +
+
+

+The pthread_attr_setschedparam function returns the following +error codes on error: +

+
+
+
EINVAL +
+ the priority specified in param is outside the range of + allowed priorities for the scheduling policy currently in attr + (1 to 99 for SCHED_FIFO and SCHED_RR; 0 for + SCHED_OTHER). +
+
+

+The pthread_attr_setschedpolicy function returns the following +error codes on error: +

+
+
+
EINVAL +
+ the specified policy is not one of SCHED_OTHER, + SCHED_FIFO, or SCHED_RR. +
+ ENOTSUP +
+ policy is not SCHED_OTHER, the only value supported + by Pthreads-w32.
+
+

+The pthread_attr_setinheritsched function returns the +following error codes on error: +

+
+
+
EINVAL +
+ the specified inherit is not one of PTHREAD_INHERIT_SCHED + or PTHREAD_EXPLICIT_SCHED. +
+
+

+The pthread_attr_setscope function returns the following error +codes on error: +

+
+
+
EINVAL +
+ the specified scope is not one of PTHREAD_SCOPE_SYSTEM + or PTHREAD_SCOPE_PROCESS. +
+ ENOTSUP +
+ the specified scope is PTHREAD_SCOPE_PROCESS (not + supported by Pthreads-w32). +
+
+

+Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

pthread_create(3) , +pthread_join(3) , +pthread_detach(3) , +pthread_setschedparam(3) +. +

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_attr_setstackaddr.html b/w32-pthreads/manual/pthread_attr_setstackaddr.html new file mode 100644 index 000000000..868832c0a --- /dev/null +++ b/w32-pthreads/manual/pthread_attr_setstackaddr.html @@ -0,0 +1,158 @@ + + + + + "PTHREAD_ATTR_GETSTACKADDR"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_attr_getstackaddr, pthread_attr_setstackaddr - get and set +the stackaddr attribute +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_attr_getstackaddr(const pthread_attr_t *restrict +attr, void **restrict stackaddr);
int +pthread_attr_setstackaddr(pthread_attr_t *
attr, void +*stackaddr); +

+

Description

+

The pthread_attr_getstackaddr and pthread_attr_setstackaddr +functions, respectively, shall get and set the thread creation +stackaddr attribute in the attr object. +

+

The stackaddr attribute specifies the location of storage +to be used for the created threadā€™s stack. The size of the storage +shall be at least {PTHREAD_STACK_MIN}. +

+

Pthreads-w32 defines _POSIX_THREAD_ATTR_STACKADDR in +pthread.h as -1 to indicate that these routines are implemented but +cannot used to set or get the stack address. These routines always +return the error ENOSYS when called.

+

Return Value

+

Upon successful completion, pthread_attr_getstackaddr and +pthread_attr_setstackaddr shall return a value of 0; +otherwise, an error number shall be returned to indicate the error. +

+

The pthread_attr_getstackaddr function stores the stackaddr +attribute value in stackaddr if successful. +

+

Errors

+

The pthread_attr_setstackaddr function always returns the +following error code: +

+
+
+
ENOSYS
+ The function is not supported. +
+
+

+The pthread_attr_getstackaddr function always returns the +following error code: +

+
+
+
ENOSYS
+ The function is not supported. +
+
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

The specification of the stackaddr attribute presents +several ambiguities that make portable use of these interfaces +impossible. The description of the single address parameter as a +"stack" does not specify a particular relationship between +the address and the "stack" implied by that address. For +example, the address may be taken as the low memory address of a +buffer intended for use as a stack, or it may be taken as the address +to be used as the initial stack pointer register value for the new +thread. These two are not the same except for a machine on which the +stack grows "up" from low memory to high, and on which a +"push" operation first stores the value in memory and then +increments the stack pointer register. Further, on a machine where +the stack grows "down" from high memory to low, +interpretation of the address as the "low memory" address +requires a determination of the intended size of the stack. +IEEE Std 1003.1-2001 has introduced the new interfaces +pthread_attr_setstack(3) +and pthread_attr_getstack(3) +to resolve these ambiguities. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_attr_destroy(3) +, pthread_attr_getdetachstate(3) +, pthread_attr_getstack(3) +, pthread_attr_getstacksize(3) +, pthread_attr_setstack(3) +, pthread_create(3) , the +Base Definitions volume of IEEE Std 1003.1-2001, +<limits.h>, <pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_attr_setstacksize.html b/w32-pthreads/manual/pthread_attr_setstacksize.html new file mode 100644 index 000000000..ae9d031f4 --- /dev/null +++ b/w32-pthreads/manual/pthread_attr_setstacksize.html @@ -0,0 +1,127 @@ + + + + + "PTHREAD_ATTR_GETSTACKSIZE"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_attr_getstacksize, pthread_attr_setstacksize - get and set +the stacksize attribute +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_attr_getstacksize(const pthread_attr_t *restrict +attr, size_t *restrict stacksize);
int +pthread_attr_setstacksize(pthread_attr_t *
attr, size_t +stacksize); +

+

Description

+

The pthread_attr_getstacksize and pthread_attr_setstacksize +functions, respectively, shall get and set the thread creation +stacksize attribute in the attr object. +

+

The stacksize attribute shall define the minimum stack size +(in bytes) allocated for the created threads stack. +

+

Pthreads-w32 defines _POSIX_THREAD_ATTR_STACKSIZE in +pthread.h to indicate that these routines are implemented and may be +used to set or get the stack size.

+

Default value: 0 (in Pthreads-w32 a value of 0 means the stack +will grow as required)

+

Return Value

+

Upon successful completion, pthread_attr_getstacksize and +pthread_attr_setstacksize shall return a value of 0; +otherwise, an error number shall be returned to indicate the error. +

+

The pthread_attr_getstacksize function stores the stacksize +attribute value in stacksize if successful. +

+

Errors

+

The pthread_attr_setstacksize function shall fail if: +

+
+
EINVAL +
+ The value of stacksize is less than {PTHREAD_STACK_MIN} or + exceeds a system-imposed limit. +
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

None. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_attr_destroy(3) +, pthread_attr_getstackaddr(3) +, pthread_attr_getdetachstate(3) +, pthread_create(3) , +the Base Definitions volume of IEEE Std 1003.1-2001, +<limits.h>, <pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_barrier_init.html b/w32-pthreads/manual/pthread_barrier_init.html new file mode 100644 index 000000000..f58135803 --- /dev/null +++ b/w32-pthreads/manual/pthread_barrier_init.html @@ -0,0 +1,197 @@ + + + + + "PTHREAD_BARRIER_DESTROY"(P) manual page + + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_barrier_destroy, pthread_barrier_init - destroy and +initialize a barrier object (ADVANCED REALTIME THREADS) +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_barrier_destroy(pthread_barrier_t *barrier); +
int pthread_barrier_init(pthread_barrier_t *restrict
barrier, +const pthread_barrierattr_t *restrict attr, unsigned +count); +

+

Description

+

The pthread_barrier_destroy function shall destroy the +barrier referenced by barrier and release any resources used +by the barrier. The effect of subsequent use of the barrier is +undefined until the barrier is reinitialized by another call to +pthread_barrier_init . An implementation may use this function +to set barrier to an invalid value. An error code is returned if pthread_barrier_destroy is called when any thread is +blocked on the barrier, or if this function is called with an +uninitialized barrier. +

+

The pthread_barrier_init function shall allocate any +resources required to use the barrier referenced by barrier +and shall initialize the barrier with attributes referenced by attr. +If attr is NULL, the default barrier attributes shall be used; +the effect is the same as passing the address of a default barrier +attributes object. The results are undefined if pthread_barrier_init +is called when any thread is blocked on the barrier (that is, has not +returned from the pthread_barrier_wait(3) +call). The results are undefined if a barrier is used without first +being initialized. The results are undefined if pthread_barrier_init +is called specifying an already initialized barrier. +

+

The count argument specifies the number of threads that +must call pthread_barrier_wait(3) +before any of them successfully return from the call. The value +specified by count must be greater than zero. +

+

If the pthread_barrier_init function fails, the barrier +shall not be initialized and the contents of barrier are +undefined. +

+

Only the object referenced by barrier may be used for +performing synchronization. The result of referring to copies of that +object in calls to pthread_barrier_destroy or +pthread_barrier_wait(3) +is undefined.

+

Return Value

+

Upon successful completion, these functions shall return zero; +otherwise, an error number shall be returned to indicate the error. +

+

Errors

+

The pthread_barrier_destroy function may fail if: +

+
+
EBUSY +
+ The implementation has detected an attempt to destroy a barrier + while it is in use (for example, while being used in a + pthread_barrier_wait(3) + call) by another thread. +
+ EINVAL +
+ The value specified by barrier is invalid. +
+

+The pthread_barrier_init function shall fail if: +

+
+
EAGAIN +
+ The system lacks the necessary resources to initialize another + barrier. +
+ EINVAL +
+ The value specified by count is equal to zero. +
+ ENOMEM +
+ Insufficient memory exists to initialize the barrier. +
+

+The pthread_barrier_init function may fail if: +

+
+
EBUSY +
+ The implementation has detected an attempt to reinitialize a barrier + while it is in use (for example, while being used in a + pthread_barrier_wait(3) + call) by another thread. +
+ EINVAL +
+ The value specified by attr is invalid. +
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

The pthread_barrier_destroy and pthread_barrier_init +functions are part of the Barriers option and need not be provided on +all implementations. +

+

Pthreads-w32 defines _POSIX_BARRIERS to indicate +that these routines are implemented and may be used.

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

Known Bugs

+
+
In + pthreads-win32, + the behaviour of threads which enter pthread_barrier_wait(3) + while the barrier is being destroyed is undefined. +
+

+See Also

+

pthread_barrier_wait(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + \ No newline at end of file diff --git a/w32-pthreads/manual/pthread_barrier_wait.html b/w32-pthreads/manual/pthread_barrier_wait.html new file mode 100644 index 000000000..f407aa5a8 --- /dev/null +++ b/w32-pthreads/manual/pthread_barrier_wait.html @@ -0,0 +1,161 @@ + + + + + "PTHREAD_BARRIER_WAIT"(P) manual page + + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_barrier_wait - synchronize at a barrier (ADVANCED +REALTIME THREADS) +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_barrier_wait(pthread_barrier_t *barrier); + +

+

Description

+

The pthread_barrier_wait function shall synchronize +participating threads at the barrier referenced by barrier. +The calling thread shall block until the required number of threads +have called pthread_barrier_wait specifying the barrier. +

+

When the required number of threads have called +pthread_barrier_wait specifying the barrier, the constant +PTHREAD_BARRIER_SERIAL_THREAD shall be returned to one +unspecified thread and zero shall be returned to each of the +remaining threads. At this point, the barrier shall be reset to the +state it had as a result of the most recent pthread_barrier_init(3) +function that referenced it. +

+

The constant PTHREAD_BARRIER_SERIAL_THREAD is defined in +<pthread.h> and its value shall be distinct from any +other value returned by pthread_barrier_wait . +

+

The results are undefined if this function is called with an +uninitialized barrier. +

+

If a signal is delivered to a thread blocked on a barrier, upon +return from the signal handler the thread shall resume waiting at the +barrier if the barrier wait has not completed (that is, if the +required number of threads have not arrived at the barrier during the +execution of the signal handler); otherwise, the thread shall +continue as normal from the completed barrier wait. Until the thread +in the signal handler returns from it, it is unspecified whether +other threads may proceed past the barrier once they have all reached +it. +

+

A thread that has blocked on a barrier shall not prevent any +unblocked thread that is eligible to use the same processing +resources from eventually making forward progress in its execution. +Eligibility for processing resources shall be determined by the +scheduling policy. +

+

Return Value

+

Upon successful completion, the pthread_barrier_wait +function shall return PTHREAD_BARRIER_SERIAL_THREAD for a +single (arbitrary) thread synchronized at the barrier and zero for +each of the other threads. Otherwise, an error number shall be +returned to indicate the error. +

+

Errors

+

The pthread_barrier_wait function may fail if: +

+
+
EINVAL +
+ The value specified by barrier does not refer to an + initialized barrier object. +
+

+This function shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

Applications using this function may be subject to priority +inversion, as discussed in the Base Definitions volume of +IEEE Std 1003.1-2001, Section 3.285, Priority Inversion. +

+

The pthread_barrier_wait function is part of the Barriers +option and need not be provided on all implementations. +

+

Pthreads-w32 defines _POSIX_BARRIERS to indicate +that this routine is implemented and may be used.

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

Known Bugs

+
+ None.
+

+See Also

+

pthread_barrier_destroy(3), +pthread_barrier_init(3), +the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + \ No newline at end of file diff --git a/w32-pthreads/manual/pthread_barrierattr_init.html b/w32-pthreads/manual/pthread_barrierattr_init.html new file mode 100644 index 000000000..a7c802735 --- /dev/null +++ b/w32-pthreads/manual/pthread_barrierattr_init.html @@ -0,0 +1,142 @@ + + + + + "PTHREAD_BARRIERATTR_DESTROY"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_barrierattr_destroy, pthread_barrierattr_init - destroy +and initialize the barrier attributes object (ADVANCED REALTIME +THREADS) +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_barrierattr_destroy(pthread_barrierattr_t *attr); +
int pthread_barrierattr_init(pthread_barrierattr_t *
attr); + +

+

Description

+

The pthread_barrierattr_destroy function shall destroy a +barrier attributes object. A destroyed attr attributes object +can be reinitialized using pthread_barrierattr_init ; the +results of otherwise referencing the object after it has been +destroyed are undefined. An implementation may cause +pthread_barrierattr_destroy to set the object referenced by +attr to an invalid value. +

+

The pthread_barrierattr_init function shall initialize a +barrier attributes object attr with the default value for all +of the attributes defined by the implementation. +

+

Results are undefined if pthread_barrierattr_init is called +specifying an already initialized attr attributes object. +

+

After a barrier attributes object has been used to initialize one +or more barriers, any function affecting the attributes object +(including destruction) shall not affect any previously initialized +barrier. +

+

Return Value

+

If successful, the pthread_barrierattr_destroy and +pthread_barrierattr_init functions shall return zero; +otherwise, an error number shall be returned to indicate the error. +

+

Errors

+

The pthread_barrierattr_destroy function may fail if: +

+
+
EINVAL +
+ The value specified by attr is invalid. +
+

+The pthread_barrierattr_init function shall fail if: +

+
+
ENOMEM +
+ Insufficient memory exists to initialize the barrier attributes + object. +
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

The pthread_barrierattr_destroy and +pthread_barrierattr_init functions are part of the Barriers +option and need not be provided on all implementations. +

+

Pthreads-w32 defines _POSIX_BARRIERS to indicate +that these routines are implemented and may be used.

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_barrierattr_getpshared(3) +, pthread_barrierattr_setpshared(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h>. +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_barrierattr_setpshared.html b/w32-pthreads/manual/pthread_barrierattr_setpshared.html new file mode 100644 index 000000000..2c62d3dce --- /dev/null +++ b/w32-pthreads/manual/pthread_barrierattr_setpshared.html @@ -0,0 +1,159 @@ + + + + + "PTHREAD_BARRIERATTR_GETPSHARED"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_barrierattr_getpshared, pthread_barrierattr_setpshared - +get and set the process-shared attribute of the barrier attributes +object (ADVANCED REALTIME THREADS) +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_barrierattr_getpshared(const pthread_barrierattr_t +* restrict attr, int *restrict pshared); +
int pthread_barrierattr_setpshared(pthread_barrierattr_t *
attr, +int pshared); +

+

Description

+

The pthread_barrierattr_getpshared function shall obtain +the value of the process-shared attribute from the attributes +object referenced by attr. The pthread_barrierattr_setpshared +function shall set the process-shared attribute in an +initialized attributes object referenced by attr. +

+

The process-shared attribute is set to +PTHREAD_PROCESS_SHARED to permit a barrier to be operated upon by any +thread that has access to the memory where the barrier is allocated. +If the process-shared attribute is PTHREAD_PROCESS_PRIVATE, +the barrier shall only be operated upon by threads created within the +same process as the thread that initialized the barrier; if threads +of different processes attempt to operate on such a barrier, the +behavior is undefined. The default value of the attribute shall be +PTHREAD_PROCESS_PRIVATE. Both constants PTHREAD_PROCESS_SHARED and +PTHREAD_PROCESS_PRIVATE are defined in <pthread.h>. +

+

Pthreads-w32 defines _POSIX_THREAD_PROCESS_SHARED in +pthread.h as -1 to indicate that these routines are implemented but +that the process shared attribute is not supported.

+

Additional attributes, their default values, and the names of the +associated functions to get and set those attribute values are +implementation-defined. +

+

Return Value

+

If successful, the pthread_barrierattr_getpshared function +shall return zero and store the value of the process-shared +attribute of attr into the object referenced by the pshared +parameter. Otherwise, an error number shall be returned to indicate +the error. +

+

If successful, the pthread_barrierattr_setpshared function +shall return zero; otherwise, an error number shall be returned to +indicate the error. +

+

Errors

+

These functions may fail if: +

+
+
EINVAL +
+ The value specified by attr is invalid. +
+ The pthread_barrierattr_setpshared function may fail if: +
+ EINVAL +
+ The new value specified for the process-shared attribute is + not one of the legal values PTHREAD_PROCESS_SHARED or + PTHREAD_PROCESS_PRIVATE. +
+ ENOSYS +
+ The value specified by attr was PTHREAD_PROCESS_SHARED + (Pthreads-w32).
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

The pthread_barrierattr_getpshared and +pthread_barrierattr_setpshared functions are part of the +Barriers option and need not be provided on all implementations. +

+

Pthreads-w32 defines _POSIX_BARRIERS and +_POSIX_THREAD_PROCESS_SHARED in pthread.h as -1 to indicate +that these routines are implemented and may be used, but do not +support the process shared option.

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_barrier_destroy(3) +, pthread_barrierattr_destroy(3) +, pthread_barrierattr_init(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_cancel.html b/w32-pthreads/manual/pthread_cancel.html new file mode 100644 index 000000000..d9acd7727 --- /dev/null +++ b/w32-pthreads/manual/pthread_cancel.html @@ -0,0 +1,205 @@ + + + + + PTHREAD_CANCEL(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_cancel, pthread_setcancelstate, pthread_setcanceltype, +pthread_testcancel - thread cancellation +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_cancel(pthread_t thread); +

+

int pthread_setcancelstate(int state, int +*oldstate); +

+

int pthread_setcanceltype(int type, int +*oldtype); +

+

void pthread_testcancel(void); +

+

Description

+

Cancellation is the mechanism by which a thread can terminate the +execution of another thread. More precisely, a thread can send a +cancellation request to another thread. Depending on its settings, +the target thread can then either ignore the request, honor it +immediately, or defer it until it reaches a cancellation point. +

+

When a thread eventually honors a cancellation request, it +performs as if pthread_exit(PTHREAD_CANCELED) has been called +at that point: all cleanup handlers are executed in reverse order, +destructor functions for thread-specific data are called, and finally +the thread stops executing with the return value PTHREAD_CANCELED. +See pthread_exit(3) for more +information. +

+

pthread_cancel sends a cancellation request to the thread +denoted by the thread argument. +

+

pthread_setcancelstate changes the cancellation state for +the calling thread -- that is, whether cancellation requests are +ignored or not. The state argument is the new cancellation +state: either PTHREAD_CANCEL_ENABLE to enable cancellation, or +PTHREAD_CANCEL_DISABLE to disable cancellation (cancellation +requests are ignored). If oldstate is not NULL, the +previous cancellation state is stored in the location pointed to by +oldstate, and can thus be restored later by another call to +pthread_setcancelstate. +

+

pthread_setcanceltype changes the type of responses to +cancellation requests for the calling thread: asynchronous +(immediate) or deferred. The type argument is the new +cancellation type: either PTHREAD_CANCEL_ASYNCHRONOUS to +cancel the calling thread as soon as the cancellation request is +received, or PTHREAD_CANCEL_DEFERRED to keep the cancellation +request pending until the next cancellation point. If oldtype +is not NULL, the previous cancellation state is stored in the +location pointed to by oldtype, and can thus be restored later +by another call to pthread_setcanceltype. +

+

Pthreads-w32 provides two levels of support for +PTHREAD_CANCEL_ASYNCHRONOUS: full and partial. Full support +requires an additional DLL and driver be installed on the Windows +system (see the See Also section below) that allows blocked threads +to be cancelled immediately. Partial support means that the target +thread will not cancel until it resumes execution naturally. Partial +support is provided if either the DLL or the driver are not +automatically detected by the pthreads-w32 library at run-time.

+

Threads are always created by pthread_create(3) +with cancellation enabled and deferred. That is, the initial +cancellation state is PTHREAD_CANCEL_ENABLE and the initial +type is PTHREAD_CANCEL_DEFERRED. +

+

Cancellation points are those points in the program execution +where a test for pending cancellation requests is performed and +cancellation is executed if positive. The following POSIX threads +functions are cancellation points: +

+

pthread_join(3) +
pthread_cond_wait(3) +
pthread_cond_timedwait(3) +
pthread_testcancel(3)
sem_wait(3) +
sem_timedwait(3)
sigwait(3)

+

Pthreads-w32 provides two functions to enable additional +cancellation points to be created in user functions that block on +Win32 HANDLEs:

+

pthreadCancelableWait() +
pthreadCancelableTimedWait()

+

All other POSIX threads functions are guaranteed not to be +cancellation points. That is, they never perform cancellation in +deferred cancellation mode. +

+

pthread_testcancel does nothing except testing for pending +cancellation and executing it. Its purpose is to introduce explicit +checks for cancellation in long sequences of code that do not call +cancellation point functions otherwise. +

+

Return Value

+

pthread_cancel, pthread_setcancelstate and +pthread_setcanceltype return 0 on success and a non-zero error +code on error. +

+

Errors

+

pthread_cancel returns the following error code on error: +

+
+
+
ESRCH +
+ no thread could be found corresponding to that specified by the + thread ID. +
+
+

+pthread_setcancelstate returns the following error code on +error: +

+
+
+
EINVAL +
+ the state argument is not +
+
+
+PTHREAD_CANCEL_ENABLE nor PTHREAD_CANCEL_DISABLE +
+

pthread_setcanceltype returns the following error code on +error: +

+
+
+
EINVAL +
+ the type argument is not +
+
+
+PTHREAD_CANCEL_DEFERRED nor PTHREAD_CANCEL_ASYNCHRONOUS +
+

Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

pthread_exit(3) , +pthread_cleanup_push(3) +, pthread_cleanup_pop(3) +, Pthreads-w32 package README file 'Prerequisites' section. +

+

Bugs

+

POSIX specifies that a number of system calls (basically, all +system calls that may block, such as read(2) +, write(2) , wait(2) +, etc.) and library functions that may call these system calls (e.g. +fprintf(3) ) are cancellation +points. Pthreads-win32 is not integrated enough with the C +library to implement this, and thus none of the C library functions +is a cancellation point. +

+

A workaround for these calls is to temporarily switch to +asynchronous cancellation (assuming full asynchronous cancellation +support is installed). So, checking for cancellation during a read +system call, for instance, can be achieved as follows: +

+


+
+
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldCancelType);
+read(fd, buffer, length);
+pthread_setcanceltype(oldCancelType, NULL);
+
+
Table of Contents
+ + + diff --git a/w32-pthreads/manual/pthread_cleanup_push.html b/w32-pthreads/manual/pthread_cleanup_push.html new file mode 100644 index 000000000..0fc071e19 --- /dev/null +++ b/w32-pthreads/manual/pthread_cleanup_push.html @@ -0,0 +1,140 @@ + + + + + PTHREAD_CLEANUP(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_cleanup_push, pthread_cleanup_pop - install and remove +cleanup handlers +

+

Synopsis

+

#include <pthread.h> +

+

void pthread_cleanup_push(void (*routine) (void +*), void *arg); +

+

void pthread_cleanup_pop(int execute); +

+

Description

+

Cleanup handlers are functions that get called when a thread +terminates, either by calling pthread_exit(3) +or because of cancellation. Cleanup handlers are installed and +removed following a stack-like discipline. +

+

The purpose of cleanup handlers is to free the resources that a +thread may hold at the time it terminates. In particular, if a thread +exits or is cancelled while it owns a locked mutex, the mutex will +remain locked forever and prevent other threads from executing +normally. The best way to avoid this is, just before locking the +mutex, to install a cleanup handler whose effect is to unlock the +mutex. Cleanup handlers can be used similarly to free blocks +allocated with malloc(3) or close +file descriptors on thread termination. +

+

pthread_cleanup_push installs the routine function +with argument arg as a cleanup handler. From this point on to +the matching pthread_cleanup_pop, the function routine +will be called with arguments arg when the thread terminates, +either through pthread_exit(3) +or by cancellation. If several cleanup handlers are active at that +point, they are called in LIFO order: the most recently installed +handler is called first. +

+

pthread_cleanup_pop removes the most recently installed +cleanup handler. If the execute argument is not 0, it also +executes the handler, by calling the routine function with +arguments arg. If the execute argument is 0, the +handler is only removed but not executed. +

+

Matching pairs of pthread_cleanup_push and +pthread_cleanup_pop must occur in the same function, at the +same level of block nesting. Actually, pthread_cleanup_push +and pthread_cleanup_pop are macros, and the expansion of +pthread_cleanup_push introduces an open brace { with +the matching closing brace } being introduced by the expansion +of the matching pthread_cleanup_pop. +

+

Return Value

+
None. +
+

Errors

+
None. +
+

Author

+
Xavier Leroy +<Xavier.Leroy@inria.fr> +
+
Modified by +Ross Johnson for use with Pthreads-w32.
+

See Also

+
pthread_exit(3) +, pthread_cancel(3) , +pthread_setcanceltype(3) . +
+

Example

+
Here is how +to lock a mutex mut in such a way that it will be unlocked if +the thread is canceled while mut is locked: +
+
pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
+pthread_mutex_lock(&mut);
+/* do some work */
+pthread_mutex_unlock(&mut);
+pthread_cleanup_pop(0);
+Equivalently, the last two lines can be replaced by +
+
pthread_cleanup_pop(1);
+Notice that the code above is safe only in deferred cancellation mode +(see pthread_setcanceltype(3) +). In asynchronous cancellation mode, a cancellation can occur +between pthread_cleanup_push and pthread_mutex_lock, or +between pthread_mutex_unlock and pthread_cleanup_pop, +resulting in both cases in the thread trying to unlock a mutex not +locked by the current thread. This is the main reason why +asynchronous cancellation is difficult to use. +
+
If the code +above must also work in asynchronous cancellation mode, then it must +switch to deferred mode for locking and unlocking the mutex: +
+
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
+pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
+pthread_mutex_lock(&mut);
+/* do some work */
+pthread_cleanup_pop(1);
+pthread_setcanceltype(oldtype, NULL);
+
+
+Table of Contents
+ + + diff --git a/w32-pthreads/manual/pthread_cond_init.html b/w32-pthreads/manual/pthread_cond_init.html new file mode 100644 index 000000000..937e490a0 --- /dev/null +++ b/w32-pthreads/manual/pthread_cond_init.html @@ -0,0 +1,313 @@ + + + + + PTHREAD_COND(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_cond_init, pthread_cond_destroy, pthread_cond_signal, +pthread_cond_broadcast, pthread_cond_wait, pthread_cond_timedwait - +operations on conditions +

+

Synopsis

+

#include <pthread.h> +

+

pthread_cond_t cond = PTHREAD_COND_INITIALIZER; +

+

int pthread_cond_init(pthread_cond_t *cond, +pthread_condattr_t *cond_attr); +

+

int pthread_cond_signal(pthread_cond_t *cond); +

+

int pthread_cond_broadcast(pthread_cond_t *cond); +

+

int pthread_cond_wait(pthread_cond_t *cond, +pthread_mutex_t *mutex); +

+

int pthread_cond_timedwait(pthread_cond_t *cond, +pthread_mutex_t *mutex, const struct timespec +*abstime); +

+

int pthread_cond_destroy(pthread_cond_t *cond); +

+

Description

+

A condition (short for ā€˜ā€˜condition variableā€™ā€™) is a +synchronization device that allows threads to suspend execution and +relinquish the processors until some predicate on shared data is +satisfied. The basic operations on conditions are: signal the +condition (when the predicate becomes true), and wait for the +condition, suspending the thread execution until another thread +signals the condition. +

+

A condition variable must always be associated with a mutex, to +avoid the race condition where a thread prepares to wait on a +condition variable and another thread signals the condition just +before the first thread actually waits on it. +

+

pthread_cond_init initializes the condition variable cond, +using the condition attributes specified in cond_attr, or +default attributes if cond_attr is NULL. +

+

Variables of type pthread_cond_t can also be initialized +statically, using the constant PTHREAD_COND_INITIALIZER. In +the Pthreads-w32 implementation, an application should still +call pthread_cond_destroy at some point to ensure that any +resources consumed by the condition variable are released.

+

pthread_cond_signal restarts one of the threads that are +waiting on the condition variable cond. If no threads are +waiting on cond, nothing happens. If several threads are +waiting on cond, exactly one is restarted, but it is not +specified which. +

+

pthread_cond_broadcast restarts all the threads that are +waiting on the condition variable cond. Nothing happens if no +threads are waiting on cond. +

+

pthread_cond_wait atomically unlocks the mutex (as +per pthread_unlock_mutex) and waits for the condition variable +cond to be signalled. The thread execution is suspended and +does not consume any CPU time until the condition variable is +signalled. The mutex must be locked by the calling thread on +entrance to pthread_cond_wait. Before returning to the calling +thread, pthread_cond_wait re-acquires mutex (as per +pthread_lock_mutex). +

+

Unlocking the mutex and suspending on the condition variable is +done atomically. Thus, if all threads always acquire the mutex before +signalling the condition, this guarantees that the condition cannot +be signalled (and thus ignored) between the time a thread locks the +mutex and the time it waits on the condition variable. +

+

pthread_cond_timedwait atomically unlocks mutex and +waits on cond, as pthread_cond_wait does, but it also +bounds the duration of the wait. If cond has not been +signalled within the amount of time specified by abstime, the +mutex mutex is re-acquired and pthread_cond_timedwait +returns the error ETIMEDOUT. The abstime parameter +specifies an absolute time, with the same origin as time(2) +and gettimeofday(2). +

+

pthread_cond_destroy destroys a condition variable, freeing +the resources it might hold. No threads must be waiting on the +condition variable on entrance to pthread_cond_destroy.

+

Cancellation

+

pthread_cond_wait and pthread_cond_timedwait are +cancellation points. If a thread is cancelled while suspended in one +of these functions, the thread immediately resumes execution, then +locks again the mutex argument to pthread_cond_wait and +pthread_cond_timedwait, and finally executes the cancellation. +Consequently, cleanup handlers are assured that mutex is +locked when they are called. +

+

Async-signal Safety

+

The condition functions are not async-signal safe, and should not +be called from a signal handler. In particular, calling +pthread_cond_signal or pthread_cond_broadcast from a +signal handler may deadlock the calling thread. +

+

Return Value

+

All condition variable functions return 0 on success and a +non-zero error code on error. +

+

Errors

+

pthread_cond_init, pthread_cond_signal, +pthread_cond_broadcast, and pthread_cond_wait never +return an error code. +

+

The pthread_cond_init function returns the following error +codes on error: +

+
+
+
EINVAL +
+ The cond argument is invalid. +
+ ENOMEM +
+
+
+There was not enough memory to allocate the condition variable. +
+

The pthread_cond_signal function returns the following +error codes on error: +

+
+
+
EINVAL +
+ The cond argument is invalid. +
+
+

+The pthread_cond_broadcast function returns the following +error codes on error: +

+
+
+
EINVAL +
+ The cond argument is invalid. +
+
+

+The pthread_cond_wait function returns the following error +codes on error: +

+
+
+
EINVAL +
+ The cond argument is invalid. +
+ ENOMEM +
+
+
+There was not enough memory to allocate the statically initialised +condition variable. Statically initialised condition variables are +dynamically allocated by the first thread to wait on them.
+

The pthread_cond_timedwait function returns the following +error codes on error: +

+
+
+
EINVAL +
+
+

+The cond argument is invalid. +

+
+
+
ETIMEDOUT +
+ The condition variable was not signalled before the timeout + specified by abstime +
+ ENOMEM +
+
+
+There was not enough memory to allocate the statically initialised +condition variable. Statically initialised condition variables are +dynamically allocated by the first thread to wait on them. +
+

The pthread_cond_destroy function returns the following +error code on error: +

+
+
+
EINVAL +
+
+

+The cond argument is invalid. +

+
+
+
EBUSY +
+ Some threads are currently waiting on cond. +
+
+

+Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

pthread_condattr_init(3) +, pthread_mutex_lock(3) +, pthread_mutex_unlock(3) +, pthread_cancel(3). +

+

Example

+

Consider two shared variables x and y, protected by +the mutex mut, and a condition variable cond that is to +be signaled whenever x becomes greater than y. +

+
int x,y;
+pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
+pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
+Waiting until x is greater than y is performed as +follows: +
+
pthread_mutex_lock(&mut);
+while (x <= y) {
+        pthread_cond_wait(&cond, &mut);
+}
+/* operate on x and y */
+pthread_mutex_unlock(&mut);
+Modifications on x and y that may cause x to +become greater than y should signal the condition if needed: +
+
pthread_mutex_lock(&mut);
+/* modify x and y */
+if (x > y) pthread_cond_broadcast(&cond);
+pthread_mutex_unlock(&mut);
+If it can be proved that at most one waiting thread needs to be waken +up (for instance, if there are only two threads communicating through +x and y), pthread_cond_signal can be used as a +slightly more efficient alternative to pthread_cond_broadcast. +If in doubt, use pthread_cond_broadcast. +
+
To wait for x to +become greater than y with a timeout of 5 seconds, do: +
+
struct timeval now;
+struct timespec timeout;
+int retcode;
+pthread_mutex_lock(&mut);
+gettimeofday(&now);
+timeout.tv_sec = now.tv_sec + 5;
+timeout.tv_nsec = now.tv_usec * 1000;
+retcode = 0;
+while (x <= y && retcode != ETIMEDOUT) {
+        retcode = pthread_cond_timedwait(&cond, &mut, &timeout);
+}
+if (retcode == ETIMEDOUT) {
+        /* timeout occurred */
+} else {
+        /* operate on x and y */
+}
+pthread_mutex_unlock(&mut);
+
+
+Table of Contents
+ + + diff --git a/w32-pthreads/manual/pthread_condattr_init.html b/w32-pthreads/manual/pthread_condattr_init.html new file mode 100644 index 000000000..8b8b2f2aa --- /dev/null +++ b/w32-pthreads/manual/pthread_condattr_init.html @@ -0,0 +1,98 @@ + + + + + PTHREAD_CONDATTR(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_condattr_init, pthread_condattr_destroy - condition +creation +

+

attributes +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_condattr_init(pthread_condattr_t *attr); +

+

int pthread_condattr_destroy(pthread_condattr_t *attr); +

+

Description

+

Condition attributes can be specified at condition creation time, +by passing a condition attribute object as second argument to +pthread_cond_init(3) . +Passing NULL is equivalent to passing a condition attribute +object with all attributes set to their default values. +

+

pthread_condattr_init initializes the condition attribute +object attr and fills it with default values for the +attributes. pthread_condattr_destroy destroys a condition +attribute object, which must not be reused until it is reinitialized.

+

Pthreads-w32 defines _POSIX_THREAD_PROCESS_SHARED in +pthread.h as -1 to indicate that the attribute routines are +implemented but that the process shared attribute is not supported.

+

Return Value

+

All condition variable functions return 0 on success and a +non-zero error code on error.

+

Errors

+

The pthread_condattr_init function returns the following +error code on error: +

+
+
+
ENOMEM +
+ The was insufficient memory to create the attribute. + +
+
+

+The pthread_condattr_destroy function returns the following +error code on error: +

+
+
+
EINVAL +
+ The attr argument is not valid. + +
+
+

+Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

pthread_cond_init(3) . +

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_condattr_setpshared.html b/w32-pthreads/manual/pthread_condattr_setpshared.html new file mode 100644 index 000000000..eda357e07 --- /dev/null +++ b/w32-pthreads/manual/pthread_condattr_setpshared.html @@ -0,0 +1,153 @@ + + + + + "PTHREAD_CONDATTR_GETPSHARED"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_condattr_getpshared, pthread_condattr_setpshared - get and +set the process-shared condition variable attributes +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_condattr_getpshared(const pthread_condattr_t +*restrict attr, int *restrict pshared); +
int pthread_condattr_setpshared(pthread_condattr_t *
attr, +int pshared); +

+

Description

+

The pthread_condattr_getpshared function shall obtain the +value of the process-shared attribute from the attributes +object referenced by attr. The pthread_condattr_setpshared +function shall set the process-shared attribute in an +initialized attributes object referenced by attr. +

+

The process-shared attribute is set to +PTHREAD_PROCESS_SHARED to permit a condition variable to be +operated upon by any thread that has access to the memory where the +condition variable is allocated, even if the condition variable is +allocated in memory that is shared by multiple processes. If the +process-shared attribute is PTHREAD_PROCESS_PRIVATE, +the condition variable shall only be operated upon by threads created +within the same process as the thread that initialized the condition +variable; if threads of differing processes attempt to operate on +such a condition variable, the behavior is undefined. The default +value of the attribute is PTHREAD_PROCESS_PRIVATE. +

+

Pthreads-w32 defines _POSIX_THREAD_PROCESS_SHARED in +pthread.h as -1 to indicate that these routines are implemented but +that the process shared attribute is not supported.

+

Return Value

+

If successful, the pthread_condattr_setpshared function +shall return zero; otherwise, an error number shall be returned to +indicate the error. +

+

If successful, the pthread_condattr_getpshared function +shall return zero and store the value of the process-shared +attribute of attr into the object referenced by the pshared +parameter. Otherwise, an error number shall be returned to indicate +the error. +

+

Errors

+

The pthread_condattr_getpshared and +pthread_condattr_setpshared functions may fail if: +

+
+
EINVAL +
+ The value specified by attr is invalid. +
+

+The pthread_condattr_setpshared function may fail if: +

+
+
EINVAL +
+ The new value specified for the attribute is outside the range of + legal values for that attribute. +
+ ENOSYS +
+ The value specified by attr was PTHREAD_PROCESS_SHARED + (Pthreads-w32).
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

Pthreads-w32 defines _POSIX_THREAD_PROCESS_SHARED in +pthread.h as -1 to indicate that these routines are implemented and +may be used, but do not support the process shared option.

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_create(3) , +pthread_cond_destroy(3) , +pthread_condattr_destroy(3) +, pthread_mutex_destroy(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_create.html b/w32-pthreads/manual/pthread_create.html new file mode 100644 index 000000000..d1ebbc3e1 --- /dev/null +++ b/w32-pthreads/manual/pthread_create.html @@ -0,0 +1,94 @@ + + + + + PTHREAD_CREATE(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_create - create a new thread +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_create(pthread_t * thread, +pthread_attr_t * attr, void * (*start_routine)(void +*), void * arg); +

+

Description

+

pthread_create creates a new thread of control that +executes concurrently with the calling thread. The new thread applies +the function start_routine passing it arg as first +argument. The new thread terminates either explicitly, by calling +pthread_exit(3) , or +implicitly, by returning from the start_routine function. The +latter case is equivalent to calling pthread_exit(3) +with the result returned by start_routine as exit code. +

+

The initial signal state of the new thread is inherited from it's +creating thread and there are no pending signals. Pthreads-w32 +does not yet implement signals.

+

The attr argument specifies thread attributes to be applied +to the new thread. See pthread_attr_init(3) +for a complete list of thread attributes. The attr argument +can also be NULL, in which case default attributes are used: +the created thread is joinable (not detached) and has default (non +real-time) scheduling policy. +

+

Return Value

+

On success, the identifier of the newly created thread is stored +in the location pointed by the thread argument, and a 0 is +returned. On error, a non-zero error code is returned. +

+

Errors

+
+
EAGAIN +
+
+
+ Not enough system resources to create a process for the new + thread, or
more than PTHREAD_THREADS_MAX threads are + already active. +
+
+
+

+Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

pthread_exit(3) , +pthread_join(3) , +pthread_detach(3) , +pthread_attr_init(3) . +

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_delay_np.html b/w32-pthreads/manual/pthread_delay_np.html new file mode 100644 index 000000000..ce533e24e --- /dev/null +++ b/w32-pthreads/manual/pthread_delay_np.html @@ -0,0 +1,71 @@ + + + + + PTHREAD_DELAY_NP manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_delay_np ā€“ suspend the +thread for a specified period

+

Synopsis

+

#include <pthread.h> +

+

int pthread_delay_np (const struct timespec *interval);

+

Description

+

pthread_delay_np causes a thread to delay execution for a +specific period of time. This period ends at the current time plus +the specified interval. The routine will not return before the end of +the period is reached, but may return an arbitrary amount of time +after the period has gone by. This can be due to system load, thread +priorities, and system timer granularity.

+

Specifying an interval of zero (0) seconds and zero (0) +nanoseconds is allowed and can be used to force the thread to give up +the processor or to deliver a pending cancellation request.

+

Cancellation

+

pthread_delay_np is a cancellation point.

+

Return Value

+

If an error condition occurs, pthread_delay_np returns an +integer value indicating the type of error.

+

Errors

+

The pthread_delay_np function returns the following error +code on error: +

+
+
+
EINVAL +
+
+

+The value specified by interval is invalid.

+

Author

+

Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_detach.html b/w32-pthreads/manual/pthread_detach.html new file mode 100644 index 000000000..252adb813 --- /dev/null +++ b/w32-pthreads/manual/pthread_detach.html @@ -0,0 +1,90 @@ + + + + + PTHREAD_DETACH(3) manual page + + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_detach - put a running thread in the detached state +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_detach(pthread_t th); +

+

Description

+

pthread_detach puts the thread th in the detached +state. This guarantees that the resources consumed by th will +be freed immediately when th terminates. However, this +prevents other threads from synchronizing on the termination of th +using pthread_join. If, when pthread_detach is called, +th has already terminated, all of th's remaining +resources will be freed.

+

A thread can be created initially in the detached state, using the +detachstate attribute to pthread_create(3) +. In contrast, pthread_detach applies to threads created in +the joinable state, and which need to be put in the detached state +later. +

+

After pthread_detach completes, subsequent attempts to +perform pthread_join on th will fail. If another thread +is already joining the thread th at the time pthread_detach +is called, th will be detached and pthread_join will +eventually return when th terminates but may not return with +th's correct return code. +

+

Return Value

+

On success, 0 is returned. On error, a non-zero error code is +returned. +

+

Errors

+
+
ESRCH +
+ No thread could be found corresponding to that specified by th +
+ EINVAL +
+ the thread th is already in the detached state +
+

+Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

pthread_create(3) , +pthread_join(3) , +pthread_attr_setdetachstate(3) +

+
+

Table of Contents

+ + + \ No newline at end of file diff --git a/w32-pthreads/manual/pthread_equal.html b/w32-pthreads/manual/pthread_equal.html new file mode 100644 index 000000000..6f610634e --- /dev/null +++ b/w32-pthreads/manual/pthread_equal.html @@ -0,0 +1,48 @@ + + + + + +PTHREAD_EQUAL(3) manual page + + +Table of Contents

+ +

+

Name

+pthread_equal - compare two thread identifiers +

+

Synopsis

+#include <pthread.h> + +

int pthread_equal(pthread_t thread1, pthread_t thread2); +

+

Description

+pthread_equal +determines if two thread identifiers refer to the same thread. +

+

Return Value

+A +non-zero value is returned if thread1 and thread2 refer to the same thread. +Otherwise, 0 is returned. +

+

Author

+Xavier Leroy <Xavier.Leroy@inria.fr> +

+

See Also

+pthread_self(3) +. +

+ +


+Table of Contents

+

+ + diff --git a/w32-pthreads/manual/pthread_exit.html b/w32-pthreads/manual/pthread_exit.html new file mode 100644 index 000000000..e97318f54 --- /dev/null +++ b/w32-pthreads/manual/pthread_exit.html @@ -0,0 +1,59 @@ + + + + + +PTHREAD_EXIT(3) manual page + + +Table of Contents

+ +

+

Name

+pthread_exit - terminate the calling thread +

+

Synopsis

+#include <pthread.h> + +

void pthread_exit(void *retval); +

+

Description

+pthread_exit terminates the +execution of the calling thread. All cleanup handlers that have been set +for the calling thread with pthread_cleanup_push(3) + are executed in reverse +order (the most recently pushed handler is executed first). Finalization +functions for thread-specific data are then called for all keys that have +non- NULL values associated with them in the calling thread (see pthread_key_create(3) +). +Finally, execution of the calling thread is stopped. +

The retval argument +is the return value of the thread. It can be consulted from another thread +using pthread_join(3) +. +

+

Return Value

+The pthread_exit function never returns. + +

+

Author

+Xavier Leroy <Xavier.Leroy@inria.fr> +

+

See Also

+pthread_create(3) +, pthread_join(3) +. +

+ +


+Table of Contents

+

+ + diff --git a/w32-pthreads/manual/pthread_getunique_np.html b/w32-pthreads/manual/pthread_getunique_np.html new file mode 100644 index 000000000..182ce73c6 --- /dev/null +++ b/w32-pthreads/manual/pthread_getunique_np.html @@ -0,0 +1,76 @@ + + + + + PTHREAD_GETW32THREADHANDLE_NP manual page + + + + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - +Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_getunique_np ā€“ get the +unique sequence number associated with a thread

+

Synopsis

+

#include <pthread.h> +

+

unsigned long long pthread_getunique_np(pthread_t thread);

+

Description

+

Returns the unique 64 bit +sequence number assigned to thread.

+

In Pthreads-win32:

+
    +
  • the value returned is not reused after the thread terminates + so it is unique for the life of the process

    +
  • Windows native threads may obtain their own POSIX thread + sequence number by first retrieving their pthread_t handle + via pthread_self to use as the thread argument.

    +
+

This function was added for source code compatibility with some +other POSIX threads implementations.

+

Cancellation

+

None.

+

Return Value

+

pthread_getunique_np returns the unique sequence number for +thread.

+

Errors

+

None.

+

Author

+

Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + \ No newline at end of file diff --git a/w32-pthreads/manual/pthread_getw32threadhandle_np.html b/w32-pthreads/manual/pthread_getw32threadhandle_np.html new file mode 100644 index 000000000..7e8de6438 --- /dev/null +++ b/w32-pthreads/manual/pthread_getw32threadhandle_np.html @@ -0,0 +1,57 @@ + + + + + PTHREAD_GETW32THREADHANDLE_NP manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_getw32threadhandle_np ā€“ get +the Win32 thread handle associated with a thread

+

Synopsis

+

#include <pthread.h> +

+

HANDLE pthread_getw32threadhandle_np(pthread_t thread);

+

Description

+

Returns the Win32 native thread HANDLE that the POSIX +thread thread is running as.

+

Applications can use the Win32 handle to set Win32 specific +attributes of the thread.

+

Cancellation

+

None.

+

Return Value

+

pthread_getw32threadhandle_np returns the Win32 native +thread HANDLE for the specified POSIX thread thread.

+

Errors

+

None.

+

Author

+

Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_join.html b/w32-pthreads/manual/pthread_join.html new file mode 100644 index 000000000..3e3f3b902 --- /dev/null +++ b/w32-pthreads/manual/pthread_join.html @@ -0,0 +1,118 @@ + + + + + PTHREAD_JOIN(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_join - wait for termination of another thread +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_join(pthread_t th, void +**thread_return); +

+

Description

+

pthread_join suspends the execution of the calling thread +until the thread identified by th terminates, either by +calling pthread_exit(3) or by +being cancelled. +

+

If thread_return is not NULL, the return value of th +is stored in the location pointed to by thread_return. The +return value of th is either the argument it gave to +pthread_exit(3) , or +PTHREAD_CANCELED if th was cancelled. +

+

The joined thread th must be in the joinable state: it must +not have been detached using pthread_detach(3) +or the PTHREAD_CREATE_DETACHED attribute to pthread_create(3) +. +

+

When a joinable thread terminates, its memory resources (thread +descriptor and stack) are not deallocated until another thread +performs pthread_join on it. Therefore, pthread_join +must be called once for each joinable thread created to avoid memory +leaks. +

+

At most one thread can wait for the termination of a given thread. +Calling pthread_join on a thread th on which another +thread is already waiting for termination returns an error. +

+

Cancellation

+

pthread_join is a cancellation point. If a thread is +cancelled while suspended in pthread_join, the thread +execution resumes immediately and the cancellation is executed +without waiting for the th thread to terminate. If +cancellation occurs during pthread_join, the th thread +remains not joined. +

+

Return Value

+

On success, the return value of th is stored in the +location pointed to by thread_return, and 0 is returned. On +error, a non-zero error code is returned. +

+

Errors

+
+
ESRCH +
+ No thread could be found corresponding to that specified by th. +
+ EINVAL +
+ The th thread has been detached. +
+ EINVAL +
+ Another thread is already waiting on termination of th. +
+ EDEADLK +
+ The th argument refers to the calling thread. +
+

+Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

See Also

+

pthread_exit(3) , +pthread_detach(3) , +pthread_create(3) , +pthread_attr_setdetachstate(3) +, pthread_cleanup_push(3) +, pthread_key_create(3) +. +

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_key_create.html b/w32-pthreads/manual/pthread_key_create.html new file mode 100644 index 000000000..5ecca6995 --- /dev/null +++ b/w32-pthreads/manual/pthread_key_create.html @@ -0,0 +1,211 @@ + + + + + PTHREAD_SPECIFIC(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_key_create, pthread_key_delete, pthread_setspecific, +pthread_getspecific - management of thread-specific data +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_key_create(pthread_key_t *key, void +(*destr_function) (void *)); +

+

int pthread_key_delete(pthread_key_t key); +

+

int pthread_setspecific(pthread_key_t key, const +void *pointer); +

+

void * pthread_getspecific(pthread_key_t key); +

+

Description

+

Programs often need global or static variables that have different +values in different threads. Since threads share one memory space, +this cannot be achieved with regular variables. Thread-specific data +is the POSIX threads answer to this need. +

+

Each thread possesses a private memory block, the thread-specific +data area, or TSD area for short. This area is indexed by TSD keys. +The TSD area associates values of type void * to TSD keys. TSD +keys are common to all threads, but the value associated with a given +TSD key can be different in each thread. +

+

For concreteness, the TSD areas can be viewed as arrays of void +* pointers, TSD keys as integer indices into these arrays, and +the value of a TSD key as the value of the corresponding array +element in the calling thread. +

+

When a thread is created, its TSD area initially associates NULL +with all keys. +

+

pthread_key_create allocates a new TSD key. The key is +stored in the location pointed to by key. There is a limit of +PTHREAD_KEYS_MAX on the number of keys allocated at a given +time. The value initially associated with the returned key is NULL +in all currently executing threads. +

+

The destr_function argument, if not NULL, specifies +a destructor function associated with the key. When a thread +terminates via pthread_exit or by cancellation, destr_function +is called with arguments the value associated with the key in that +thread. The destr_function is not called if that value is NULL +or the key has been deleted. The order in which destructor +functions are called at thread termination time is unspecified. +

+

Before the destructor function is called, the NULL value is +associated with the key in the current thread. A destructor function +might, however, re-associate non- NULL values to that key or +some other key. To deal with this, if after all the destructors have +been called for all non- NULL values, there are still some +non- NULL values with associated destructors, then the process +is repeated.

+

pthread_key_delete deallocates a TSD key. It does not check +whether non- NULL values are associated with that key in the +currently executing threads, nor call the destructor function +associated with the key. +

+

pthread_setspecific changes the value associated with key +in the calling thread, storing the given pointer instead. +

+

pthread_getspecific returns the value currently associated +with key in the calling thread. +

+

The routines pthread_setspecific, pthread_getspecific, +and pthread_key_delete can be called from destr_function +targeting any valid key including the key on which destr_function +is currently operating. If pthread_getspecific is called on +the key whose thread specific data is being destroyed, the value NULL +is returned, unless pthread_setspecific was called previously +on that key from within destr_function to set the value to +non-NULL. For some implementations the effect of calling +pthread_setspecific from within destr_function can be +either memory leakage or infinite loops if destr_function has +already been called at least PTHREAD_DESTRUCTOR_ITERATIONS +times.

+

Pthreads-w32 stops running key +destr_function routines after PTHREAD_DESTRUCTOR_ITERATIONS +iterations, even if some non- NULL values with associated +descriptors remain. If memory is allocated and associated with a key +from within destr_function, that memory may not be reclaimed +because that key's destr_function, may not run again.

+

Return Value

+

pthread_key_create, pthread_key_delete, and +pthread_setspecific return 0 on success and a non-zero error +code on failure. If successful, pthread_key_create stores the +newly allocated key in the location pointed to by its key +argument. +

+

pthread_getspecific returns the value associated with key +on success, and NULL on error. +

+

Errors

+

pthread_key_create returns the following error code on +error: +

+
+
+
EAGAIN +
+
+
+PTHREAD_KEYS_MAX keys are already allocated +
+
+
+
ENOMEM +
+
+
+Insufficient memory to allocate the key. +
+

pthread_key_delete and pthread_setspecific return +the following error code on error: +

+
+
+
EINVAL +
+ key is not a valid, allocated TSD key +
+
+

+pthread_getspecific returns NULL if key is not a +valid, allocated TSD key. +

+

Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

pthread_create(3) , +pthread_exit(3) , +pthread_testcancel(3) . +

+

Example

+

The following code fragment allocates a thread-specific array of +100 characters, with automatic reclamation at thread exit: +

+


+
+
/* Key for the thread-specific buffer */
+static pthread_key_t buffer_key;
+/* Once-only initialisation of the key */
+static pthread_once_t buffer_key_once = PTHREAD_ONCE_INIT;
+/* Allocate the thread-specific buffer */
+void buffer_alloc(void)
+{
+  pthread_once(&buffer_key_once, buffer_key_alloc);
+  pthread_setspecific(buffer_key, malloc(100));
+}
+/* Return the thread-specific buffer */
+char * get_buffer(void)
+{
+  return (char *) pthread_getspecific(buffer_key);
+}
+/* Allocate the key */
+static void buffer_key_alloc()
+{
+  pthread_key_create(&buffer_key, buffer_destroy);
+}
+/* Free the thread-specific buffer */
+static void buffer_destroy(void * buf)
+{
+  free(buf);
+}
+
+
+Table of Contents
+ + + \ No newline at end of file diff --git a/w32-pthreads/manual/pthread_kill.html b/w32-pthreads/manual/pthread_kill.html new file mode 100644 index 000000000..33d61b21c --- /dev/null +++ b/w32-pthreads/manual/pthread_kill.html @@ -0,0 +1,152 @@ + + + + + PTHREAD_SIGNAL(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_sigmask, pthread_kill, sigwait - handling of signals in +threads +

+

Synopsis

+

#include <pthread.h>
#include <signal.h> +

+

int pthread_sigmask(int how, const sigset_t +*newmask, sigset_t *oldmask); +

+

int pthread_kill(pthread_t thread, int signo); +

+

int sigwait(const sigset_t *set, int *sig);

+

Description

+

pthread_sigmask changes the signal mask for the calling +thread as described by the how and newmask arguments. +If oldmask is not NULL, the previous signal mask is +stored in the location pointed to by oldmask. Pthreads-w32 +implements this function but no other function uses the signal mask +yet.

+

The meaning of the how and newmask arguments is the +same as for sigprocmask(2). +If how is SIG_SETMASK, the signal mask is set to +newmask. If how is SIG_BLOCK, the signals +specified to newmask are added to the current signal mask. If +how is SIG_UNBLOCK, the signals specified to newmask +are removed from the current signal mask. +

+

Recall that signal masks are set on a per-thread basis, but signal +actions and signal handlers, as set with sigaction(2), are +shared between all threads. +

+

pthread_kill send signal number signo to the thread +thread. Pthreads-w32 only supports signal number 0, +which does not send any signal but causes pthread_kill to +return an error if thread is not valid.

+

sigwait suspends the calling thread until one of the +signals in set is delivered to the calling thread. It then +stores the number of the signal received in the location pointed to +by sig and returns. The signals in set must be blocked +and not ignored on entrance to sigwait. If the delivered +signal has a signal handler function attached, that function is not +called. Pthreads-w32 implements this function as a +cancellation point only - it does not wait for any signals and does +not change the location pointed to by sig.

+

Cancellation

+

sigwait is a cancellation point. +

+

Return Value

+

On success, 0 is returned. On failure, a non-zero error code is +returned. +

+

Errors

+

The pthread_sigmask function returns the following error +codes on error: +

+
+
+
EINVAL +
+ how is not one of SIG_SETMASK, SIG_BLOCK, or + SIG_UNBLOCK +
+
+

+The pthread_kill function returns the following error codes on +error: +

+
+
+
EINVAL +
+ signo is not a valid signal number or is unsupported.
+ ESRCH +
+ the thread thread does not exist (e.g. it has already + terminated) +
+
+

+The sigwait function never returns an error. +

+

Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

+

+

Notes

+

In any implementation, for sigwait to work reliably, the +signals being waited for must be blocked in all threads, not only in +the calling thread, since otherwise the POSIX semantics for signal +delivery do not guarantee that itā€™s the thread doing the sigwait +that will receive the signal. The best way to achieve this is to +block those signals before any threads are created, and never unblock +them in the program other than by calling sigwait. This works +because all threads inherit their initial sigmask from their creating +thread.

+

Bugs

+

Pthreads-w32 does not implement signals yet and so these +routines have almost no use except to prevent the compiler or linker +from complaining. pthread_kill is useful in determining if the +thread is a valid thread, but since many threads implementations +reuse thread IDs, the valid thread may no longer be the thread you +think it is, and so this method of determining thread validity is not +portable, and very risky. Pthreads-w32 from version 1.0.0 +onwards implements pseudo-unique thread IDs, so applications that use +this technique (but really shouldn't) have some protection.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_mutex_init.html b/w32-pthreads/manual/pthread_mutex_init.html new file mode 100644 index 000000000..cdb333e10 --- /dev/null +++ b/w32-pthreads/manual/pthread_mutex_init.html @@ -0,0 +1,356 @@ + + + + + PTHREAD_MUTEX(3) manual page + + + + + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - +Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_mutex_init, pthread_mutex_lock, pthread_mutex_trylock, +pthread_mutex_timedlock, pthread_mutex_unlock, +pthread_mutex_consistent, pthread_mutex_destroy - operations on +mutexes +

+

Synopsis

+

#include <pthread.h> +

+

#include <time.h>

+

pthread_mutex_t fastmutex = +PTHREAD_MUTEX_INITIALIZER; +

+

pthread_mutex_t recmutex = +PTHREAD_RECURSIVE_MUTEX_INITIALIZER; +

+

pthread_mutex_t errchkmutex = +PTHREAD_ERRORCHECK_MUTEX_INITIALIZER; +

+

pthread_mutex_t recmutex = +PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; +

+

pthread_mutex_t errchkmutex = +PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP; +

+

int pthread_mutex_init(pthread_mutex_t *mutex, +const pthread_mutexattr_t *mutexattr); +

+

int pthread_mutex_lock(pthread_mutex_t *mutex); +

+

int pthread_mutex_trylock(pthread_mutex_t *mutex); +

+

int pthread_mutex_timedlock(pthread_mutex_t *mutex, +const struct timespec *abs_timeout); +

+

int pthread_mutex_unlock(pthread_mutex_t *mutex); +

+

int pthread_mutex_consistent(pthread_mutex_t *mutex); +

+

int pthread_mutex_destroy(pthread_mutex_t *mutex); +

+

Description

+

A mutex is a MUTual EXclusion device, and is useful for protecting +shared data structures from concurrent modifications, and +implementing critical sections and monitors. +

+

A mutex has two possible states: unlocked (not owned by any +thread), and locked (owned by one thread). A mutex can never be owned +by two different threads simultaneously. A thread attempting to lock +a mutex that is already locked by another thread is suspended until +the owning thread unlocks the mutex first. +

+

pthread_mutex_init initializes the mutex object pointed to +by mutex according to the mutex attributes specified in +mutexattr. If mutexattr is NULL, default +attributes are used instead. +

+

The type of a mutex determines whether it can be locked again by a +thread that already owns it. The default type is ā€œnormalā€. See +pthread_mutexattr_init(3) +for more information on mutex attributes. +

+

Variables of type pthread_mutex_t can also be initialized +statically, using the constants PTHREAD_MUTEX_INITIALIZER (for +normal ā€œfastā€ mutexes), PTHREAD_RECURSIVE_MUTEX_INITIALIZER +(for recursive mutexes), and PTHREAD_ERRORCHECK_MUTEX_INITIALIZER +(for error checking mutexes). In +the Pthreads-w32 implementation, +an application should still call pthread_mutex_destroy +at some point to ensure that any +resources consumed by the mutex are released.

+

Any mutex type can be +initialized as a robust mutex. +See pthread_mutexattr_init(3) +for more information as well as the +section Robust Mutexes +below.

+

pthread_mutex_lock locks the given mutex. If the mutex is +currently unlocked, it becomes locked and owned by the calling +thread, and pthread_mutex_lock returns immediately. If the +mutex is already locked by another thread, pthread_mutex_lock +suspends the calling thread until the mutex is unlocked.

+

If the mutex is already locked by the calling thread, the behavior +of pthread_mutex_lock depends on the type of the mutex. If the +mutex is of the ā€œnormalā€ type, the calling thread is suspended +until the mutex is unlocked, thus effectively causing the calling +thread to deadlock. If the mutex is of the ā€˜ā€˜error checkingā€™ā€™ +type, pthread_mutex_lock returns immediately with the error +code EDEADLK. If the mutex is of the ā€˜ā€˜recursiveā€™ā€™ +type, pthread_mutex_lock succeeds and returns immediately, +recording the number of times the calling thread has locked the +mutex. An equal number of pthread_mutex_unlock operations must +be performed before the mutex returns to the unlocked state. +

+

pthread_mutex_trylock behaves identically to +pthread_mutex_lock, except that it does not block the calling +thread if the mutex is already locked by another thread (or by the +calling thread in the case of a ā€œnormalā€ or ā€œerrorcheckā€ +mutex). Instead, pthread_mutex_trylock returns immediately +with the error code EBUSY. +

+

pthread_mutex_timedlock behaves identically to +pthread_mutex_lock, except that if it cannot acquire the lock +before the abs_timeout time, the call returns with the error +code ETIMEDOUT. If the mutex can be locked immediately it is, +and the abs_timeout parameter is ignored.

+

pthread_mutex_consistent may only be called for +PTHREAD_MUTEX_ROBUST mutexes. It simply marks the mutex as +consistent. See Robust Mutexes below.

+

pthread_mutex_unlock unlocks the given mutex. The mutex is +assumed to be locked and owned by the calling thread on entrance to +pthread_mutex_unlock. If the mutex is of the ā€œnormalā€ +type, pthread_mutex_unlock always returns it to the unlocked +state. If it is of the ā€˜ā€˜recursiveā€™ā€™ type, it decrements the +locking count of the mutex (number of pthread_mutex_lock +operations performed on it by the calling thread), and only when this +count reaches zero is the mutex actually unlocked. In Pthreads-win32, +non-robust normal or default mutex types do not check the owner of +the mutex. For all types of robust mutexes the owner is checked and +an error code is returned if the calling thread does not own the +mutex.

+

On ā€˜ā€˜error checkingā€™ā€™ mutexes, pthread_mutex_unlock +actually checks at run-time that the mutex is locked on entrance, and +that it was locked by the same thread that is now calling +pthread_mutex_unlock. If these conditions are not met, an +error code is returned and the mutex remains unchanged. ā€˜ā€˜Normalā€™ā€™ +[non-robust] mutexes perform no such checks, thus allowing a locked +mutex to be unlocked by a thread other than its owner. This is +non-portable behavior and is not meant to be used as a feature.

+

pthread_mutex_destroy destroys a mutex object, freeing the +resources it might hold. The mutex must be unlocked on entrance.

+

Robust Mutexes

+

If the mutex is PTHREAD_MUTEX_ROBUST and the owning thread +terminates without unlocking the mutex the implementation will wake +one waiting thread, if any. The next thread to acquire the mutex will +receive the error code EOWNERDEAD, +in which case that thread should if possible ensure that the state +protected by the mutex is consistent and then call +pthread_mutex_consistent before +unlocking. The mutex may then be used normally from then on.

+

If the thread cannot recover the +state then it must call pthread_mutex_unlock +without calling pthread_mutex_consistent. +This will mark the mutex as unusable and wake all currently waiting +threads with the return code ENOTRECOVERABLE. +The error indicates that the mutex is no longer usable and any +threads that receive this error code from any lock operation have not +acquired the mutex. The mutex can be made consistent by calling +pthread_mutex_destroy to +uninitialize the mutex, and calling pthread_mutex_int +to reinitialize the mutex. However, +the state that was protected by the mutex remains inconsistent and +some form of application recovery is required.

+

If a thread that receives the +EOWNERDEAD error code +itself terminates without unlocking the mutex then this behaviour +repeats for the next acquiring thread.

+

Applications must ensure that +they check the return values from all calls targeting robust mutexes.

+

Robust mutexes are slower because they +require some additional overhead, however they are not very much +slower than the non-robust recursive type.

+

Cancellation

+

None of the mutex functions is a cancellation point, not even +pthread_mutex_lock, in spite of the fact that it can suspend a +thread for arbitrary durations. This way, the status of mutexes at +cancellation points is predictable, allowing cancellation handlers to +unlock precisely those mutexes that need to be unlocked before the +thread stops executing. Consequently, threads using deferred +cancellation should never hold a mutex for extended periods of time. +

+

Async-signal Safety

+

The mutex functions are not async-signal safe. What this means is +that they should not be called from a signal handler. In particular, +calling pthread_mutex_lock or pthread_mutex_unlock from +a signal handler may deadlock the calling thread. +

+

Return Value

+

pthread_mutex_init always returns 0. The other mutex +functions return 0 on success and a non-zero error code on error. +

+

Errors

+

The pthread_mutex_lock function returns the following error +code on error: +

+
+
+
EINVAL
+ the mutex has not been properly initialized. +
+ EDEADLK
+ the mutex is already locked by the calling thread (ā€˜ā€˜error + checkingā€™ā€™ mutexes only). +
+ EOWNERDEAD
+ the robust mutex is now locked by the calling thread after the + previous owner terminated without unlocking it.
+ ENOTRECOVERABLE
+ the robust mutex is not locked and is no longer usable after the + previous owner unlocked it without calling + pthread_mutex_consistent.
+
+ The pthread_mutex_trylock function returns the following + error codes on error: +
+
+ EBUSY +
+ the mutex could not be acquired because it was currently locked. +
+ EINVAL +
+ the mutex has not been properly initialized. +
+ EOWNERDEAD
+ the robust mutex is now locked by the calling thread after the + previous owner terminated without unlocking it.
+ ENOTRECOVERABLE
+ the robust mutex is not locked and is no longer usable after the + previous owner unlocked it without calling + pthread_mutex_consistent.
+
+

+The pthread_mutex_timedlock function returns the following +error codes on error: +

+
+
+
ETIMEDOUT +
+ the mutex could not be acquired before the abs_timeout time + arrived. +
+ EINVAL +
+ the mutex has not been properly initialized. +
+ EOWNERDEAD
+ the robust mutex is now locked by the calling thread after the + previous owner terminated without unlocking it.
+ ENOTRECOVERABLE
+ the robust mutex is not locked and is no longer usable after the + previous owner unlocked it without calling + pthread_mutex_consistent.
+
+

+The pthread_mutex_unlock function returns the following error +code on error: +

+
+
+
EINVAL +
+ the mutex has not been properly initialized. +
+ EPERM +
+ the calling thread does not own the mutex (ā€˜ā€˜error checkingā€™ā€™ + mutexes only). +
+
+

+The pthread_mutex_destroy function returns the following error +code on error: +

+
+
+
EBUSY +
+ the mutex is currently locked. +
+
+

+Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

pthread_mutexattr_init(3) +, pthread_mutexattr_settype(3) +, pthread_cancel(3) . +

+

Example

+

A shared global variable x can be protected by a mutex as +follows: +

+
int x;
+pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
+All accesses and modifications to x should be bracketed by +calls to pthread_mutex_lock and pthread_mutex_unlock as +follows: +
+
pthread_mutex_lock(&mut);
+/* operate on x */
+pthread_mutex_unlock(&mut);
+
+
Table +of Contents
+ + + \ No newline at end of file diff --git a/w32-pthreads/manual/pthread_mutexattr_init.html b/w32-pthreads/manual/pthread_mutexattr_init.html new file mode 100644 index 000000000..760521f41 --- /dev/null +++ b/w32-pthreads/manual/pthread_mutexattr_init.html @@ -0,0 +1,207 @@ + + + + + PTHREAD_MUTEXATTR(3) manual page + + + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - +Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_mutexattr_init, pthread_mutexattr_destroy, +pthread_mutexattr_settype, pthread_mutexattr_gettype - mutex creation +attributes +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_mutexattr_init(pthread_mutexattr_t *attr); +

+

int pthread_mutexattr_destroy(pthread_mutexattr_t *attr); +

+

int pthread_mutexattr_settype(pthread_mutexattr_t *attr, +int type); +

+

int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, +int *type); +

+

int pthread_mutexattr_setkind_np(pthread_mutexattr_t *attr, +int type); +

+

int pthread_mutexattr_getkind_np(const pthread_mutexattr_t +*attr, int *type); +

+

int pthread_mutexattr_setrobust(pthread_mutexattr_t *attr, +int robust); +

+

int pthread_mutexattr_getrobust(pthread_mutexattr_t *attr, +int *robust); +

+

Description

+

Mutex attributes can be specified at mutex creation time, by +passing a mutex attribute object as second argument to +pthread_mutex_init(3) . +Passing NULL is equivalent to passing a mutex attribute object +with all attributes set to their default values. +

+

pthread_mutexattr_init initializes the mutex attribute +object attr and fills it with default values for the +attributes. +

+

pthread_mutexattr_destroy destroys a mutex attribute +object, which must not be reused until it is reinitialized.

+

pthread_mutexattr_settype sets the mutex type attribute in +attr to the value specified by type. +

+

pthread_mutexattr_gettype retrieves the current value of +the mutex kind attribute in attr and stores it in the location +pointed to by type. +

+

Pthreads-w32 also recognises the following equivalent +functions that are used in Linux:

+

pthread_mutexattr_setkind_np is an alias for +pthread_mutexattr_settype. +

+

pthread_mutexattr_getkind_np is +an alias for pthread_mutexattr_gettype. +

+

The following mutex types are supported:

+

PTHREAD_MUTEX_NORMAL - for +ā€˜ā€˜fastā€™ā€™ mutexes.

+

PTHREAD_MUTEX_RECURSIVE - for +ā€˜ā€˜recursiveā€™ā€™ mutexes.

+

PTHREAD_MUTEX_ERRORCHECK - for +ā€˜ā€˜error checkingā€™ā€™ mutexes.

+

The mutex type determines what happens if a thread attempts to +lock a mutex it already owns with pthread_mutex_lock(3) +. If the mutex is of the ā€œnormalā€ or ā€œfastā€ type, +pthread_mutex_lock(3) +simply suspends the calling thread forever. If the mutex is of the +ā€˜ā€˜error checkingā€™ā€™ type, pthread_mutex_lock(3) +returns immediately with the error code EDEADLK. If the mutex +is of the ā€˜ā€˜recursiveā€™ā€™ type, the call to +pthread_mutex_lock(3) +returns immediately with a success return code. The number of times +the thread owning the mutex has locked it is recorded in the mutex. +The owning thread must call pthread_mutex_unlock(3) +the same number of times before the mutex returns to the unlocked +state. +

+

The default mutex type is PTHREAD_MUTEX_NORMAL

+

Pthreads-w32 also recognises the following equivalent types +that are used by Linux:

+

PTHREAD_MUTEX_FAST_NP +ā€“ equivalent to PTHREAD_MUTEX_NORMAL

+

PTHREAD_MUTEX_RECURSIVE_NP

+

PTHREAD_MUTEX_ERRORCHECK_NP

+

pthread_mutexattr_setrobust +sets the robustness attribute to the value given by robust.

+

pthread_mutexattr_getrobust +returns the current robustness value to the location given by +*robust.

+

The possible values for robust +are:

+

PTHREAD_MUTEX_STALLED +- when the owner of the mutex terminates without unlocking the mutex, +all subsequent calls to pthread_mutex_*lock() are blocked from +progress in an unspecified manner.

+

PTHREAD_MUTEX_ROBUST +- when the owner of the mutex terminates without unlocking the mutex, +the mutex is unlocked. The next owner of this mutex acquires the +mutex with an error return of EOWNERDEAD.

+

Return Value

+

On success all functions return +0, otherwise they return an error code as follows:

+

pthread_mutexattr_init

+

ENOMEM +- insufficient memory for attr.

+

pthread_mutexattr_destroy

+

EINVAL +- attr +is invalid.

+

pthread_mutexattr_gettype

+

EINVAL +- attr +is invalid.

+

pthread_mutexattr_settype

+
+
+
+
EINVAL - attr + is invalid or type + is none of:
+
+
+ PTHREAD_MUTEX_NORMAL
PTHREAD_MUTEX_FAST_NP
PTHREAD_MUTEX_RECURSIVE
PTHREAD_MUTEX_RECURSIVE_NP
PTHREAD_MUTEX_ERRORCHECK
PTHREAD_MUTEX_ERRORCHECK_NP
+
+
+
+
+
+
+

+pthread_mutexattr_getrobust

+

EINVAL +ā€“ attr +or robust +is invalid.

+

pthread_mutexattr_setrobust

+

EINVAL +ā€“ attr +or robust +is invalid.

+

Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

pthread_mutex_init(3) +, pthread_mutex_lock(3) +, pthread_mutex_unlock(3) +. +

+

Notes

+

For speed, Pthreads-w32 never checks the thread ownership +of non-robust mutexes of type PTHREAD_MUTEX_NORMAL (or +PTHREAD_MUTEX_FAST_NP) when performing operations on the +mutex. It is therefore possible for one thread to lock such a mutex +and another to unlock it.

+

When developing code, it is a common +precaution to substitute the error checking type, then drop in the +normal type for release if the extra performance is required.

+
+

Table of Contents

+ + + \ No newline at end of file diff --git a/w32-pthreads/manual/pthread_mutexattr_setpshared.html b/w32-pthreads/manual/pthread_mutexattr_setpshared.html new file mode 100644 index 000000000..25bf9f60b --- /dev/null +++ b/w32-pthreads/manual/pthread_mutexattr_setpshared.html @@ -0,0 +1,151 @@ + + + + + "PTHREAD_MUTEXATTR_GETPSHARED"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_mutexattr_getpshared, pthread_mutexattr_setpshared - get +and set the process-shared attribute +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_mutexattr_getpshared(const pthread_mutexattr_t * +restrict attr, int *restrict pshared); +
int pthread_mutexattr_setpshared(pthread_mutexattr_t *
attr, +int pshared); +

+

Description

+

The pthread_mutexattr_getpshared function shall obtain the +value of the process-shared attribute from the attributes +object referenced by attr. The pthread_mutexattr_setpshared +function shall set the process-shared attribute in an +initialized attributes object referenced by attr. +

+

The process-shared attribute is set to +PTHREAD_PROCESS_SHARED to permit a mutex to be operated upon +by any thread that has access to the memory where the mutex is +allocated, even if the mutex is allocated in memory that is shared by +multiple processes. If the process-shared attribute is +PTHREAD_PROCESS_PRIVATE, the mutex shall only be operated upon +by threads created within the same process as the thread that +initialized the mutex; if threads of differing processes attempt to +operate on such a mutex, the behavior is undefined. The default value +of the attribute shall be PTHREAD_PROCESS_PRIVATE. +

+

Pthreads-w32 defines _POSIX_THREAD_PROCESS_SHARED in +pthread.h as -1 to indicate that these routines are implemented but +the process shared option is not supported.

+

Return Value

+

Upon successful completion, pthread_mutexattr_setpshared +shall return zero; otherwise, an error number shall be returned to +indicate the error. +

+

Upon successful completion, pthread_mutexattr_getpshared +shall return zero and store the value of the process-shared +attribute of attr into the object referenced by the pshared +parameter. Otherwise, an error number shall be returned to indicate +the error. +

+

Errors

+

The pthread_mutexattr_getpshared and +pthread_mutexattr_setpshared functions may fail if: +

+
+
EINVAL +
+ The value specified by attr is invalid. +
+

+The pthread_mutexattr_setpshared function may fail if: +

+
+
EINVAL +
+ The new value specified for the attribute is outside the range of + legal values for that attribute. +
+ ENOTSUP +
+ The new value specified for the attribute is PTHREAD_PROCESS_SHARED. +
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

None. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_cond_destroy(3) +, pthread_create(3) , +pthread_mutex_destroy(3) +, pthread_mutexattr_destroy(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_num_processors_np.html b/w32-pthreads/manual/pthread_num_processors_np.html new file mode 100644 index 000000000..050941065 --- /dev/null +++ b/w32-pthreads/manual/pthread_num_processors_np.html @@ -0,0 +1,57 @@ + + + + + PTHREAD_NUM_PROCESSORS_NP manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_num_processors_np ā€“ get the +number of processors (CPUs) in use by the process

+

Synopsis

+

#include <pthread.h> +

+

int pthread_num_processors_np(void);

+

Description

+

pthread_num_processors_np returns the number of processors +in the system. This implementation actually returns the number of +processors available to the process, which can be a lower number than +the system's number, depending on the process's affinity mask.

+

Cancellation

+

None.

+

Return Value

+

pthread_num_processors_np returns the number of processors +currently available to the process.

+

Errors

+

None.

+

Author

+

Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_once.html b/w32-pthreads/manual/pthread_once.html new file mode 100644 index 000000000..856fb8653 --- /dev/null +++ b/w32-pthreads/manual/pthread_once.html @@ -0,0 +1,83 @@ + + + + + PTHREAD_ONCE(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_once - once-only initialization +

+

Synopsis

+

#include <pthread.h> +

+

pthread_once_t once_control = PTHREAD_ONCE_INIT; +

+

int pthread_once(pthread_once_t *once_control, +void (*init_routine) (void)); +

+

Description

+

The purpose of pthread_once is to ensure that a piece of +initialization code is executed at most once. The once_control +argument points to a static or extern variable statically initialized +to PTHREAD_ONCE_INIT. +

+

The first time pthread_once is called with a given +once_control argument, it calls init_routine with no +argument and changes the value of the once_control variable to +record that initialization has been performed. Subsequent calls to +pthread_once with the same once_control argument do +nothing. +

+

Cancellation

+

While pthread_once is not a cancellation point, +init_routine can be. The effect on once_control of a +cancellation inside the init_routine is to leave it as if +pthread_once had not been called by the cancelled thread.

+

Return Value

+

pthread_once +returns 0 on success, or an error code on failure.

+

Errors

+

The pthread_once function returns the following error code +on error: +

+
+
+
EINVAL +
+
+

+The once_control or init_routine parameter is NULL.

+

Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + \ No newline at end of file diff --git a/w32-pthreads/manual/pthread_rwlock_init.html b/w32-pthreads/manual/pthread_rwlock_init.html new file mode 100644 index 000000000..530df93d4 --- /dev/null +++ b/w32-pthreads/manual/pthread_rwlock_init.html @@ -0,0 +1,193 @@ + + + + + "PTHREAD_RWLOCK_DESTROY"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_rwlock_destroy, pthread_rwlock_init - destroy and +initialize a read-write lock object +

+

Synopsis

+

#include <pthread.h> +

+

pthread_wrlock_t rwlock = +PTHREAD_RWLOCK_INITIALIZER;

+

int pthread_rwlock_destroy(pthread_rwlock_t *rwlock); +
int pthread_rwlock_init(pthread_rwlock_t *restrict
rwlock, +const pthread_rwlockattr_t *restrict attr); +

+

Description

+

The pthread_rwlock_destroy function shall destroy the +read-write lock object referenced by rwlock and release any +resources used by the lock. The effect of subsequent use of the lock +is undefined until the lock is reinitialized by another call to +pthread_rwlock_init. An implementation may cause +pthread_rwlock_destroy to set the object referenced by rwlock +to an invalid value. Results are undefined if pthread_rwlock_destroy +is called when any thread holds rwlock. Attempting to destroy +an uninitialized read-write lock results in undefined behavior. +

+

The pthread_rwlock_init function shall allocate any +resources required to use the read-write lock referenced by rwlock +and initializes the lock to an unlocked state with attributes +referenced by attr. If attr is NULL, the default +read-write lock attributes shall be used; the effect is the same as +passing the address of a default read-write lock attributes object. +Once initialized, the lock can be used any number of times without +being reinitialized. Results are undefined if pthread_rwlock_init +is called specifying an already initialized read-write lock. Results +are undefined if a read-write lock is used without first being +initialized. +

+

If the pthread_rwlock_init function fails, rwlock +shall not be initialized and the contents of rwlock are +undefined. +

+

Pthreads-w32 supports statically initialized rwlock +objects using PTHREAD_RWLOCK_INITIALIZER. +An application should still call pthread_rwlock_destroy at +some point to ensure that any resources consumed by the read/write +lock are released.

+

Only the object referenced by rwlock may be used for +performing synchronization. The result of referring to copies of that +object in calls to pthread_rwlock_destroy , +pthread_rwlock_rdlock , pthread_rwlock_timedrdlock , +pthread_rwlock_timedwrlock , pthread_rwlock_tryrdlock , +pthread_rwlock_trywrlock , pthread_rwlock_unlock , or +pthread_rwlock_wrlock is undefined. +

+

Pthreads-w32 defines _POSIX_READER_WRITER_LOCKS in +pthread.h as 200112L to indicate that the reader/writer routines are +implemented and may be used.

+

Return Value

+

If successful, the pthread_rwlock_destroy and +pthread_rwlock_init functions shall return zero; otherwise, an +error number shall be returned to indicate the error. +

+

The [EBUSY] and [EINVAL] error checks, if implemented, act as if +they were performed immediately at the beginning of processing for +the function and caused an error return prior to modifying the state +of the read-write lock specified by rwlock. +

+

Errors

+

The pthread_rwlock_destroy function may fail if: +

+
+
EBUSY +
+ The implementation has detected an attempt to destroy the object + referenced by rwlock while it is locked. +
+ EINVAL +
+ The value specified by rwlock is invalid. +
+

+The pthread_rwlock_init function shall fail if: +

+
+
EAGAIN +
+ The system lacked the necessary resources (other than memory) to + initialize another read-write lock. +
+ ENOMEM +
+ Insufficient memory exists to initialize the read-write lock. +
+

+
+

+The pthread_rwlock_init function may fail if: +

+
+
EINVAL +
+ The value specified by attr is invalid. +
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

Applications using these and related read-write lock functions may +be subject to priority inversion, as discussed in the Base +Definitions volume of IEEE Std 1003.1-2001, Section 3.285, +Priority Inversion. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_rwlock_rdlock(3) +, pthread_rwlock_timedrdlock(3) +, pthread_rwlock_timedwrlock(3) +, pthread_rwlock_tryrdlock(3) +, pthread_rwlock_trywrlock(3) +, pthread_rwlock_unlock(3) +, pthread_rwlock_wrlock(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_rwlock_rdlock.html b/w32-pthreads/manual/pthread_rwlock_rdlock.html new file mode 100644 index 000000000..3b63f255c --- /dev/null +++ b/w32-pthreads/manual/pthread_rwlock_rdlock.html @@ -0,0 +1,168 @@ + + + + + "PTHREAD_RWLOCK_RDLOCK"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_rwlock_rdlock, pthread_rwlock_tryrdlock - lock a +read-write lock object for reading +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock); +
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock); + +

+

Description

+

The pthread_rwlock_rdlock function shall apply a read lock +to the read-write lock referenced by rwlock. The calling +thread acquires the read lock if a writer does not hold the lock and +there are no writers blocked on the lock. +

+

Pthreads-win32 does not prefer either writers or readers in +acquiring the lock ā€“ all threads enter a single prioritised FIFO +queue. While this may not be optimally efficient for some +applications, it does ensure that one type does not starve the other.

+

A thread may hold multiple concurrent read locks on rwlock +(that is, successfully call the pthread_rwlock_rdlock function +n times). If so, the application shall ensure that the thread +performs matching unlocks (that is, it calls the +pthread_rwlock_unlock(3) +function n times). +

+

The pthread_rwlock_tryrdlock function shall apply a read +lock as in the pthread_rwlock_rdlock function, with the +exception that the function shall fail if the equivalent +pthread_rwlock_rdlock call would have blocked the calling +thread. In no case shall the pthread_rwlock_tryrdlock function +ever block; it always either acquires the lock or fails and returns +immediately. +

+

Results are undefined if any of these functions are called with an +uninitialized read-write lock. +

+

Pthreads-w32 does not detect deadlock if the thread already +owns the lock for writing.

+

Pthreads-w32 defines _POSIX_READER_WRITER_LOCKS in +pthread.h as 200112L to indicate that the reader/writer routines are +implemented and may be used.

+

Return Value

+

If successful, the pthread_rwlock_rdlock function shall +return zero; otherwise, an error number shall be returned to indicate +the error. +

+

The pthread_rwlock_tryrdlock function shall return zero if +the lock for reading on the read-write lock object referenced by +rwlock is acquired. Otherwise, an error number shall be +returned to indicate the error. +

+

Errors

+

The pthread_rwlock_tryrdlock function shall fail if: +

+
+
EBUSY +
+ The read-write lock could not be acquired for reading because a + writer holds the lock or a writer with the appropriate priority was + blocked on it. +
+

+The pthread_rwlock_rdlock and pthread_rwlock_tryrdlock +functions may fail if: +

+
+
EINVAL +
+ The value specified by rwlock does not refer to an + initialized read-write lock object. +
+ EAGAIN +
+ The read lock could not be acquired because the maximum number of + read locks for rwlock has been exceeded. +
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

Applications using these functions may be subject to priority +inversion, as discussed in the Base Definitions volume of +IEEE Std 1003.1-2001, Section 3.285, Priority Inversion. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_rwlock_destroy(3) +, pthread_rwlock_timedrdlock(3) +, pthread_rwlock_timedwrlock(3) +, pthread_rwlock_trywrlock(3) +, pthread_rwlock_unlock(3) +, pthread_rwlock_wrlock(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_rwlock_timedrdlock.html b/w32-pthreads/manual/pthread_rwlock_timedrdlock.html new file mode 100644 index 000000000..1b9ca630f --- /dev/null +++ b/w32-pthreads/manual/pthread_rwlock_timedrdlock.html @@ -0,0 +1,156 @@ + + + + + "PTHREAD_RWLOCK_TIMEDRDLOCK"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_rwlock_timedrdlock - lock a read-write lock for reading +

+

Synopsis

+

#include <pthread.h>
#include <time.h> +

+

int pthread_rwlock_timedrdlock(pthread_rwlock_t *restrict +rwlock, const struct timespec *restrict abs_timeout); + +

+

Description

+

The pthread_rwlock_timedrdlock function shall apply a read +lock to the read-write lock referenced by rwlock as in the +pthread_rwlock_rdlock(3) +function. However, if the lock cannot be acquired without waiting for +other threads to unlock the lock, this wait shall be terminated when +the specified timeout expires. The timeout shall expire when the +absolute time specified by abs_timeout passes, as measured by +the clock on which timeouts are based (that is, when the value of +that clock equals or exceeds abs_timeout), or if the absolute +time specified by abs_timeout has already been passed at the +time of the call. +

+

The timespec data type is defined in the <time.h> +header. Under no circumstances shall the function fail with a timeout +if the lock can be acquired immediately. The validity of the +abs_timeout parameter need not be checked if the lock can be +immediately acquired. +

+

The calling thread may deadlock if at the time the call is made it +holds a write lock on rwlock. The results are undefined if +this function is called with an uninitialized read-write lock. +

+

Pthreads-w32 defines _POSIX_READER_WRITER_LOCKS in +pthread.h as 200112L to indicate that the reader/writer routines are +implemented and may be used.

+

Return Value

+

The pthread_rwlock_timedrdlock function shall return zero +if the lock for reading on the read-write lock object referenced by +rwlock is acquired. Otherwise, an error number shall be +returned to indicate the error. +

+

Errors

+

The pthread_rwlock_timedrdlock function shall fail if: +

+
+
ETIMEDOUT +
+ The lock could not be acquired before the specified timeout expired. +
+

+The pthread_rwlock_timedrdlock function may fail if: +

+
+
EAGAIN +
+ The read lock could not be acquired because the maximum number of + read locks for lock would be exceeded. +
+ EINVAL +
+ The value specified by rwlock does not refer to an + initialized read-write lock object, or the abs_timeout + nanosecond value is less than zero or greater than or equal to 1000 + million. +
+

+This function shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

Applications using this function may be subject to priority +inversion, as discussed in the Base Definitions volume of +IEEE Std 1003.1-2001, Section 3.285, Priority Inversion. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_rwlock_destroy(3) +, pthread_rwlock_rdlock(3) +, pthread_rwlock_timedwrlock(3) +, pthread_rwlock_tryrdlock(3) +, pthread_rwlock_trywrlock(3) +, pthread_rwlock_unlock(3) +, pthread_rwlock_wrlock(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h>, <time.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_rwlock_timedwrlock.html b/w32-pthreads/manual/pthread_rwlock_timedwrlock.html new file mode 100644 index 000000000..0213bab40 --- /dev/null +++ b/w32-pthreads/manual/pthread_rwlock_timedwrlock.html @@ -0,0 +1,150 @@ + + + + + "PTHREAD_RWLOCK_TIMEDWRLOCK"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_rwlock_timedwrlock - lock a read-write lock for writing +

+

Synopsis

+

#include <pthread.h>
#include <time.h> +

+

int pthread_rwlock_timedwrlock(pthread_rwlock_t *restrict +rwlock, const struct timespec *restrict abs_timeout); + +

+

Description

+

The pthread_rwlock_timedwrlock function shall apply a write +lock to the read-write lock referenced by rwlock as in the +pthread_rwlock_wrlock(3) +function. However, if the lock cannot be acquired without waiting for +other threads to unlock the lock, this wait shall be terminated when +the specified timeout expires. The timeout shall expire when the +absolute time specified by abs_timeout passes, as measured by +the clock on which timeouts are based (that is, when the value of +that clock equals or exceeds abs_timeout), or if the absolute +time specified by abs_timeout has already been passed at the +time of the call. +

+

The timespec data type is defined in the <time.h> +header. Under no circumstances shall the function fail with a timeout +if the lock can be acquired immediately. The validity of the +abs_timeout parameter need not be checked if the lock can be +immediately acquired. +

+

The calling thread may deadlock if at the time the call is made it +holds the read-write lock. The results are undefined if this function +is called with an uninitialized read-write lock. +

+

Pthreads-w32 defines _POSIX_READER_WRITER_LOCKS in +pthread.h as 200112L to indicate that the reader/writer routines are +implemented and may be used.

+

Return Value

+

The pthread_rwlock_timedwrlock function shall return zero +if the lock for writing on the read-write lock object referenced by +rwlock is acquired. Otherwise, an error number shall be +returned to indicate the error. +

+

Errors

+

The pthread_rwlock_timedwrlock function shall fail if: +

+
+
ETIMEDOUT +
+ The lock could not be acquired before the specified timeout expired. +
+

+The pthread_rwlock_timedwrlock function may fail if: +

+
+
EINVAL +
+ The value specified by rwlock does not refer to an initialized + read-write lock object, or the abs_timeout nanosecond value + is less than zero or greater than or equal to 1000 million. +
+

+This function shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

Applications using this function may be subject to priority +inversion, as discussed in the Base Definitions volume of +IEEE Std 1003.1-2001, Section 3.285, Priority Inversion. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_rwlock_destroy(3) +, pthread_rwlock_rdlock(3) +, pthread_rwlock_timedrdlock(3) +, pthread_rwlock_tryrdlock(3) +, pthread_rwlock_trywrlock(3) +, pthread_rwlock_unlock(3) +, pthread_rwlock_wrlock(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h>, <time.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_rwlock_unlock.html b/w32-pthreads/manual/pthread_rwlock_unlock.html new file mode 100644 index 000000000..09725cc3e --- /dev/null +++ b/w32-pthreads/manual/pthread_rwlock_unlock.html @@ -0,0 +1,141 @@ + + + + + "PTHREAD_RWLOCK_UNLOCK"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_rwlock_unlock - unlock a read-write lock object +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_rwlock_unlock(pthread_rwlock_t *rwlock); + +

+

Description

+

The pthread_rwlock_unlock function shall release a lock +held on the read-write lock object referenced by rwlock. +Results are undefined if the read-write lock rwlock is not +held by the calling thread. +

+

If this function is called to release a read lock from the +read-write lock object and there are other read locks currently held +on this read-write lock object, the read-write lock object remains in +the read locked state. If this function releases the last read lock +for this read-write lock object, the read-write lock object shall be +put in the unlocked state with no owners. +

+

If this function is called to release a write lock for this +read-write lock object, the read-write lock object shall be put in +the unlocked state. +

+

Pthreads-win32 does not prefer either writers or readers in +acquiring the lock ā€“ all threads enter a single prioritised FIFO +queue. While this may not be optimally efficient for some +applications, it does ensure that one type does not starve the other.

+

Results are undefined if any of these functions are called with an +uninitialized read-write lock. +

+

Pthreads-w32 defines _POSIX_READER_WRITER_LOCKS in +pthread.h as 200112L to indicate that the reader/writer routines are +implemented and may be used.

+

Return Value

+

If successful, the pthread_rwlock_unlock function shall +return zero; otherwise, an error number shall be returned to indicate +the error. +

+

Errors

+

The pthread_rwlock_unlock function may fail if: +

+
+
EINVAL +
+ The value specified by rwlock does not refer to an + initialized read-write lock object. +
+

+
+

+The pthread_rwlock_unlock function shall not return an error +code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

None. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_rwlock_destroy(3) +, pthread_rwlock_rdlock(3) +, pthread_rwlock_timedrdlock(3) +, pthread_rwlock_timedwrlock(3) +, pthread_rwlock_tryrdlock(3) +, pthread_rwlock_trywrlock(3) +, pthread_rwlock_wrlock(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_rwlock_wrlock.html b/w32-pthreads/manual/pthread_rwlock_wrlock.html new file mode 100644 index 000000000..02b3a19ea --- /dev/null +++ b/w32-pthreads/manual/pthread_rwlock_wrlock.html @@ -0,0 +1,153 @@ + + + + + "PTHREAD_RWLOCK_TRYWRLOCK"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_rwlock_trywrlock, pthread_rwlock_wrlock - lock a +read-write lock object for writing +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock); +
int pthread_rwlock_wrlock(pthread_rwlock_t *
rwlock); + +

+

Description

+

The pthread_rwlock_trywrlock function shall apply a write +lock like the pthread_rwlock_wrlock function, with the +exception that the function shall fail if any thread currently holds +rwlock (for reading or writing). +

+

The pthread_rwlock_wrlock function shall apply a write lock +to the read-write lock referenced by rwlock. The calling +thread acquires the write lock if no other thread (reader or writer) +holds the read-write lock rwlock. Otherwise, the thread shall +block until it can acquire the lock. The calling thread may deadlock +if at the time the call is made it holds the read-write lock (whether +a read or write lock). +

+

Pthreads-win32 does not prefer either writers or readers in +acquiring the lock ā€“ all threads enter a single prioritised FIFO +queue. While this may not be optimally efficient for some +applications, it does ensure that one type does not starve the other.

+

Results are undefined if any of these functions are called with an +uninitialized read-write lock. +

+

Pthreads-w32 defines _POSIX_READER_WRITER_LOCKS in +pthread.h as 200112L to indicate that the reader/writer routines are +implemented and may be used.

+

Return Value

+

The pthread_rwlock_trywrlock function shall return zero if +the lock for writing on the read-write lock object referenced by +rwlock is acquired. Otherwise, an error number shall be +returned to indicate the error. +

+

If successful, the pthread_rwlock_wrlock function shall +return zero; otherwise, an error number shall be returned to indicate +the error. +

+

Errors

+

The pthread_rwlock_trywrlock function shall fail if: +

+
+
EBUSY +
+ The read-write lock could not be acquired for writing because it was + already locked for reading or writing. +
+

+The pthread_rwlock_trywrlock and pthread_rwlock_wrlock +functions may fail if: +

+
+
EINVAL +
+ The value specified by rwlock does not refer to an + initialized read-write lock object. +
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

Applications using these functions may be subject to priority +inversion, as discussed in the Base Definitions volume of +IEEE Std 1003.1-2001, Section 3.285, Priority Inversion. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_rwlock_destroy(3) +, pthread_rwlock_rdlock(3) +, pthread_rwlock_timedrdlock(3) +, pthread_rwlock_timedwrlock(3) +, pthread_rwlock_tryrdlock(3) +, pthread_rwlock_unlock(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_rwlockattr_init.html b/w32-pthreads/manual/pthread_rwlockattr_init.html new file mode 100644 index 000000000..67da876cc --- /dev/null +++ b/w32-pthreads/manual/pthread_rwlockattr_init.html @@ -0,0 +1,141 @@ + + + + + "PTHREAD_RWLOCKATTR_DESTROY"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_rwlockattr_destroy, pthread_rwlockattr_init - destroy and +initialize the read-write lock attributes object +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_rwlockattr_destroy(pthread_rwlockattr_t *attr); +
int pthread_rwlockattr_init(pthread_rwlockattr_t *
attr); + +

+

Description

+

The pthread_rwlockattr_destroy function shall destroy a +read-write lock attributes object. A destroyed attr attributes +object can be reinitialized using pthread_rwlockattr_init ; +the results of otherwise referencing the object after it has been +destroyed are undefined. An implementation may cause +pthread_rwlockattr_destroy to set the object referenced by +attr to an invalid value. +

+

The pthread_rwlockattr_init function shall initialize a +read-write lock attributes object attr with the default value +for all of the attributes defined by the implementation. +

+

Results are undefined if pthread_rwlockattr_init is called +specifying an already initialized attr attributes object. +

+

After a read-write lock attributes object has been used to +initialize one or more read-write locks, any function affecting the +attributes object (including destruction) shall not affect any +previously initialized read-write locks. +

+

Pthreads-w32 defines _POSIX_READER_WRITER_LOCKS in +pthread.h as 200112L to indicate that the reader/writer routines are +implemented and may be used.

+

Return Value

+

If successful, the pthread_rwlockattr_destroy and +pthread_rwlockattr_init functions shall return zero; +otherwise, an error number shall be returned to indicate the error. +

+

Errors

+

The pthread_rwlockattr_destroy function may fail if: +

+
+
EINVAL +
+ The value specified by attr is invalid. +
+

+The pthread_rwlockattr_init function shall fail if: +

+
+
ENOMEM +
+ Insufficient memory exists to initialize the read-write lock + attributes object. +
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

None. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_rwlock_destroy(3) +, pthread_rwlockattr_getpshared(3) +, pthread_rwlockattr_setpshared(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_rwlockattr_setpshared.html b/w32-pthreads/manual/pthread_rwlockattr_setpshared.html new file mode 100644 index 000000000..9db6f4cdc --- /dev/null +++ b/w32-pthreads/manual/pthread_rwlockattr_setpshared.html @@ -0,0 +1,160 @@ + + + + + "PTHREAD_RWLOCKATTR_GETPSHARED"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_rwlockattr_getpshared, pthread_rwlockattr_setpshared - get +and set the process-shared attribute of the read-write lock +attributes object +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t * +restrict attr, int *restrict pshared); +
int pthread_rwlockattr_setpshared(pthread_rwlockattr_t *
attr, +int pshared); +

+

Description

+

The pthread_rwlockattr_getpshared function shall obtain the +value of the process-shared attribute from the initialized +attributes object referenced by attr. The +pthread_rwlockattr_setpshared function shall set the +process-shared attribute in an initialized attributes object +referenced by attr. +

+

The process-shared attribute shall be set to +PTHREAD_PROCESS_SHARED to permit a read-write lock to be +operated upon by any thread that has access to the memory where the +read-write lock is allocated, even if the read-write lock is +allocated in memory that is shared by multiple processes. If the +process-shared attribute is PTHREAD_PROCESS_PRIVATE, +the read-write lock shall only be operated upon by threads created +within the same process as the thread that initialized the read-write +lock; if threads of differing processes attempt to operate on such a +read-write lock, the behavior is undefined. The default value of the +process-shared attribute shall be PTHREAD_PROCESS_PRIVATE. +

+

Pthreads-w32 defines _POSIX_THREAD_PROCESS_SHARED in +pthread.h as -1 to indicate that these routines are implemented but +they do not support the process shared option.

+

Additional attributes, their default values, and the names of the +associated functions to get and set those attribute values are +implementation-defined. +

+

Pthreads-w32 defines _POSIX_READER_WRITER_LOCKS in +pthread.h as 200112L to indicate that the reader/writer routines are +implemented and may be used.

+

Return Value

+

Upon successful completion, the pthread_rwlockattr_getpshared +function shall return zero and store the value of the process-shared +attribute of attr into the object referenced by the pshared +parameter. Otherwise, an error number shall be returned to indicate +the error. +

+

If successful, the pthread_rwlockattr_setpshared function +shall return zero; otherwise, an error number shall be returned to +indicate the error. +

+

Errors

+

The pthread_rwlockattr_getpshared and +pthread_rwlockattr_setpshared functions may fail if: +

+
+
EINVAL +
+ The value specified by attr is invalid. +
+

+The pthread_rwlockattr_setpshared function may fail if: +

+
+
EINVAL +
+ The new value specified for the attribute is outside the range of + legal values for that attribute. +
+ ENOTSUP +
+ The new value specified for the attribute is PTHREAD_PROCESS_SHARED. +
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

None. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_rwlock_destroy(3) +, pthread_rwlockattr_destroy(3) +, pthread_rwlockattr_init(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_self.html b/w32-pthreads/manual/pthread_self.html new file mode 100644 index 000000000..82e16eaa7 --- /dev/null +++ b/w32-pthreads/manual/pthread_self.html @@ -0,0 +1,70 @@ + + + + + PTHREAD_SELF(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_self - return identifier of current thread +

+

Synopsis

+

#include <pthread.h> +

+

pthread_t pthread_self(void); +

+

Description

+

pthread_self return the thread identifier for the calling +thread. +

+

Pthreads-w32 also provides support for Win32 native +threads to interact with POSIX threads through the pthreads API. +Whereas all threads created via a call to pthread_create have a POSIX +thread ID and thread state, the library ensures that any Win32 native +threads that interact through the Pthreads API also generate a POSIX +thread ID and thread state when and if necessary. This provides full +reciprocity between Win32 and POSIX +threads. Win32 native threads that generate a POSIX thread ID and +state are treated by the library as having been created with the +PTHREAD_CREATE_DETACHED attribute.

+

Any Win32 native thread may call pthread_self directly to +return it's POSIX thread identifier. The ID and state will be +generated if it does not already exist. Win32 native threads do not +need to call pthread_self before calling Pthreads-w32 routines +unless that routine requires a pthread_t parameter.

+

Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

pthread_equal(3) , +pthread_join(3) , +pthread_detach(3) , +pthread_setschedparam(3) +, pthread_getschedparam(3) +. +

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_setcancelstate.html b/w32-pthreads/manual/pthread_setcancelstate.html new file mode 100644 index 000000000..3ce65c44d --- /dev/null +++ b/w32-pthreads/manual/pthread_setcancelstate.html @@ -0,0 +1,207 @@ + + + + + PTHREAD_CANCEL(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_cancel, pthread_setcancelstate, pthread_setcanceltype, +pthread_testcancel - thread cancellation +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_cancel(pthread_t thread); +

+

int pthread_setcancelstate(int state, int +*oldstate); +

+

int pthread_setcanceltype(int type, int +*oldtype); +

+

void pthread_testcancel(void); +

+

Description

+

Cancellation is the mechanism by which a thread can terminate the +execution of another thread. More precisely, a thread can send a +cancellation request to another thread. Depending on its settings, +the target thread can then either ignore the request, honor it +immediately, or defer it until it reaches a cancellation point. +

+

When a thread eventually honors a cancellation request, it +performs as if pthread_exit(PTHREAD_CANCELED) has been called +at that point: all cleanup handlers are executed in reverse order, +destructor functions for thread-specific data are called, and finally +the thread stops executing with the return value PTHREAD_CANCELED. +See pthread_exit(3) for more +information. +

+

pthread_cancel sends a cancellation request to the thread +denoted by the thread argument. +

+

pthread_setcancelstate changes the cancellation state for +the calling thread -- that is, whether cancellation requests are +ignored or not. The state argument is the new cancellation +state: either PTHREAD_CANCEL_ENABLE to enable cancellation, or +PTHREAD_CANCEL_DISABLE to disable cancellation (cancellation +requests are ignored). If oldstate is not NULL, the +previous cancellation state is stored in the location pointed to by +oldstate, and can thus be restored later by another call to +pthread_setcancelstate. +

+

pthread_setcanceltype changes the type of responses to +cancellation requests for the calling thread: asynchronous +(immediate) or deferred. The type argument is the new +cancellation type: either PTHREAD_CANCEL_ASYNCHRONOUS to +cancel the calling thread as soon as the cancellation request is +received, or PTHREAD_CANCEL_DEFERRED to keep the cancellation +request pending until the next cancellation point. If oldtype +is not NULL, the previous cancellation state is stored in the +location pointed to by oldtype, and can thus be restored later +by another call to pthread_setcanceltype. +

+

Pthreads-w32 provides two levels of support for +PTHREAD_CANCEL_ASYNCHRONOUS: full and partial. Full support +requires an additional DLL and driver be installed on the Windows +system (see the See Also section below) that allows blocked threads +to be cancelled immediately. Partial support means that the target +thread will not cancel until it resumes execution naturally. Partial +support is provided if either the DLL or the driver are not +automatically detected by the pthreads-w32 library at run-time.

+

Threads are always created by pthread_create(3) +with cancellation enabled and deferred. That is, the initial +cancellation state is PTHREAD_CANCEL_ENABLE and the initial +type is PTHREAD_CANCEL_DEFERRED. +

+

Cancellation points are those points in the program execution +where a test for pending cancellation requests is performed and +cancellation is executed if positive. The following POSIX threads +functions are cancellation points: +

+

pthread_join(3) +
pthread_cond_wait(3) +
pthread_cond_timedwait(3) +
pthread_testcancel(3) +
sem_wait(3)
sem_timedwait(3) +
sigwait(3) (not supported under +Pthreads-w32)

+

Pthreads-w32 provides two functions to enable additional +cancellation points to be created in user functions that block on +Win32 HANDLEs:

+

pthreadCancelableWait() +
pthreadCancelableTimedWait()

+

All other POSIX threads functions are guaranteed not to be +cancellation points. That is, they never perform cancellation in +deferred cancellation mode. +

+

pthread_testcancel does nothing except testing for pending +cancellation and executing it. Its purpose is to introduce explicit +checks for cancellation in long sequences of code that do not call +cancellation point functions otherwise. +

+

Return Value

+

pthread_cancel, pthread_setcancelstate and +pthread_setcanceltype return 0 on success and a non-zero error +code on error. +

+

Errors

+

pthread_cancel returns the following error code on error: +

+
+
+
ESRCH +
+ no thread could be found corresponding to that specified by the + thread ID. +
+
+

+pthread_setcancelstate returns the following error code on +error: +

+
+
+
EINVAL +
+ the state argument is not +
+
+
+PTHREAD_CANCEL_ENABLE nor PTHREAD_CANCEL_DISABLE +
+

pthread_setcanceltype returns the following error code on +error: +

+
+
+
EINVAL +
+ the type argument is not +
+
+
+PTHREAD_CANCEL_DEFERRED nor PTHREAD_CANCEL_ASYNCHRONOUS +
+

Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

pthread_exit(3) , +pthread_cleanup_push(3) +, pthread_cleanup_pop(3) +, Pthreads-w32 package README file 'Prerequisites' section. +

+

Bugs

+

POSIX specifies that a number of system calls (basically, all +system calls that may block, such as read(2) +, write(2) , wait(2) +, etc.) and library functions that may call these system calls (e.g. +fprintf(3) ) are cancellation +points. Pthreads-win32 is not integrated enough with the C +library to implement this, and thus none of the C library functions +is a cancellation point. +

+

A workaround for these calls is to temporarily switch to +asynchronous cancellation (assuming full asynchronous cancellation +support is installed). So, checking for cancellation during a read +system call, for instance, can be achieved as follows: +

+


+
+
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldCancelType);
+read(fd, buffer, length);
+pthread_setcanceltype(oldCancelType, NULL);
+
+
Table of Contents
+ + + diff --git a/w32-pthreads/manual/pthread_setcanceltype.html b/w32-pthreads/manual/pthread_setcanceltype.html new file mode 100644 index 000000000..935ed822c --- /dev/null +++ b/w32-pthreads/manual/pthread_setcanceltype.html @@ -0,0 +1,207 @@ + + + + + PTHREAD_CANCEL(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_cancel, pthread_setcancelstate, pthread_setcanceltype, +pthread_testcancel - thread cancellation +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_cancel(pthread_t thread); +

+

int pthread_setcancelstate(int state, int +*oldstate); +

+

int pthread_setcanceltype(int type, int +*oldtype); +

+

void pthread_testcancel(void); +

+

Description

+

Cancellation is the mechanism by which a thread can terminate the +execution of another thread. More precisely, a thread can send a +cancellation request to another thread. Depending on its settings, +the target thread can then either ignore the request, honor it +immediately, or defer it until it reaches a cancellation point. +

+

When a thread eventually honors a cancellation request, it +performs as if pthread_exit(PTHREAD_CANCELED) has been called +at that point: all cleanup handlers are executed in reverse order, +destructor functions for thread-specific data are called, and finally +the thread stops executing with the return value PTHREAD_CANCELED. +See pthread_exit(3) for more +information. +

+

pthread_cancel sends a cancellation request to the thread +denoted by the thread argument. +

+

pthread_setcancelstate changes the cancellation state for +the calling thread -- that is, whether cancellation requests are +ignored or not. The state argument is the new cancellation +state: either PTHREAD_CANCEL_ENABLE to enable cancellation, or +PTHREAD_CANCEL_DISABLE to disable cancellation (cancellation +requests are ignored). If oldstate is not NULL, the +previous cancellation state is stored in the location pointed to by +oldstate, and can thus be restored later by another call to +pthread_setcancelstate. +

+

pthread_setcanceltype changes the type of responses to +cancellation requests for the calling thread: asynchronous +(immediate) or deferred. The type argument is the new +cancellation type: either PTHREAD_CANCEL_ASYNCHRONOUS to +cancel the calling thread as soon as the cancellation request is +received, or PTHREAD_CANCEL_DEFERRED to keep the cancellation +request pending until the next cancellation point. If oldtype +is not NULL, the previous cancellation state is stored in the +location pointed to by oldtype, and can thus be restored later +by another call to pthread_setcanceltype. +

+

Pthreads-w32 provides two levels of support for +PTHREAD_CANCEL_ASYNCHRONOUS: full and partial. Full support +requires an additional DLL and driver be installed on the Windows +system (see the See Also section below) that allows blocked threads +to be cancelled immediately. Partial support means that the target +thread will not cancel until it resumes execution naturally. Partial +support is provided if either the DLL or the driver are not +automatically detected by the pthreads-w32 library at run-time.

+

Threads are always created by pthread_create(3) +with cancellation enabled and deferred. That is, the initial +cancellation state is PTHREAD_CANCEL_ENABLE and the initial +type is PTHREAD_CANCEL_DEFERRED. +

+

Cancellation points are those points in the program execution +where a test for pending cancellation requests is performed and +cancellation is executed if positive. The following POSIX threads +functions are cancellation points: +

+

pthread_join(3) +
pthread_cond_wait(3) +
pthread_cond_timedwait(3) +
pthread_testcancel(3) +
sem_wait(3)
sem_timedwait(3) +
sigwait(3) (not supported under +Pthreads-w32)

+

Pthreads-w32 provides two functions to enable additional +cancellation points to be created in user functions that block on +Win32 HANDLEs:

+

pthreadCancelableWait() +
pthreadCancelableTimedWait()

+

All other POSIX threads functions are guaranteed not to be +cancellation points. That is, they never perform cancellation in +deferred cancellation mode. +

+

pthread_testcancel does nothing except testing for pending +cancellation and executing it. Its purpose is to introduce explicit +checks for cancellation in long sequences of code that do not call +cancellation point functions otherwise. +

+

Return Value

+

pthread_cancel, pthread_setcancelstate and +pthread_setcanceltype return 0 on success and a non-zero error +code on error. +

+

Errors

+

pthread_cancel returns the following error code on error: +

+
+
+
ESRCH +
+ no thread could be found corresponding to that specified by the + thread ID. +
+
+

+pthread_setcancelstate returns the following error code on +error: +

+
+
+
EINVAL +
+ the state argument is not +
+
+
+PTHREAD_CANCEL_ENABLE nor PTHREAD_CANCEL_DISABLE +
+

pthread_setcanceltype returns the following error code on +error: +

+
+
+
EINVAL +
+ the type argument is not +
+
+
+PTHREAD_CANCEL_DEFERRED nor PTHREAD_CANCEL_ASYNCHRONOUS +
+

Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

pthread_exit(3) , +pthread_cleanup_push(3) +, pthread_cleanup_pop(3) +, Pthreads-w32 package README file 'Prerequisites' section. +

+

Bugs

+

POSIX specifies that a number of system calls (basically, all +system calls that may block, such as read(2) +, write(2) , wait(2) +, etc.) and library functions that may call these system calls (e.g. +fprintf(3) ) are cancellation +points. Pthreads-win32 is not integrated enough with the C +library to implement this, and thus none of the C library functions +is a cancellation point. +

+

A workaround for these calls is to temporarily switch to +asynchronous cancellation (assuming full asynchronous cancellation +support is installed). So, checking for cancellation during a read +system call, for instance, can be achieved as follows: +

+


+
+
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldCancelType);
+read(fd, buffer, length);
+pthread_setcanceltype(oldCancelType, NULL);
+
+
Table of Contents
+ + + diff --git a/w32-pthreads/manual/pthread_setconcurrency.html b/w32-pthreads/manual/pthread_setconcurrency.html new file mode 100644 index 000000000..cdd4f5840 --- /dev/null +++ b/w32-pthreads/manual/pthread_setconcurrency.html @@ -0,0 +1,155 @@ + + + + + "PTHREAD_GETCONCURRENCY"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_getconcurrency, pthread_setconcurrency - get and set the +level of concurrency +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_getconcurrency(void);
int +pthread_setconcurrency(int new_level); +

+

Description

+

Unbound threads in a process may or may not be required to be +simultaneously active. By default, the threads implementation ensures +that a sufficient number of threads are active so that the process +can continue to make progress. While this conserves system resources, +it may not produce the most effective level of concurrency. +

+

The pthread_setconcurrency function allows an application +to inform the threads implementation of its desired concurrency +level, new_level. The actual level of concurrency provided by +the implementation as a result of this function call is unspecified. +

+

If new_level is zero, it causes the implementation to +maintain the concurrency level at its discretion as if +pthread_setconcurrency had never been called. +

+

The pthread_getconcurrency function shall return the value +set by a previous call to the pthread_setconcurrency function. +If the pthread_setconcurrency function was not previously +called, this function shall return zero to indicate that the +implementation is maintaining the concurrency level. +

+

A call to pthread_setconcurrency shall inform the +implementation of its desired concurrency level. The implementation +shall use this as a hint, not a requirement. +

+

If an implementation does not support multiplexing of user threads +on top of several kernel-scheduled entities, the +pthread_setconcurrency and pthread_getconcurrency +functions are provided for source code compatibility but they shall +have no effect when called. To maintain the function semantics, the +new_level parameter is saved when pthread_setconcurrency +is called so that a subsequent call to pthread_getconcurrency +shall return the same value. +

+

Pthreads-w32 provides these routines for source code +compatibility only, as described in the previous paragraph.

+

Return Value

+

If successful, the pthread_setconcurrency function shall +return zero; otherwise, an error number shall be returned to indicate +the error. +

+

The pthread_getconcurrency function shall always return the +concurrency level set by a previous call to pthread_setconcurrency +. If the pthread_setconcurrency function has never been +called, pthread_getconcurrency shall return zero. +

+

Errors

+

The pthread_setconcurrency function shall fail if: +

+
+
EINVAL +
+ The value specified by new_level is negative. +
+ EAGAIN +
+ The value specific by new_level would cause a system resource + to be exceeded. +
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

Use of these functions changes the state of the underlying +concurrency upon which the application depends. Library developers +are advised to not use the pthread_getconcurrency and +pthread_setconcurrency functions since their use may conflict +with an applications use of these functions. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

The Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_setschedparam.html b/w32-pthreads/manual/pthread_setschedparam.html new file mode 100644 index 000000000..8dbb9c421 --- /dev/null +++ b/w32-pthreads/manual/pthread_setschedparam.html @@ -0,0 +1,114 @@ + + + + + PTHREAD_SETSCHEDPARAM(3) manual page + + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_setschedparam, pthread_getschedparam - control thread +scheduling +

+

parameters +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_setschedparam(pthread_t target_thread, +int policy, const struct sched_param *param); +

+

int pthread_getschedparam(pthread_t target_thread, +int *policy, struct sched_param *param); +

+

Description

+

pthread_setschedparam sets the scheduling parameters for +the thread target_thread as indicated by policy and +param. policy can be either SCHED_OTHER +(regular, non-real-time scheduling), SCHED_RR (real-time, +round-robin) or SCHED_FIFO (real-time, first-in first-out). +param specifies the scheduling priority for the two real-time +policies.

+

Pthreads-w32 only supports SCHED_OTHER and does not support +the real-time scheduling policies SCHED_RR and SCHED_FIFO. +

+

pthread_getschedparam retrieves the scheduling policy and +scheduling parameters for the thread target_thread and stores +them in the locations pointed to by policy and param, +respectively. +

+

Return Value

+

pthread_setschedparam and pthread_getschedparam +return 0 on success and a non-zero error code on error. +

+

Errors

+

On error, pthread_setschedparam returns the following error +codes: +

+
+
+
ENOTSUP +
+ policy is not SCHED_OTHER.
+ EINVAL +
+ One of the arguments is invalid, or the priority value specified by + param is not valid for the specified policy.
+ ESRCH +
+ The target_thread is invalid or has already terminated +
+
+

+On error, pthread_getschedparam returns the following error +codes: +

+
+
+
ESRCH +
+ the target_thread is invalid or has already terminated +
+
+

+Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

sched_setscheduler(2) +, sched_getscheduler(2) +, sched_getparam(2) , +pthread_attr_setschedpolicy(3) +, pthread_attr_setschedparam(3) +. +

+
+

Table of Contents

+ + + \ No newline at end of file diff --git a/w32-pthreads/manual/pthread_spin_init.html b/w32-pthreads/manual/pthread_spin_init.html new file mode 100644 index 000000000..35e657be4 --- /dev/null +++ b/w32-pthreads/manual/pthread_spin_init.html @@ -0,0 +1,176 @@ + + + + + "PTHREAD_SPIN_DESTROY"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_spin_destroy, pthread_spin_init - destroy or initialize a +spin lock object (ADVANCED REALTIME THREADS) +

+

Synopsis

+

#include <pthread.h> +

+

pthread_spinlock_t lock = +PTHREAD_SPINLOCK_INITIALIZER;

+

int pthread_spin_destroy(pthread_spinlock_t *lock); +
int pthread_spin_init(pthread_spinlock_t *
lock, int +pshared); +

+

Description

+

The pthread_spin_destroy function shall destroy the spin +lock referenced by lock and release any resources used by the +lock. The effect of subsequent use of the lock is undefined until the +lock is reinitialized by another call to pthread_spin_init . +The results are undefined if pthread_spin_destroy is called +when a thread holds the lock, or if this function is called with an +uninitialized thread spin lock. +

+

The pthread_spin_init function shall allocate any resources +required to use the spin lock referenced by lock and +initialize the lock to an unlocked state. +

+

Pthreads-w32 supports single and multiple processor systems +as well as process CPU affinity masking by checking the mask when the +spin lock is initialized. If the process is using only a single +processor at the time pthread_spin_init is called then the +spin lock is initialized as a PTHREAD_MUTEX_NORMAL mutex object. A +thread that calls pthread_spin_lock(3) +will block rather than spin in this case. If the process CPU affinity +mask is altered after the spin lock has been initialised, the spin +lock is not modified, and may no longer be optimal for the number of +CPUs available.

+

Pthreads-w32 defines _POSIX_THREAD_PROCESS_SHARED in +pthread.h as -1 to indicate that these routines do not support the +PTHREAD_PROCESS_SHARED attribute. pthread_spin_init +will return the error ENOTSUP if the value of pshared +is not PTHREAD_PROCESS_PRIVATE.

+

The results are undefined if pthread_spin_init is called +specifying an already initialized spin lock. The results are +undefined if a spin lock is used without first being initialized. +

+

If the pthread_spin_init function fails, the lock is not +initialized and the contents of lock are undefined. +

+

Only the object referenced by lock may be used for +performing synchronization. +

+

The result of referring to copies of that object in calls to +pthread_spin_destroy , pthread_spin_lock(3) +, pthread_spin_trylock(3), +or pthread_spin_unlock(3) +is undefined. +

+

Pthreads-w32 supports statically initialized spin locks +using PTHREAD_SPINLOCK_INITIALIZER. An application should +still call pthread_spin_destroy at some point to ensure that +any resources consumed by the spin lock are released.

+

Return Value

+

Upon successful completion, these functions shall return zero; +otherwise, an error number shall be returned to indicate the error. +

+

Errors

+

These functions may fail if: +

+
+
EBUSY +
+ The implementation has detected an attempt to initialize or destroy + a spin lock while it is in use (for example, while being used in a + pthread_spin_lock(3) + call) by another thread. +
+ EINVAL +
+ The value specified by lock is invalid. +
+

+The pthread_spin_init function shall fail if: +

+
+
ENOTSUP +
+ The value of pshared is not PTHREAD_PROCESS_PRIVATE.
+ ENOMEM +
+ Insufficient memory exists to initialize the lock. +
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

The pthread_spin_destroy and pthread_spin_init +functions are part of the Spin Locks option and need not be provided +on all implementations. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_spin_lock(3) , +pthread_spin_unlock(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_spin_lock.html b/w32-pthreads/manual/pthread_spin_lock.html new file mode 100644 index 000000000..dd180ae6a --- /dev/null +++ b/w32-pthreads/manual/pthread_spin_lock.html @@ -0,0 +1,141 @@ + + + + + "PTHREAD_SPIN_LOCK"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_spin_lock, pthread_spin_trylock - lock a spin lock object +(ADVANCED REALTIME THREADS) +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_spin_lock(pthread_spinlock_t *lock); +
int pthread_spin_trylock(pthread_spinlock_t *
lock); + +

+

Description

+

The pthread_spin_lock function shall lock the spin lock +referenced by lock. The calling thread shall acquire the lock +if it is not held by another thread. Otherwise, the thread shall spin +(that is, shall not return from the pthread_spin_lock call) +until the lock becomes available. The results are undefined if the +calling thread holds the lock at the time the call is made.

+

Pthreads-w32 supports single and multiple processor systems +as well as process CPU affinity masking by checking the mask when the +spin lock is initialized. If the process is using only a single +processor at the time pthread_spin_init(3) +is called then the spin lock is initialized as a PTHREAD_MUTEX_NORMAL +mutex object. A thread that calls pthread_spin_lock will block +rather than spin in this case. If the process CPU affinity mask is +altered after the spin lock has been initialised, the spin lock is +not modified, and may no longer be optimal for the number of CPUs +available.

+

The pthread_spin_trylock function shall lock the spin lock +referenced by lock if it is not held by any thread. Otherwise, +the function shall fail. +

+

The results are undefined if any of these functions is called with +an uninitialized spin lock. +

+

Return Value

+

Upon successful completion, these functions shall return zero; +otherwise, an error number shall be returned to indicate the error. +

+

Errors

+

These functions may fail if: +

+
+
EINVAL +
+ The value specified by lock does not refer to an initialized + spin lock object. +
+

+The pthread_spin_trylock function shall fail if: +

+
+
EBUSY +
+ A thread currently holds the lock. +
+

+These functions shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

Applications using this function may be subject to priority +inversion, as discussed in the Base Definitions volume of +IEEE Std 1003.1-2001, Section 3.285, Priority Inversion. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_spin_destroy(3) +, pthread_spin_unlock(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_spin_unlock.html b/w32-pthreads/manual/pthread_spin_unlock.html new file mode 100644 index 000000000..221570058 --- /dev/null +++ b/w32-pthreads/manual/pthread_spin_unlock.html @@ -0,0 +1,124 @@ + + + + + "PTHREAD_SPIN_UNLOCK"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_spin_unlock - unlock a spin lock object (ADVANCED +REALTIME THREADS) +

+

Synopsis

+

#include <pthread.h> +

+

int pthread_spin_unlock(pthread_spinlock_t *lock); + +

+

Description

+

The pthread_spin_unlock function shall release the spin +lock referenced by lock which was locked via the +pthread_spin_lock(3) or +pthread_spin_trylock(3) +functions. If there are threads spinning on the lock when +pthread_spin_unlock is called, the lock becomes available and +an unspecified spinning thread shall acquire the lock. +

+

Pthreads-w32 does not check ownership of the lock and it is +therefore possible for a thread other than the locker to unlock the +spin lock. This is not a feature that should be exploited.

+

The results are undefined if this function is called with an +uninitialized thread spin lock. +

+

Return Value

+

Upon successful completion, the pthread_spin_unlock +function shall return zero; otherwise, an error number shall be +returned to indicate the error. +

+

Errors

+

The pthread_spin_unlock function may fail if: +

+
+
EINVAL +
+ An invalid argument was specified. +
+
+
+

+This function shall not return an error code of [EINTR]. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

Pthreads-w32 does not check ownership of the lock and it is +therefore possible for a thread other than the locker to unlock the +spin lock. This is not a feature that should be exploited.

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

pthread_spin_destroy(3) +, pthread_spin_lock(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<pthread.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_timechange_handler_np.html b/w32-pthreads/manual/pthread_timechange_handler_np.html new file mode 100644 index 000000000..54226da7d --- /dev/null +++ b/w32-pthreads/manual/pthread_timechange_handler_np.html @@ -0,0 +1,76 @@ + + + + + PTHREAD_TIMECHANGE_HANDLER_NP manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_timechange_handler_np ā€“ +alert timed waiting condition variables to system time changes.

+

Synopsis

+

#include <pthread.h> +

+

void * pthread_timechange_handler_np(void * dummy);

+

Description

+

To improve tolerance against operator or time service initiated +system clock changes.

+

pthread_timechange_handler_np can be called by an +application when it receives a WM_TIMECHANGE message from the system. +At present it broadcasts all condition variables so that waiting +threads can wake up and re-evaluate their conditions and restart +their timed waits if required.

+

pthread_timechange_handler_np has the same return type and +argument type as a thread routine so that it may be called directly +through pthread_create(), i.e. as a separate thread. If run as a +thread, the return code must be retrieved through pthread_join().

+

Although the dummy parameter is required it is not used and +any value including NULL can be given.

+

Cancellation

+

None.

+

Return Value

+

pthread_timechange_handler_np returns 0 on success, or an +error code.

+

Errors

+

The pthread_timechange_handler_np function returns the +following error code on error: +

+
+
+
EAGAIN +
+
+

+To indicate that not all condition variables were signalled for some +reason.

+

Author

+

Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_win32_attach_detach_np.html b/w32-pthreads/manual/pthread_win32_attach_detach_np.html new file mode 100644 index 000000000..f8cfc361f --- /dev/null +++ b/w32-pthreads/manual/pthread_win32_attach_detach_np.html @@ -0,0 +1,74 @@ + + + + + PTHREAD_WIN32_ATTACH_DETACH_NP manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_win32_process_attach_np, +pthread_win32_process_detach_np, pthread_win32_thread_attach_np, +pthread_win32_thread_detach_np ā€“ exposed versions of the +pthreads-w32 DLL dllMain() switch functionality for use when +statically linking the library.

+

Synopsis

+

#include <pthread.h> +

+

BOOL pthread_win32_process_attach_np (void);

+

BOOL pthread_win32_process_detach_np (void);

+

BOOL pthread_win32_thread_attach_np (void);

+

BOOL pthread_win32_thread_detach_np (void);

+

Description

+

These functions contain the code normally run via dllMain +when the library is used as a dll but which need to be called +explicitly by an application when the library is statically linked. As of version 2.9.0, the static library built using either MSC or GCC includes RT hooks which will call the pthread_win32_process_*_np routines automatically on start/exit of the application.

+

You will need to call pthread_win32_process_attach_np +before you can call any pthread routines when statically linking. You +should call pthread_win32_process_detach_np before exiting +your application to clean up.

+

pthread_win32_thread_attach_np is currently a no-op, but +pthread_win32_thread_detach_np is needed to clean up the +implicit pthread handle that is allocated to a Win32 thread if it +calls certain pthreads routines. Call this routine when the Win32 +thread exits.

+

These functions invariably return TRUE except for +pthread_win32_process_attach_np which will return FALSE if +pthreads-w32 initialisation fails.

+

Cancellation

+

None.

+

Return Value

+

These routines return TRUE (non-zero) on success, or FALSE (0) if +they fail.

+

Errors

+

None.

+

Author

+

Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/pthread_win32_test_features_np.html b/w32-pthreads/manual/pthread_win32_test_features_np.html new file mode 100644 index 000000000..1d8e11233 --- /dev/null +++ b/w32-pthreads/manual/pthread_win32_test_features_np.html @@ -0,0 +1,68 @@ + + + + + PTHREAD_WIN32_TEST_FEATURES_NP manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

pthread_win32_test_features_np ā€“ +find out what features were detected at process attach time.

+

Synopsis

+

#include <pthread.h> +

+

BOOL pthread_win32_test_features_np(int mask);

+

Description

+

pthread_win32_test_features_np allows an application to +check which run-time auto-detected features are available within the +library.

+

The possible features are:

+

PTW32_SYSTEM_INTERLOCKED_COMPARE_EXCHANGE

+

Return TRUE if the Win32 version of +InterlockedCompareExchange() is being used. On IA32 systems the +library can use optimised and inlinable assembler versions of +InterlockedExchange() and InterlockedCompareExchange().

+

PTW32_ALERTABLE_ASYNC_CANCEL

+

Return TRUE if the QueueUserAPCEx package +QUSEREX.DLL and the AlertDrv.sys driver was detected. This package +provides alertable (pre-emptive) asynchronous threads cancellation. +If this feature returns FALSE then the default async cancel scheme is +in use, which cannot cancel blocked threads.

+

Cancellation

+

None.

+

Return Value

+

pthread_win32_test_features_np returns TRUE (non-zero) if +the specified feature is present, and FALSE (0) otherwise.

+

Errors

+

None.

+

Author

+

Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + \ No newline at end of file diff --git a/w32-pthreads/manual/sched_get_priority_max.html b/w32-pthreads/manual/sched_get_priority_max.html new file mode 100644 index 000000000..54869029b --- /dev/null +++ b/w32-pthreads/manual/sched_get_priority_max.html @@ -0,0 +1,115 @@ + + + + + "SCHED_GET_PRIORITY_MAX"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

sched_get_priority_max, sched_get_priority_min - get priority +limits (REALTIME) +

+

Synopsis

+

#include <sched.h> +

+

int sched_get_priority_max(int policy);
int +sched_get_priority_min(int
policy); +

+

Description

+

The sched_get_priority_max and sched_get_priority_min +functions shall return the appropriate maximum or minimum, +respectively, for the scheduling policy specified by policy. +

+

The value of policy shall be one of the scheduling policy +values defined in <sched.h>. +

+

Return Value

+

If successful, the sched_get_priority_max and +sched_get_priority_min functions shall return the appropriate +maximum or minimum values, respectively. If unsuccessful, they shall +return a value of -1 and set errno to indicate the error. +

+

Errors

+

The sched_get_priority_max and sched_get_priority_min +functions shall fail if: +

+
+
EINVAL +
+ The value of the policy parameter does not represent a + defined scheduling policy. +
+

+The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

None. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

sched_getscheduler(3) +, sched_setscheduler(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<sched.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + \ No newline at end of file diff --git a/w32-pthreads/manual/sched_getscheduler.html b/w32-pthreads/manual/sched_getscheduler.html new file mode 100644 index 000000000..0089e244f --- /dev/null +++ b/w32-pthreads/manual/sched_getscheduler.html @@ -0,0 +1,127 @@ + + + + + "SCHED_GETSCHEDULER"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

sched_getscheduler - get scheduling policy (REALTIME) +

+

Synopsis

+

#include <sched.h> +

+

int sched_getscheduler(pid_t pid); +

+

Description

+

The sched_getscheduler function shall return the scheduling +policy of the process specified by pid. If the value of pid +is negative, the behavior of the sched_getscheduler function +is unspecified. +

+

The values that can be returned by sched_getscheduler are +defined in the <sched.h> header. +

+

Pthreads-w32 only supports the SCHED_OTHER policy, +which is the only value that can be returned. However, checks on pid +and permissions are performed first so that the other useful side +effects of this routine are retained.

+

If a process specified by pid exists, and if the calling +process has permission, the scheduling policy shall be returned for +the process whose process ID is equal to pid. +

+

If pid is zero, the scheduling policy shall be returned for +the calling process. +

+

Return Value

+

Upon successful completion, the sched_getscheduler function +shall return the scheduling policy of the specified process. If +unsuccessful, the function shall return -1 and set errno to +indicate the error. +

+

Errors

+

The sched_getscheduler function shall fail if: +

+
+
EPERM +
+ The requesting process does not have permission to determine the + scheduling policy of the specified process. +
+ ESRCH +
+ No process can be found corresponding to that specified by pid. +
+

+The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

None. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

sched_setscheduler(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<sched.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/sched_setscheduler.html b/w32-pthreads/manual/sched_setscheduler.html new file mode 100644 index 000000000..c6e62ae0d --- /dev/null +++ b/w32-pthreads/manual/sched_setscheduler.html @@ -0,0 +1,181 @@ + + + + + "SCHED_SETSCHEDULER"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

sched_setscheduler - set scheduling policy and parameters +(REALTIME) +

+

Synopsis

+

#include <sched.h> +

+

int sched_setscheduler(pid_t pid, int policy, +const struct sched_param *param); +

+

Description

+

The sched_setscheduler function shall set the scheduling +policy and scheduling parameters of the process specified by pid +to policy and the parameters specified in the sched_param +structure pointed to by param, respectively. The value of the +sched_priority member in the sched_param structure +shall be any integer within the inclusive priority range for the +scheduling policy specified by policy. If the value of pid +is negative, the behavior of the sched_setscheduler function +is unspecified. +

+

The possible values for the policy parameter are defined in +the <sched.h> header. +

+

Pthreads-w32 only supports the SCHED_OTHER policy. +Any other value for policy will return failure with errno set +to ENOSYS. However, checks on pid and permissions are +performed first so that the other useful side effects of this routine +are retained.

+

If a process specified by pid exists, and if the calling +process has permission, the scheduling policy and scheduling +parameters shall be set for the process whose process ID is equal to +pid. +

+

If pid is zero, the scheduling policy and scheduling +parameters shall be set for the calling process. +

+

Implementations may require that the requesting process have +permission to set its own scheduling parameters or those of another +process. Additionally, implementation-defined restrictions may apply +as to the appropriate privileges required to set a processā€™ own +scheduling policy, or another processā€™ scheduling policy, to a +particular value. +

+

The sched_setscheduler function shall be considered +successful if it succeeds in setting the scheduling policy and +scheduling parameters of the process specified by pid to the +values specified by policy and the structure pointed to by +param, respectively. +

+

The effect of this function on individual threads is dependent on +the scheduling contention scope of the threads: +

+
+
* +
+ For threads with system scheduling contention scope, these functions + shall have no effect on their scheduling. +
+ * +
+ For threads with process scheduling contention scope, the threadsā€™ + scheduling policy and associated parameters shall not be affected. + However, the scheduling of these threads with respect to threads in + other processes may be dependent on the scheduling parameters of + their process, which are governed using these functions. +
+

+This function is not atomic with respect to other threads in the +process. Threads may continue to execute while this function call is +in the process of changing the scheduling policy and associated +scheduling parameters for the underlying kernel-scheduled entities +used by the process contention scope threads. +

+

Return Value

+

Upon successful completion, the function shall return the former +scheduling policy of the specified process. If the sched_setscheduler +function fails to complete successfully, the policy and scheduling +parameters shall remain unchanged, and the function shall return a +value of -1 and set errno to indicate the error. +

+

Errors

+

The sched_setscheduler function shall fail if: +

+
+
EINVAL +
+ The value of the policy parameter is invalid, or one or more + of the parameters contained in param is outside the valid + range for the specified scheduling policy. +
+ EPERM +
+ The requesting process does not have permission to set either or + both of the scheduling parameters or the scheduling policy of the + specified process. +
+ ESRCH +
+ No process can be found corresponding to that specified by pid. +
+

+The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

None. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

sched_getscheduler(3) +, the Base Definitions volume of IEEE Std 1003.1-2001, +<sched.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+

Modified by Ross Johnson for use with Pthreads-w32.

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/sched_yield.html b/w32-pthreads/manual/sched_yield.html new file mode 100644 index 000000000..fa5ed04d5 --- /dev/null +++ b/w32-pthreads/manual/sched_yield.html @@ -0,0 +1,98 @@ + + + + + "SCHED_YIELD"(P) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

sched_yield - yield the processor +

+

Synopsis

+

#include <sched.h> +

+

int sched_yield(void); +

+

Description

+

The sched_yield function shall force the running thread to +relinquish the processor until it again becomes the head of its +thread list. It takes no arguments. +

+

Return Value

+

The sched_yield function shall return 0 if it completes +successfully; otherwise, it shall return a value of -1 and set errno +to indicate the error. +

+

Errors

+

No errors are defined. +

+

The following sections are informative. +

+

Examples

+

None. +

+

Application Usage

+

None. +

+

Rationale

+

None. +

+

Future Directions

+

None. +

+

See Also

+

The Base Definitions volume of IEEE Std 1003.1-2001, +<sched.h> +

+

Copyright

+

Portions of this text are reprinted and reproduced in electronic +form from IEEE Std 1003.1, 2003 Edition, Standard for Information +Technology -- Portable Operating System Interface (POSIX), The Open +Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the +Institute of Electrical and Electronics Engineers, Inc and The Open +Group. In the event of any discrepancy between this version and the +original IEEE and The Open Group Standard, the original IEEE and The +Open Group Standard is the referee document. The original Standard +can be obtained online at http://www.opengroup.org/unix/online.html +. +

+
+

Table of Contents

+ + + diff --git a/w32-pthreads/manual/sem_init.html b/w32-pthreads/manual/sem_init.html new file mode 100644 index 000000000..80e0580dc --- /dev/null +++ b/w32-pthreads/manual/sem_init.html @@ -0,0 +1,200 @@ + + + + + SEMAPHORES(3) manual page + + + + + + + +

POSIX Threads for Windows ā€“ REFERENCE - Pthreads-w32

+

Reference Index

+

Table of Contents

+

Name

+

sem_init, sem_wait, sem_trywait, sem_post, sem_getvalue, +sem_destroy - operations on semaphores +

+

Synopsis

+

#include <semaphore.h> +

+

int sem_init(sem_t *sem, int pshared, +unsigned int value); +

+

int sem_wait(sem_t * sem); +

+

int sem_timedwait(sem_t * sem, const struct +timespec *abstime); +

+

int sem_trywait(sem_t * sem); +

+

int sem_post(sem_t * sem); +

+

int sem_post_multiple(sem_t * sem, int +number); +

+

int sem_getvalue(sem_t * sem, int * sval); +

+

int sem_destroy(sem_t * sem); +

+

Description

+

Semaphores are counters for resources shared between threads. The +basic operations on semaphores are: increment the counter atomically, +and wait until the counter is non-null and decrement it atomically. +

+

sem_init initializes the semaphore object pointed to by +sem. The count associated with the semaphore is set initially +to value. The pshared argument indicates whether the +semaphore is local to the current process ( pshared is zero) +or is to be shared between several processes ( pshared is not +zero).

+

Pthreads-w32 currently does not support process-shared +semaphores, thus sem_init always returns with error EPERM +if pshared is not zero. +

+

sem_wait atomically decrements sem's count if it is +greater than 0 and returns immediately or it suspends the calling +thread until it can resume following a call to sem_post or +sem_post_multiple.

+

sem_timedwait atomically decrements sem's count if +it is greater than 0 and returns immediately, or it suspends the +calling thread. If abstime time arrives before the thread can +resume following a call to sem_post or sem_post_multiple, +then sem_timedwait returns with a return code of -1 after +having set errno to ETIMEDOUT. If the call can return +without suspending then abstime is not checked.

+

sem_trywait atomically decrements sem's count if it +is greater than 0 and returns immediately, or it returns immediately +with a return code of -1 after having set errno to EAGAIN. +sem_trywait never blocks.

+

sem_post either releases one thread if there are any +waiting on sem, or it atomically increments sem's +count.

+

sem_post_multiple either releases multiple threads if there +are any waiting on sem and/or it atomically increases sem's +count. If there are currently n waiters, where n the +largest number less than or equal to number, then n +waiters are released and sem's count is incremented by number +minus n.

+

sem_getvalue stores in the location pointed to by sval +the current count of the semaphore sem. In the Pthreads-w32 +implementation: if the value returned in sval is greater than +or equal to 0 it was the sem's count at some point during the +call to sem_getvalue. If the value returned in sval is +less than 0 then it's absolute value represents the number of threads +waiting on sem at some point during the call to sem_getvalue. +POSIX does not require an implementation of sem_getvalue +to return a value in sval that is less than 0, but if it does +then it's absolute value must represent the number of waiters.

+

sem_destroy destroys a semaphore object, freeing the +resources it might hold. No threads should be waiting on the +semaphore at the time sem_destroy is called.

+

Cancellation

+

sem_wait and sem_timedwait are cancellation points. +

+

Async-signal Safety

+

These routines are not async-cancel safe.

+

Return Value

+

All semaphore functions return 0 on success, or -1 on error in +which case they write an error code in errno. +

+

Errors

+

The sem_init function sets errno to the following +codes on error: +

+
+
+
EINVAL +
+ value exceeds the maximal counter value SEM_VALUE_MAX +
+ ENOSYS +
+
+
+pshared is not zero +
+

The sem_timedwait function sets errno to the +following error code on error: +

+
+
+
ETIMEDOUT +
+
+
+if abstime arrives before the waiting thread can resume +following a call to sem_post or sem_post_multiple. +
+

The sem_trywait function sets errno to the following +error code on error: +

+
+
+
EAGAIN +
+
+
+if the semaphore count is currently 0 +
+

The sem_post and sem_post_multiple functions set +errno to the following error code on error: +

+
+
+
ERANGE +
+ if after incrementing, the semaphore count would exceed + SEM_VALUE_MAX (the semaphore count is left unchanged in this + case) +
+
+

+The sem_destroy function sets errno to the following +error code on error: +

+
+
+
EBUSY +
+ if some threads are currently blocked waiting on the semaphore. +
+
+

+Author

+

Xavier Leroy <Xavier.Leroy@inria.fr> +

+

Modified by Ross Johnson for use with Pthreads-w32.

+

See Also

+

pthread_mutex_init(3) +, pthread_cond_init(3) , +pthread_cancel(3) . +

+
+

Table of Contents

+ + + \ No newline at end of file diff --git a/w32-pthreads/misc.c b/w32-pthreads/misc.c new file mode 100644 index 000000000..06d1d2137 --- /dev/null +++ b/w32-pthreads/misc.c @@ -0,0 +1,50 @@ +/* + * misc.c + * + * Description: + * This translation unit implements miscellaneous thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +#include "pthread_kill.c" +#include "pthread_once.c" +#include "pthread_self.c" +#include "pthread_equal.c" +#include "pthread_setconcurrency.c" +#include "pthread_getconcurrency.c" +#include "ptw32_new.c" +#include "ptw32_calloc.c" +#include "ptw32_reuse.c" +#include "w32_CancelableWait.c" diff --git a/w32-pthreads/mutex.c b/w32-pthreads/mutex.c new file mode 100644 index 000000000..c2b3607ca --- /dev/null +++ b/w32-pthreads/mutex.c @@ -0,0 +1,62 @@ +/* + * mutex.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#if ! defined(_UWIN) && ! defined(WINCE) +# include +#endif +#if !defined(NEED_FTIME) +#include +#endif +#include "pthread.h" +#include "implement.h" + + +#include "ptw32_mutex_check_need_init.c" +#include "pthread_mutex_init.c" +#include "pthread_mutex_destroy.c" +#include "pthread_mutexattr_init.c" +#include "pthread_mutexattr_destroy.c" +#include "pthread_mutexattr_getpshared.c" +#include "pthread_mutexattr_setpshared.c" +#include "pthread_mutexattr_settype.c" +#include "pthread_mutexattr_gettype.c" +#include "pthread_mutexattr_setrobust.c" +#include "pthread_mutexattr_getrobust.c" +#include "pthread_mutex_lock.c" +#include "pthread_mutex_timedlock.c" +#include "pthread_mutex_unlock.c" +#include "pthread_mutex_trylock.c" +#include "pthread_mutex_consistent.c" diff --git a/w32-pthreads/need_errno.h b/w32-pthreads/need_errno.h new file mode 100644 index 000000000..abf1c9557 --- /dev/null +++ b/w32-pthreads/need_errno.h @@ -0,0 +1,145 @@ +/*** +* errno.h - system wide error numbers (set by system calls) +* +* Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved. +* +* Purpose: +* This file defines the system-wide error numbers (set by +* system calls). Conforms to the XENIX standard. Extended +* for compatibility with Uniforum standard. +* [System V] +* +* [Public] +* +****/ + +#if _MSC_VER > 1000 +#pragma once +#endif + +#if !defined(_INC_ERRNO) +#define _INC_ERRNO + +#if !defined(_WIN32) +#error ERROR: Only Win32 targets supported! +#endif + +#include + +#if defined(__cplusplus) +extern "C" { +#endif + + + +/* Define _CRTIMP */ + +#ifndef _CRTIMP +#if defined(_DLL) +#define _CRTIMP __declspec(dllimport) +#else /* ndef _DLL */ +#define _CRTIMP +#endif /* _DLL */ +#endif /* _CRTIMP */ + + +/* Define __cdecl for non-Microsoft compilers */ + +#if ( !defined(_MSC_VER) && !defined(__cdecl) ) +#define __cdecl +#endif + +/* Define _CRTAPI1 (for compatibility with the NT SDK) */ + +#if !defined(_CRTAPI1) +#if _MSC_VER >= 800 && _M_IX86 >= 300 +#define _CRTAPI1 __cdecl +#else +#define _CRTAPI1 +#endif +#endif + +#if !defined(PTW32_STATIC_LIB) +# if defined(PTW32_BUILD) +# define PTW32_DLLPORT __declspec (dllexport) +# else +# define PTW32_DLLPORT __declspec (dllimport) +# endif +#else +# define PTW32_DLLPORT +#endif + +/* declare reference to errno */ + +#if (defined(_MT) || defined(_MD) || defined(_DLL)) && !defined(_MAC) +PTW32_DLLPORT int * __cdecl _errno(void); +#define errno (*_errno()) +#else /* ndef _MT && ndef _MD && ndef _DLL */ +_CRTIMP extern int errno; +#endif /* _MT || _MD || _DLL */ + +/* Error Codes */ + +#define EPERM 1 +#define ENOENT 2 +#define ESRCH 3 +#define EINTR 4 +#define EIO 5 +#define ENXIO 6 +#define E2BIG 7 +#define ENOEXEC 8 +#define EBADF 9 +#define ECHILD 10 +#define EAGAIN 11 +#define ENOMEM 12 +#define EACCES 13 +#define EFAULT 14 +#define EBUSY 16 +#define EEXIST 17 +#define EXDEV 18 +#define ENODEV 19 +#define ENOTDIR 20 +#define EISDIR 21 +#define EINVAL 22 +#define ENFILE 23 +#define EMFILE 24 +#define ENOTTY 25 +#define EFBIG 27 +#define ENOSPC 28 +#define ESPIPE 29 +#define EROFS 30 +#define EMLINK 31 +#define EPIPE 32 +#define EDOM 33 +#define ERANGE 34 +#define EDEADLK 36 + +/* defined differently in winsock.h on WinCE */ +#if !defined(ENAMETOOLONG) +#define ENAMETOOLONG 38 +#endif + +#define ENOLCK 39 +#define ENOSYS 40 + +/* defined differently in winsock.h on WinCE */ +#if !defined(ENOTEMPTY) +#define ENOTEMPTY 41 +#endif + +#define EILSEQ 42 + +/* POSIX 2008 - robust mutexes */ +#define EOWNERDEAD 43 +#define ENOTRECOVERABLE 44 + +/* + * Support EDEADLOCK for compatibiity with older MS-C versions. + */ +#define EDEADLOCK EDEADLK + +#if defined(__cplusplus) +} +#endif + +#endif /* _INC_ERRNO */ diff --git a/w32-pthreads/nonportable.c b/w32-pthreads/nonportable.c new file mode 100644 index 000000000..742cb969b --- /dev/null +++ b/w32-pthreads/nonportable.c @@ -0,0 +1,47 @@ +/* + * nonportable.c + * + * Description: + * This translation unit implements non-portable thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +#include "pthread_mutexattr_setkind_np.c" +#include "pthread_mutexattr_getkind_np.c" +#include "pthread_getw32threadhandle_np.c" +#include "pthread_getunique_np.c" +#include "pthread_delay_np.c" +#include "pthread_num_processors_np.c" +#include "pthread_win32_attach_detach_np.c" +#include "pthread_timechange_handler_np.c" diff --git a/w32-pthreads/private.c b/w32-pthreads/private.c new file mode 100644 index 000000000..1b1ccb7c5 --- /dev/null +++ b/w32-pthreads/private.c @@ -0,0 +1,54 @@ +/* + * private.c + * + * Description: + * This translation unit implements routines which are private to + * the implementation and may be used throughout it. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +#include "ptw32_MCS_lock.c" +#include "ptw32_is_attr.c" +#include "ptw32_processInitialize.c" +#include "ptw32_processTerminate.c" +#include "ptw32_threadStart.c" +#include "ptw32_threadDestroy.c" +#include "ptw32_tkAssocCreate.c" +#include "ptw32_tkAssocDestroy.c" +#include "ptw32_callUserDestroyRoutines.c" +#include "ptw32_semwait.c" +#include "ptw32_timespec.c" +#include "ptw32_relmillisecs.c" +#include "ptw32_throw.c" +#include "ptw32_getprocessors.c" diff --git a/w32-pthreads/pthread.c b/w32-pthreads/pthread.c new file mode 100644 index 000000000..60b53412b --- /dev/null +++ b/w32-pthreads/pthread.c @@ -0,0 +1,66 @@ +/* + * pthread.c + * + * Description: + * This translation unit agregates pthreads-win32 translation units. + * It is used for inline optimisation of the library, + * maximising for speed at the expense of size. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* The following are ordered for inlining */ + +#include "private.c" +#include "attr.c" +#include "barrier.c" +#include "cancel.c" +#include "cleanup.c" +#include "condvar.c" +#include "create.c" +#include "dll.c" +#include "autostatic.c" +#include "errno.c" +#include "exit.c" +#include "fork.c" +#include "global.c" +#include "misc.c" +#include "mutex.c" +#include "nonportable.c" +#include "rwlock.c" +#include "sched.c" +#include "semaphore.c" +#include "signal.c" +#include "spin.c" +#include "sync.c" +#include "tsd.c" diff --git a/w32-pthreads/pthread.dsp b/w32-pthreads/pthread.dsp new file mode 100644 index 000000000..112bff72a --- /dev/null +++ b/w32-pthreads/pthread.dsp @@ -0,0 +1,142 @@ +# Microsoft Developer Studio Project File - Name="pthread" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 + +CFG=pthread - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "pthread.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "pthread.mak" CFG="pthread - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "pthread - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE "pthread - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "pthread - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "." +# PROP Intermediate_Dir "." +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PTW32_BUILD" /YX /FD /c +# ADD CPP /nologo /MD /W3 /GX /O2 /I "." /D "__CLEANUP_C" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PTW32_BUILD" /YX /FD /c +# SUBTRACT CPP /u +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x809 /d "NDEBUG" +# ADD RSC /l 0x409 /i "." /d "NDEBUG" /d "PTW32_RC_MSC" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 +# ADD LINK32 kernel32.lib user32.lib ws2_32.lib /nologo /dll /pdb:none /machine:I386 /out:".\pthreadVC2.dll" + +!ELSEIF "$(CFG)" == "pthread - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "." +# PROP Intermediate_Dir "." +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PTW32_BUILD" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "." /D "__CLEANUP_C" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PTW32_BUILD" /YX /FD /GZ /c +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x809 /d "_DEBUG" +# ADD RSC /l 0x409 /i "." /d "_DEBUG" /d "PTW32_RC_MSC" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib ws2_32.lib /nologo /dll /map /debug /machine:I386 /out:".\pthreadVC2.dll" /pdbtype:sept +# SUBTRACT LINK32 /pdb:none + +!ENDIF + +# Begin Target + +# Name "pthread - Win32 Release" +# Name "pthread - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\pthread.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\implement.h +# End Source File +# Begin Source File + +SOURCE=.\pthread.h +# End Source File +# Begin Source File + +SOURCE=.\sched.h +# End Source File +# Begin Source File + +SOURCE=.\semaphore.h +# End Source File +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# Begin Source File + +SOURCE=.\version.rc + +!IF "$(CFG)" == "pthread - Win32 Release" + +# ADD BASE RSC /l 0xc09 +# ADD RSC /l 0x409 /i "." /d "PTW32_RC_MSC" + +!ELSEIF "$(CFG)" == "pthread - Win32 Debug" + +# ADD BASE RSC /l 0xc09 +# ADD RSC /l 0x409 /i "." /d "PTW32_RC_MSC" + +!ENDIF + +# End Source File +# End Group +# End Target +# End Project diff --git a/w32-pthreads/pthread.dsw b/w32-pthreads/pthread.dsw new file mode 100644 index 000000000..815a67872 --- /dev/null +++ b/w32-pthreads/pthread.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "pthread"=.\pthread.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/w32-pthreads/pthread.h b/w32-pthreads/pthread.h new file mode 100644 index 000000000..aadc99d05 --- /dev/null +++ b/w32-pthreads/pthread.h @@ -0,0 +1,1368 @@ +/* This is an implementation of the threads API of POSIX 1003.1-2001. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#if !defined( PTHREAD_H ) +#define PTHREAD_H + +/* + * See the README file for an explanation of the pthreads-win32 version + * numbering scheme and how the DLL is named etc. + */ +#define PTW32_VERSION 2,9,1,0 +#define PTW32_VERSION_STRING "2, 9, 1, 0\0" + +/* There are three implementations of cancel cleanup. + * Note that pthread.h is included in both application + * compilation units and also internally for the library. + * The code here and within the library aims to work + * for all reasonable combinations of environments. + * + * The three implementations are: + * + * WIN32 SEH + * C + * C++ + * + * Please note that exiting a push/pop block via + * "return", "exit", "break", or "continue" will + * lead to different behaviour amongst applications + * depending upon whether the library was built + * using SEH, C++, or C. For example, a library built + * with SEH will call the cleanup routine, while both + * C++ and C built versions will not. + */ + +/* + * Define defaults for cleanup code. + * Note: Unless the build explicitly defines one of the following, then + * we default to standard C style cleanup. This style uses setjmp/longjmp + * in the cancelation and thread exit implementations and therefore won't + * do stack unwinding if linked to applications that have it (e.g. + * C++ apps). This is currently consistent with most/all commercial Unix + * POSIX threads implementations. + */ +#if !defined( __CLEANUP_SEH ) && !defined( __CLEANUP_CXX ) && !defined( __CLEANUP_C ) +# define __CLEANUP_C +#endif + +#if defined( __CLEANUP_SEH ) && ( !defined( _MSC_VER ) && !defined(PTW32_RC_MSC)) +#error ERROR [__FILE__, line __LINE__]: SEH is not supported for this compiler. +#endif + +/* + * Stop here if we are being included by the resource compiler. + */ +#if !defined(RC_INVOKED) + +#undef PTW32_LEVEL + +#if defined(_POSIX_SOURCE) +#define PTW32_LEVEL 0 +/* Early POSIX */ +#endif + +#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309 +#undef PTW32_LEVEL +#define PTW32_LEVEL 1 +/* Include 1b, 1c and 1d */ +#endif + +#if defined(INCLUDE_NP) +#undef PTW32_LEVEL +#define PTW32_LEVEL 2 +/* Include Non-Portable extensions */ +#endif + +#define PTW32_LEVEL_MAX 3 + +#if ( defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112 ) || !defined(PTW32_LEVEL) +#define PTW32_LEVEL PTW32_LEVEL_MAX +/* Include everything */ +#endif + +#if defined(_UWIN) +# define HAVE_STRUCT_TIMESPEC 1 +# define HAVE_SIGNAL_H 1 +# undef HAVE_PTW32_CONFIG_H +# pragma comment(lib, "pthread") +#endif + +/* + * ------------------------------------------------------------- + * + * + * Module: pthread.h + * + * Purpose: + * Provides an implementation of PThreads based upon the + * standard: + * + * POSIX 1003.1-2001 + * and + * The Single Unix Specification version 3 + * + * (these two are equivalent) + * + * in order to enhance code portability between Windows, + * various commercial Unix implementations, and Linux. + * + * See the ANNOUNCE file for a full list of conforming + * routines and defined constants, and a list of missing + * routines and constants not defined in this implementation. + * + * Authors: + * There have been many contributors to this library. + * The initial implementation was contributed by + * John Bossom, and several others have provided major + * sections or revisions of parts of the implementation. + * Often significant effort has been contributed to + * find and fix important bugs and other problems to + * improve the reliability of the library, which sometimes + * is not reflected in the amount of code which changed as + * result. + * As much as possible, the contributors are acknowledged + * in the ChangeLog file in the source code distribution + * where their changes are noted in detail. + * + * Contributors are listed in the CONTRIBUTORS file. + * + * As usual, all bouquets go to the contributors, and all + * brickbats go to the project maintainer. + * + * Maintainer: + * The code base for this project is coordinated and + * eventually pre-tested, packaged, and made available by + * + * Ross Johnson + * + * QA Testers: + * Ultimately, the library is tested in the real world by + * a host of competent and demanding scientists and + * engineers who report bugs and/or provide solutions + * which are then fixed or incorporated into subsequent + * versions of the library. Each time a bug is fixed, a + * test case is written to prove the fix and ensure + * that later changes to the code don't reintroduce the + * same error. The number of test cases is slowly growing + * and therefore so is the code reliability. + * + * Compliance: + * See the file ANNOUNCE for the list of implemented + * and not-implemented routines and defined options. + * Of course, these are all defined is this file as well. + * + * Web site: + * The source code and other information about this library + * are available from + * + * http://sources.redhat.com/pthreads-win32/ + * + * ------------------------------------------------------------- + */ + +/* Try to avoid including windows.h */ +#if (defined(__MINGW64__) || defined(__MINGW32__)) && defined(__cplusplus) +#define PTW32_INCLUDE_WINDOWS_H +#endif + +#if defined(PTW32_INCLUDE_WINDOWS_H) +#include +#endif + +#if defined(_MSC_VER) && _MSC_VER < 1300 || defined(__DMC__) +/* + * VC++6.0 or early compiler's header has no DWORD_PTR type. + */ +typedef unsigned long DWORD_PTR; +typedef unsigned long ULONG_PTR; +#endif +/* + * ----------------- + * autoconf switches + * ----------------- + */ + +#if defined(HAVE_PTW32_CONFIG_H) +#include "config.h" +#endif /* HAVE_PTW32_CONFIG_H */ + +#if !defined(NEED_FTIME) +#include +#else /* NEED_FTIME */ +/* use native WIN32 time API */ +#endif /* NEED_FTIME */ + +#if defined(HAVE_SIGNAL_H) +#include +#endif /* HAVE_SIGNAL_H */ + +#include + +/* + * Boolean values to make us independent of system includes. + */ +enum { + PTW32_FALSE = 0, + PTW32_TRUE = (! PTW32_FALSE) +}; + +/* + * This is a duplicate of what is in the autoconf config.h, + * which is only used when building the pthread-win32 libraries. + */ + +#if !defined(PTW32_CONFIG_H) +# if defined(WINCE) +# define NEED_ERRNO +# define NEED_SEM +# endif +# if defined(__MINGW64__) +# define HAVE_STRUCT_TIMESPEC +# define HAVE_MODE_T +# elif defined(_UWIN) || defined(__MINGW32__) +# define HAVE_MODE_T +# endif +#endif + +/* + * + */ + +#if PTW32_LEVEL >= PTW32_LEVEL_MAX +#if defined(NEED_ERRNO) +#include "need_errno.h" +#else +#include +#endif +#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */ + +/* + * Several systems don't define some error numbers. + */ +#if !defined(ENOTSUP) +# define ENOTSUP 48 /* This is the value in Solaris. */ +#endif + +#if !defined(ETIMEDOUT) +# define ETIMEDOUT 10060 /* Same as WSAETIMEDOUT */ +#endif + +#if !defined(ENOSYS) +# define ENOSYS 140 /* Semi-arbitrary value */ +#endif + +#if !defined(EDEADLK) +# if defined(EDEADLOCK) +# define EDEADLK EDEADLOCK +# else +# define EDEADLK 36 /* This is the value in MSVC. */ +# endif +#endif + +/* POSIX 2008 - related to robust mutexes */ +#if !defined(EOWNERDEAD) +# define EOWNERDEAD 43 +#endif +#if !defined(ENOTRECOVERABLE) +# define ENOTRECOVERABLE 44 +#endif + +#include "sched.h" + +/* + * To avoid including windows.h we define only those things that we + * actually need from it. + */ +#if !defined(PTW32_INCLUDE_WINDOWS_H) +#if !defined(HANDLE) +# define PTW32__HANDLE_DEF +# define HANDLE void * +#endif +#if !defined(DWORD) +# define PTW32__DWORD_DEF +# define DWORD unsigned long +#endif +#endif + +#if !defined(HAVE_STRUCT_TIMESPEC) +#define HAVE_STRUCT_TIMESPEC +#if !defined(_TIMESPEC_DEFINED) +#define _TIMESPEC_DEFINED +struct timespec { + time_t tv_sec; + long tv_nsec; +}; +#endif /* _TIMESPEC_DEFINED */ +#endif /* HAVE_STRUCT_TIMESPEC */ + +#if !defined(SIG_BLOCK) +#define SIG_BLOCK 0 +#endif /* SIG_BLOCK */ + +#if !defined(SIG_UNBLOCK) +#define SIG_UNBLOCK 1 +#endif /* SIG_UNBLOCK */ + +#if !defined(SIG_SETMASK) +#define SIG_SETMASK 2 +#endif /* SIG_SETMASK */ + +#if defined(__cplusplus) +extern "C" +{ +#endif /* __cplusplus */ + +/* + * ------------------------------------------------------------- + * + * POSIX 1003.1-2001 Options + * ========================= + * + * Options are normally set in , which is not provided + * with pthreads-win32. + * + * For conformance with the Single Unix Specification (version 3), all of the + * options below are defined, and have a value of either -1 (not supported) + * or 200112L (supported). + * + * These options can neither be left undefined nor have a value of 0, because + * either indicates that sysconf(), which is not implemented, may be used at + * runtime to check the status of the option. + * + * _POSIX_THREADS (== 200112L) + * If == 200112L, you can use threads + * + * _POSIX_THREAD_ATTR_STACKSIZE (== 200112L) + * If == 200112L, you can control the size of a thread's + * stack + * pthread_attr_getstacksize + * pthread_attr_setstacksize + * + * _POSIX_THREAD_ATTR_STACKADDR (== -1) + * If == 200112L, you can allocate and control a thread's + * stack. If not supported, the following functions + * will return ENOSYS, indicating they are not + * supported: + * pthread_attr_getstackaddr + * pthread_attr_setstackaddr + * + * _POSIX_THREAD_PRIORITY_SCHEDULING (== -1) + * If == 200112L, you can use realtime scheduling. + * This option indicates that the behaviour of some + * implemented functions conforms to the additional TPS + * requirements in the standard. E.g. rwlocks favour + * writers over readers when threads have equal priority. + * + * _POSIX_THREAD_PRIO_INHERIT (== -1) + * If == 200112L, you can create priority inheritance + * mutexes. + * pthread_mutexattr_getprotocol + + * pthread_mutexattr_setprotocol + + * + * _POSIX_THREAD_PRIO_PROTECT (== -1) + * If == 200112L, you can create priority ceiling mutexes + * Indicates the availability of: + * pthread_mutex_getprioceiling + * pthread_mutex_setprioceiling + * pthread_mutexattr_getprioceiling + * pthread_mutexattr_getprotocol + + * pthread_mutexattr_setprioceiling + * pthread_mutexattr_setprotocol + + * + * _POSIX_THREAD_PROCESS_SHARED (== -1) + * If set, you can create mutexes and condition + * variables that can be shared with another + * process.If set, indicates the availability + * of: + * pthread_mutexattr_getpshared + * pthread_mutexattr_setpshared + * pthread_condattr_getpshared + * pthread_condattr_setpshared + * + * _POSIX_THREAD_SAFE_FUNCTIONS (== 200112L) + * If == 200112L you can use the special *_r library + * functions that provide thread-safe behaviour + * + * _POSIX_READER_WRITER_LOCKS (== 200112L) + * If == 200112L, you can use read/write locks + * + * _POSIX_SPIN_LOCKS (== 200112L) + * If == 200112L, you can use spin locks + * + * _POSIX_BARRIERS (== 200112L) + * If == 200112L, you can use barriers + * + * + These functions provide both 'inherit' and/or + * 'protect' protocol, based upon these macro + * settings. + * + * ------------------------------------------------------------- + */ + +/* + * POSIX Options + */ +#undef _POSIX_THREADS +#define _POSIX_THREADS 200809L + +#undef _POSIX_READER_WRITER_LOCKS +#define _POSIX_READER_WRITER_LOCKS 200809L + +#undef _POSIX_SPIN_LOCKS +#define _POSIX_SPIN_LOCKS 200809L + +#undef _POSIX_BARRIERS +#define _POSIX_BARRIERS 200809L + +#undef _POSIX_THREAD_SAFE_FUNCTIONS +#define _POSIX_THREAD_SAFE_FUNCTIONS 200809L + +#undef _POSIX_THREAD_ATTR_STACKSIZE +#define _POSIX_THREAD_ATTR_STACKSIZE 200809L + +/* + * The following options are not supported + */ +#undef _POSIX_THREAD_ATTR_STACKADDR +#define _POSIX_THREAD_ATTR_STACKADDR -1 + +#undef _POSIX_THREAD_PRIO_INHERIT +#define _POSIX_THREAD_PRIO_INHERIT -1 + +#undef _POSIX_THREAD_PRIO_PROTECT +#define _POSIX_THREAD_PRIO_PROTECT -1 + +/* TPS is not fully supported. */ +#undef _POSIX_THREAD_PRIORITY_SCHEDULING +#define _POSIX_THREAD_PRIORITY_SCHEDULING -1 + +#undef _POSIX_THREAD_PROCESS_SHARED +#define _POSIX_THREAD_PROCESS_SHARED -1 + + +/* + * POSIX 1003.1-2001 Limits + * =========================== + * + * These limits are normally set in , which is not provided with + * pthreads-win32. + * + * PTHREAD_DESTRUCTOR_ITERATIONS + * Maximum number of attempts to destroy + * a thread's thread-specific data on + * termination (must be at least 4) + * + * PTHREAD_KEYS_MAX + * Maximum number of thread-specific data keys + * available per process (must be at least 128) + * + * PTHREAD_STACK_MIN + * Minimum supported stack size for a thread + * + * PTHREAD_THREADS_MAX + * Maximum number of threads supported per + * process (must be at least 64). + * + * SEM_NSEMS_MAX + * The maximum number of semaphores a process can have. + * (must be at least 256) + * + * SEM_VALUE_MAX + * The maximum value a semaphore can have. + * (must be at least 32767) + * + */ +#undef _POSIX_THREAD_DESTRUCTOR_ITERATIONS +#define _POSIX_THREAD_DESTRUCTOR_ITERATIONS 4 + +#undef PTHREAD_DESTRUCTOR_ITERATIONS +#define PTHREAD_DESTRUCTOR_ITERATIONS _POSIX_THREAD_DESTRUCTOR_ITERATIONS + +#undef _POSIX_THREAD_KEYS_MAX +#define _POSIX_THREAD_KEYS_MAX 128 + +#undef PTHREAD_KEYS_MAX +#define PTHREAD_KEYS_MAX _POSIX_THREAD_KEYS_MAX + +#undef PTHREAD_STACK_MIN +#define PTHREAD_STACK_MIN 0 + +#undef _POSIX_THREAD_THREADS_MAX +#define _POSIX_THREAD_THREADS_MAX 64 + + /* Arbitrary value */ +#undef PTHREAD_THREADS_MAX +#define PTHREAD_THREADS_MAX 2019 + +#undef _POSIX_SEM_NSEMS_MAX +#define _POSIX_SEM_NSEMS_MAX 256 + + /* Arbitrary value */ +#undef SEM_NSEMS_MAX +#define SEM_NSEMS_MAX 1024 + +#undef _POSIX_SEM_VALUE_MAX +#define _POSIX_SEM_VALUE_MAX 32767 + +#undef SEM_VALUE_MAX +#define SEM_VALUE_MAX INT_MAX + + +#if defined(__GNUC__) && !defined(__declspec) +# error Please upgrade your GNU compiler to one that supports __declspec. +#endif + +/* + * When building the library, you should define PTW32_BUILD so that + * the variables/functions are exported correctly. When using the library, + * do NOT define PTW32_BUILD, and then the variables/functions will + * be imported correctly. + */ +#if !defined(PTW32_STATIC_LIB) +# if defined(PTW32_BUILD) +# define PTW32_DLLPORT __declspec (dllexport) +# else +# define PTW32_DLLPORT +# endif +#else +# define PTW32_DLLPORT +#endif + +/* + * The Open Watcom C/C++ compiler uses a non-standard calling convention + * that passes function args in registers unless __cdecl is explicitly specified + * in exposed function prototypes. + * + * We force all calls to cdecl even though this could slow Watcom code down + * slightly. If you know that the Watcom compiler will be used to build both + * the DLL and application, then you can probably define this as a null string. + * Remember that pthread.h (this file) is used for both the DLL and application builds. + */ +#define PTW32_CDECL __cdecl + +#if defined(_UWIN) && PTW32_LEVEL >= PTW32_LEVEL_MAX +# include +#else +/* + * Generic handle type - intended to extend uniqueness beyond + * that available with a simple pointer. It should scale for either + * IA-32 or IA-64. + */ +typedef struct { + void * p; /* Pointer to actual object */ + unsigned int x; /* Extra information - reuse count etc */ +} ptw32_handle_t; + +typedef ptw32_handle_t pthread_t; +typedef struct pthread_attr_t_ * pthread_attr_t; +typedef struct pthread_once_t_ pthread_once_t; +typedef struct pthread_key_t_ * pthread_key_t; +typedef struct pthread_mutex_t_ * pthread_mutex_t; +typedef struct pthread_mutexattr_t_ * pthread_mutexattr_t; +typedef struct pthread_cond_t_ * pthread_cond_t; +typedef struct pthread_condattr_t_ * pthread_condattr_t; +#endif +typedef struct pthread_rwlock_t_ * pthread_rwlock_t; +typedef struct pthread_rwlockattr_t_ * pthread_rwlockattr_t; +typedef struct pthread_spinlock_t_ * pthread_spinlock_t; +typedef struct pthread_barrier_t_ * pthread_barrier_t; +typedef struct pthread_barrierattr_t_ * pthread_barrierattr_t; + +/* + * ==================== + * ==================== + * POSIX Threads + * ==================== + * ==================== + */ + +enum { +/* + * pthread_attr_{get,set}detachstate + */ + PTHREAD_CREATE_JOINABLE = 0, /* Default */ + PTHREAD_CREATE_DETACHED = 1, + +/* + * pthread_attr_{get,set}inheritsched + */ + PTHREAD_INHERIT_SCHED = 0, + PTHREAD_EXPLICIT_SCHED = 1, /* Default */ + +/* + * pthread_{get,set}scope + */ + PTHREAD_SCOPE_PROCESS = 0, + PTHREAD_SCOPE_SYSTEM = 1, /* Default */ + +/* + * pthread_setcancelstate paramters + */ + PTHREAD_CANCEL_ENABLE = 0, /* Default */ + PTHREAD_CANCEL_DISABLE = 1, + +/* + * pthread_setcanceltype parameters + */ + PTHREAD_CANCEL_ASYNCHRONOUS = 0, + PTHREAD_CANCEL_DEFERRED = 1, /* Default */ + +/* + * pthread_mutexattr_{get,set}pshared + * pthread_condattr_{get,set}pshared + */ + PTHREAD_PROCESS_PRIVATE = 0, + PTHREAD_PROCESS_SHARED = 1, + +/* + * pthread_mutexattr_{get,set}robust + */ + PTHREAD_MUTEX_STALLED = 0, /* Default */ + PTHREAD_MUTEX_ROBUST = 1, + +/* + * pthread_barrier_wait + */ + PTHREAD_BARRIER_SERIAL_THREAD = -1 +}; + +/* + * ==================== + * ==================== + * Cancelation + * ==================== + * ==================== + */ +#define PTHREAD_CANCELED ((void *)(size_t) -1) + + +/* + * ==================== + * ==================== + * Once Key + * ==================== + * ==================== + */ +#define PTHREAD_ONCE_INIT { PTW32_FALSE, 0, 0, 0} + +struct pthread_once_t_ +{ + int done; /* indicates if user function has been executed */ + void * lock; + int reserved1; + int reserved2; +}; + + +/* + * ==================== + * ==================== + * Object initialisers + * ==================== + * ==================== + */ +#define PTHREAD_MUTEX_INITIALIZER ((pthread_mutex_t)(size_t) -1) +#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER ((pthread_mutex_t)(size_t) -2) +#define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER ((pthread_mutex_t)(size_t) -3) + +/* + * Compatibility with LinuxThreads + */ +#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP PTHREAD_RECURSIVE_MUTEX_INITIALIZER +#define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP PTHREAD_ERRORCHECK_MUTEX_INITIALIZER + +#define PTHREAD_COND_INITIALIZER ((pthread_cond_t)(size_t) -1) + +#define PTHREAD_RWLOCK_INITIALIZER ((pthread_rwlock_t)(size_t) -1) + +#define PTHREAD_SPINLOCK_INITIALIZER ((pthread_spinlock_t)(size_t) -1) + + +/* + * Mutex types. + */ +enum +{ + /* Compatibility with LinuxThreads */ + PTHREAD_MUTEX_FAST_NP, + PTHREAD_MUTEX_RECURSIVE_NP, + PTHREAD_MUTEX_ERRORCHECK_NP, + PTHREAD_MUTEX_TIMED_NP = PTHREAD_MUTEX_FAST_NP, + PTHREAD_MUTEX_ADAPTIVE_NP = PTHREAD_MUTEX_FAST_NP, + /* For compatibility with POSIX */ + PTHREAD_MUTEX_NORMAL = PTHREAD_MUTEX_FAST_NP, + PTHREAD_MUTEX_RECURSIVE = PTHREAD_MUTEX_RECURSIVE_NP, + PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP, + PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL +}; + + +typedef struct ptw32_cleanup_t ptw32_cleanup_t; + +#if defined(_MSC_VER) +/* Disable MSVC 'anachronism used' warning */ +#pragma warning( disable : 4229 ) +#endif + +typedef void (* PTW32_CDECL ptw32_cleanup_callback_t)(void *); + +#if defined(_MSC_VER) +#pragma warning( default : 4229 ) +#endif + +struct ptw32_cleanup_t +{ + ptw32_cleanup_callback_t routine; + void *arg; + struct ptw32_cleanup_t *prev; +}; + +#if defined(__CLEANUP_SEH) + /* + * WIN32 SEH version of cancel cleanup. + */ + +#define pthread_cleanup_push( _rout, _arg ) \ + { \ + ptw32_cleanup_t _cleanup; \ + \ + _cleanup.routine = (ptw32_cleanup_callback_t)(_rout); \ + _cleanup.arg = (_arg); \ + __try \ + { \ + +#define pthread_cleanup_pop( _execute ) \ + } \ + __finally \ + { \ + if( _execute || AbnormalTermination()) \ + { \ + (*(_cleanup.routine))( _cleanup.arg ); \ + } \ + } \ + } + +#else /* __CLEANUP_SEH */ + +#if defined(__CLEANUP_C) + + /* + * C implementation of PThreads cancel cleanup + */ + +#define pthread_cleanup_push( _rout, _arg ) \ + { \ + ptw32_cleanup_t _cleanup; \ + \ + ptw32_push_cleanup( &_cleanup, (ptw32_cleanup_callback_t) (_rout), (_arg) ); \ + +#define pthread_cleanup_pop( _execute ) \ + (void) ptw32_pop_cleanup( _execute ); \ + } + +#else /* __CLEANUP_C */ + +#if defined(__CLEANUP_CXX) + + /* + * C++ version of cancel cleanup. + * - John E. Bossom. + */ + + class PThreadCleanup { + /* + * PThreadCleanup + * + * Purpose + * This class is a C++ helper class that is + * used to implement pthread_cleanup_push/ + * pthread_cleanup_pop. + * The destructor of this class automatically + * pops the pushed cleanup routine regardless + * of how the code exits the scope + * (i.e. such as by an exception) + */ + ptw32_cleanup_callback_t cleanUpRout; + void * obj; + int executeIt; + + public: + PThreadCleanup() : + cleanUpRout( 0 ), + obj( 0 ), + executeIt( 0 ) + /* + * No cleanup performed + */ + { + } + + PThreadCleanup( + ptw32_cleanup_callback_t routine, + void * arg ) : + cleanUpRout( routine ), + obj( arg ), + executeIt( 1 ) + /* + * Registers a cleanup routine for 'arg' + */ + { + } + + ~PThreadCleanup() + { + if ( executeIt && ((void *) cleanUpRout != (void *) 0) ) + { + (void) (*cleanUpRout)( obj ); + } + } + + void execute( int exec ) + { + executeIt = exec; + } + }; + + /* + * C++ implementation of PThreads cancel cleanup; + * This implementation takes advantage of a helper + * class who's destructor automatically calls the + * cleanup routine if we exit our scope weirdly + */ +#define pthread_cleanup_push( _rout, _arg ) \ + { \ + PThreadCleanup cleanup((ptw32_cleanup_callback_t)(_rout), \ + (void *) (_arg) ); + +#define pthread_cleanup_pop( _execute ) \ + cleanup.execute( _execute ); \ + } + +#else + +#error ERROR [__FILE__, line __LINE__]: Cleanup type undefined. + +#endif /* __CLEANUP_CXX */ + +#endif /* __CLEANUP_C */ + +#endif /* __CLEANUP_SEH */ + +/* + * =============== + * =============== + * Methods + * =============== + * =============== + */ + +/* + * PThread Attribute Functions + */ +PTW32_DLLPORT int PTW32_CDECL pthread_attr_init (pthread_attr_t * attr); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_destroy (pthread_attr_t * attr); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_getdetachstate (const pthread_attr_t * attr, + int *detachstate); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_getstackaddr (const pthread_attr_t * attr, + void **stackaddr); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_getstacksize (const pthread_attr_t * attr, + size_t * stacksize); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_setdetachstate (pthread_attr_t * attr, + int detachstate); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_setstackaddr (pthread_attr_t * attr, + void *stackaddr); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_setstacksize (pthread_attr_t * attr, + size_t stacksize); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_getschedparam (const pthread_attr_t *attr, + struct sched_param *param); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_setschedparam (pthread_attr_t *attr, + const struct sched_param *param); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_setschedpolicy (pthread_attr_t *, + int); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_getschedpolicy (const pthread_attr_t *, + int *); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_setinheritsched(pthread_attr_t * attr, + int inheritsched); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_getinheritsched(const pthread_attr_t * attr, + int * inheritsched); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_setscope (pthread_attr_t *, + int); + +PTW32_DLLPORT int PTW32_CDECL pthread_attr_getscope (const pthread_attr_t *, + int *); + +/* + * PThread Functions + */ +PTW32_DLLPORT int PTW32_CDECL pthread_create (pthread_t * tid, + const pthread_attr_t * attr, + void *(PTW32_CDECL *start) (void *), + void *arg); + +PTW32_DLLPORT int PTW32_CDECL pthread_detach (pthread_t tid); + +PTW32_DLLPORT int PTW32_CDECL pthread_equal (pthread_t t1, + pthread_t t2); + +PTW32_DLLPORT void PTW32_CDECL pthread_exit (void *value_ptr); + +PTW32_DLLPORT int PTW32_CDECL pthread_join (pthread_t thread, + void **value_ptr); + +PTW32_DLLPORT pthread_t PTW32_CDECL pthread_self (void); + +PTW32_DLLPORT int PTW32_CDECL pthread_cancel (pthread_t thread); + +PTW32_DLLPORT int PTW32_CDECL pthread_setcancelstate (int state, + int *oldstate); + +PTW32_DLLPORT int PTW32_CDECL pthread_setcanceltype (int type, + int *oldtype); + +PTW32_DLLPORT void PTW32_CDECL pthread_testcancel (void); + +PTW32_DLLPORT int PTW32_CDECL pthread_once (pthread_once_t * once_control, + void (PTW32_CDECL *init_routine) (void)); + +#if PTW32_LEVEL >= PTW32_LEVEL_MAX +PTW32_DLLPORT ptw32_cleanup_t * PTW32_CDECL ptw32_pop_cleanup (int execute); + +PTW32_DLLPORT void PTW32_CDECL ptw32_push_cleanup (ptw32_cleanup_t * cleanup, + ptw32_cleanup_callback_t routine, + void *arg); +#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */ + +/* + * Thread Specific Data Functions + */ +PTW32_DLLPORT int PTW32_CDECL pthread_key_create (pthread_key_t * key, + void (PTW32_CDECL *destructor) (void *)); + +PTW32_DLLPORT int PTW32_CDECL pthread_key_delete (pthread_key_t key); + +PTW32_DLLPORT int PTW32_CDECL pthread_setspecific (pthread_key_t key, + const void *value); + +PTW32_DLLPORT void * PTW32_CDECL pthread_getspecific (pthread_key_t key); + + +/* + * Mutex Attribute Functions + */ +PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_init (pthread_mutexattr_t * attr); + +PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_destroy (pthread_mutexattr_t * attr); + +PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getpshared (const pthread_mutexattr_t + * attr, + int *pshared); + +PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setpshared (pthread_mutexattr_t * attr, + int pshared); + +PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_settype (pthread_mutexattr_t * attr, int kind); +PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_gettype (const pthread_mutexattr_t * attr, int *kind); + +PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setrobust( + pthread_mutexattr_t *attr, + int robust); +PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getrobust( + const pthread_mutexattr_t * attr, + int * robust); + +/* + * Barrier Attribute Functions + */ +PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_init (pthread_barrierattr_t * attr); + +PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_destroy (pthread_barrierattr_t * attr); + +PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_getpshared (const pthread_barrierattr_t + * attr, + int *pshared); + +PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_setpshared (pthread_barrierattr_t * attr, + int pshared); + +/* + * Mutex Functions + */ +PTW32_DLLPORT int PTW32_CDECL pthread_mutex_init (pthread_mutex_t * mutex, + const pthread_mutexattr_t * attr); + +PTW32_DLLPORT int PTW32_CDECL pthread_mutex_destroy (pthread_mutex_t * mutex); + +PTW32_DLLPORT int PTW32_CDECL pthread_mutex_lock (pthread_mutex_t * mutex); + +PTW32_DLLPORT int PTW32_CDECL pthread_mutex_timedlock(pthread_mutex_t * mutex, + const struct timespec *abstime); + +PTW32_DLLPORT int PTW32_CDECL pthread_mutex_trylock (pthread_mutex_t * mutex); + +PTW32_DLLPORT int PTW32_CDECL pthread_mutex_unlock (pthread_mutex_t * mutex); + +PTW32_DLLPORT int PTW32_CDECL pthread_mutex_consistent (pthread_mutex_t * mutex); + +/* + * Spinlock Functions + */ +PTW32_DLLPORT int PTW32_CDECL pthread_spin_init (pthread_spinlock_t * lock, int pshared); + +PTW32_DLLPORT int PTW32_CDECL pthread_spin_destroy (pthread_spinlock_t * lock); + +PTW32_DLLPORT int PTW32_CDECL pthread_spin_lock (pthread_spinlock_t * lock); + +PTW32_DLLPORT int PTW32_CDECL pthread_spin_trylock (pthread_spinlock_t * lock); + +PTW32_DLLPORT int PTW32_CDECL pthread_spin_unlock (pthread_spinlock_t * lock); + +/* + * Barrier Functions + */ +PTW32_DLLPORT int PTW32_CDECL pthread_barrier_init (pthread_barrier_t * barrier, + const pthread_barrierattr_t * attr, + unsigned int count); + +PTW32_DLLPORT int PTW32_CDECL pthread_barrier_destroy (pthread_barrier_t * barrier); + +PTW32_DLLPORT int PTW32_CDECL pthread_barrier_wait (pthread_barrier_t * barrier); + +/* + * Condition Variable Attribute Functions + */ +PTW32_DLLPORT int PTW32_CDECL pthread_condattr_init (pthread_condattr_t * attr); + +PTW32_DLLPORT int PTW32_CDECL pthread_condattr_destroy (pthread_condattr_t * attr); + +PTW32_DLLPORT int PTW32_CDECL pthread_condattr_getpshared (const pthread_condattr_t * attr, + int *pshared); + +PTW32_DLLPORT int PTW32_CDECL pthread_condattr_setpshared (pthread_condattr_t * attr, + int pshared); + +/* + * Condition Variable Functions + */ +PTW32_DLLPORT int PTW32_CDECL pthread_cond_init (pthread_cond_t * cond, + const pthread_condattr_t * attr); + +PTW32_DLLPORT int PTW32_CDECL pthread_cond_destroy (pthread_cond_t * cond); + +PTW32_DLLPORT int PTW32_CDECL pthread_cond_wait (pthread_cond_t * cond, + pthread_mutex_t * mutex); + +PTW32_DLLPORT int PTW32_CDECL pthread_cond_timedwait (pthread_cond_t * cond, + pthread_mutex_t * mutex, + const struct timespec *abstime); + +PTW32_DLLPORT int PTW32_CDECL pthread_cond_signal (pthread_cond_t * cond); + +PTW32_DLLPORT int PTW32_CDECL pthread_cond_broadcast (pthread_cond_t * cond); + +/* + * Scheduling + */ +PTW32_DLLPORT int PTW32_CDECL pthread_setschedparam (pthread_t thread, + int policy, + const struct sched_param *param); + +PTW32_DLLPORT int PTW32_CDECL pthread_getschedparam (pthread_t thread, + int *policy, + struct sched_param *param); + +PTW32_DLLPORT int PTW32_CDECL pthread_setconcurrency (int); + +PTW32_DLLPORT int PTW32_CDECL pthread_getconcurrency (void); + +/* + * Read-Write Lock Functions + */ +PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_init(pthread_rwlock_t *lock, + const pthread_rwlockattr_t *attr); + +PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_destroy(pthread_rwlock_t *lock); + +PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_tryrdlock(pthread_rwlock_t *); + +PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_trywrlock(pthread_rwlock_t *); + +PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_rdlock(pthread_rwlock_t *lock); + +PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_timedrdlock(pthread_rwlock_t *lock, + const struct timespec *abstime); + +PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_wrlock(pthread_rwlock_t *lock); + +PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_timedwrlock(pthread_rwlock_t *lock, + const struct timespec *abstime); + +PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_unlock(pthread_rwlock_t *lock); + +PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_init (pthread_rwlockattr_t * attr); + +PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_destroy (pthread_rwlockattr_t * attr); + +PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_getpshared (const pthread_rwlockattr_t * attr, + int *pshared); + +PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_setpshared (pthread_rwlockattr_t * attr, + int pshared); + +#if PTW32_LEVEL >= PTW32_LEVEL_MAX - 1 + +/* + * Signal Functions. Should be defined in but MSVC and MinGW32 + * already have signal.h that don't define these. + */ +PTW32_DLLPORT int PTW32_CDECL pthread_kill(pthread_t thread, int sig); + +/* + * Non-portable functions + */ + +/* + * Compatibility with Linux. + */ +PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setkind_np(pthread_mutexattr_t * attr, + int kind); +PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getkind_np(pthread_mutexattr_t * attr, + int *kind); + +/* + * Possibly supported by other POSIX threads implementations + */ +PTW32_DLLPORT int PTW32_CDECL pthread_delay_np (struct timespec * interval); +PTW32_DLLPORT int PTW32_CDECL pthread_num_processors_np(void); +PTW32_DLLPORT unsigned __int64 PTW32_CDECL pthread_getunique_np(pthread_t thread); + +/* + * Useful if an application wants to statically link + * the lib rather than load the DLL at run-time. + */ +PTW32_DLLPORT int PTW32_CDECL pthread_win32_process_attach_np(void); +PTW32_DLLPORT int PTW32_CDECL pthread_win32_process_detach_np(void); +PTW32_DLLPORT int PTW32_CDECL pthread_win32_thread_attach_np(void); +PTW32_DLLPORT int PTW32_CDECL pthread_win32_thread_detach_np(void); + +/* + * Features that are auto-detected at load/run time. + */ +PTW32_DLLPORT int PTW32_CDECL pthread_win32_test_features_np(int); +enum ptw32_features { + PTW32_SYSTEM_INTERLOCKED_COMPARE_EXCHANGE = 0x0001, /* System provides it. */ + PTW32_ALERTABLE_ASYNC_CANCEL = 0x0002 /* Can cancel blocked threads. */ +}; + +/* + * Register a system time change with the library. + * Causes the library to perform various functions + * in response to the change. Should be called whenever + * the application's top level window receives a + * WM_TIMECHANGE message. It can be passed directly to + * pthread_create() as a new thread if desired. + */ +PTW32_DLLPORT void * PTW32_CDECL pthread_timechange_handler_np(void *); + +#endif /*PTW32_LEVEL >= PTW32_LEVEL_MAX - 1 */ + +#if PTW32_LEVEL >= PTW32_LEVEL_MAX + +/* + * Returns the Win32 HANDLE for the POSIX thread. + */ +PTW32_DLLPORT HANDLE PTW32_CDECL pthread_getw32threadhandle_np(pthread_t thread); +/* + * Returns the win32 thread ID for POSIX thread. + */ +PTW32_DLLPORT DWORD PTW32_CDECL pthread_getw32threadid_np (pthread_t thread); + + +/* + * Protected Methods + * + * This function blocks until the given WIN32 handle + * is signaled or pthread_cancel had been called. + * This function allows the caller to hook into the + * PThreads cancel mechanism. It is implemented using + * + * WaitForMultipleObjects + * + * on 'waitHandle' and a manually reset WIN32 Event + * used to implement pthread_cancel. The 'timeout' + * argument to TimedWait is simply passed to + * WaitForMultipleObjects. + */ +PTW32_DLLPORT int PTW32_CDECL pthreadCancelableWait (HANDLE waitHandle); +PTW32_DLLPORT int PTW32_CDECL pthreadCancelableTimedWait (HANDLE waitHandle, + DWORD timeout); + +#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */ + +/* + * Thread-Safe C Runtime Library Mappings. + */ +#if !defined(_UWIN) +# if defined(NEED_ERRNO) + PTW32_DLLPORT int * PTW32_CDECL _errno( void ); +# else +# if !defined(errno) +# if (defined(_MT) || defined(_DLL)) + __declspec(dllimport) extern int * __cdecl _errno(void); +# define errno (*_errno()) +# endif +# endif +# endif +#endif + +/* + * Some compiler environments don't define some things. + */ +#if defined(__BORLANDC__) +# define _ftime ftime +# define _timeb timeb +#endif + +#if defined(__cplusplus) + +/* + * Internal exceptions + */ +class ptw32_exception {}; +class ptw32_exception_cancel : public ptw32_exception {}; +class ptw32_exception_exit : public ptw32_exception {}; + +#endif + +#if PTW32_LEVEL >= PTW32_LEVEL_MAX + +/* FIXME: This is only required if the library was built using SEH */ +/* + * Get internal SEH tag + */ +PTW32_DLLPORT DWORD PTW32_CDECL ptw32_get_exception_services_code(void); + +#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */ + +#if !defined(PTW32_BUILD) + +#if defined(__CLEANUP_SEH) + +/* + * Redefine the SEH __except keyword to ensure that applications + * propagate our internal exceptions up to the library's internal handlers. + */ +#define __except( E ) \ + __except( ( GetExceptionCode() == ptw32_get_exception_services_code() ) \ + ? EXCEPTION_CONTINUE_SEARCH : ( E ) ) + +#endif /* __CLEANUP_SEH */ + +#if defined(__CLEANUP_CXX) + +/* + * Redefine the C++ catch keyword to ensure that applications + * propagate our internal exceptions up to the library's internal handlers. + */ +#if defined(_MSC_VER) + /* + * WARNING: Replace any 'catch( ... )' with 'PtW32CatchAll' + * if you want Pthread-Win32 cancelation and pthread_exit to work. + */ + +#if !defined(PtW32NoCatchWarn) + +#pragma message("Specify \"/DPtW32NoCatchWarn\" compiler flag to skip this message.") +#pragma message("------------------------------------------------------------------") +#pragma message("When compiling applications with MSVC++ and C++ exception handling:") +#pragma message(" Replace any 'catch( ... )' in routines called from POSIX threads") +#pragma message(" with 'PtW32CatchAll' or 'CATCHALL' if you want POSIX thread") +#pragma message(" cancelation and pthread_exit to work. For example:") +#pragma message("") +#pragma message(" #if defined(PtW32CatchAll)") +#pragma message(" PtW32CatchAll") +#pragma message(" #else") +#pragma message(" catch(...)") +#pragma message(" #endif") +#pragma message(" {") +#pragma message(" /* Catchall block processing */") +#pragma message(" }") +#pragma message("------------------------------------------------------------------") + +#endif + +#define PtW32CatchAll \ + catch( ptw32_exception & ) { throw; } \ + catch( ... ) + +#else /* _MSC_VER */ + +#define catch( E ) \ + catch( ptw32_exception & ) { throw; } \ + catch( E ) + +#endif /* _MSC_VER */ + +#endif /* __CLEANUP_CXX */ + +#endif /* ! PTW32_BUILD */ + +#if defined(__cplusplus) +} /* End of extern "C" */ +#endif /* __cplusplus */ + +#if defined(PTW32__HANDLE_DEF) +# undef HANDLE +#endif +#if defined(PTW32__DWORD_DEF) +# undef DWORD +#endif + +#undef PTW32_LEVEL +#undef PTW32_LEVEL_MAX + +#endif /* ! RC_INVOKED */ + +#endif /* PTHREAD_H */ diff --git a/w32-pthreads/pthread.lastbuildstate b/w32-pthreads/pthread.lastbuildstate new file mode 100644 index 000000000..71ee68ae7 --- /dev/null +++ b/w32-pthreads/pthread.lastbuildstate @@ -0,0 +1,2 @@ +#v4.0:v100:false +Release-Static|x64|D:\OBS2\liboms-util\w32-pthreads\| diff --git a/w32-pthreads/pthread.sln b/w32-pthreads/pthread.sln new file mode 100644 index 000000000..fbf599138 --- /dev/null +++ b/w32-pthreads/pthread.sln @@ -0,0 +1,38 @@ +ļ»æ +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pthread", "pthread.vcxproj", "{969D9298-8CEF-14A3-8EEF-E3C596896C8D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Debug-Static|Win32 = Debug-Static|Win32 + Debug-Static|x64 = Debug-Static|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + Release-Static|Win32 = Release-Static|Win32 + Release-Static|x64 = Release-Static|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Debug|Win32.ActiveCfg = Debug|Win32 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Debug|Win32.Build.0 = Debug|Win32 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Debug|x64.ActiveCfg = Debug|x64 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Debug|x64.Build.0 = Debug|x64 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Debug-Static|Win32.ActiveCfg = Debug-Static|Win32 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Debug-Static|Win32.Build.0 = Debug-Static|Win32 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Debug-Static|x64.ActiveCfg = Debug-Static|x64 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Debug-Static|x64.Build.0 = Debug-Static|x64 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Release|Win32.ActiveCfg = Release|Win32 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Release|Win32.Build.0 = Release|Win32 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Release|x64.ActiveCfg = Release|x64 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Release|x64.Build.0 = Release|x64 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Release-Static|Win32.ActiveCfg = Release-Static|Win32 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Release-Static|Win32.Build.0 = Release-Static|Win32 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Release-Static|x64.ActiveCfg = Release-Static|x64 + {969D9298-8CEF-14A3-8EEF-E3C596896C8D}.Release-Static|x64.Build.0 = Release-Static|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/w32-pthreads/pthread.vcxproj b/w32-pthreads/pthread.vcxproj new file mode 100644 index 000000000..8a17fed21 --- /dev/null +++ b/w32-pthreads/pthread.vcxproj @@ -0,0 +1,514 @@ +ļ»æ + + + + Debug-Static + Win32 + + + Debug-Static + x64 + + + Debug + Win32 + + + Debug + x64 + + + Release-Static + Win32 + + + Release-Static + x64 + + + Release + Win32 + + + Release + x64 + + + + + + + + + DynamicLibrary + false + MultiByte + + + DynamicLibrary + false + MultiByte + + + DynamicLibrary + false + MultiByte + + + StaticLibrary + false + MultiByte + + + DynamicLibrary + false + MultiByte + + + DynamicLibrary + false + MultiByte + + + DynamicLibrary + false + MultiByte + + + StaticLibrary + false + MultiByte + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + .\.\ + .\.\ + false + + + .\.\ + .\.\ + false + + + .\.\ + .\.\ + false + + + .\.\ + .\.\ + false + + + .\.\ + .\.\ + true + + + .\.\ + .\.\ + true + + + .\.\ + .\.\ + true + + + .\.\ + .\.\ + true + + + + MultiThreadedDLL + OnlyExplicitInline + true + true + MaxSpeed + true + Level3 + .;%(AdditionalIncludeDirectories) + false + __CLEANUP_C;WIN32;NDEBUG;_WINDOWS;_USRDLL;PTW32_BUILD;%(PreprocessorDefinitions) + .\.\ + .\.\pthread.pch + .\.\ + .\.\ + + + true + NDEBUG;%(PreprocessorDefinitions) + .\.\pthread.tlb + true + Win32 + + + 0x0409 + .;%(AdditionalIncludeDirectories) + NDEBUG;PTW32_RC_MSC;%(PreprocessorDefinitions) + + + true + .\.\pthread.bsc + + + true + true + Console + .\pthreadVC2.dll + .\.\pthreadVC2.lib + ws2_32.lib;%(AdditionalDependencies) + + + + + MultiThreadedDLL + OnlyExplicitInline + true + true + MaxSpeed + true + Level3 + .;%(AdditionalIncludeDirectories) + false + __CLEANUP_C;WIN32;NDEBUG;_WINDOWS;_USRDLL;PTW32_BUILD;%(PreprocessorDefinitions) + .\.\ + .\.\pthread.pch + .\.\ + .\.\ + + + true + NDEBUG;%(PreprocessorDefinitions) + .\.\pthread.tlb + true + Win32 + + + 0x0409 + .;%(AdditionalIncludeDirectories) + NDEBUG;PTW32_RC_MSC;%(PreprocessorDefinitions) + + + true + .\.\pthread.bsc + + + true + true + Console + .\pthreadVC2.dll + .\.\pthreadVC2.lib + ws2_32.lib;%(AdditionalDependencies) + + + + + MultiThreadedDLL + OnlyExplicitInline + true + true + MaxSpeed + true + Level3 + .;%(AdditionalIncludeDirectories) + false + __CLEANUP_C;WIN32;NDEBUG;_WINDOWS;_USRDLL;PTW32_BUILD;%(PreprocessorDefinitions) + .\.\ + .\.\pthread.pch + .\.\ + .\.\ + + + true + NDEBUG;%(PreprocessorDefinitions) + .\.\pthread.tlb + true + + + 0x0409 + .;%(AdditionalIncludeDirectories) + NDEBUG;PTW32_RC_MSC;%(PreprocessorDefinitions) + + + true + .\.\pthread.bsc + + + true + true + Console + .\pthreadVC2.dll + .\.\pthreadVC2.lib + ws2_32.lib;%(AdditionalDependencies) + + + + + MultiThreadedDLL + OnlyExplicitInline + true + true + MaxSpeed + true + Level3 + .;%(AdditionalIncludeDirectories) + false + __CLEANUP_C;WIN32;NDEBUG;_WINDOWS;_USRDLL;PTW32_BUILD;%(PreprocessorDefinitions) + .\.\ + .\.\pthread.pch + .\.\ + .\.\ + + + true + NDEBUG;%(PreprocessorDefinitions) + .\.\pthread.tlb + true + + + 0x0409 + .;%(AdditionalIncludeDirectories) + NDEBUG;PTW32_RC_MSC;%(PreprocessorDefinitions) + + + true + .\.\pthread.bsc + + + true + true + Console + .\pthreadVC2.dll + .\.\pthreadVC2.lib + ws2_32.lib;%(AdditionalDependencies) + + + .\pthreadVC2.lib + + + + + MultiThreadedDebugDLL + Default + false + Disabled + true + Level3 + true + EditAndContinue + .;%(AdditionalIncludeDirectories) + __CLEANUP_C;WIN32;_DEBUG;_WINDOWS;_USRDLL;PTW32_BUILD;%(PreprocessorDefinitions) + .\.\ + .\.\pthread.pch + .\.\ + .\.\ + EnableFastChecks + + + true + _DEBUG;%(PreprocessorDefinitions) + .\.\pthread.tlb + true + Win32 + + + 0x0409 + .;%(AdditionalIncludeDirectories) + _DEBUG;PTW32_RC_MSC;%(PreprocessorDefinitions) + + + true + .\.\pthread.bsc + + + true + true + true + Console + .\pthreadVC2.dll + .\.\pthreadVC2.lib + ws2_32.lib;%(AdditionalDependencies) + + + + + MultiThreadedDebugDLL + Default + false + Disabled + true + Level3 + true + EditAndContinue + .;%(AdditionalIncludeDirectories) + __CLEANUP_C;WIN32;_DEBUG;_WINDOWS;_USRDLL;PTW32_BUILD;%(PreprocessorDefinitions) + .\.\ + .\.\pthread.pch + .\.\ + .\.\ + EnableFastChecks + + + true + _DEBUG;%(PreprocessorDefinitions) + .\.\pthread.tlb + true + Win32 + + + 0x0409 + .;%(AdditionalIncludeDirectories) + _DEBUG;PTW32_RC_MSC;%(PreprocessorDefinitions) + + + true + .\.\pthread.bsc + + + true + true + true + Console + .\pthreadVC2.dll + .\.\pthreadVC2.lib + ws2_32.lib;%(AdditionalDependencies) + + + + + MultiThreadedDebugDLL + Default + false + Disabled + true + Level3 + ProgramDatabase + .;%(AdditionalIncludeDirectories) + __CLEANUP_C;WIN32;_DEBUG;_WINDOWS;_USRDLL;PTW32_BUILD;%(PreprocessorDefinitions) + .\.\ + .\.\pthread.pch + .\.\ + .\.\ + EnableFastChecks + + + true + _DEBUG;%(PreprocessorDefinitions) + .\.\pthread.tlb + true + + + 0x0409 + .;%(AdditionalIncludeDirectories) + _DEBUG;PTW32_RC_MSC;%(PreprocessorDefinitions) + + + true + .\.\pthread.bsc + + + true + true + true + Console + .\pthreadVC2.dll + .\.\pthreadVC2.lib + ws2_32.lib;%(AdditionalDependencies) + + + + + MultiThreadedDebugDLL + Default + false + Disabled + true + Level3 + ProgramDatabase + .;%(AdditionalIncludeDirectories) + __CLEANUP_C;WIN32;_DEBUG;_WINDOWS;_USRDLL;PTW32_BUILD;%(PreprocessorDefinitions) + .\.\ + .\.\pthread.pch + .\.\ + .\.\ + EnableFastChecks + + + true + _DEBUG;%(PreprocessorDefinitions) + .\.\pthread.tlb + true + + + 0x0409 + .;%(AdditionalIncludeDirectories) + _DEBUG;PTW32_RC_MSC;%(PreprocessorDefinitions) + + + true + .\.\pthread.bsc + + + true + true + true + Console + .\pthreadVC2.dll + .\.\pthreadVC2.lib + ws2_32.lib;%(AdditionalDependencies) + + + .\pthreadVC2.lib + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/w32-pthreads/pthread.vcxproj.filters b/w32-pthreads/pthread.vcxproj.filters new file mode 100644 index 000000000..fc5c64a43 --- /dev/null +++ b/w32-pthreads/pthread.vcxproj.filters @@ -0,0 +1,36 @@ +ļ»æ + + + + {ed014216-ffe7-4e4f-b783-9812a5e778d7} + cpp;c;cxx;rc;def;r;odl;idl;hpj;bat + + + {a9cc5beb-e838-4849-9cbd-ee1de4bda860} + h;hpp;hxx;hm;inl + + + {636c1d95-8104-45b5-aa12-6e8e3c5ebcee} + ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/w32-pthreads/pthread_attr_destroy.c b/w32-pthreads/pthread_attr_destroy.c new file mode 100644 index 000000000..8b3e04c53 --- /dev/null +++ b/w32-pthreads/pthread_attr_destroy.c @@ -0,0 +1,79 @@ +/* + * pthread_attr_destroy.c + * + * Description: + * This translation unit implements operations on thread attribute objects. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_attr_destroy (pthread_attr_t * attr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Destroys a thread attributes object. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_attr_t + * + * + * DESCRIPTION + * Destroys a thread attributes object. + * + * NOTES: + * 1) Does not affect threads created with 'attr'. + * + * RESULTS + * 0 successfully destroyed attr, + * EINVAL 'attr' is invalid. + * + * ------------------------------------------------------ + */ +{ + if (ptw32_is_attr (attr) != 0) + { + return EINVAL; + } + + /* + * Set the attribute object to a specific invalid value. + */ + (*attr)->valid = 0; + free (*attr); + *attr = NULL; + + return 0; +} diff --git a/w32-pthreads/pthread_attr_getdetachstate.c b/w32-pthreads/pthread_attr_getdetachstate.c new file mode 100644 index 000000000..188533b13 --- /dev/null +++ b/w32-pthreads/pthread_attr_getdetachstate.c @@ -0,0 +1,86 @@ +/* + * pthread_attr_getdetachstate.c + * + * Description: + * This translation unit implements operations on thread attribute objects. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_attr_getdetachstate (const pthread_attr_t * attr, int *detachstate) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function determines whether threads created with + * 'attr' will run detached. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_attr_t + * + * detachstate + * pointer to an integer into which is returned one + * of: + * + * PTHREAD_CREATE_JOINABLE + * Thread ID is valid, must be joined + * + * PTHREAD_CREATE_DETACHED + * Thread ID is invalid, cannot be joined, + * canceled, or modified + * + * + * DESCRIPTION + * This function determines whether threads created with + * 'attr' will run detached. + * + * NOTES: + * 1) You cannot join or cancel detached threads. + * + * RESULTS + * 0 successfully retrieved detach state, + * EINVAL 'attr' is invalid + * + * ------------------------------------------------------ + */ +{ + if (ptw32_is_attr (attr) != 0 || detachstate == NULL) + { + return EINVAL; + } + + *detachstate = (*attr)->detachstate; + return 0; +} diff --git a/w32-pthreads/pthread_attr_getinheritsched.c b/w32-pthreads/pthread_attr_getinheritsched.c new file mode 100644 index 000000000..9c6885ed9 --- /dev/null +++ b/w32-pthreads/pthread_attr_getinheritsched.c @@ -0,0 +1,51 @@ +/* + * pthread_attr_getinheritsched.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +int +pthread_attr_getinheritsched (const pthread_attr_t * attr, int *inheritsched) +{ + if (ptw32_is_attr (attr) != 0 || inheritsched == NULL) + { + return EINVAL; + } + + *inheritsched = (*attr)->inheritsched; + return 0; +} diff --git a/w32-pthreads/pthread_attr_getschedparam.c b/w32-pthreads/pthread_attr_getschedparam.c new file mode 100644 index 000000000..ab89b2241 --- /dev/null +++ b/w32-pthreads/pthread_attr_getschedparam.c @@ -0,0 +1,52 @@ +/* + * pthread_attr_getschedparam.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +int +pthread_attr_getschedparam (const pthread_attr_t * attr, + struct sched_param *param) +{ + if (ptw32_is_attr (attr) != 0 || param == NULL) + { + return EINVAL; + } + + memcpy (param, &(*attr)->param, sizeof (*param)); + return 0; +} diff --git a/w32-pthreads/pthread_attr_getschedpolicy.c b/w32-pthreads/pthread_attr_getschedpolicy.c new file mode 100644 index 000000000..94a257d60 --- /dev/null +++ b/w32-pthreads/pthread_attr_getschedpolicy.c @@ -0,0 +1,61 @@ +/* + * pthread_attr_getschedpolicy.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +int +pthread_attr_getschedpolicy (const pthread_attr_t * attr, int *policy) +{ + if (ptw32_is_attr (attr) != 0 || policy == NULL) + { + return EINVAL; + } + + /* + * Validate the policy arg. + * Check that a policy constant wasn't passed rather than &policy. + */ + if (policy <= (int *) SCHED_MAX) + { + return EINVAL; + } + + *policy = SCHED_OTHER; + + return 0; +} diff --git a/w32-pthreads/pthread_attr_getscope.c b/w32-pthreads/pthread_attr_getscope.c new file mode 100644 index 000000000..2efdb2fe6 --- /dev/null +++ b/w32-pthreads/pthread_attr_getscope.c @@ -0,0 +1,54 @@ +/* + * pthread_attr_getscope.c + * + * Description: + * This translation unit implements operations on thread attribute objects. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* ignore warning "unreferenced formal parameter" */ +#if defined(_MSC_VER) +#pragma warning( disable : 4100 ) +#endif + +int +pthread_attr_getscope (const pthread_attr_t * attr, int *contentionscope) +{ +#if defined(_POSIX_THREAD_PRIORITY_SCHEDULING) + *contentionscope = (*attr)->contentionscope; + return 0; +#else + return ENOSYS; +#endif +} diff --git a/w32-pthreads/pthread_attr_getstackaddr.c b/w32-pthreads/pthread_attr_getstackaddr.c new file mode 100644 index 000000000..1a2da01c7 --- /dev/null +++ b/w32-pthreads/pthread_attr_getstackaddr.c @@ -0,0 +1,97 @@ +/* + * pthread_attr_getstackaddr.c + * + * Description: + * This translation unit implements operations on thread attribute objects. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* ignore warning "unreferenced formal parameter" */ +#if defined(_MSC_VER) +#pragma warning( disable : 4100 ) +#endif + +int +pthread_attr_getstackaddr (const pthread_attr_t * attr, void **stackaddr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function determines the address of the stack + * on which threads created with 'attr' will run. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_attr_t + * + * stackaddr + * pointer into which is returned the stack address. + * + * + * DESCRIPTION + * This function determines the address of the stack + * on which threads created with 'attr' will run. + * + * NOTES: + * 1) Function supported only if this macro is + * defined: + * + * _POSIX_THREAD_ATTR_STACKADDR + * + * 2) Create only one thread for each stack + * address.. + * + * RESULTS + * 0 successfully retreived stack address, + * EINVAL 'attr' is invalid + * ENOSYS function not supported + * + * ------------------------------------------------------ + */ +{ +#if defined( _POSIX_THREAD_ATTR_STACKADDR ) + + if (ptw32_is_attr (attr) != 0) + { + return EINVAL; + } + + *stackaddr = (*attr)->stackaddr; + return 0; + +#else + + return ENOSYS; + +#endif /* _POSIX_THREAD_ATTR_STACKADDR */ +} diff --git a/w32-pthreads/pthread_attr_getstacksize.c b/w32-pthreads/pthread_attr_getstacksize.c new file mode 100644 index 000000000..dff9230f2 --- /dev/null +++ b/w32-pthreads/pthread_attr_getstacksize.c @@ -0,0 +1,100 @@ +/* + * pthread_attr_getstacksize.c + * + * Description: + * This translation unit implements operations on thread attribute objects. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* ignore warning "unreferenced formal parameter" */ +#if defined(_MSC_VER) +#pragma warning( disable : 4100 ) +#endif + +int +pthread_attr_getstacksize (const pthread_attr_t * attr, size_t * stacksize) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function determines the size of the stack on + * which threads created with 'attr' will run. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_attr_t + * + * stacksize + * pointer to size_t into which is returned the + * stack size, in bytes. + * + * + * DESCRIPTION + * This function determines the size of the stack on + * which threads created with 'attr' will run. + * + * NOTES: + * 1) Function supported only if this macro is + * defined: + * + * _POSIX_THREAD_ATTR_STACKSIZE + * + * 2) Use on newly created attributes object to + * find the default stack size. + * + * RESULTS + * 0 successfully retrieved stack size, + * EINVAL 'attr' is invalid + * ENOSYS function not supported + * + * ------------------------------------------------------ + */ +{ +#if defined(_POSIX_THREAD_ATTR_STACKSIZE) + + if (ptw32_is_attr (attr) != 0) + { + return EINVAL; + } + + /* Everything is okay. */ + *stacksize = (*attr)->stacksize; + return 0; + +#else + + return ENOSYS; + +#endif /* _POSIX_THREAD_ATTR_STACKSIZE */ + +} diff --git a/w32-pthreads/pthread_attr_init.c b/w32-pthreads/pthread_attr_init.c new file mode 100644 index 000000000..ae9d3eb5f --- /dev/null +++ b/w32-pthreads/pthread_attr_init.c @@ -0,0 +1,117 @@ +/* + * pthread_attr_init.c + * + * Description: + * This translation unit implements operations on thread attribute objects. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_attr_init (pthread_attr_t * attr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Initializes a thread attributes object with default + * attributes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_attr_t + * + * + * DESCRIPTION + * Initializes a thread attributes object with default + * attributes. + * + * NOTES: + * 1) Used to define thread attributes + * + * RESULTS + * 0 successfully initialized attr, + * ENOMEM insufficient memory for attr. + * + * ------------------------------------------------------ + */ +{ + pthread_attr_t attr_result; + + if (attr == NULL) + { + /* This is disallowed. */ + return EINVAL; + } + + attr_result = (pthread_attr_t) malloc (sizeof (*attr_result)); + + if (attr_result == NULL) + { + return ENOMEM; + } + +#if defined(_POSIX_THREAD_ATTR_STACKSIZE) + /* + * Default to zero size. Unless changed explicitly this + * will allow Win32 to set the size to that of the + * main thread. + */ + attr_result->stacksize = 0; +#endif + +#if defined(_POSIX_THREAD_ATTR_STACKADDR) + /* FIXME: Set this to something sensible when we support it. */ + attr_result->stackaddr = NULL; +#endif + + attr_result->detachstate = PTHREAD_CREATE_JOINABLE; + +#if defined(HAVE_SIGSET_T) + memset (&(attr_result->sigmask), 0, sizeof (sigset_t)); +#endif /* HAVE_SIGSET_T */ + + /* + * Win32 sets new threads to THREAD_PRIORITY_NORMAL and + * not to that of the parent thread. We choose to default to + * this arrangement. + */ + attr_result->param.sched_priority = THREAD_PRIORITY_NORMAL; + attr_result->inheritsched = PTHREAD_EXPLICIT_SCHED; + attr_result->contentionscope = PTHREAD_SCOPE_SYSTEM; + + attr_result->valid = PTW32_ATTR_VALID; + + *attr = attr_result; + + return 0; +} diff --git a/w32-pthreads/pthread_attr_setdetachstate.c b/w32-pthreads/pthread_attr_setdetachstate.c new file mode 100644 index 000000000..784642a80 --- /dev/null +++ b/w32-pthreads/pthread_attr_setdetachstate.c @@ -0,0 +1,91 @@ +/* + * pthread_attr_setdetachstate.c + * + * Description: + * This translation unit implements operations on thread attribute objects. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_attr_setdetachstate (pthread_attr_t * attr, int detachstate) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function specifies whether threads created with + * 'attr' will run detached. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_attr_t + * + * detachstate + * an integer containing one of: + * + * PTHREAD_CREATE_JOINABLE + * Thread ID is valid, must be joined + * + * PTHREAD_CREATE_DETACHED + * Thread ID is invalid, cannot be joined, + * canceled, or modified + * + * + * DESCRIPTION + * This function specifies whether threads created with + * 'attr' will run detached. + * + * NOTES: + * 1) You cannot join or cancel detached threads. + * + * RESULTS + * 0 successfully set detach state, + * EINVAL 'attr' or 'detachstate' is invalid + * + * ------------------------------------------------------ + */ +{ + if (ptw32_is_attr (attr) != 0) + { + return EINVAL; + } + + if (detachstate != PTHREAD_CREATE_JOINABLE && + detachstate != PTHREAD_CREATE_DETACHED) + { + return EINVAL; + } + + (*attr)->detachstate = detachstate; + return 0; +} diff --git a/w32-pthreads/pthread_attr_setinheritsched.c b/w32-pthreads/pthread_attr_setinheritsched.c new file mode 100644 index 000000000..e0a407a3b --- /dev/null +++ b/w32-pthreads/pthread_attr_setinheritsched.c @@ -0,0 +1,57 @@ +/* + * pthread_attr_setinheritsched.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +int +pthread_attr_setinheritsched (pthread_attr_t * attr, int inheritsched) +{ + if (ptw32_is_attr (attr) != 0) + { + return EINVAL; + } + + if (PTHREAD_INHERIT_SCHED != inheritsched + && PTHREAD_EXPLICIT_SCHED != inheritsched) + { + return EINVAL; + } + + (*attr)->inheritsched = inheritsched; + return 0; +} diff --git a/w32-pthreads/pthread_attr_setschedparam.c b/w32-pthreads/pthread_attr_setschedparam.c new file mode 100644 index 000000000..f246bfae7 --- /dev/null +++ b/w32-pthreads/pthread_attr_setschedparam.c @@ -0,0 +1,63 @@ +/* + * pthread_attr_setschedparam.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +int +pthread_attr_setschedparam (pthread_attr_t * attr, + const struct sched_param *param) +{ + int priority; + + if (ptw32_is_attr (attr) != 0 || param == NULL) + { + return EINVAL; + } + + priority = param->sched_priority; + + /* Validate priority level. */ + if (priority < sched_get_priority_min (SCHED_OTHER) || + priority > sched_get_priority_max (SCHED_OTHER)) + { + return EINVAL; + } + + memcpy (&(*attr)->param, param, sizeof (*param)); + return 0; +} diff --git a/w32-pthreads/pthread_attr_setschedpolicy.c b/w32-pthreads/pthread_attr_setschedpolicy.c new file mode 100644 index 000000000..45ff16597 --- /dev/null +++ b/w32-pthreads/pthread_attr_setschedpolicy.c @@ -0,0 +1,55 @@ +/* + * pthread_attr_setschedpolicy.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +int +pthread_attr_setschedpolicy (pthread_attr_t * attr, int policy) +{ + if (ptw32_is_attr (attr) != 0) + { + return EINVAL; + } + + if (policy != SCHED_OTHER) + { + return ENOTSUP; + } + + return 0; +} diff --git a/w32-pthreads/pthread_attr_setscope.c b/w32-pthreads/pthread_attr_setscope.c new file mode 100644 index 000000000..39a51df88 --- /dev/null +++ b/w32-pthreads/pthread_attr_setscope.c @@ -0,0 +1,62 @@ +/* + * pthread_attr_setscope.c + * + * Description: + * This translation unit implements operations on thread attribute objects. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* ignore warning "unreferenced formal parameter" */ +#if defined(_MSC_VER) +#pragma warning( disable : 4100 ) +#endif + +int +pthread_attr_setscope (pthread_attr_t * attr, int contentionscope) +{ +#if defined(_POSIX_THREAD_PRIORITY_SCHEDULING) + switch (contentionscope) + { + case PTHREAD_SCOPE_SYSTEM: + (*attr)->contentionscope = contentionscope; + return 0; + case PTHREAD_SCOPE_PROCESS: + return ENOTSUP; + default: + return EINVAL; + } +#else + return ENOSYS; +#endif +} diff --git a/w32-pthreads/pthread_attr_setstackaddr.c b/w32-pthreads/pthread_attr_setstackaddr.c new file mode 100644 index 000000000..1316c0659 --- /dev/null +++ b/w32-pthreads/pthread_attr_setstackaddr.c @@ -0,0 +1,97 @@ +/* + * pthread_attr_setstackaddr.c + * + * Description: + * This translation unit implements operations on thread attribute objects. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_attr_setstackaddr (pthread_attr_t * attr, void *stackaddr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Threads created with 'attr' will run on the stack + * starting at 'stackaddr'. + * Stack must be at least PTHREAD_STACK_MIN bytes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_attr_t + * + * stackaddr + * the address of the stack to use + * + * + * DESCRIPTION + * Threads created with 'attr' will run on the stack + * starting at 'stackaddr'. + * Stack must be at least PTHREAD_STACK_MIN bytes. + * + * NOTES: + * 1) Function supported only if this macro is + * defined: + * + * _POSIX_THREAD_ATTR_STACKADDR + * + * 2) Create only one thread for each stack + * address.. + * + * 3) Ensure that stackaddr is aligned. + * + * RESULTS + * 0 successfully set stack address, + * EINVAL 'attr' is invalid + * ENOSYS function not supported + * + * ------------------------------------------------------ + */ +{ +#if defined( _POSIX_THREAD_ATTR_STACKADDR ) + + if (ptw32_is_attr (attr) != 0) + { + return EINVAL; + } + + (*attr)->stackaddr = stackaddr; + return 0; + +#else + + return ENOSYS; + +#endif /* _POSIX_THREAD_ATTR_STACKADDR */ +} diff --git a/w32-pthreads/pthread_attr_setstacksize.c b/w32-pthreads/pthread_attr_setstacksize.c new file mode 100644 index 000000000..eb13589a0 --- /dev/null +++ b/w32-pthreads/pthread_attr_setstacksize.c @@ -0,0 +1,110 @@ +/* + * pthread_attr_setstacksize.c + * + * Description: + * This translation unit implements operations on thread attribute objects. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_attr_setstacksize (pthread_attr_t * attr, size_t stacksize) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function specifies the size of the stack on + * which threads created with 'attr' will run. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_attr_t + * + * stacksize + * stack size, in bytes. + * + * + * DESCRIPTION + * This function specifies the size of the stack on + * which threads created with 'attr' will run. + * + * NOTES: + * 1) Function supported only if this macro is + * defined: + * + * _POSIX_THREAD_ATTR_STACKSIZE + * + * 2) Find the default first (using + * pthread_attr_getstacksize), then increase + * by multiplying. + * + * 3) Only use if thread needs more than the + * default. + * + * RESULTS + * 0 successfully set stack size, + * EINVAL 'attr' is invalid or stacksize too + * small or too big. + * ENOSYS function not supported + * + * ------------------------------------------------------ + */ +{ +#if defined(_POSIX_THREAD_ATTR_STACKSIZE) + +#if PTHREAD_STACK_MIN > 0 + + /* Verify that the stack size is within range. */ + if (stacksize < PTHREAD_STACK_MIN) + { + return EINVAL; + } + +#endif + + if (ptw32_is_attr (attr) != 0) + { + return EINVAL; + } + + /* Everything is okay. */ + (*attr)->stacksize = stacksize; + return 0; + +#else + + return ENOSYS; + +#endif /* _POSIX_THREAD_ATTR_STACKSIZE */ + +} diff --git a/w32-pthreads/pthread_barrier_destroy.c b/w32-pthreads/pthread_barrier_destroy.c new file mode 100644 index 000000000..55163cc85 --- /dev/null +++ b/w32-pthreads/pthread_barrier_destroy.c @@ -0,0 +1,103 @@ +/* + * pthread_barrier_destroy.c + * + * Description: + * This translation unit implements barrier primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +int +pthread_barrier_destroy (pthread_barrier_t * barrier) +{ + int result = 0; + pthread_barrier_t b; + ptw32_mcs_local_node_t node; + + if (barrier == NULL || *barrier == (pthread_barrier_t) PTW32_OBJECT_INVALID) + { + return EINVAL; + } + + if (0 != ptw32_mcs_lock_try_acquire(&(*barrier)->lock, &node)) + { + return EBUSY; + } + + b = *barrier; + + if (b->nCurrentBarrierHeight < b->nInitialBarrierHeight) + { + result = EBUSY; + } + else + { + if (0 == (result = sem_destroy (&(b->semBarrierBreeched)))) + { + *barrier = (pthread_barrier_t) PTW32_OBJECT_INVALID; + /* + * Release the lock before freeing b. + * + * FIXME: There may be successors which, when we release the lock, + * will be linked into b->lock, which will be corrupted at some + * point with undefined results for the application. To fix this + * will require changing pthread_barrier_t from a pointer to + * pthread_barrier_t_ to an instance. This is a change to the ABI + * and will require a major version number increment. + */ + ptw32_mcs_lock_release(&node); + (void) free (b); + return 0; + } + else + { + /* + * This should not ever be reached. + * Restore the barrier to working condition before returning. + */ + (void) sem_init (&(b->semBarrierBreeched), b->pshared, 0); + } + + if (result != 0) + { + /* + * The barrier still exists and is valid + * in the event of any error above. + */ + result = EBUSY; + } + } + + ptw32_mcs_lock_release(&node); + return (result); +} diff --git a/w32-pthreads/pthread_barrier_init.c b/w32-pthreads/pthread_barrier_init.c new file mode 100644 index 000000000..618bfae26 --- /dev/null +++ b/w32-pthreads/pthread_barrier_init.c @@ -0,0 +1,69 @@ +/* + * pthread_barrier_init.c + * + * Description: + * This translation unit implements barrier primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_barrier_init (pthread_barrier_t * barrier, + const pthread_barrierattr_t * attr, unsigned int count) +{ + pthread_barrier_t b; + + if (barrier == NULL || count == 0) + { + return EINVAL; + } + + if (NULL != (b = (pthread_barrier_t) calloc (1, sizeof (*b)))) + { + b->pshared = (attr != NULL && *attr != NULL + ? (*attr)->pshared : PTHREAD_PROCESS_PRIVATE); + + b->nCurrentBarrierHeight = b->nInitialBarrierHeight = count; + b->lock = 0; + + if (0 == sem_init (&(b->semBarrierBreeched), b->pshared, 0)) + { + *barrier = b; + return 0; + } + (void) free (b); + } + + return ENOMEM; +} diff --git a/w32-pthreads/pthread_barrier_wait.c b/w32-pthreads/pthread_barrier_wait.c new file mode 100644 index 000000000..e0e97e6c7 --- /dev/null +++ b/w32-pthreads/pthread_barrier_wait.c @@ -0,0 +1,104 @@ +/* + * pthread_barrier_wait.c + * + * Description: + * This translation unit implements barrier primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_barrier_wait (pthread_barrier_t * barrier) +{ + int result; + pthread_barrier_t b; + + ptw32_mcs_local_node_t node; + + if (barrier == NULL || *barrier == (pthread_barrier_t) PTW32_OBJECT_INVALID) + { + return EINVAL; + } + + ptw32_mcs_lock_acquire(&(*barrier)->lock, &node); + + b = *barrier; + if (--b->nCurrentBarrierHeight == 0) + { + /* + * We are the last thread to arrive at the barrier before it releases us. + * Move our MCS local node to the global scope barrier handle so that the + * last thread out (not necessarily us) can release the lock. + */ + ptw32_mcs_node_transfer(&b->proxynode, &node); + + /* + * Any threads that have not quite entered sem_wait below when the + * multiple_post has completed will nevertheless continue through + * the semaphore (barrier). + */ + result = (b->nInitialBarrierHeight > 1 + ? sem_post_multiple (&(b->semBarrierBreeched), + b->nInitialBarrierHeight - 1) : 0); + } + else + { + ptw32_mcs_lock_release(&node); + /* + * Use the non-cancelable version of sem_wait(). + * + * It is possible that all nInitialBarrierHeight-1 threads are + * at this point when the last thread enters the barrier, resets + * nCurrentBarrierHeight = nInitialBarrierHeight and leaves. + * If pthread_barrier_destroy is called at that moment then the + * barrier will be destroyed along with the semas. + */ + result = ptw32_semwait (&(b->semBarrierBreeched)); + } + + if ((PTW32_INTERLOCKED_LONG)PTW32_INTERLOCKED_INCREMENT_LONG((PTW32_INTERLOCKED_LONGPTR)&b->nCurrentBarrierHeight) + == (PTW32_INTERLOCKED_LONG)b->nInitialBarrierHeight) + { + /* + * We are the last thread to cross this barrier + */ + ptw32_mcs_lock_release(&b->proxynode); + if (0 == result) + { + result = PTHREAD_BARRIER_SERIAL_THREAD; + } + } + + return (result); +} diff --git a/w32-pthreads/pthread_barrierattr_destroy.c b/w32-pthreads/pthread_barrierattr_destroy.c new file mode 100644 index 000000000..5ab662e3f --- /dev/null +++ b/w32-pthreads/pthread_barrierattr_destroy.c @@ -0,0 +1,83 @@ +/* + * pthread_barrier_attr_destroy.c + * + * Description: + * This translation unit implements barrier primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_barrierattr_destroy (pthread_barrierattr_t * attr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Destroys a barrier attributes object. The object can + * no longer be used. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_barrierattr_t + * + * + * DESCRIPTION + * Destroys a barrier attributes object. The object can + * no longer be used. + * + * NOTES: + * 1) Does not affect barrieres created using 'attr' + * + * RESULTS + * 0 successfully released attr, + * EINVAL 'attr' is invalid. + * + * ------------------------------------------------------ + */ +{ + int result = 0; + + if (attr == NULL || *attr == NULL) + { + result = EINVAL; + } + else + { + pthread_barrierattr_t ba = *attr; + + *attr = NULL; + free (ba); + } + + return (result); +} /* pthread_barrierattr_destroy */ diff --git a/w32-pthreads/pthread_barrierattr_getpshared.c b/w32-pthreads/pthread_barrierattr_getpshared.c new file mode 100644 index 000000000..44c467e2b --- /dev/null +++ b/w32-pthreads/pthread_barrierattr_getpshared.c @@ -0,0 +1,95 @@ +/* + * pthread_barrier_attr_getpshared.c + * + * Description: + * This translation unit implements barrier primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_barrierattr_getpshared (const pthread_barrierattr_t * attr, + int *pshared) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Determine whether barriers created with 'attr' can be + * shared between processes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_barrierattr_t + * + * pshared + * will be set to one of: + * + * PTHREAD_PROCESS_SHARED + * May be shared if in shared memory + * + * PTHREAD_PROCESS_PRIVATE + * Cannot be shared. + * + * + * DESCRIPTION + * Mutexes creatd with 'attr' can be shared between + * processes if pthread_barrier_t variable is allocated + * in memory shared by these processes. + * NOTES: + * 1) pshared barriers MUST be allocated in shared + * memory. + * 2) The following macro is defined if shared barriers + * are supported: + * _POSIX_THREAD_PROCESS_SHARED + * + * RESULTS + * 0 successfully retrieved attribute, + * EINVAL 'attr' is invalid, + * + * ------------------------------------------------------ + */ +{ + int result; + + if ((attr != NULL && *attr != NULL) && (pshared != NULL)) + { + *pshared = (*attr)->pshared; + result = 0; + } + else + { + result = EINVAL; + } + + return (result); +} /* pthread_barrierattr_getpshared */ diff --git a/w32-pthreads/pthread_barrierattr_init.c b/w32-pthreads/pthread_barrierattr_init.c new file mode 100644 index 000000000..342f8b0c6 --- /dev/null +++ b/w32-pthreads/pthread_barrierattr_init.c @@ -0,0 +1,85 @@ +/* + * pthread_barrier_attr_init.c + * + * Description: + * This translation unit implements barrier primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_barrierattr_init (pthread_barrierattr_t * attr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Initializes a barrier attributes object with default + * attributes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_barrierattr_t + * + * + * DESCRIPTION + * Initializes a barrier attributes object with default + * attributes. + * + * NOTES: + * 1) Used to define barrier types + * + * RESULTS + * 0 successfully initialized attr, + * ENOMEM insufficient memory for attr. + * + * ------------------------------------------------------ + */ +{ + pthread_barrierattr_t ba; + int result = 0; + + ba = (pthread_barrierattr_t) calloc (1, sizeof (*ba)); + + if (ba == NULL) + { + result = ENOMEM; + } + else + { + ba->pshared = PTHREAD_PROCESS_PRIVATE; + } + + *attr = ba; + + return (result); +} /* pthread_barrierattr_init */ diff --git a/w32-pthreads/pthread_barrierattr_setpshared.c b/w32-pthreads/pthread_barrierattr_setpshared.c new file mode 100644 index 000000000..08c6fde30 --- /dev/null +++ b/w32-pthreads/pthread_barrierattr_setpshared.c @@ -0,0 +1,119 @@ +/* + * pthread_barrier_attr_setpshared.c + * + * Description: + * This translation unit implements barrier primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_barrierattr_setpshared (pthread_barrierattr_t * attr, int pshared) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Barriers created with 'attr' can be shared between + * processes if pthread_barrier_t variable is allocated + * in memory shared by these processes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_barrierattr_t + * + * pshared + * must be one of: + * + * PTHREAD_PROCESS_SHARED + * May be shared if in shared memory + * + * PTHREAD_PROCESS_PRIVATE + * Cannot be shared. + * + * DESCRIPTION + * Mutexes creatd with 'attr' can be shared between + * processes if pthread_barrier_t variable is allocated + * in memory shared by these processes. + * + * NOTES: + * 1) pshared barriers MUST be allocated in shared + * memory. + * + * 2) The following macro is defined if shared barriers + * are supported: + * _POSIX_THREAD_PROCESS_SHARED + * + * RESULTS + * 0 successfully set attribute, + * EINVAL 'attr' or pshared is invalid, + * ENOSYS PTHREAD_PROCESS_SHARED not supported, + * + * ------------------------------------------------------ + */ +{ + int result; + + if ((attr != NULL && *attr != NULL) && + ((pshared == PTHREAD_PROCESS_SHARED) || + (pshared == PTHREAD_PROCESS_PRIVATE))) + { + if (pshared == PTHREAD_PROCESS_SHARED) + { + +#if !defined( _POSIX_THREAD_PROCESS_SHARED ) + + result = ENOSYS; + pshared = PTHREAD_PROCESS_PRIVATE; + +#else + + result = 0; + +#endif /* _POSIX_THREAD_PROCESS_SHARED */ + + } + else + { + result = 0; + } + + (*attr)->pshared = pshared; + } + else + { + result = EINVAL; + } + + return (result); + +} /* pthread_barrierattr_setpshared */ diff --git a/w32-pthreads/pthread_cancel.c b/w32-pthreads/pthread_cancel.c new file mode 100644 index 000000000..ae60b7293 --- /dev/null +++ b/w32-pthreads/pthread_cancel.c @@ -0,0 +1,189 @@ +/* + * pthread_cancel.c + * + * Description: + * POSIX thread functions related to thread cancellation. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "context.h" + +static void +ptw32_cancel_self (void) +{ + ptw32_throw (PTW32_EPS_CANCEL); + + /* Never reached */ +} + +static void CALLBACK +ptw32_cancel_callback (ULONG_PTR unused) +{ + ptw32_throw (PTW32_EPS_CANCEL); + + /* Never reached */ +} + +/* + * ptw32_RegisterCancelation() - + * Must have args of same type as QueueUserAPCEx because this function + * is a substitute for QueueUserAPCEx if it's not available. + */ +DWORD +ptw32_RegisterCancelation (PAPCFUNC unused1, HANDLE threadH, DWORD unused2) +{ + CONTEXT context; + + context.ContextFlags = CONTEXT_CONTROL; + GetThreadContext (threadH, &context); + PTW32_PROGCTR (context) = (DWORD_PTR) ptw32_cancel_self; + SetThreadContext (threadH, &context); + return 0; +} + +int +pthread_cancel (pthread_t thread) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function requests cancellation of 'thread'. + * + * PARAMETERS + * thread + * reference to an instance of pthread_t + * + * + * DESCRIPTION + * This function requests cancellation of 'thread'. + * NOTE: cancellation is asynchronous; use pthread_join to + * wait for termination of 'thread' if necessary. + * + * RESULTS + * 0 successfully requested cancellation, + * ESRCH no thread found corresponding to 'thread', + * ENOMEM implicit self thread create failed. + * ------------------------------------------------------ + */ +{ + int result; + int cancel_self; + pthread_t self; + ptw32_thread_t * tp; + ptw32_mcs_local_node_t stateLock; + + result = pthread_kill (thread, 0); + + if (0 != result) + { + return result; + } + + if ((self = pthread_self ()).p == NULL) + { + return ENOMEM; + }; + + /* + * For self cancellation we need to ensure that a thread can't + * deadlock itself trying to cancel itself asynchronously + * (pthread_cancel is required to be an async-cancel + * safe function). + */ + cancel_self = pthread_equal (thread, self); + + tp = (ptw32_thread_t *) thread.p; + + /* + * Lock for async-cancel safety. + */ + ptw32_mcs_lock_acquire (&tp->stateLock, &stateLock); + + if (tp->cancelType == PTHREAD_CANCEL_ASYNCHRONOUS + && tp->cancelState == PTHREAD_CANCEL_ENABLE + && tp->state < PThreadStateCanceling) + { + if (cancel_self) + { + tp->state = PThreadStateCanceling; + tp->cancelState = PTHREAD_CANCEL_DISABLE; + + ptw32_mcs_lock_release (&stateLock); + ptw32_throw (PTW32_EPS_CANCEL); + + /* Never reached */ + } + else + { + HANDLE threadH = tp->threadH; + + SuspendThread (threadH); + + if (WaitForSingleObject (threadH, 0) == WAIT_TIMEOUT) + { + tp->state = PThreadStateCanceling; + tp->cancelState = PTHREAD_CANCEL_DISABLE; + /* + * If alertdrv and QueueUserAPCEx is available then the following + * will result in a call to QueueUserAPCEx with the args given, otherwise + * this will result in a call to ptw32_RegisterCancelation and only + * the threadH arg will be used. + */ + ptw32_register_cancelation ((PAPCFUNC)ptw32_cancel_callback, threadH, 0); + ptw32_mcs_lock_release (&stateLock); + ResumeThread (threadH); + } + } + } + else + { + /* + * Set for deferred cancellation. + */ + if (tp->state < PThreadStateCancelPending) + { + tp->state = PThreadStateCancelPending; + if (!SetEvent (tp->cancelEvent)) + { + result = ESRCH; + } + } + else if (tp->state >= PThreadStateCanceling) + { + result = ESRCH; + } + + ptw32_mcs_lock_release (&stateLock); + } + + return (result); +} diff --git a/w32-pthreads/pthread_cond_destroy.c b/w32-pthreads/pthread_cond_destroy.c new file mode 100644 index 000000000..40d4a0896 --- /dev/null +++ b/w32-pthreads/pthread_cond_destroy.c @@ -0,0 +1,253 @@ +/* + * pthread_cond_destroy.c + * + * Description: + * This translation unit implements condition variables and their primitives. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +int +pthread_cond_destroy (pthread_cond_t * cond) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function destroys a condition variable + * + * + * PARAMETERS + * cond + * pointer to an instance of pthread_cond_t + * + * + * DESCRIPTION + * This function destroys a condition variable. + * + * NOTES: + * 1) A condition variable can be destroyed + * immediately after all the threads that + * are blocked on it are awakened. e.g. + * + * struct list { + * pthread_mutex_t lm; + * ... + * } + * + * struct elt { + * key k; + * int busy; + * pthread_cond_t notbusy; + * ... + * } + * + * + * struct elt * + * list_find(struct list *lp, key k) + * { + * struct elt *ep; + * + * pthread_mutex_lock(&lp->lm); + * while ((ep = find_elt(l,k) != NULL) && ep->busy) + * pthread_cond_wait(&ep->notbusy, &lp->lm); + * if (ep != NULL) + * ep->busy = 1; + * pthread_mutex_unlock(&lp->lm); + * return(ep); + * } + * + * delete_elt(struct list *lp, struct elt *ep) + * { + * pthread_mutex_lock(&lp->lm); + * assert(ep->busy); + * ... remove ep from list ... + * ep->busy = 0; + * (A) pthread_cond_broadcast(&ep->notbusy); + * pthread_mutex_unlock(&lp->lm); + * (B) pthread_cond_destroy(&rp->notbusy); + * free(ep); + * } + * + * In this example, the condition variable + * and its list element may be freed (line B) + * immediately after all threads waiting for + * it are awakened (line A), since the mutex + * and the code ensure that no other thread + * can touch the element to be deleted. + * + * RESULTS + * 0 successfully released condition variable, + * EINVAL 'cond' is invalid, + * EBUSY 'cond' is in use, + * + * ------------------------------------------------------ + */ +{ + pthread_cond_t cv; + int result = 0, result1 = 0, result2 = 0; + + /* + * Assuming any race condition here is harmless. + */ + if (cond == NULL || *cond == NULL) + { + return EINVAL; + } + + if (*cond != PTHREAD_COND_INITIALIZER) + { + ptw32_mcs_local_node_t node; + ptw32_mcs_lock_acquire(&ptw32_cond_list_lock, &node); + + cv = *cond; + + /* + * Close the gate; this will synchronize this thread with + * all already signaled waiters to let them retract their + * waiter status - SEE NOTE 1 ABOVE!!! + */ + if (ptw32_semwait (&(cv->semBlockLock)) != 0) /* Non-cancelable */ + { + result = errno; + } + else + { + /* + * !TRY! lock mtxUnblockLock; try will detect busy condition + * and will not cause a deadlock with respect to concurrent + * signal/broadcast. + */ + if ((result = pthread_mutex_trylock (&(cv->mtxUnblockLock))) != 0) + { + (void) sem_post (&(cv->semBlockLock)); + } + } + + if (result != 0) + { + ptw32_mcs_lock_release(&node); + return result; + } + + /* + * Check whether cv is still busy (still has waiters) + */ + if (cv->nWaitersBlocked > cv->nWaitersGone) + { + if (sem_post (&(cv->semBlockLock)) != 0) + { + result = errno; + } + result1 = pthread_mutex_unlock (&(cv->mtxUnblockLock)); + result2 = EBUSY; + } + else + { + /* + * Now it is safe to destroy + */ + *cond = NULL; + + if (sem_destroy (&(cv->semBlockLock)) != 0) + { + result = errno; + } + if (sem_destroy (&(cv->semBlockQueue)) != 0) + { + result1 = errno; + } + if ((result2 = pthread_mutex_unlock (&(cv->mtxUnblockLock))) == 0) + { + result2 = pthread_mutex_destroy (&(cv->mtxUnblockLock)); + } + + /* Unlink the CV from the list */ + + if (ptw32_cond_list_head == cv) + { + ptw32_cond_list_head = cv->next; + } + else + { + cv->prev->next = cv->next; + } + + if (ptw32_cond_list_tail == cv) + { + ptw32_cond_list_tail = cv->prev; + } + else + { + cv->next->prev = cv->prev; + } + + (void) free (cv); + } + + ptw32_mcs_lock_release(&node); + } + else + { + ptw32_mcs_local_node_t node; + /* + * See notes in ptw32_cond_check_need_init() above also. + */ + ptw32_mcs_lock_acquire(&ptw32_cond_test_init_lock, &node); + + /* + * Check again. + */ + if (*cond == PTHREAD_COND_INITIALIZER) + { + /* + * This is all we need to do to destroy a statically + * initialised cond that has not yet been used (initialised). + * If we get to here, another thread waiting to initialise + * this cond will get an EINVAL. That's OK. + */ + *cond = NULL; + } + else + { + /* + * The cv has been initialised while we were waiting + * so assume it's in use. + */ + result = EBUSY; + } + + ptw32_mcs_lock_release(&node); + } + + return ((result != 0) ? result : ((result1 != 0) ? result1 : result2)); +} diff --git a/w32-pthreads/pthread_cond_init.c b/w32-pthreads/pthread_cond_init.c new file mode 100644 index 000000000..f28fd67b4 --- /dev/null +++ b/w32-pthreads/pthread_cond_init.c @@ -0,0 +1,167 @@ +/* + * pthread_cond_init.c + * + * Description: + * This translation unit implements condition variables and their primitives. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_cond_init (pthread_cond_t * cond, const pthread_condattr_t * attr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function initializes a condition variable. + * + * PARAMETERS + * cond + * pointer to an instance of pthread_cond_t + * + * attr + * specifies optional creation attributes. + * + * + * DESCRIPTION + * This function initializes a condition variable. + * + * RESULTS + * 0 successfully created condition variable, + * EINVAL 'attr' is invalid, + * EAGAIN insufficient resources (other than + * memory, + * ENOMEM insufficient memory, + * EBUSY 'cond' is already initialized, + * + * ------------------------------------------------------ + */ +{ + int result; + pthread_cond_t cv = NULL; + + if (cond == NULL) + { + return EINVAL; + } + + if ((attr != NULL && *attr != NULL) && + ((*attr)->pshared == PTHREAD_PROCESS_SHARED)) + { + /* + * Creating condition variable that can be shared between + * processes. + */ + result = ENOSYS; + goto DONE; + } + + cv = (pthread_cond_t) calloc (1, sizeof (*cv)); + + if (cv == NULL) + { + result = ENOMEM; + goto DONE; + } + + cv->nWaitersBlocked = 0; + cv->nWaitersToUnblock = 0; + cv->nWaitersGone = 0; + + if (sem_init (&(cv->semBlockLock), 0, 1) != 0) + { + result = errno; + goto FAIL0; + } + + if (sem_init (&(cv->semBlockQueue), 0, 0) != 0) + { + result = errno; + goto FAIL1; + } + + if ((result = pthread_mutex_init (&(cv->mtxUnblockLock), 0)) != 0) + { + goto FAIL2; + } + + result = 0; + + goto DONE; + + /* + * ------------- + * Failed... + * ------------- + */ +FAIL2: + (void) sem_destroy (&(cv->semBlockQueue)); + +FAIL1: + (void) sem_destroy (&(cv->semBlockLock)); + +FAIL0: + (void) free (cv); + cv = NULL; + +DONE: + if (0 == result) + { + ptw32_mcs_local_node_t node; + + ptw32_mcs_lock_acquire(&ptw32_cond_list_lock, &node); + + cv->next = NULL; + cv->prev = ptw32_cond_list_tail; + + if (ptw32_cond_list_tail != NULL) + { + ptw32_cond_list_tail->next = cv; + } + + ptw32_cond_list_tail = cv; + + if (ptw32_cond_list_head == NULL) + { + ptw32_cond_list_head = cv; + } + + ptw32_mcs_lock_release(&node); + } + + *cond = cv; + + return result; + +} /* pthread_cond_init */ diff --git a/w32-pthreads/pthread_cond_signal.c b/w32-pthreads/pthread_cond_signal.c new file mode 100644 index 000000000..2b4f6d4d4 --- /dev/null +++ b/w32-pthreads/pthread_cond_signal.c @@ -0,0 +1,231 @@ +/* + * pthread_cond_signal.c + * + * Description: + * This translation unit implements condition variables and their primitives. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * ------------------------------------------------------------- + * Algorithm: + * See the comments at the top of pthread_cond_wait.c. + */ + +#include "pthread.h" +#include "implement.h" + +static INLINE int +ptw32_cond_unblock (pthread_cond_t * cond, int unblockAll) + /* + * Notes. + * + * Does not use the external mutex for synchronisation, + * therefore semBlockLock is needed. + * mtxUnblockLock is for LEVEL-2 synch. LEVEL-2 is the + * state where the external mutex is not necessarily locked by + * any thread, ie. between cond_wait unlocking and re-acquiring + * the lock after having been signaled or a timeout or + * cancellation. + * + * Uses the following CV elements: + * nWaitersBlocked + * nWaitersToUnblock + * nWaitersGone + * mtxUnblockLock + * semBlockLock + * semBlockQueue + */ +{ + int result; + pthread_cond_t cv; + int nSignalsToIssue; + + if (cond == NULL || *cond == NULL) + { + return EINVAL; + } + + cv = *cond; + + /* + * No-op if the CV is static and hasn't been initialised yet. + * Assuming that any race condition is harmless. + */ + if (cv == PTHREAD_COND_INITIALIZER) + { + return 0; + } + + if ((result = pthread_mutex_lock (&(cv->mtxUnblockLock))) != 0) + { + return result; + } + + if (0 != cv->nWaitersToUnblock) + { + if (0 == cv->nWaitersBlocked) + { + return pthread_mutex_unlock (&(cv->mtxUnblockLock)); + } + if (unblockAll) + { + cv->nWaitersToUnblock += (nSignalsToIssue = cv->nWaitersBlocked); + cv->nWaitersBlocked = 0; + } + else + { + nSignalsToIssue = 1; + cv->nWaitersToUnblock++; + cv->nWaitersBlocked--; + } + } + else if (cv->nWaitersBlocked > cv->nWaitersGone) + { + /* Use the non-cancellable version of sem_wait() */ + if (ptw32_semwait (&(cv->semBlockLock)) != 0) + { + result = errno; + (void) pthread_mutex_unlock (&(cv->mtxUnblockLock)); + return result; + } + if (0 != cv->nWaitersGone) + { + cv->nWaitersBlocked -= cv->nWaitersGone; + cv->nWaitersGone = 0; + } + if (unblockAll) + { + nSignalsToIssue = cv->nWaitersToUnblock = cv->nWaitersBlocked; + cv->nWaitersBlocked = 0; + } + else + { + nSignalsToIssue = cv->nWaitersToUnblock = 1; + cv->nWaitersBlocked--; + } + } + else + { + return pthread_mutex_unlock (&(cv->mtxUnblockLock)); + } + + if ((result = pthread_mutex_unlock (&(cv->mtxUnblockLock))) == 0) + { + if (sem_post_multiple (&(cv->semBlockQueue), nSignalsToIssue) != 0) + { + result = errno; + } + } + + return result; + +} /* ptw32_cond_unblock */ + +int +pthread_cond_signal (pthread_cond_t * cond) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function signals a condition variable, waking + * one waiting thread. + * If SCHED_FIFO or SCHED_RR policy threads are waiting + * the highest priority waiter is awakened; otherwise, + * an unspecified waiter is awakened. + * + * PARAMETERS + * cond + * pointer to an instance of pthread_cond_t + * + * + * DESCRIPTION + * This function signals a condition variable, waking + * one waiting thread. + * If SCHED_FIFO or SCHED_RR policy threads are waiting + * the highest priority waiter is awakened; otherwise, + * an unspecified waiter is awakened. + * + * NOTES: + * + * 1) Use when any waiter can respond and only one need + * respond (all waiters being equal). + * + * RESULTS + * 0 successfully signaled condition, + * EINVAL 'cond' is invalid, + * + * ------------------------------------------------------ + */ +{ + /* + * The '0'(FALSE) unblockAll arg means unblock ONE waiter. + */ + return (ptw32_cond_unblock (cond, 0)); + +} /* pthread_cond_signal */ + +int +pthread_cond_broadcast (pthread_cond_t * cond) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function broadcasts the condition variable, + * waking all current waiters. + * + * PARAMETERS + * cond + * pointer to an instance of pthread_cond_t + * + * + * DESCRIPTION + * This function signals a condition variable, waking + * all waiting threads. + * + * NOTES: + * + * 1) Use when more than one waiter may respond to + * predicate change or if any waiting thread may + * not be able to respond + * + * RESULTS + * 0 successfully signalled condition to all + * waiting threads, + * EINVAL 'cond' is invalid + * ENOSPC a required resource has been exhausted, + * + * ------------------------------------------------------ + */ +{ + /* + * The TRUE unblockAll arg means unblock ALL waiters. + */ + return (ptw32_cond_unblock (cond, PTW32_TRUE)); + +} /* pthread_cond_broadcast */ diff --git a/w32-pthreads/pthread_cond_wait.c b/w32-pthreads/pthread_cond_wait.c new file mode 100644 index 000000000..359219ae9 --- /dev/null +++ b/w32-pthreads/pthread_cond_wait.c @@ -0,0 +1,567 @@ +/* + * pthread_cond_wait.c + * + * Description: + * This translation unit implements condition variables and their primitives. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * ------------------------------------------------------------- + * Algorithm: + * The algorithm used in this implementation is that developed by + * Alexander Terekhov in colaboration with Louis Thomas. The bulk + * of the discussion is recorded in the file README.CV, which contains + * several generations of both colaborators original algorithms. The final + * algorithm used here is the one referred to as + * + * Algorithm 8a / IMPL_SEM,UNBLOCK_STRATEGY == UNBLOCK_ALL + * + * presented below in pseudo-code as it appeared: + * + * + * given: + * semBlockLock - bin.semaphore + * semBlockQueue - semaphore + * mtxExternal - mutex or CS + * mtxUnblockLock - mutex or CS + * nWaitersGone - int + * nWaitersBlocked - int + * nWaitersToUnblock - int + * + * wait( timeout ) { + * + * [auto: register int result ] // error checking omitted + * [auto: register int nSignalsWasLeft ] + * [auto: register int nWaitersWasGone ] + * + * sem_wait( semBlockLock ); + * nWaitersBlocked++; + * sem_post( semBlockLock ); + * + * unlock( mtxExternal ); + * bTimedOut = sem_wait( semBlockQueue,timeout ); + * + * lock( mtxUnblockLock ); + * if ( 0 != (nSignalsWasLeft = nWaitersToUnblock) ) { + * if ( bTimeout ) { // timeout (or canceled) + * if ( 0 != nWaitersBlocked ) { + * nWaitersBlocked--; + * } + * else { + * nWaitersGone++; // count spurious wakeups. + * } + * } + * if ( 0 == --nWaitersToUnblock ) { + * if ( 0 != nWaitersBlocked ) { + * sem_post( semBlockLock ); // open the gate. + * nSignalsWasLeft = 0; // do not open the gate + * // below again. + * } + * else if ( 0 != (nWaitersWasGone = nWaitersGone) ) { + * nWaitersGone = 0; + * } + * } + * } + * else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or + * // spurious semaphore :-) + * sem_wait( semBlockLock ); + * nWaitersBlocked -= nWaitersGone; // something is going on here + * // - test of timeouts? :-) + * sem_post( semBlockLock ); + * nWaitersGone = 0; + * } + * unlock( mtxUnblockLock ); + * + * if ( 1 == nSignalsWasLeft ) { + * if ( 0 != nWaitersWasGone ) { + * // sem_adjust( semBlockQueue,-nWaitersWasGone ); + * while ( nWaitersWasGone-- ) { + * sem_wait( semBlockQueue ); // better now than spurious later + * } + * } sem_post( semBlockLock ); // open the gate + * } + * + * lock( mtxExternal ); + * + * return ( bTimedOut ) ? ETIMEOUT : 0; + * } + * + * signal(bAll) { + * + * [auto: register int result ] + * [auto: register int nSignalsToIssue] + * + * lock( mtxUnblockLock ); + * + * if ( 0 != nWaitersToUnblock ) { // the gate is closed!!! + * if ( 0 == nWaitersBlocked ) { // NO-OP + * return unlock( mtxUnblockLock ); + * } + * if (bAll) { + * nWaitersToUnblock += nSignalsToIssue=nWaitersBlocked; + * nWaitersBlocked = 0; + * } + * else { + * nSignalsToIssue = 1; + * nWaitersToUnblock++; + * nWaitersBlocked--; + * } + * } + * else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION! + * sem_wait( semBlockLock ); // close the gate + * if ( 0 != nWaitersGone ) { + * nWaitersBlocked -= nWaitersGone; + * nWaitersGone = 0; + * } + * if (bAll) { + * nSignalsToIssue = nWaitersToUnblock = nWaitersBlocked; + * nWaitersBlocked = 0; + * } + * else { + * nSignalsToIssue = nWaitersToUnblock = 1; + * nWaitersBlocked--; + * } + * } + * else { // NO-OP + * return unlock( mtxUnblockLock ); + * } + * + * unlock( mtxUnblockLock ); + * sem_post( semBlockQueue,nSignalsToIssue ); + * return result; + * } + * ------------------------------------------------------------- + * + * Algorithm 9 / IMPL_SEM,UNBLOCK_STRATEGY == UNBLOCK_ALL + * + * presented below in pseudo-code; basically 8a... + * ...BUT W/O "spurious wakes" prevention: + * + * + * given: + * semBlockLock - bin.semaphore + * semBlockQueue - semaphore + * mtxExternal - mutex or CS + * mtxUnblockLock - mutex or CS + * nWaitersGone - int + * nWaitersBlocked - int + * nWaitersToUnblock - int + * + * wait( timeout ) { + * + * [auto: register int result ] // error checking omitted + * [auto: register int nSignalsWasLeft ] + * + * sem_wait( semBlockLock ); + * ++nWaitersBlocked; + * sem_post( semBlockLock ); + * + * unlock( mtxExternal ); + * bTimedOut = sem_wait( semBlockQueue,timeout ); + * + * lock( mtxUnblockLock ); + * if ( 0 != (nSignalsWasLeft = nWaitersToUnblock) ) { + * --nWaitersToUnblock; + * } + * else if ( INT_MAX/2 == ++nWaitersGone ) { // timeout/canceled or + * // spurious semaphore :-) + * sem_wait( semBlockLock ); + * nWaitersBlocked -= nWaitersGone; // something is going on here + * // - test of timeouts? :-) + * sem_post( semBlockLock ); + * nWaitersGone = 0; + * } + * unlock( mtxUnblockLock ); + * + * if ( 1 == nSignalsWasLeft ) { + * sem_post( semBlockLock ); // open the gate + * } + * + * lock( mtxExternal ); + * + * return ( bTimedOut ) ? ETIMEOUT : 0; + * } + * + * signal(bAll) { + * + * [auto: register int result ] + * [auto: register int nSignalsToIssue] + * + * lock( mtxUnblockLock ); + * + * if ( 0 != nWaitersToUnblock ) { // the gate is closed!!! + * if ( 0 == nWaitersBlocked ) { // NO-OP + * return unlock( mtxUnblockLock ); + * } + * if (bAll) { + * nWaitersToUnblock += nSignalsToIssue=nWaitersBlocked; + * nWaitersBlocked = 0; + * } + * else { + * nSignalsToIssue = 1; + * ++nWaitersToUnblock; + * --nWaitersBlocked; + * } + * } + * else if ( nWaitersBlocked > nWaitersGone ) { // HARMLESS RACE CONDITION! + * sem_wait( semBlockLock ); // close the gate + * if ( 0 != nWaitersGone ) { + * nWaitersBlocked -= nWaitersGone; + * nWaitersGone = 0; + * } + * if (bAll) { + * nSignalsToIssue = nWaitersToUnblock = nWaitersBlocked; + * nWaitersBlocked = 0; + * } + * else { + * nSignalsToIssue = nWaitersToUnblock = 1; + * --nWaitersBlocked; + * } + * } + * else { // NO-OP + * return unlock( mtxUnblockLock ); + * } + * + * unlock( mtxUnblockLock ); + * sem_post( semBlockQueue,nSignalsToIssue ); + * return result; + * } + * ------------------------------------------------------------- + * + */ + +#include "pthread.h" +#include "implement.h" + +/* + * Arguments for cond_wait_cleanup, since we can only pass a + * single void * to it. + */ +typedef struct +{ + pthread_mutex_t *mutexPtr; + pthread_cond_t cv; + int *resultPtr; +} ptw32_cond_wait_cleanup_args_t; + +static void PTW32_CDECL +ptw32_cond_wait_cleanup (void *args) +{ + ptw32_cond_wait_cleanup_args_t *cleanup_args = + (ptw32_cond_wait_cleanup_args_t *) args; + pthread_cond_t cv = cleanup_args->cv; + int *resultPtr = cleanup_args->resultPtr; + int nSignalsWasLeft; + int result; + + /* + * Whether we got here as a result of signal/broadcast or because of + * timeout on wait or thread cancellation we indicate that we are no + * longer waiting. The waiter is responsible for adjusting waiters + * (to)unblock(ed) counts (protected by unblock lock). + */ + if ((result = pthread_mutex_lock (&(cv->mtxUnblockLock))) != 0) + { + *resultPtr = result; + return; + } + + if (0 != (nSignalsWasLeft = cv->nWaitersToUnblock)) + { + --(cv->nWaitersToUnblock); + } + else if (INT_MAX / 2 == ++(cv->nWaitersGone)) + { + /* Use the non-cancellable version of sem_wait() */ + if (ptw32_semwait (&(cv->semBlockLock)) != 0) + { + *resultPtr = errno; + /* + * This is a fatal error for this CV, + * so we deliberately don't unlock + * cv->mtxUnblockLock before returning. + */ + return; + } + cv->nWaitersBlocked -= cv->nWaitersGone; + if (sem_post (&(cv->semBlockLock)) != 0) + { + *resultPtr = errno; + /* + * This is a fatal error for this CV, + * so we deliberately don't unlock + * cv->mtxUnblockLock before returning. + */ + return; + } + cv->nWaitersGone = 0; + } + + if ((result = pthread_mutex_unlock (&(cv->mtxUnblockLock))) != 0) + { + *resultPtr = result; + return; + } + + if (1 == nSignalsWasLeft) + { + if (sem_post (&(cv->semBlockLock)) != 0) + { + *resultPtr = errno; + return; + } + } + + /* + * XSH: Upon successful return, the mutex has been locked and is owned + * by the calling thread. + */ + if ((result = pthread_mutex_lock (cleanup_args->mutexPtr)) != 0) + { + *resultPtr = result; + } +} /* ptw32_cond_wait_cleanup */ + +static INLINE int +ptw32_cond_timedwait (pthread_cond_t * cond, + pthread_mutex_t * mutex, const struct timespec *abstime) +{ + int result = 0; + pthread_cond_t cv; + ptw32_cond_wait_cleanup_args_t cleanup_args; + + if (cond == NULL || *cond == NULL) + { + return EINVAL; + } + + /* + * We do a quick check to see if we need to do more work + * to initialise a static condition variable. We check + * again inside the guarded section of ptw32_cond_check_need_init() + * to avoid race conditions. + */ + if (*cond == PTHREAD_COND_INITIALIZER) + { + result = ptw32_cond_check_need_init (cond); + } + + if (result != 0 && result != EBUSY) + { + return result; + } + + cv = *cond; + + /* Thread can be cancelled in sem_wait() but this is OK */ + if (sem_wait (&(cv->semBlockLock)) != 0) + { + return errno; + } + + ++(cv->nWaitersBlocked); + + if (sem_post (&(cv->semBlockLock)) != 0) + { + return errno; + } + + /* + * Setup this waiter cleanup handler + */ + cleanup_args.mutexPtr = mutex; + cleanup_args.cv = cv; + cleanup_args.resultPtr = &result; + +#if defined(_MSC_VER) && _MSC_VER < 1400 +#pragma inline_depth(0) +#endif + pthread_cleanup_push (ptw32_cond_wait_cleanup, (void *) &cleanup_args); + + /* + * Now we can release 'mutex' and... + */ + if ((result = pthread_mutex_unlock (mutex)) == 0) + { + + /* + * ...wait to be awakened by + * pthread_cond_signal, or + * pthread_cond_broadcast, or + * timeout, or + * thread cancellation + * + * Note: + * + * sem_timedwait is a cancellation point, + * hence providing the mechanism for making + * pthread_cond_wait a cancellation point. + * We use the cleanup mechanism to ensure we + * re-lock the mutex and adjust (to)unblock(ed) waiters + * counts if we are cancelled, timed out or signalled. + */ + if (sem_timedwait (&(cv->semBlockQueue), abstime) != 0) + { + result = errno; + } + } + + /* + * Always cleanup + */ + pthread_cleanup_pop (1); +#if defined(_MSC_VER) && _MSC_VER < 1400 +#pragma inline_depth() +#endif + + /* + * "result" can be modified by the cleanup handler. + */ + return result; + +} /* ptw32_cond_timedwait */ + + +int +pthread_cond_wait (pthread_cond_t * cond, pthread_mutex_t * mutex) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function waits on a condition variable until + * awakened by a signal or broadcast. + * + * Caller MUST be holding the mutex lock; the + * lock is released and the caller is blocked waiting + * on 'cond'. When 'cond' is signaled, the mutex + * is re-acquired before returning to the caller. + * + * PARAMETERS + * cond + * pointer to an instance of pthread_cond_t + * + * mutex + * pointer to an instance of pthread_mutex_t + * + * + * DESCRIPTION + * This function waits on a condition variable until + * awakened by a signal or broadcast. + * + * NOTES: + * + * 1) The function must be called with 'mutex' LOCKED + * by the calling thread, or undefined behaviour + * will result. + * + * 2) This routine atomically releases 'mutex' and causes + * the calling thread to block on the condition variable. + * The blocked thread may be awakened by + * pthread_cond_signal or + * pthread_cond_broadcast. + * + * Upon successful completion, the 'mutex' has been locked and + * is owned by the calling thread. + * + * + * RESULTS + * 0 caught condition; mutex released, + * EINVAL 'cond' or 'mutex' is invalid, + * EINVAL different mutexes for concurrent waits, + * EINVAL mutex is not held by the calling thread, + * + * ------------------------------------------------------ + */ +{ + /* + * The NULL abstime arg means INFINITE waiting. + */ + return (ptw32_cond_timedwait (cond, mutex, NULL)); + +} /* pthread_cond_wait */ + + +int +pthread_cond_timedwait (pthread_cond_t * cond, + pthread_mutex_t * mutex, + const struct timespec *abstime) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function waits on a condition variable either until + * awakened by a signal or broadcast; or until the time + * specified by abstime passes. + * + * PARAMETERS + * cond + * pointer to an instance of pthread_cond_t + * + * mutex + * pointer to an instance of pthread_mutex_t + * + * abstime + * pointer to an instance of (const struct timespec) + * + * + * DESCRIPTION + * This function waits on a condition variable either until + * awakened by a signal or broadcast; or until the time + * specified by abstime passes. + * + * NOTES: + * 1) The function must be called with 'mutex' LOCKED + * by the calling thread, or undefined behaviour + * will result. + * + * 2) This routine atomically releases 'mutex' and causes + * the calling thread to block on the condition variable. + * The blocked thread may be awakened by + * pthread_cond_signal or + * pthread_cond_broadcast. + * + * + * RESULTS + * 0 caught condition; mutex released, + * EINVAL 'cond', 'mutex', or abstime is invalid, + * EINVAL different mutexes for concurrent waits, + * EINVAL mutex is not held by the calling thread, + * ETIMEDOUT abstime ellapsed before cond was signaled. + * + * ------------------------------------------------------ + */ +{ + if (abstime == NULL) + { + return EINVAL; + } + + return (ptw32_cond_timedwait (cond, mutex, abstime)); + +} /* pthread_cond_timedwait */ diff --git a/w32-pthreads/pthread_condattr_destroy.c b/w32-pthreads/pthread_condattr_destroy.c new file mode 100644 index 000000000..58a14828f --- /dev/null +++ b/w32-pthreads/pthread_condattr_destroy.c @@ -0,0 +1,86 @@ +/* + * condvar_attr_destroy.c + * + * Description: + * This translation unit implements condition variables and their primitives. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_condattr_destroy (pthread_condattr_t * attr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Destroys a condition variable attributes object. + * The object can no longer be used. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_condattr_t + * + * + * DESCRIPTION + * Destroys a condition variable attributes object. + * The object can no longer be used. + * + * NOTES: + * 1) Does not affect condition variables created + * using 'attr' + * + * RESULTS + * 0 successfully released attr, + * EINVAL 'attr' is invalid. + * + * ------------------------------------------------------ + */ +{ + int result = 0; + + if (attr == NULL || *attr == NULL) + { + result = EINVAL; + } + else + { + (void) free (*attr); + + *attr = NULL; + result = 0; + } + + return result; + +} /* pthread_condattr_destroy */ diff --git a/w32-pthreads/pthread_condattr_getpshared.c b/w32-pthreads/pthread_condattr_getpshared.c new file mode 100644 index 000000000..a0ac6d882 --- /dev/null +++ b/w32-pthreads/pthread_condattr_getpshared.c @@ -0,0 +1,97 @@ +/* + * pthread_condattr_getpshared.c + * + * Description: + * This translation unit implements condition variables and their primitives. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_condattr_getpshared (const pthread_condattr_t * attr, int *pshared) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Determine whether condition variables created with 'attr' + * can be shared between processes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_condattr_t + * + * pshared + * will be set to one of: + * + * PTHREAD_PROCESS_SHARED + * May be shared if in shared memory + * + * PTHREAD_PROCESS_PRIVATE + * Cannot be shared. + * + * + * DESCRIPTION + * Condition Variables created with 'attr' can be shared + * between processes if pthread_cond_t variable is allocated + * in memory shared by these processes. + * NOTES: + * 1) pshared condition variables MUST be allocated in + * shared memory. + * + * 2) The following macro is defined if shared mutexes + * are supported: + * _POSIX_THREAD_PROCESS_SHARED + * + * RESULTS + * 0 successfully retrieved attribute, + * EINVAL 'attr' or 'pshared' is invalid, + * + * ------------------------------------------------------ + */ +{ + int result; + + if ((attr != NULL && *attr != NULL) && (pshared != NULL)) + { + *pshared = (*attr)->pshared; + result = 0; + } + else + { + result = EINVAL; + } + + return result; + +} /* pthread_condattr_getpshared */ diff --git a/w32-pthreads/pthread_condattr_init.c b/w32-pthreads/pthread_condattr_init.c new file mode 100644 index 000000000..5987878e0 --- /dev/null +++ b/w32-pthreads/pthread_condattr_init.c @@ -0,0 +1,87 @@ +/* + * pthread_condattr_init.c + * + * Description: + * This translation unit implements condition variables and their primitives. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_condattr_init (pthread_condattr_t * attr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Initializes a condition variable attributes object + * with default attributes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_condattr_t + * + * + * DESCRIPTION + * Initializes a condition variable attributes object + * with default attributes. + * + * NOTES: + * 1) Use to define condition variable types + * 2) It is up to the application to ensure + * that it doesn't re-init an attribute + * without destroying it first. Otherwise + * a memory leak is created. + * + * RESULTS + * 0 successfully initialized attr, + * ENOMEM insufficient memory for attr. + * + * ------------------------------------------------------ + */ +{ + pthread_condattr_t attr_result; + int result = 0; + + attr_result = (pthread_condattr_t) calloc (1, sizeof (*attr_result)); + + if (attr_result == NULL) + { + result = ENOMEM; + } + + *attr = attr_result; + + return result; + +} /* pthread_condattr_init */ diff --git a/w32-pthreads/pthread_condattr_setpshared.c b/w32-pthreads/pthread_condattr_setpshared.c new file mode 100644 index 000000000..954fb3829 --- /dev/null +++ b/w32-pthreads/pthread_condattr_setpshared.c @@ -0,0 +1,117 @@ +/* + * pthread_condattr_setpshared.c + * + * Description: + * This translation unit implements condition variables and their primitives. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_condattr_setpshared (pthread_condattr_t * attr, int pshared) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Mutexes created with 'attr' can be shared between + * processes if pthread_mutex_t variable is allocated + * in memory shared by these processes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_mutexattr_t + * + * pshared + * must be one of: + * + * PTHREAD_PROCESS_SHARED + * May be shared if in shared memory + * + * PTHREAD_PROCESS_PRIVATE + * Cannot be shared. + * + * DESCRIPTION + * Mutexes creatd with 'attr' can be shared between + * processes if pthread_mutex_t variable is allocated + * in memory shared by these processes. + * + * NOTES: + * 1) pshared mutexes MUST be allocated in shared + * memory. + * + * 2) The following macro is defined if shared mutexes + * are supported: + * _POSIX_THREAD_PROCESS_SHARED + * + * RESULTS + * 0 successfully set attribute, + * EINVAL 'attr' or pshared is invalid, + * ENOSYS PTHREAD_PROCESS_SHARED not supported, + * + * ------------------------------------------------------ + */ +{ + int result; + + if ((attr != NULL && *attr != NULL) + && ((pshared == PTHREAD_PROCESS_SHARED) + || (pshared == PTHREAD_PROCESS_PRIVATE))) + { + if (pshared == PTHREAD_PROCESS_SHARED) + { + +#if !defined( _POSIX_THREAD_PROCESS_SHARED ) + result = ENOSYS; + pshared = PTHREAD_PROCESS_PRIVATE; +#else + result = 0; + +#endif /* _POSIX_THREAD_PROCESS_SHARED */ + + } + else + { + result = 0; + } + + (*attr)->pshared = pshared; + } + else + { + result = EINVAL; + } + + return result; + +} /* pthread_condattr_setpshared */ diff --git a/w32-pthreads/pthread_delay_np.c b/w32-pthreads/pthread_delay_np.c new file mode 100644 index 000000000..e6c96d807 --- /dev/null +++ b/w32-pthreads/pthread_delay_np.c @@ -0,0 +1,172 @@ +/* + * pthreads_delay_np.c + * + * Description: + * This translation unit implements non-portable thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* + * pthread_delay_np + * + * DESCRIPTION + * + * This routine causes a thread to delay execution for a specific period of time. + * This period ends at the current time plus the specified interval. The routine + * will not return before the end of the period is reached, but may return an + * arbitrary amount of time after the period has gone by. This can be due to + * system load, thread priorities, and system timer granularity. + * + * Specifying an interval of zero (0) seconds and zero (0) nanoseconds is + * allowed and can be used to force the thread to give up the processor or to + * deliver a pending cancelation request. + * + * The timespec structure contains the following two fields: + * + * tv_sec is an integer number of seconds. + * tv_nsec is an integer number of nanoseconds. + * + * Return Values + * + * If an error condition occurs, this routine returns an integer value indicating + * the type of error. Possible return values are as follows: + * + * 0 + * Successful completion. + * [EINVAL] + * The value specified by interval is invalid. + * + * Example + * + * The following code segment would wait for 5 and 1/2 seconds + * + * struct timespec tsWait; + * int intRC; + * + * tsWait.tv_sec = 5; + * tsWait.tv_nsec = 500000000L; + * intRC = pthread_delay_np(&tsWait); + */ +int +pthread_delay_np (struct timespec *interval) +{ + DWORD wait_time; + DWORD secs_in_millisecs; + DWORD millisecs; + DWORD status; + pthread_t self; + ptw32_thread_t * sp; + + if (interval == NULL) + { + return EINVAL; + } + + if (interval->tv_sec == 0L && interval->tv_nsec == 0L) + { + pthread_testcancel (); + Sleep (0); + pthread_testcancel (); + return (0); + } + + /* convert secs to millisecs */ + secs_in_millisecs = (DWORD)interval->tv_sec * 1000L; + + /* convert nanosecs to millisecs (rounding up) */ + millisecs = (interval->tv_nsec + 999999L) / 1000000L; + +#if defined(__WATCOMC__) +#pragma disable_message (124) +#endif + + /* + * Most compilers will issue a warning 'comparison always 0' + * because the variable type is unsigned, but we need to keep this + * for some reason I can't recall now. + */ + if (0 > (wait_time = secs_in_millisecs + millisecs)) + { + return EINVAL; + } + +#if defined(__WATCOMC__) +#pragma enable_message (124) +#endif + + if (NULL == (self = pthread_self ()).p) + { + return ENOMEM; + } + + sp = (ptw32_thread_t *) self.p; + + if (sp->cancelState == PTHREAD_CANCEL_ENABLE) + { + /* + * Async cancelation won't catch us until wait_time is up. + * Deferred cancelation will cancel us immediately. + */ + if (WAIT_OBJECT_0 == + (status = WaitForSingleObject (sp->cancelEvent, wait_time))) + { + ptw32_mcs_local_node_t stateLock; + /* + * Canceling! + */ + ptw32_mcs_lock_acquire (&sp->stateLock, &stateLock); + if (sp->state < PThreadStateCanceling) + { + sp->state = PThreadStateCanceling; + sp->cancelState = PTHREAD_CANCEL_DISABLE; + ptw32_mcs_lock_release (&stateLock); + + ptw32_throw (PTW32_EPS_CANCEL); + } + + ptw32_mcs_lock_release (&stateLock); + return ESRCH; + } + else if (status != WAIT_TIMEOUT) + { + return EINVAL; + } + } + else + { + Sleep (wait_time); + } + + return (0); +} diff --git a/w32-pthreads/pthread_detach.c b/w32-pthreads/pthread_detach.c new file mode 100644 index 000000000..9ff6587f3 --- /dev/null +++ b/w32-pthreads/pthread_detach.c @@ -0,0 +1,136 @@ +/* + * pthread_detach.c + * + * Description: + * This translation unit implements functions related to thread + * synchronisation. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* + * Not needed yet, but defining it should indicate clashes with build target + * environment that should be fixed. + */ +#if !defined(WINCE) +# include +#endif + + +int +pthread_detach (pthread_t thread) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function detaches the given thread. + * + * PARAMETERS + * thread + * an instance of a pthread_t + * + * + * DESCRIPTION + * This function detaches the given thread. You may use it to + * detach the main thread or to detach a joinable thread. + * NOTE: detached threads cannot be joined; + * storage is freed immediately on termination. + * + * RESULTS + * 0 successfully detached the thread, + * EINVAL thread is not a joinable thread, + * ENOSPC a required resource has been exhausted, + * ESRCH no thread could be found for 'thread', + * + * ------------------------------------------------------ + */ +{ + int result; + BOOL destroyIt = PTW32_FALSE; + ptw32_thread_t * tp = (ptw32_thread_t *) thread.p; + ptw32_mcs_local_node_t node; + + ptw32_mcs_lock_acquire(&ptw32_thread_reuse_lock, &node); + + if (NULL == tp + || thread.x != tp->ptHandle.x) + { + result = ESRCH; + } + else if (PTHREAD_CREATE_DETACHED == tp->detachState) + { + result = EINVAL; + } + else + { + ptw32_mcs_local_node_t stateLock; + /* + * Joinable ptw32_thread_t structs are not scavenged until + * a join or detach is done. The thread may have exited already, + * but all of the state and locks etc are still there. + */ + result = 0; + + ptw32_mcs_lock_acquire (&tp->stateLock, &stateLock); + if (tp->state != PThreadStateLast) + { + tp->detachState = PTHREAD_CREATE_DETACHED; + } + else if (tp->detachState != PTHREAD_CREATE_DETACHED) + { + /* + * Thread is joinable and has exited or is exiting. + */ + destroyIt = PTW32_TRUE; + } + ptw32_mcs_lock_release (&stateLock); + } + + ptw32_mcs_lock_release(&node); + + if (result == 0) + { + /* Thread is joinable */ + + if (destroyIt) + { + /* The thread has exited or is exiting but has not been joined or + * detached. Need to wait in case it's still exiting. + */ + (void) WaitForSingleObject(tp->threadH, INFINITE); + ptw32_threadDestroy (thread); + } + } + + return (result); + +} /* pthread_detach */ diff --git a/w32-pthreads/pthread_equal.c b/w32-pthreads/pthread_equal.c new file mode 100644 index 000000000..5ddd82acb --- /dev/null +++ b/w32-pthreads/pthread_equal.c @@ -0,0 +1,76 @@ +/* + * pthread_equal.c + * + * Description: + * This translation unit implements miscellaneous thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_equal (pthread_t t1, pthread_t t2) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function returns nonzero if t1 and t2 are equal, else + * returns zero + * + * PARAMETERS + * t1, + * t2 + * thread IDs + * + * + * DESCRIPTION + * This function returns nonzero if t1 and t2 are equal, else + * returns zero. + * + * RESULTS + * non-zero if t1 and t2 refer to the same thread, + * 0 t1 and t2 do not refer to the same thread + * + * ------------------------------------------------------ + */ +{ + int result; + + /* + * We also accept NULL == NULL - treating NULL as a thread + * for this special case, because there is no error that we can return. + */ + result = ( t1.p == t2.p && t1.x == t2.x ); + + return (result); + +} /* pthread_equal */ diff --git a/w32-pthreads/pthread_exit.c b/w32-pthreads/pthread_exit.c new file mode 100644 index 000000000..37b3c0990 --- /dev/null +++ b/w32-pthreads/pthread_exit.c @@ -0,0 +1,106 @@ +/* + * pthread_exit.c + * + * Description: + * This translation unit implements routines associated with exiting from + * a thread. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#if !defined(_UWIN) +/*# include */ +#endif + +void +pthread_exit (void *value_ptr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function terminates the calling thread, returning + * the value 'value_ptr' to any joining thread. + * + * PARAMETERS + * value_ptr + * a generic data value (i.e. not the address of a value) + * + * + * DESCRIPTION + * This function terminates the calling thread, returning + * the value 'value_ptr' to any joining thread. + * NOTE: thread should be joinable. + * + * RESULTS + * N/A + * + * ------------------------------------------------------ + */ +{ + ptw32_thread_t * sp; + + /* + * Don't use pthread_self() to avoid creating an implicit POSIX thread handle + * unnecessarily. + */ + sp = (ptw32_thread_t *) pthread_getspecific (ptw32_selfThreadKey); + +#if defined(_UWIN) + if (--pthread_count <= 0) + exit ((int) value_ptr); +#endif + + if (NULL == sp) + { + /* + * A POSIX thread handle was never created. I.e. this is a + * Win32 thread that has never called a pthreads-win32 routine that + * required a POSIX handle. + * + * Implicit POSIX handles are cleaned up in ptw32_throw() now. + */ + +#if ! (defined (__MINGW64__) || defined(__MINGW32__)) || defined (__MSVCRT__) || defined (__DMC__) + _endthreadex ((unsigned) (size_t) value_ptr); +#else + _endthread (); +#endif + + /* Never reached */ + } + + sp->exitStatus = value_ptr; + + ptw32_throw (PTW32_EPS_EXIT); + + /* Never reached. */ + +} diff --git a/w32-pthreads/pthread_getconcurrency.c b/w32-pthreads/pthread_getconcurrency.c new file mode 100644 index 000000000..cf9e9c85c --- /dev/null +++ b/w32-pthreads/pthread_getconcurrency.c @@ -0,0 +1,45 @@ +/* + * pthread_getconcurrency.c + * + * Description: + * This translation unit implements miscellaneous thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_getconcurrency (void) +{ + return ptw32_concurrency; +} diff --git a/w32-pthreads/pthread_getschedparam.c b/w32-pthreads/pthread_getschedparam.c new file mode 100644 index 000000000..0afcfb74a --- /dev/null +++ b/w32-pthreads/pthread_getschedparam.c @@ -0,0 +1,75 @@ +/* + * sched_getschedparam.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +int +pthread_getschedparam (pthread_t thread, int *policy, + struct sched_param *param) +{ + int result; + + /* Validate the thread id. */ + result = pthread_kill (thread, 0); + if (0 != result) + { + return result; + } + + /* + * Validate the policy and param args. + * Check that a policy constant wasn't passed rather than &policy. + */ + if (policy <= (int *) SCHED_MAX || param == NULL) + { + return EINVAL; + } + + /* Fill out the policy. */ + *policy = SCHED_OTHER; + + /* + * This function must return the priority value set by + * the most recent pthread_setschedparam() or pthread_create() + * for the target thread. It must not return the actual thread + * priority as altered by any system priority adjustments etc. + */ + param->sched_priority = ((ptw32_thread_t *)thread.p)->sched_priority; + + return 0; +} diff --git a/w32-pthreads/pthread_getspecific.c b/w32-pthreads/pthread_getspecific.c new file mode 100644 index 000000000..5ee1641dc --- /dev/null +++ b/w32-pthreads/pthread_getspecific.c @@ -0,0 +1,87 @@ +/* + * pthread_getspecific.c + * + * Description: + * POSIX thread functions which implement thread-specific data (TSD). + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +void * +pthread_getspecific (pthread_key_t key) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function returns the current value of key in the + * calling thread. If no value has been set for 'key' in + * the thread, NULL is returned. + * + * PARAMETERS + * key + * an instance of pthread_key_t + * + * + * DESCRIPTION + * This function returns the current value of key in the + * calling thread. If no value has been set for 'key' in + * the thread, NULL is returned. + * + * RESULTS + * key value or NULL on failure + * + * ------------------------------------------------------ + */ +{ + void * ptr; + + if (key == NULL) + { + ptr = NULL; + } + else + { + int lasterror = GetLastError (); +#if defined(RETAIN_WSALASTERROR) + int lastWSAerror = WSAGetLastError (); +#endif + ptr = TlsGetValue (key->key); + + SetLastError (lasterror); +#if defined(RETAIN_WSALASTERROR) + WSASetLastError (lastWSAerror); +#endif + } + + return ptr; +} diff --git a/w32-pthreads/pthread_getunique_np.c b/w32-pthreads/pthread_getunique_np.c new file mode 100644 index 000000000..4496c68bf --- /dev/null +++ b/w32-pthreads/pthread_getunique_np.c @@ -0,0 +1,47 @@ +/* + * pthread_getunique_np.c + * + * Description: + * This translation unit implements non-portable thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* + * + */ +unsigned __int64 +pthread_getunique_np (pthread_t thread) +{ + return ((ptw32_thread_t*)thread.p)->seqNumber; +} diff --git a/w32-pthreads/pthread_getw32threadhandle_np.c b/w32-pthreads/pthread_getw32threadhandle_np.c new file mode 100644 index 000000000..309a8f281 --- /dev/null +++ b/w32-pthreads/pthread_getw32threadhandle_np.c @@ -0,0 +1,65 @@ +/* + * pthread_getw32threadhandle_np.c + * + * Description: + * This translation unit implements non-portable thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* + * pthread_getw32threadhandle_np() + * + * Returns the win32 thread handle that the POSIX + * thread "thread" is running as. + * + * Applications can use the win32 handle to set + * win32 specific attributes of the thread. + */ +HANDLE +pthread_getw32threadhandle_np (pthread_t thread) +{ + return ((ptw32_thread_t *)thread.p)->threadH; +} + +/* + * pthread_getw32threadid_np() + * + * Returns the win32 thread id that the POSIX + * thread "thread" is running as. + */ +DWORD +pthread_getw32threadid_np (pthread_t thread) +{ + return ((ptw32_thread_t *)thread.p)->thread; +} diff --git a/w32-pthreads/pthread_join.c b/w32-pthreads/pthread_join.c new file mode 100644 index 000000000..c2b7c1e75 --- /dev/null +++ b/w32-pthreads/pthread_join.c @@ -0,0 +1,157 @@ +/* + * pthread_join.c + * + * Description: + * This translation unit implements functions related to thread + * synchronisation. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* + * Not needed yet, but defining it should indicate clashes with build target + * environment that should be fixed. + */ +#if !defined(WINCE) +# include +#endif + + +int +pthread_join (pthread_t thread, void **value_ptr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function waits for 'thread' to terminate and + * returns the thread's exit value if 'value_ptr' is not + * NULL. This also detaches the thread on successful + * completion. + * + * PARAMETERS + * thread + * an instance of pthread_t + * + * value_ptr + * pointer to an instance of pointer to void + * + * + * DESCRIPTION + * This function waits for 'thread' to terminate and + * returns the thread's exit value if 'value_ptr' is not + * NULL. This also detaches the thread on successful + * completion. + * NOTE: detached threads cannot be joined or canceled + * + * RESULTS + * 0 'thread' has completed + * EINVAL thread is not a joinable thread, + * ESRCH no thread could be found with ID 'thread', + * ENOENT thread couldn't find it's own valid handle, + * EDEADLK attempt to join thread with self + * + * ------------------------------------------------------ + */ +{ + int result; + pthread_t self; + ptw32_thread_t * tp = (ptw32_thread_t *) thread.p; + ptw32_mcs_local_node_t node; + + ptw32_mcs_lock_acquire(&ptw32_thread_reuse_lock, &node); + + if (NULL == tp + || thread.x != tp->ptHandle.x) + { + result = ESRCH; + } + else if (PTHREAD_CREATE_DETACHED == tp->detachState) + { + result = EINVAL; + } + else + { + result = 0; + } + + ptw32_mcs_lock_release(&node); + + if (result == 0) + { + /* + * The target thread is joinable and can't be reused before we join it. + */ + self = pthread_self(); + + if (NULL == self.p) + { + result = ENOENT; + } + else if (pthread_equal (self, thread)) + { + result = EDEADLK; + } + else + { + /* + * Pthread_join is a cancelation point. + * If we are canceled then our target thread must not be + * detached (destroyed). This is guarranteed because + * pthreadCancelableWait will not return if we + * are canceled. + */ + result = pthreadCancelableWait (tp->threadH); + + if (0 == result) + { + if (value_ptr != NULL) + { + *value_ptr = tp->exitStatus; + } + + /* + * The result of making multiple simultaneous calls to + * pthread_join() or pthread_detach() specifying the same + * target is undefined. + */ + result = pthread_detach (thread); + } + else + { + result = ESRCH; + } + } + } + + return (result); + +} /* pthread_join */ diff --git a/w32-pthreads/pthread_key_create.c b/w32-pthreads/pthread_key_create.c new file mode 100644 index 000000000..65c6f9508 --- /dev/null +++ b/w32-pthreads/pthread_key_create.c @@ -0,0 +1,108 @@ +/* + * pthread_key_create.c + * + * Description: + * POSIX thread functions which implement thread-specific data (TSD). + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +/* TLS_OUT_OF_INDEXES not defined on WinCE */ +#if !defined(TLS_OUT_OF_INDEXES) +#define TLS_OUT_OF_INDEXES 0xffffffff +#endif + +int +pthread_key_create (pthread_key_t * key, void (PTW32_CDECL *destructor) (void *)) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function creates a thread-specific data key visible + * to all threads. All existing and new threads have a value + * NULL for key until set using pthread_setspecific. When any + * thread with a non-NULL value for key terminates, 'destructor' + * is called with key's current value for that thread. + * + * PARAMETERS + * key + * pointer to an instance of pthread_key_t + * + * + * DESCRIPTION + * This function creates a thread-specific data key visible + * to all threads. All existing and new threads have a value + * NULL for key until set using pthread_setspecific. When any + * thread with a non-NULL value for key terminates, 'destructor' + * is called with key's current value for that thread. + * + * RESULTS + * 0 successfully created semaphore, + * EAGAIN insufficient resources or PTHREAD_KEYS_MAX + * exceeded, + * ENOMEM insufficient memory to create the key, + * + * ------------------------------------------------------ + */ +{ + int result = 0; + pthread_key_t newkey; + + if ((newkey = (pthread_key_t) calloc (1, sizeof (*newkey))) == NULL) + { + result = ENOMEM; + } + else if ((newkey->key = TlsAlloc ()) == TLS_OUT_OF_INDEXES) + { + result = EAGAIN; + + free (newkey); + newkey = NULL; + } + else if (destructor != NULL) + { + /* + * Have to manage associations between thread and key; + * Therefore, need a lock that allows competing threads + * to gain exclusive access to the key->threads list. + * + * The mutex will only be created when it is first locked. + */ + newkey->keyLock = 0; + newkey->destructor = destructor; + } + + *key = newkey; + + return (result); +} diff --git a/w32-pthreads/pthread_key_delete.c b/w32-pthreads/pthread_key_delete.c new file mode 100644 index 000000000..09d70c63f --- /dev/null +++ b/w32-pthreads/pthread_key_delete.c @@ -0,0 +1,125 @@ +/* + * pthread_key_delete.c + * + * Description: + * POSIX thread functions which implement thread-specific data (TSD). + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_key_delete (pthread_key_t key) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function deletes a thread-specific data key. This + * does not change the value of the thread specific data key + * for any thread and does not run the key's destructor + * in any thread so it should be used with caution. + * + * PARAMETERS + * key + * pointer to an instance of pthread_key_t + * + * + * DESCRIPTION + * This function deletes a thread-specific data key. This + * does not change the value of the thread specific data key + * for any thread and does not run the key's destructor + * in any thread so it should be used with caution. + * + * RESULTS + * 0 successfully deleted the key, + * EINVAL key is invalid, + * + * ------------------------------------------------------ + */ +{ + ptw32_mcs_local_node_t keyLock; + int result = 0; + + if (key != NULL) + { + if (key->threads != NULL && key->destructor != NULL) + { + ThreadKeyAssoc *assoc; + ptw32_mcs_lock_acquire (&(key->keyLock), &keyLock); + /* + * Run through all Thread<-->Key associations + * for this key. + * + * While we hold at least one of the locks guarding + * the assoc, we know that the assoc pointed to by + * key->threads is valid. + */ + while ((assoc = (ThreadKeyAssoc *) key->threads) != NULL) + { + ptw32_mcs_local_node_t threadLock; + ptw32_thread_t * thread = assoc->thread; + + if (assoc == NULL) + { + /* Finished */ + break; + } + + ptw32_mcs_lock_acquire (&(thread->threadLock), &threadLock); + /* + * Since we are starting at the head of the key's threads + * chain, this will also point key->threads at the next assoc. + * While we hold key->keyLock, no other thread can insert + * a new assoc via pthread_setspecific. + */ + ptw32_tkAssocDestroy (assoc); + ptw32_mcs_lock_release (&threadLock); + ptw32_mcs_lock_release (&keyLock); + } + } + + TlsFree (key->key); + if (key->destructor != NULL) + { + /* A thread could be holding the keyLock */ + ptw32_mcs_lock_acquire (&(key->keyLock), &keyLock); + ptw32_mcs_lock_release (&keyLock); + } + +#if defined( _DEBUG ) + memset ((char *) key, 0, sizeof (*key)); +#endif + free (key); + } + + return (result); +} diff --git a/w32-pthreads/pthread_kill.c b/w32-pthreads/pthread_kill.c new file mode 100644 index 000000000..5473b43cd --- /dev/null +++ b/w32-pthreads/pthread_kill.c @@ -0,0 +1,105 @@ +/* + * pthread_kill.c + * + * Description: + * This translation unit implements the pthread_kill routine. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* + * Not needed yet, but defining it should indicate clashes with build target + * environment that should be fixed. + */ +#if !defined(WINCE) +# include +#endif + +int +pthread_kill (pthread_t thread, int sig) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function requests that a signal be delivered to the + * specified thread. If sig is zero, error checking is + * performed but no signal is actually sent such that this + * function can be used to check for a valid thread ID. + * + * PARAMETERS + * thread reference to an instances of pthread_t + * sig signal. Currently only a value of 0 is supported. + * + * + * DESCRIPTION + * This function requests that a signal be delivered to the + * specified thread. If sig is zero, error checking is + * performed but no signal is actually sent such that this + * function can be used to check for a valid thread ID. + * + * RESULTS + * ESRCH the thread is not a valid thread ID, + * EINVAL the value of the signal is invalid + * or unsupported. + * 0 the signal was successfully sent. + * + * ------------------------------------------------------ + */ +{ + int result = 0; + ptw32_thread_t * tp; + ptw32_mcs_local_node_t node; + + ptw32_mcs_lock_acquire(&ptw32_thread_reuse_lock, &node); + + tp = (ptw32_thread_t *) thread.p; + + if (NULL == tp + || thread.x != tp->ptHandle.x + || NULL == tp->threadH) + { + result = ESRCH; + } + + ptw32_mcs_lock_release(&node); + + if (0 == result && 0 != sig) + { + /* + * Currently does not support any signals. + */ + result = EINVAL; + } + + return result; + +} /* pthread_kill */ diff --git a/w32-pthreads/pthread_mutex_consistent.c b/w32-pthreads/pthread_mutex_consistent.c new file mode 100644 index 000000000..2e0659862 --- /dev/null +++ b/w32-pthreads/pthread_mutex_consistent.c @@ -0,0 +1,157 @@ +/* + * pthread_mutex_consistent.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ +#if !defined(_UWIN) +/*# include */ +#endif +#include "pthread.h" +#include "implement.h" + +INLINE +int +ptw32_robust_mutex_inherit(pthread_mutex_t * mutex) +{ + int result; + pthread_mutex_t mx = *mutex; + ptw32_robust_node_t* robust = mx->robustNode; + + switch ((LONG)PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR)&robust->stateInconsistent, + (PTW32_INTERLOCKED_LONG)PTW32_ROBUST_INCONSISTENT, + (PTW32_INTERLOCKED_LONG)-1 /* The terminating thread sets this */)) + { + case -1L: + result = EOWNERDEAD; + break; + case (LONG)PTW32_ROBUST_NOTRECOVERABLE: + result = ENOTRECOVERABLE; + break; + default: + result = 0; + break; + } + + return result; +} + +/* + * The next two internal support functions depend on only being + * called by the thread that owns the robust mutex. This enables + * us to avoid additional locks. + * Any mutex currently in the thread's robust mutex list is held + * by the thread, again eliminating the need for locks. + * The forward/backward links allow the thread to unlock mutexes + * in any order, not necessarily the reverse locking order. + * This is all possible because it is an error if a thread that + * does not own the [robust] mutex attempts to unlock it. + */ + +INLINE +void +ptw32_robust_mutex_add(pthread_mutex_t* mutex, pthread_t self) +{ + ptw32_robust_node_t** list; + pthread_mutex_t mx = *mutex; + ptw32_thread_t* tp = (ptw32_thread_t*)self.p; + ptw32_robust_node_t* robust = mx->robustNode; + + list = &tp->robustMxList; + mx->ownerThread = self; + if (NULL == *list) + { + robust->prev = NULL; + robust->next = NULL; + *list = robust; + } + else + { + robust->prev = NULL; + robust->next = *list; + (*list)->prev = robust; + *list = robust; + } +} + +INLINE +void +ptw32_robust_mutex_remove(pthread_mutex_t* mutex, ptw32_thread_t* otp) +{ + ptw32_robust_node_t** list; + pthread_mutex_t mx = *mutex; + ptw32_robust_node_t* robust = mx->robustNode; + + list = &(((ptw32_thread_t*)mx->ownerThread.p)->robustMxList); + mx->ownerThread.p = otp; + if (robust->next != NULL) + { + robust->next->prev = robust->prev; + } + if (robust->prev != NULL) + { + robust->prev->next = robust->next; + } + if (*list == robust) + { + *list = robust->next; + } +} + + +int +pthread_mutex_consistent (pthread_mutex_t* mutex) +{ + pthread_mutex_t mx = *mutex; + int result = 0; + + /* + * Let the system deal with invalid pointers. + */ + if (mx == NULL) + { + return EINVAL; + } + + if (mx->kind >= 0 + || (PTW32_INTERLOCKED_LONG)PTW32_ROBUST_INCONSISTENT != PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR)&mx->robustNode->stateInconsistent, + (PTW32_INTERLOCKED_LONG)PTW32_ROBUST_CONSISTENT, + (PTW32_INTERLOCKED_LONG)PTW32_ROBUST_INCONSISTENT)) + { + result = EINVAL; + } + + return (result); +} + diff --git a/w32-pthreads/pthread_mutex_destroy.c b/w32-pthreads/pthread_mutex_destroy.c new file mode 100644 index 000000000..7b8c9cd65 --- /dev/null +++ b/w32-pthreads/pthread_mutex_destroy.c @@ -0,0 +1,148 @@ +/* + * pthread_mutex_destroy.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_mutex_destroy (pthread_mutex_t * mutex) +{ + int result = 0; + pthread_mutex_t mx; + + /* + * Let the system deal with invalid pointers. + */ + + /* + * Check to see if we have something to delete. + */ + if (*mutex < PTHREAD_ERRORCHECK_MUTEX_INITIALIZER) + { + mx = *mutex; + + result = pthread_mutex_trylock (&mx); + + /* + * If trylock succeeded and the mutex is not recursively locked it + * can be destroyed. + */ + if (0 == result || ENOTRECOVERABLE == result) + { + if (mx->kind != PTHREAD_MUTEX_RECURSIVE || 1 == mx->recursive_count) + { + /* + * FIXME!!! + * The mutex isn't held by another thread but we could still + * be too late invalidating the mutex below since another thread + * may already have entered mutex_lock and the check for a valid + * *mutex != NULL. + */ + *mutex = NULL; + + result = (0 == result)?pthread_mutex_unlock(&mx):0; + + if (0 == result) + { + if (mx->robustNode != NULL) + { + free(mx->robustNode); + } + if (!CloseHandle (mx->event)) + { + *mutex = mx; + result = EINVAL; + } + else + { + free (mx); + } + } + else + { + /* + * Restore the mutex before we return the error. + */ + *mutex = mx; + } + } + else /* mx->recursive_count > 1 */ + { + /* + * The mutex must be recursive and already locked by us (this thread). + */ + mx->recursive_count--; /* Undo effect of pthread_mutex_trylock() above */ + result = EBUSY; + } + } + } + else + { + ptw32_mcs_local_node_t node; + + /* + * See notes in ptw32_mutex_check_need_init() above also. + */ + + ptw32_mcs_lock_acquire(&ptw32_mutex_test_init_lock, &node); + + /* + * Check again. + */ + if (*mutex >= PTHREAD_ERRORCHECK_MUTEX_INITIALIZER) + { + /* + * This is all we need to do to destroy a statically + * initialised mutex that has not yet been used (initialised). + * If we get to here, another thread + * waiting to initialise this mutex will get an EINVAL. + */ + *mutex = NULL; + } + else + { + /* + * The mutex has been initialised while we were waiting + * so assume it's in use. + */ + result = EBUSY; + } + ptw32_mcs_lock_release(&node); + } + + return (result); +} diff --git a/w32-pthreads/pthread_mutex_init.c b/w32-pthreads/pthread_mutex_init.c new file mode 100644 index 000000000..daf805e5b --- /dev/null +++ b/w32-pthreads/pthread_mutex_init.c @@ -0,0 +1,130 @@ +/* + * pthread_mutex_init.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_mutex_init (pthread_mutex_t * mutex, const pthread_mutexattr_t * attr) +{ + int result = 0; + pthread_mutex_t mx; + + if (mutex == NULL) + { + return EINVAL; + } + + if (attr != NULL && *attr != NULL) + { + if ((*attr)->pshared == PTHREAD_PROCESS_SHARED) + { + /* + * Creating mutex that can be shared between + * processes. + */ +#if _POSIX_THREAD_PROCESS_SHARED >= 0 + + /* + * Not implemented yet. + */ + +#error ERROR [__FILE__, line __LINE__]: Process shared mutexes are not supported yet. + +#else + + return ENOSYS; + +#endif /* _POSIX_THREAD_PROCESS_SHARED */ + } + } + + mx = (pthread_mutex_t) calloc (1, sizeof (*mx)); + + if (mx == NULL) + { + result = ENOMEM; + } + else + { + mx->lock_idx = 0; + mx->recursive_count = 0; + mx->robustNode = NULL; + if (attr == NULL || *attr == NULL) + { + mx->kind = PTHREAD_MUTEX_DEFAULT; + } + else + { + mx->kind = (*attr)->kind; + if ((*attr)->robustness == PTHREAD_MUTEX_ROBUST) + { + /* + * Use the negative range to represent robust types. + * Replaces a memory fetch with a register negate and incr + * in pthread_mutex_lock etc. + * + * Map 0,1,..,n to -1,-2,..,(-n)-1 + */ + mx->kind = -mx->kind - 1; + + mx->robustNode = (ptw32_robust_node_t*) malloc(sizeof(ptw32_robust_node_t)); + mx->robustNode->stateInconsistent = PTW32_ROBUST_CONSISTENT; + mx->robustNode->mx = mx; + mx->robustNode->next = NULL; + mx->robustNode->prev = NULL; + } + } + + mx->ownerThread.p = NULL; + + mx->event = CreateEvent (NULL, PTW32_FALSE, /* manual reset = No */ + PTW32_FALSE, /* initial state = not signaled */ + NULL); /* event name */ + + if (0 == mx->event) + { + result = ENOSPC; + free (mx); + mx = NULL; + } + } + + *mutex = mx; + + return (result); +} diff --git a/w32-pthreads/pthread_mutex_lock.c b/w32-pthreads/pthread_mutex_lock.c new file mode 100644 index 000000000..eee9abe8c --- /dev/null +++ b/w32-pthreads/pthread_mutex_lock.c @@ -0,0 +1,269 @@ +/* + * pthread_mutex_lock.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#if !defined(_UWIN) +/*# include */ +#endif +#include "pthread.h" +#include "implement.h" + +int +pthread_mutex_lock (pthread_mutex_t * mutex) +{ + int kind; + pthread_mutex_t mx; + int result = 0; + + /* + * Let the system deal with invalid pointers. + */ + if (*mutex == NULL) + { + return EINVAL; + } + + /* + * We do a quick check to see if we need to do more work + * to initialise a static mutex. We check + * again inside the guarded section of ptw32_mutex_check_need_init() + * to avoid race conditions. + */ + if (*mutex >= PTHREAD_ERRORCHECK_MUTEX_INITIALIZER) + { + if ((result = ptw32_mutex_check_need_init (mutex)) != 0) + { + return (result); + } + } + + mx = *mutex; + kind = mx->kind; + + if (kind >= 0) + { + /* Non-robust */ + if (PTHREAD_MUTEX_NORMAL == kind) + { + if ((PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) 1) != 0) + { + while ((PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) -1) != 0) + { + if (WAIT_OBJECT_0 != WaitForSingleObject (mx->event, INFINITE)) + { + result = EINVAL; + break; + } + } + } + } + else + { + pthread_t self = pthread_self(); + + if ((PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) 1, + (PTW32_INTERLOCKED_LONG) 0) == 0) + { + mx->recursive_count = 1; + mx->ownerThread = self; + } + else + { + if (pthread_equal (mx->ownerThread, self)) + { + if (kind == PTHREAD_MUTEX_RECURSIVE) + { + mx->recursive_count++; + } + else + { + result = EDEADLK; + } + } + else + { + while ((PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) -1) != 0) + { + if (WAIT_OBJECT_0 != WaitForSingleObject (mx->event, INFINITE)) + { + result = EINVAL; + break; + } + } + + if (0 == result) + { + mx->recursive_count = 1; + mx->ownerThread = self; + } + } + } + } + } + else + { + /* + * Robust types + * All types record the current owner thread. + * The mutex is added to a per thread list when ownership is acquired. + */ + ptw32_robust_state_t* statePtr = &mx->robustNode->stateInconsistent; + + if ((PTW32_INTERLOCKED_LONG)PTW32_ROBUST_NOTRECOVERABLE == PTW32_INTERLOCKED_EXCHANGE_ADD_LONG( + (PTW32_INTERLOCKED_LONGPTR)statePtr, + (PTW32_INTERLOCKED_LONG)0)) + { + result = ENOTRECOVERABLE; + } + else + { + pthread_t self = pthread_self(); + + kind = -kind - 1; /* Convert to non-robust range */ + + if (PTHREAD_MUTEX_NORMAL == kind) + { + if ((PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) 1) != 0) + { + while (0 == (result = ptw32_robust_mutex_inherit(mutex)) + && (PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) -1) != 0) + { + if (WAIT_OBJECT_0 != WaitForSingleObject (mx->event, INFINITE)) + { + result = EINVAL; + break; + } + if ((PTW32_INTERLOCKED_LONG)PTW32_ROBUST_NOTRECOVERABLE == + PTW32_INTERLOCKED_EXCHANGE_ADD_LONG( + (PTW32_INTERLOCKED_LONGPTR)statePtr, + (PTW32_INTERLOCKED_LONG)0)) + { + /* Unblock the next thread */ + SetEvent(mx->event); + result = ENOTRECOVERABLE; + break; + } + } + } + if (0 == result || EOWNERDEAD == result) + { + /* + * Add mutex to the per-thread robust mutex currently-held list. + * If the thread terminates, all mutexes in this list will be unlocked. + */ + ptw32_robust_mutex_add(mutex, self); + } + } + else + { + if ((PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) 1, + (PTW32_INTERLOCKED_LONG) 0) == 0) + { + mx->recursive_count = 1; + /* + * Add mutex to the per-thread robust mutex currently-held list. + * If the thread terminates, all mutexes in this list will be unlocked. + */ + ptw32_robust_mutex_add(mutex, self); + } + else + { + if (pthread_equal (mx->ownerThread, self)) + { + if (PTHREAD_MUTEX_RECURSIVE == kind) + { + mx->recursive_count++; + } + else + { + result = EDEADLK; + } + } + else + { + while (0 == (result = ptw32_robust_mutex_inherit(mutex)) + && (PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) -1) != 0) + { + if (WAIT_OBJECT_0 != WaitForSingleObject (mx->event, INFINITE)) + { + result = EINVAL; + break; + } + if ((PTW32_INTERLOCKED_LONG)PTW32_ROBUST_NOTRECOVERABLE == + PTW32_INTERLOCKED_EXCHANGE_ADD_LONG( + (PTW32_INTERLOCKED_LONGPTR)statePtr, + (PTW32_INTERLOCKED_LONG)0)) + { + /* Unblock the next thread */ + SetEvent(mx->event); + result = ENOTRECOVERABLE; + break; + } + } + + if (0 == result || EOWNERDEAD == result) + { + mx->recursive_count = 1; + /* + * Add mutex to the per-thread robust mutex currently-held list. + * If the thread terminates, all mutexes in this list will be unlocked. + */ + ptw32_robust_mutex_add(mutex, self); + } + } + } + } + } + } + + return (result); +} + diff --git a/w32-pthreads/pthread_mutex_timedlock.c b/w32-pthreads/pthread_mutex_timedlock.c new file mode 100644 index 000000000..174531679 --- /dev/null +++ b/w32-pthreads/pthread_mutex_timedlock.c @@ -0,0 +1,324 @@ +/* + * pthread_mutex_timedlock.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +static INLINE int +ptw32_timed_eventwait (HANDLE event, const struct timespec *abstime) + /* + * ------------------------------------------------------ + * DESCRIPTION + * This function waits on an event until signaled or until + * abstime passes. + * If abstime has passed when this routine is called then + * it returns a result to indicate this. + * + * If 'abstime' is a NULL pointer then this function will + * block until it can successfully decrease the value or + * until interrupted by a signal. + * + * This routine is not a cancelation point. + * + * RESULTS + * 0 successfully signaled, + * ETIMEDOUT abstime passed + * EINVAL 'event' is not a valid event, + * + * ------------------------------------------------------ + */ +{ + + DWORD milliseconds; + DWORD status; + + if (event == NULL) + { + return EINVAL; + } + else + { + if (abstime == NULL) + { + milliseconds = INFINITE; + } + else + { + /* + * Calculate timeout as milliseconds from current system time. + */ + milliseconds = ptw32_relmillisecs (abstime); + } + + status = WaitForSingleObject (event, milliseconds); + + if (status == WAIT_OBJECT_0) + { + return 0; + } + else if (status == WAIT_TIMEOUT) + { + return ETIMEDOUT; + } + else + { + return EINVAL; + } + } + + return 0; + +} /* ptw32_timed_semwait */ + + +int +pthread_mutex_timedlock (pthread_mutex_t * mutex, + const struct timespec *abstime) +{ + pthread_mutex_t mx; + int kind; + int result = 0; + + /* + * Let the system deal with invalid pointers. + */ + + /* + * We do a quick check to see if we need to do more work + * to initialise a static mutex. We check + * again inside the guarded section of ptw32_mutex_check_need_init() + * to avoid race conditions. + */ + if (*mutex >= PTHREAD_ERRORCHECK_MUTEX_INITIALIZER) + { + if ((result = ptw32_mutex_check_need_init (mutex)) != 0) + { + return (result); + } + } + + mx = *mutex; + kind = mx->kind; + + if (kind >= 0) + { + if (mx->kind == PTHREAD_MUTEX_NORMAL) + { + if ((PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) 1) != 0) + { + while ((PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) -1) != 0) + { + if (0 != (result = ptw32_timed_eventwait (mx->event, abstime))) + { + return result; + } + } + } + } + else + { + pthread_t self = pthread_self(); + + if ((PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) 1, + (PTW32_INTERLOCKED_LONG) 0) == 0) + { + mx->recursive_count = 1; + mx->ownerThread = self; + } + else + { + if (pthread_equal (mx->ownerThread, self)) + { + if (mx->kind == PTHREAD_MUTEX_RECURSIVE) + { + mx->recursive_count++; + } + else + { + return EDEADLK; + } + } + else + { + while ((PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) -1) != 0) + { + if (0 != (result = ptw32_timed_eventwait (mx->event, abstime))) + { + return result; + } + } + + mx->recursive_count = 1; + mx->ownerThread = self; + } + } + } + } + else + { + /* + * Robust types + * All types record the current owner thread. + * The mutex is added to a per thread list when ownership is acquired. + */ + ptw32_robust_state_t* statePtr = &mx->robustNode->stateInconsistent; + + if ((PTW32_INTERLOCKED_LONG)PTW32_ROBUST_NOTRECOVERABLE == PTW32_INTERLOCKED_EXCHANGE_ADD_LONG( + (PTW32_INTERLOCKED_LONGPTR)statePtr, + (PTW32_INTERLOCKED_LONG)0)) + { + result = ENOTRECOVERABLE; + } + else + { + pthread_t self = pthread_self(); + + kind = -kind - 1; /* Convert to non-robust range */ + + if (PTHREAD_MUTEX_NORMAL == kind) + { + if ((PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) 1) != 0) + { + while (0 == (result = ptw32_robust_mutex_inherit(mutex)) + && (PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) -1) != 0) + { + if (0 != (result = ptw32_timed_eventwait (mx->event, abstime))) + { + return result; + } + if ((PTW32_INTERLOCKED_LONG)PTW32_ROBUST_NOTRECOVERABLE == + PTW32_INTERLOCKED_EXCHANGE_ADD_LONG( + (PTW32_INTERLOCKED_LONGPTR)statePtr, + (PTW32_INTERLOCKED_LONG)0)) + { + /* Unblock the next thread */ + SetEvent(mx->event); + result = ENOTRECOVERABLE; + break; + } + } + + if (0 == result || EOWNERDEAD == result) + { + /* + * Add mutex to the per-thread robust mutex currently-held list. + * If the thread terminates, all mutexes in this list will be unlocked. + */ + ptw32_robust_mutex_add(mutex, self); + } + } + } + else + { + pthread_t self = pthread_self(); + + if (0 == (PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) 1, + (PTW32_INTERLOCKED_LONG) 0)) + { + mx->recursive_count = 1; + /* + * Add mutex to the per-thread robust mutex currently-held list. + * If the thread terminates, all mutexes in this list will be unlocked. + */ + ptw32_robust_mutex_add(mutex, self); + } + else + { + if (pthread_equal (mx->ownerThread, self)) + { + if (PTHREAD_MUTEX_RECURSIVE == kind) + { + mx->recursive_count++; + } + else + { + return EDEADLK; + } + } + else + { + while (0 == (result = ptw32_robust_mutex_inherit(mutex)) + && (PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) -1) != 0) + { + if (0 != (result = ptw32_timed_eventwait (mx->event, abstime))) + { + return result; + } + } + + if ((PTW32_INTERLOCKED_LONG)PTW32_ROBUST_NOTRECOVERABLE == + PTW32_INTERLOCKED_EXCHANGE_ADD_LONG( + (PTW32_INTERLOCKED_LONGPTR)statePtr, + (PTW32_INTERLOCKED_LONG)0)) + { + /* Unblock the next thread */ + SetEvent(mx->event); + result = ENOTRECOVERABLE; + } + else if (0 == result || EOWNERDEAD == result) + { + mx->recursive_count = 1; + /* + * Add mutex to the per-thread robust mutex currently-held list. + * If the thread terminates, all mutexes in this list will be unlocked. + */ + ptw32_robust_mutex_add(mutex, self); + } + } + } + } + } + } + + return result; +} diff --git a/w32-pthreads/pthread_mutex_trylock.c b/w32-pthreads/pthread_mutex_trylock.c new file mode 100644 index 000000000..d6b68724d --- /dev/null +++ b/w32-pthreads/pthread_mutex_trylock.c @@ -0,0 +1,154 @@ +/* + * pthread_mutex_trylock.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_mutex_trylock (pthread_mutex_t * mutex) +{ + pthread_mutex_t mx; + int kind; + int result = 0; + + /* + * Let the system deal with invalid pointers. + */ + + /* + * We do a quick check to see if we need to do more work + * to initialise a static mutex. We check + * again inside the guarded section of ptw32_mutex_check_need_init() + * to avoid race conditions. + */ + if (*mutex >= PTHREAD_ERRORCHECK_MUTEX_INITIALIZER) + { + if ((result = ptw32_mutex_check_need_init (mutex)) != 0) + { + return (result); + } + } + + mx = *mutex; + kind = mx->kind; + + if (kind >= 0) + { + /* Non-robust */ + if (0 == (PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG ( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) 1, + (PTW32_INTERLOCKED_LONG) 0)) + { + if (kind != PTHREAD_MUTEX_NORMAL) + { + mx->recursive_count = 1; + mx->ownerThread = pthread_self (); + } + } + else + { + if (kind == PTHREAD_MUTEX_RECURSIVE && + pthread_equal (mx->ownerThread, pthread_self ())) + { + mx->recursive_count++; + } + else + { + result = EBUSY; + } + } + } + else + { + /* + * Robust types + * All types record the current owner thread. + * The mutex is added to a per thread list when ownership is acquired. + */ + pthread_t self; + ptw32_robust_state_t* statePtr = &mx->robustNode->stateInconsistent; + + if ((PTW32_INTERLOCKED_LONG)PTW32_ROBUST_NOTRECOVERABLE == + PTW32_INTERLOCKED_EXCHANGE_ADD_LONG( + (PTW32_INTERLOCKED_LONGPTR)statePtr, + (PTW32_INTERLOCKED_LONG)0)) + { + return ENOTRECOVERABLE; + } + + self = pthread_self(); + kind = -kind - 1; /* Convert to non-robust range */ + + if (0 == (PTW32_INTERLOCKED_LONG) PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG ( + (PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) 1, + (PTW32_INTERLOCKED_LONG) 0)) + { + if (kind != PTHREAD_MUTEX_NORMAL) + { + mx->recursive_count = 1; + } + ptw32_robust_mutex_add(mutex, self); + } + else + { + if (PTHREAD_MUTEX_RECURSIVE == kind && + pthread_equal (mx->ownerThread, pthread_self ())) + { + mx->recursive_count++; + } + else + { + if (EOWNERDEAD == (result = ptw32_robust_mutex_inherit(mutex))) + { + mx->recursive_count = 1; + ptw32_robust_mutex_add(mutex, self); + } + else + { + if (0 == result) + { + result = EBUSY; + } + } + } + } + } + + return (result); +} diff --git a/w32-pthreads/pthread_mutex_unlock.c b/w32-pthreads/pthread_mutex_unlock.c new file mode 100644 index 000000000..3d65d1a95 --- /dev/null +++ b/w32-pthreads/pthread_mutex_unlock.c @@ -0,0 +1,175 @@ +/* + * pthread_mutex_unlock.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_mutex_unlock (pthread_mutex_t * mutex) +{ + int result = 0; + int kind; + pthread_mutex_t mx; + + /* + * Let the system deal with invalid pointers. + */ + + mx = *mutex; + + /* + * If the thread calling us holds the mutex then there is no + * race condition. If another thread holds the + * lock then we shouldn't be in here. + */ + if (mx < PTHREAD_ERRORCHECK_MUTEX_INITIALIZER) + { + kind = mx->kind; + + if (kind >= 0) + { + if (kind == PTHREAD_MUTEX_NORMAL) + { + LONG idx; + + idx = (LONG) PTW32_INTERLOCKED_EXCHANGE_LONG ((PTW32_INTERLOCKED_LONGPTR)&mx->lock_idx, + (PTW32_INTERLOCKED_LONG)0); + if (idx != 0) + { + if (idx < 0) + { + /* + * Someone may be waiting on that mutex. + */ + if (SetEvent (mx->event) == 0) + { + result = EINVAL; + } + } + } + } + else + { + if (pthread_equal (mx->ownerThread, pthread_self())) + { + if (kind != PTHREAD_MUTEX_RECURSIVE + || 0 == --mx->recursive_count) + { + mx->ownerThread.p = NULL; + + if ((LONG) PTW32_INTERLOCKED_EXCHANGE_LONG ((PTW32_INTERLOCKED_LONGPTR)&mx->lock_idx, + (PTW32_INTERLOCKED_LONG)0) < 0L) + { + /* Someone may be waiting on that mutex */ + if (SetEvent (mx->event) == 0) + { + result = EINVAL; + } + } + } + } + else + { + result = EPERM; + } + } + } + else + { + /* Robust types */ + pthread_t self = pthread_self(); + kind = -kind - 1; /* Convert to non-robust range */ + + /* + * The thread must own the lock regardless of type if the mutex + * is robust. + */ + if (pthread_equal (mx->ownerThread, self)) + { + PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG((PTW32_INTERLOCKED_LONGPTR) &mx->robustNode->stateInconsistent, + (PTW32_INTERLOCKED_LONG)PTW32_ROBUST_NOTRECOVERABLE, + (PTW32_INTERLOCKED_LONG)PTW32_ROBUST_INCONSISTENT); + if (PTHREAD_MUTEX_NORMAL == kind) + { + ptw32_robust_mutex_remove(mutex, NULL); + + if ((LONG) PTW32_INTERLOCKED_EXCHANGE_LONG((PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) 0) < 0) + { + /* + * Someone may be waiting on that mutex. + */ + if (SetEvent (mx->event) == 0) + { + result = EINVAL; + } + } + } + else + { + if (kind != PTHREAD_MUTEX_RECURSIVE + || 0 == --mx->recursive_count) + { + ptw32_robust_mutex_remove(mutex, NULL); + + if ((LONG) PTW32_INTERLOCKED_EXCHANGE_LONG((PTW32_INTERLOCKED_LONGPTR) &mx->lock_idx, + (PTW32_INTERLOCKED_LONG) 0) < 0) + { + /* + * Someone may be waiting on that mutex. + */ + if (SetEvent (mx->event) == 0) + { + result = EINVAL; + } + } + } + } + } + else + { + result = EPERM; + } + } + } + else if (mx != PTHREAD_MUTEX_INITIALIZER) + { + result = EINVAL; + } + + return (result); +} diff --git a/w32-pthreads/pthread_mutexattr_destroy.c b/w32-pthreads/pthread_mutexattr_destroy.c new file mode 100644 index 000000000..9d424bfa2 --- /dev/null +++ b/w32-pthreads/pthread_mutexattr_destroy.c @@ -0,0 +1,83 @@ +/* + * pthread_mutexattr_destroy.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_mutexattr_destroy (pthread_mutexattr_t * attr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Destroys a mutex attributes object. The object can + * no longer be used. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_mutexattr_t + * + * + * DESCRIPTION + * Destroys a mutex attributes object. The object can + * no longer be used. + * + * NOTES: + * 1) Does not affect mutexes created using 'attr' + * + * RESULTS + * 0 successfully released attr, + * EINVAL 'attr' is invalid. + * + * ------------------------------------------------------ + */ +{ + int result = 0; + + if (attr == NULL || *attr == NULL) + { + result = EINVAL; + } + else + { + pthread_mutexattr_t ma = *attr; + + *attr = NULL; + free (ma); + } + + return (result); +} /* pthread_mutexattr_destroy */ diff --git a/w32-pthreads/pthread_mutexattr_getkind_np.c b/w32-pthreads/pthread_mutexattr_getkind_np.c new file mode 100644 index 000000000..2d82ec6bc --- /dev/null +++ b/w32-pthreads/pthread_mutexattr_getkind_np.c @@ -0,0 +1,44 @@ +/* + * pthread_mutexattr_getkind_np.c + * + * Description: + * This translation unit implements non-portable thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +int +pthread_mutexattr_getkind_np (pthread_mutexattr_t * attr, int *kind) +{ + return pthread_mutexattr_gettype (attr, kind); +} diff --git a/w32-pthreads/pthread_mutexattr_getpshared.c b/w32-pthreads/pthread_mutexattr_getpshared.c new file mode 100644 index 000000000..42f9589c5 --- /dev/null +++ b/w32-pthreads/pthread_mutexattr_getpshared.c @@ -0,0 +1,95 @@ +/* + * pthread_mutexattr_getpshared.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_mutexattr_getpshared (const pthread_mutexattr_t * attr, int *pshared) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Determine whether mutexes created with 'attr' can be + * shared between processes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_mutexattr_t + * + * pshared + * will be set to one of: + * + * PTHREAD_PROCESS_SHARED + * May be shared if in shared memory + * + * PTHREAD_PROCESS_PRIVATE + * Cannot be shared. + * + * + * DESCRIPTION + * Mutexes creatd with 'attr' can be shared between + * processes if pthread_mutex_t variable is allocated + * in memory shared by these processes. + * NOTES: + * 1) pshared mutexes MUST be allocated in shared + * memory. + * 2) The following macro is defined if shared mutexes + * are supported: + * _POSIX_THREAD_PROCESS_SHARED + * + * RESULTS + * 0 successfully retrieved attribute, + * EINVAL 'attr' is invalid, + * + * ------------------------------------------------------ + */ +{ + int result; + + if ((attr != NULL && *attr != NULL) && (pshared != NULL)) + { + *pshared = (*attr)->pshared; + result = 0; + } + else + { + result = EINVAL; + } + + return (result); + +} /* pthread_mutexattr_getpshared */ diff --git a/w32-pthreads/pthread_mutexattr_getrobust.c b/w32-pthreads/pthread_mutexattr_getrobust.c new file mode 100644 index 000000000..be004837b --- /dev/null +++ b/w32-pthreads/pthread_mutexattr_getrobust.c @@ -0,0 +1,113 @@ +/* + * pthread_mutexattr_getrobust.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_mutexattr_getrobust (const pthread_mutexattr_t * attr, int * robust) + /* + * ------------------------------------------------------ + * + * DOCPUBLIC + * The pthread_mutexattr_setrobust() and + * pthread_mutexattr_getrobust() functions respectively set and + * get the mutex robust attribute. This attribute is set in the + * robust parameter to these functions. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_mutexattr_t + * + * robust + * must be one of: + * + * PTHREAD_MUTEX_STALLED + * + * PTHREAD_MUTEX_ROBUST + * + * DESCRIPTION + * The pthread_mutexattr_setrobust() and + * pthread_mutexattr_getrobust() functions respectively set and + * get the mutex robust attribute. This attribute is set in the + * robust parameter to these functions. The default value of the + * robust attribute is PTHREAD_MUTEX_STALLED. + * + * The robustness of mutex is contained in the robustness attribute + * of the mutex attributes. Valid mutex robustness values are: + * + * PTHREAD_MUTEX_STALLED + * No special actions are taken if the owner of the mutex is + * terminated while holding the mutex lock. This can lead to + * deadlocks if no other thread can unlock the mutex. + * This is the default value. + * + * PTHREAD_MUTEX_ROBUST + * If the process containing the owning thread of a robust mutex + * terminates while holding the mutex lock, the next thread that + * acquires the mutex shall be notified about the termination by + * the return value [EOWNERDEAD] from the locking function. If the + * owning thread of a robust mutex terminates while holding the mutex + * lock, the next thread that acquires the mutex may be notified + * about the termination by the return value [EOWNERDEAD]. The + * notified thread can then attempt to mark the state protected by + * the mutex as consistent again by a call to + * pthread_mutex_consistent(). After a subsequent successful call to + * pthread_mutex_unlock(), the mutex lock shall be released and can + * be used normally by other threads. If the mutex is unlocked without + * a call to pthread_mutex_consistent(), it shall be in a permanently + * unusable state and all attempts to lock the mutex shall fail with + * the error [ENOTRECOVERABLE]. The only permissible operation on such + * a mutex is pthread_mutex_destroy(). + * + * RESULTS + * 0 successfully set attribute, + * EINVAL 'attr' or 'robust' is invalid, + * + * ------------------------------------------------------ + */ +{ + int result = EINVAL; + + if ((attr != NULL && *attr != NULL && robust != NULL)) + { + *robust = (*attr)->robustness; + result = 0; + } + + return (result); +} /* pthread_mutexattr_getrobust */ diff --git a/w32-pthreads/pthread_mutexattr_gettype.c b/w32-pthreads/pthread_mutexattr_gettype.c new file mode 100644 index 000000000..c63fcfa03 --- /dev/null +++ b/w32-pthreads/pthread_mutexattr_gettype.c @@ -0,0 +1,56 @@ +/* + * pthread_mutexattr_gettype.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_mutexattr_gettype (const pthread_mutexattr_t * attr, int *kind) +{ + int result = 0; + + if (attr != NULL && *attr != NULL && kind != NULL) + { + *kind = (*attr)->kind; + } + else + { + result = EINVAL; + } + + return (result); +} diff --git a/w32-pthreads/pthread_mutexattr_init.c b/w32-pthreads/pthread_mutexattr_init.c new file mode 100644 index 000000000..d2797ff24 --- /dev/null +++ b/w32-pthreads/pthread_mutexattr_init.c @@ -0,0 +1,86 @@ +/* + * pthread_mutexattr_init.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_mutexattr_init (pthread_mutexattr_t * attr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Initializes a mutex attributes object with default + * attributes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_mutexattr_t + * + * + * DESCRIPTION + * Initializes a mutex attributes object with default + * attributes. + * + * NOTES: + * 1) Used to define mutex types + * + * RESULTS + * 0 successfully initialized attr, + * ENOMEM insufficient memory for attr. + * + * ------------------------------------------------------ + */ +{ + int result = 0; + pthread_mutexattr_t ma; + + ma = (pthread_mutexattr_t) calloc (1, sizeof (*ma)); + + if (ma == NULL) + { + result = ENOMEM; + } + else + { + ma->pshared = PTHREAD_PROCESS_PRIVATE; + ma->kind = PTHREAD_MUTEX_DEFAULT; + } + + *attr = ma; + + return (result); +} /* pthread_mutexattr_init */ diff --git a/w32-pthreads/pthread_mutexattr_setkind_np.c b/w32-pthreads/pthread_mutexattr_setkind_np.c new file mode 100644 index 000000000..faa936658 --- /dev/null +++ b/w32-pthreads/pthread_mutexattr_setkind_np.c @@ -0,0 +1,44 @@ +/* + * pthread_mutexattr_setkind_np.c + * + * Description: + * This translation unit implements non-portable thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +int +pthread_mutexattr_setkind_np (pthread_mutexattr_t * attr, int kind) +{ + return pthread_mutexattr_settype (attr, kind); +} diff --git a/w32-pthreads/pthread_mutexattr_setpshared.c b/w32-pthreads/pthread_mutexattr_setpshared.c new file mode 100644 index 000000000..cfa6f7199 --- /dev/null +++ b/w32-pthreads/pthread_mutexattr_setpshared.c @@ -0,0 +1,119 @@ +/* + * pthread_mutexattr_setpshared.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_mutexattr_setpshared (pthread_mutexattr_t * attr, int pshared) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Mutexes created with 'attr' can be shared between + * processes if pthread_mutex_t variable is allocated + * in memory shared by these processes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_mutexattr_t + * + * pshared + * must be one of: + * + * PTHREAD_PROCESS_SHARED + * May be shared if in shared memory + * + * PTHREAD_PROCESS_PRIVATE + * Cannot be shared. + * + * DESCRIPTION + * Mutexes creatd with 'attr' can be shared between + * processes if pthread_mutex_t variable is allocated + * in memory shared by these processes. + * + * NOTES: + * 1) pshared mutexes MUST be allocated in shared + * memory. + * + * 2) The following macro is defined if shared mutexes + * are supported: + * _POSIX_THREAD_PROCESS_SHARED + * + * RESULTS + * 0 successfully set attribute, + * EINVAL 'attr' or pshared is invalid, + * ENOSYS PTHREAD_PROCESS_SHARED not supported, + * + * ------------------------------------------------------ + */ +{ + int result; + + if ((attr != NULL && *attr != NULL) && + ((pshared == PTHREAD_PROCESS_SHARED) || + (pshared == PTHREAD_PROCESS_PRIVATE))) + { + if (pshared == PTHREAD_PROCESS_SHARED) + { + +#if !defined( _POSIX_THREAD_PROCESS_SHARED ) + + result = ENOSYS; + pshared = PTHREAD_PROCESS_PRIVATE; + +#else + + result = 0; + +#endif /* _POSIX_THREAD_PROCESS_SHARED */ + + } + else + { + result = 0; + } + + (*attr)->pshared = pshared; + } + else + { + result = EINVAL; + } + + return (result); + +} /* pthread_mutexattr_setpshared */ diff --git a/w32-pthreads/pthread_mutexattr_setrobust.c b/w32-pthreads/pthread_mutexattr_setrobust.c new file mode 100644 index 000000000..b1acef757 --- /dev/null +++ b/w32-pthreads/pthread_mutexattr_setrobust.c @@ -0,0 +1,119 @@ +/* + * pthread_mutexattr_setrobust.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_mutexattr_setrobust (pthread_mutexattr_t * attr, int robust) + /* + * ------------------------------------------------------ + * + * DOCPUBLIC + * The pthread_mutexattr_setrobust() and + * pthread_mutexattr_getrobust() functions respectively set and + * get the mutex robust attribute. This attribute is set in the + * robust parameter to these functions. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_mutexattr_t + * + * robust + * must be one of: + * + * PTHREAD_MUTEX_STALLED + * + * PTHREAD_MUTEX_ROBUST + * + * DESCRIPTION + * The pthread_mutexattr_setrobust() and + * pthread_mutexattr_getrobust() functions respectively set and + * get the mutex robust attribute. This attribute is set in the + * robust parameter to these functions. The default value of the + * robust attribute is PTHREAD_MUTEX_STALLED. + * + * The robustness of mutex is contained in the robustness attribute + * of the mutex attributes. Valid mutex robustness values are: + * + * PTHREAD_MUTEX_STALLED + * No special actions are taken if the owner of the mutex is + * terminated while holding the mutex lock. This can lead to + * deadlocks if no other thread can unlock the mutex. + * This is the default value. + * + * PTHREAD_MUTEX_ROBUST + * If the process containing the owning thread of a robust mutex + * terminates while holding the mutex lock, the next thread that + * acquires the mutex shall be notified about the termination by + * the return value [EOWNERDEAD] from the locking function. If the + * owning thread of a robust mutex terminates while holding the mutex + * lock, the next thread that acquires the mutex may be notified + * about the termination by the return value [EOWNERDEAD]. The + * notified thread can then attempt to mark the state protected by + * the mutex as consistent again by a call to + * pthread_mutex_consistent(). After a subsequent successful call to + * pthread_mutex_unlock(), the mutex lock shall be released and can + * be used normally by other threads. If the mutex is unlocked without + * a call to pthread_mutex_consistent(), it shall be in a permanently + * unusable state and all attempts to lock the mutex shall fail with + * the error [ENOTRECOVERABLE]. The only permissible operation on such + * a mutex is pthread_mutex_destroy(). + * + * RESULTS + * 0 successfully set attribute, + * EINVAL 'attr' or 'robust' is invalid, + * + * ------------------------------------------------------ + */ +{ + int result = EINVAL; + + if ((attr != NULL && *attr != NULL)) + { + switch (robust) + { + case PTHREAD_MUTEX_STALLED: + case PTHREAD_MUTEX_ROBUST: + (*attr)->robustness = robust; + result = 0; + break; + } + } + + return (result); +} /* pthread_mutexattr_setrobust */ diff --git a/w32-pthreads/pthread_mutexattr_settype.c b/w32-pthreads/pthread_mutexattr_settype.c new file mode 100644 index 000000000..8365daf65 --- /dev/null +++ b/w32-pthreads/pthread_mutexattr_settype.c @@ -0,0 +1,143 @@ +/* + * pthread_mutexattr_settype.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_mutexattr_settype (pthread_mutexattr_t * attr, int kind) + /* + * ------------------------------------------------------ + * + * DOCPUBLIC + * The pthread_mutexattr_settype() and + * pthread_mutexattr_gettype() functions respectively set and + * get the mutex type attribute. This attribute is set in the + * type parameter to these functions. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_mutexattr_t + * + * type + * must be one of: + * + * PTHREAD_MUTEX_DEFAULT + * + * PTHREAD_MUTEX_NORMAL + * + * PTHREAD_MUTEX_ERRORCHECK + * + * PTHREAD_MUTEX_RECURSIVE + * + * DESCRIPTION + * The pthread_mutexattr_settype() and + * pthread_mutexattr_gettype() functions respectively set and + * get the mutex type attribute. This attribute is set in the + * type parameter to these functions. The default value of the + * type attribute is PTHREAD_MUTEX_DEFAULT. + * + * The type of mutex is contained in the type attribute of the + * mutex attributes. Valid mutex types include: + * + * PTHREAD_MUTEX_NORMAL + * This type of mutex does not detect deadlock. A + * thread attempting to relock this mutex without + * first unlocking it will deadlock. Attempting to + * unlock a mutex locked by a different thread + * results in undefined behavior. Attempting to + * unlock an unlocked mutex results in undefined + * behavior. + * + * PTHREAD_MUTEX_ERRORCHECK + * This type of mutex provides error checking. A + * thread attempting to relock this mutex without + * first unlocking it will return with an error. A + * thread attempting to unlock a mutex which another + * thread has locked will return with an error. A + * thread attempting to unlock an unlocked mutex will + * return with an error. + * + * PTHREAD_MUTEX_DEFAULT + * Same as PTHREAD_MUTEX_NORMAL. + * + * PTHREAD_MUTEX_RECURSIVE + * A thread attempting to relock this mutex without + * first unlocking it will succeed in locking the + * mutex. The relocking deadlock which can occur with + * mutexes of type PTHREAD_MUTEX_NORMAL cannot occur + * with this type of mutex. Multiple locks of this + * mutex require the same number of unlocks to + * release the mutex before another thread can + * acquire the mutex. A thread attempting to unlock a + * mutex which another thread has locked will return + * with an error. A thread attempting to unlock an + * unlocked mutex will return with an error. This + * type of mutex is only supported for mutexes whose + * process shared attribute is + * PTHREAD_PROCESS_PRIVATE. + * + * RESULTS + * 0 successfully set attribute, + * EINVAL 'attr' or 'type' is invalid, + * + * ------------------------------------------------------ + */ +{ + int result = 0; + + if ((attr != NULL && *attr != NULL)) + { + switch (kind) + { + case PTHREAD_MUTEX_FAST_NP: + case PTHREAD_MUTEX_RECURSIVE_NP: + case PTHREAD_MUTEX_ERRORCHECK_NP: + (*attr)->kind = kind; + break; + default: + result = EINVAL; + break; + } + } + else + { + result = EINVAL; + } + + return (result); +} /* pthread_mutexattr_settype */ diff --git a/w32-pthreads/pthread_num_processors_np.c b/w32-pthreads/pthread_num_processors_np.c new file mode 100644 index 000000000..3067d117d --- /dev/null +++ b/w32-pthreads/pthread_num_processors_np.c @@ -0,0 +1,56 @@ +/* + * pthread_num_processors_np.c + * + * Description: + * This translation unit implements non-portable thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* + * pthread_num_processors_np() + * + * Get the number of CPUs available to the process. + */ +int +pthread_num_processors_np (void) +{ + int count; + + if (ptw32_getprocessors (&count) != 0) + { + count = 1; + } + + return (count); +} diff --git a/w32-pthreads/pthread_once.c b/w32-pthreads/pthread_once.c new file mode 100644 index 000000000..3bfeb9f0b --- /dev/null +++ b/w32-pthreads/pthread_once.c @@ -0,0 +1,79 @@ +/* + * pthread_once.c + * + * Description: + * This translation unit implements miscellaneous thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +int +pthread_once (pthread_once_t * once_control, void (PTW32_CDECL *init_routine) (void)) +{ + if (once_control == NULL || init_routine == NULL) + { + return EINVAL; + } + + if ((PTW32_INTERLOCKED_LONG)PTW32_FALSE == + (PTW32_INTERLOCKED_LONG)PTW32_INTERLOCKED_EXCHANGE_ADD_LONG((PTW32_INTERLOCKED_LONGPTR)&once_control->done, + (PTW32_INTERLOCKED_LONG)0)) /* MBR fence */ + { + ptw32_mcs_local_node_t node; + + ptw32_mcs_lock_acquire((ptw32_mcs_lock_t *)&once_control->lock, &node); + + if (!once_control->done) + { + +#if defined(_MSC_VER) && _MSC_VER < 1400 +#pragma inline_depth(0) +#endif + + pthread_cleanup_push(ptw32_mcs_lock_release, &node); + (*init_routine)(); + pthread_cleanup_pop(0); + +#if defined(_MSC_VER) && _MSC_VER < 1400 +#pragma inline_depth() +#endif + + once_control->done = PTW32_TRUE; + } + + ptw32_mcs_lock_release(&node); + } + + return 0; + +} /* pthread_once */ diff --git a/w32-pthreads/pthread_rwlock_destroy.c b/w32-pthreads/pthread_rwlock_destroy.c new file mode 100644 index 000000000..245a89241 --- /dev/null +++ b/w32-pthreads/pthread_rwlock_destroy.c @@ -0,0 +1,143 @@ +/* + * pthread_rwlock_destroy.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlock_destroy (pthread_rwlock_t * rwlock) +{ + pthread_rwlock_t rwl; + int result = 0, result1 = 0, result2 = 0; + + if (rwlock == NULL || *rwlock == NULL) + { + return EINVAL; + } + + if (*rwlock != PTHREAD_RWLOCK_INITIALIZER) + { + rwl = *rwlock; + + if (rwl->nMagic != PTW32_RWLOCK_MAGIC) + { + return EINVAL; + } + + if ((result = pthread_mutex_lock (&(rwl->mtxExclusiveAccess))) != 0) + { + return result; + } + + if ((result = + pthread_mutex_lock (&(rwl->mtxSharedAccessCompleted))) != 0) + { + (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + return result; + } + + /* + * Check whether any threads own/wait for the lock (wait for ex.access); + * report "BUSY" if so. + */ + if (rwl->nExclusiveAccessCount > 0 + || rwl->nSharedAccessCount > rwl->nCompletedSharedAccessCount) + { + result = pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted)); + result1 = pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + result2 = EBUSY; + } + else + { + rwl->nMagic = 0; + + if ((result = + pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted))) != 0) + { + pthread_mutex_unlock (&rwl->mtxExclusiveAccess); + return result; + } + + if ((result = + pthread_mutex_unlock (&(rwl->mtxExclusiveAccess))) != 0) + { + return result; + } + + *rwlock = NULL; /* Invalidate rwlock before anything else */ + result = pthread_cond_destroy (&(rwl->cndSharedAccessCompleted)); + result1 = pthread_mutex_destroy (&(rwl->mtxSharedAccessCompleted)); + result2 = pthread_mutex_destroy (&(rwl->mtxExclusiveAccess)); + (void) free (rwl); + } + } + else + { + ptw32_mcs_local_node_t node; + /* + * See notes in ptw32_rwlock_check_need_init() above also. + */ + ptw32_mcs_lock_acquire(&ptw32_rwlock_test_init_lock, &node); + + /* + * Check again. + */ + if (*rwlock == PTHREAD_RWLOCK_INITIALIZER) + { + /* + * This is all we need to do to destroy a statically + * initialised rwlock that has not yet been used (initialised). + * If we get to here, another thread + * waiting to initialise this rwlock will get an EINVAL. + */ + *rwlock = NULL; + } + else + { + /* + * The rwlock has been initialised while we were waiting + * so assume it's in use. + */ + result = EBUSY; + } + + ptw32_mcs_lock_release(&node); + } + + return ((result != 0) ? result : ((result1 != 0) ? result1 : result2)); +} diff --git a/w32-pthreads/pthread_rwlock_init.c b/w32-pthreads/pthread_rwlock_init.c new file mode 100644 index 000000000..597c1ff26 --- /dev/null +++ b/w32-pthreads/pthread_rwlock_init.c @@ -0,0 +1,109 @@ +/* + * pthread_rwlock_init.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlock_init (pthread_rwlock_t * rwlock, + const pthread_rwlockattr_t * attr) +{ + int result; + pthread_rwlock_t rwl = 0; + + if (rwlock == NULL) + { + return EINVAL; + } + + if (attr != NULL && *attr != NULL) + { + result = EINVAL; /* Not supported */ + goto DONE; + } + + rwl = (pthread_rwlock_t) calloc (1, sizeof (*rwl)); + + if (rwl == NULL) + { + result = ENOMEM; + goto DONE; + } + + rwl->nSharedAccessCount = 0; + rwl->nExclusiveAccessCount = 0; + rwl->nCompletedSharedAccessCount = 0; + + result = pthread_mutex_init (&rwl->mtxExclusiveAccess, NULL); + if (result != 0) + { + goto FAIL0; + } + + result = pthread_mutex_init (&rwl->mtxSharedAccessCompleted, NULL); + if (result != 0) + { + goto FAIL1; + } + + result = pthread_cond_init (&rwl->cndSharedAccessCompleted, NULL); + if (result != 0) + { + goto FAIL2; + } + + rwl->nMagic = PTW32_RWLOCK_MAGIC; + + result = 0; + goto DONE; + +FAIL2: + (void) pthread_mutex_destroy (&(rwl->mtxSharedAccessCompleted)); + +FAIL1: + (void) pthread_mutex_destroy (&(rwl->mtxExclusiveAccess)); + +FAIL0: + (void) free (rwl); + rwl = NULL; + +DONE: + *rwlock = rwl; + + return result; +} diff --git a/w32-pthreads/pthread_rwlock_rdlock.c b/w32-pthreads/pthread_rwlock_rdlock.c new file mode 100644 index 000000000..91e180835 --- /dev/null +++ b/w32-pthreads/pthread_rwlock_rdlock.c @@ -0,0 +1,102 @@ +/* + * pthread_rwlock_rdlock.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlock_rdlock (pthread_rwlock_t * rwlock) +{ + int result; + pthread_rwlock_t rwl; + + if (rwlock == NULL || *rwlock == NULL) + { + return EINVAL; + } + + /* + * We do a quick check to see if we need to do more work + * to initialise a static rwlock. We check + * again inside the guarded section of ptw32_rwlock_check_need_init() + * to avoid race conditions. + */ + if (*rwlock == PTHREAD_RWLOCK_INITIALIZER) + { + result = ptw32_rwlock_check_need_init (rwlock); + + if (result != 0 && result != EBUSY) + { + return result; + } + } + + rwl = *rwlock; + + if (rwl->nMagic != PTW32_RWLOCK_MAGIC) + { + return EINVAL; + } + + if ((result = pthread_mutex_lock (&(rwl->mtxExclusiveAccess))) != 0) + { + return result; + } + + if (++rwl->nSharedAccessCount == INT_MAX) + { + if ((result = + pthread_mutex_lock (&(rwl->mtxSharedAccessCompleted))) != 0) + { + (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + return result; + } + + rwl->nSharedAccessCount -= rwl->nCompletedSharedAccessCount; + rwl->nCompletedSharedAccessCount = 0; + + if ((result = + pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted))) != 0) + { + (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + return result; + } + } + + return (pthread_mutex_unlock (&(rwl->mtxExclusiveAccess))); +} diff --git a/w32-pthreads/pthread_rwlock_timedrdlock.c b/w32-pthreads/pthread_rwlock_timedrdlock.c new file mode 100644 index 000000000..7133778bf --- /dev/null +++ b/w32-pthreads/pthread_rwlock_timedrdlock.c @@ -0,0 +1,109 @@ +/* + * pthread_rwlock_timedrdlock.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlock_timedrdlock (pthread_rwlock_t * rwlock, + const struct timespec *abstime) +{ + int result; + pthread_rwlock_t rwl; + + if (rwlock == NULL || *rwlock == NULL) + { + return EINVAL; + } + + /* + * We do a quick check to see if we need to do more work + * to initialise a static rwlock. We check + * again inside the guarded section of ptw32_rwlock_check_need_init() + * to avoid race conditions. + */ + if (*rwlock == PTHREAD_RWLOCK_INITIALIZER) + { + result = ptw32_rwlock_check_need_init (rwlock); + + if (result != 0 && result != EBUSY) + { + return result; + } + } + + rwl = *rwlock; + + if (rwl->nMagic != PTW32_RWLOCK_MAGIC) + { + return EINVAL; + } + + if ((result = + pthread_mutex_timedlock (&(rwl->mtxExclusiveAccess), abstime)) != 0) + { + return result; + } + + if (++rwl->nSharedAccessCount == INT_MAX) + { + if ((result = + pthread_mutex_timedlock (&(rwl->mtxSharedAccessCompleted), + abstime)) != 0) + { + if (result == ETIMEDOUT) + { + ++rwl->nCompletedSharedAccessCount; + } + (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + return result; + } + + rwl->nSharedAccessCount -= rwl->nCompletedSharedAccessCount; + rwl->nCompletedSharedAccessCount = 0; + + if ((result = + pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted))) != 0) + { + (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + return result; + } + } + + return (pthread_mutex_unlock (&(rwl->mtxExclusiveAccess))); +} diff --git a/w32-pthreads/pthread_rwlock_timedwrlock.c b/w32-pthreads/pthread_rwlock_timedwrlock.c new file mode 100644 index 000000000..8c111bbb1 --- /dev/null +++ b/w32-pthreads/pthread_rwlock_timedwrlock.c @@ -0,0 +1,139 @@ +/* + * pthread_rwlock_timedwrlock.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlock_timedwrlock (pthread_rwlock_t * rwlock, + const struct timespec *abstime) +{ + int result; + pthread_rwlock_t rwl; + + if (rwlock == NULL || *rwlock == NULL) + { + return EINVAL; + } + + /* + * We do a quick check to see if we need to do more work + * to initialise a static rwlock. We check + * again inside the guarded section of ptw32_rwlock_check_need_init() + * to avoid race conditions. + */ + if (*rwlock == PTHREAD_RWLOCK_INITIALIZER) + { + result = ptw32_rwlock_check_need_init (rwlock); + + if (result != 0 && result != EBUSY) + { + return result; + } + } + + rwl = *rwlock; + + if (rwl->nMagic != PTW32_RWLOCK_MAGIC) + { + return EINVAL; + } + + if ((result = + pthread_mutex_timedlock (&(rwl->mtxExclusiveAccess), abstime)) != 0) + { + return result; + } + + if ((result = + pthread_mutex_timedlock (&(rwl->mtxSharedAccessCompleted), + abstime)) != 0) + { + (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + return result; + } + + if (rwl->nExclusiveAccessCount == 0) + { + if (rwl->nCompletedSharedAccessCount > 0) + { + rwl->nSharedAccessCount -= rwl->nCompletedSharedAccessCount; + rwl->nCompletedSharedAccessCount = 0; + } + + if (rwl->nSharedAccessCount > 0) + { + rwl->nCompletedSharedAccessCount = -rwl->nSharedAccessCount; + + /* + * This routine may be a cancelation point + * according to POSIX 1003.1j section 18.1.2. + */ +#if defined(_MSC_VER) && _MSC_VER < 1400 +#pragma inline_depth(0) +#endif + pthread_cleanup_push (ptw32_rwlock_cancelwrwait, (void *) rwl); + + do + { + result = + pthread_cond_timedwait (&(rwl->cndSharedAccessCompleted), + &(rwl->mtxSharedAccessCompleted), + abstime); + } + while (result == 0 && rwl->nCompletedSharedAccessCount < 0); + + pthread_cleanup_pop ((result != 0) ? 1 : 0); +#if defined(_MSC_VER) && _MSC_VER < 1400 +#pragma inline_depth() +#endif + + if (result == 0) + { + rwl->nSharedAccessCount = 0; + } + } + } + + if (result == 0) + { + rwl->nExclusiveAccessCount++; + } + + return result; +} diff --git a/w32-pthreads/pthread_rwlock_tryrdlock.c b/w32-pthreads/pthread_rwlock_tryrdlock.c new file mode 100644 index 000000000..0fc545857 --- /dev/null +++ b/w32-pthreads/pthread_rwlock_tryrdlock.c @@ -0,0 +1,102 @@ +/* + * pthread_rwlock_tryrdlock.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlock_tryrdlock (pthread_rwlock_t * rwlock) +{ + int result; + pthread_rwlock_t rwl; + + if (rwlock == NULL || *rwlock == NULL) + { + return EINVAL; + } + + /* + * We do a quick check to see if we need to do more work + * to initialise a static rwlock. We check + * again inside the guarded section of ptw32_rwlock_check_need_init() + * to avoid race conditions. + */ + if (*rwlock == PTHREAD_RWLOCK_INITIALIZER) + { + result = ptw32_rwlock_check_need_init (rwlock); + + if (result != 0 && result != EBUSY) + { + return result; + } + } + + rwl = *rwlock; + + if (rwl->nMagic != PTW32_RWLOCK_MAGIC) + { + return EINVAL; + } + + if ((result = pthread_mutex_trylock (&(rwl->mtxExclusiveAccess))) != 0) + { + return result; + } + + if (++rwl->nSharedAccessCount == INT_MAX) + { + if ((result = + pthread_mutex_lock (&(rwl->mtxSharedAccessCompleted))) != 0) + { + (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + return result; + } + + rwl->nSharedAccessCount -= rwl->nCompletedSharedAccessCount; + rwl->nCompletedSharedAccessCount = 0; + + if ((result = + pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted))) != 0) + { + (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + return result; + } + } + + return (pthread_mutex_unlock (&rwl->mtxExclusiveAccess)); +} diff --git a/w32-pthreads/pthread_rwlock_trywrlock.c b/w32-pthreads/pthread_rwlock_trywrlock.c new file mode 100644 index 000000000..9997c5d7f --- /dev/null +++ b/w32-pthreads/pthread_rwlock_trywrlock.c @@ -0,0 +1,122 @@ +/* + * pthread_rwlock_trywrlock.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlock_trywrlock (pthread_rwlock_t * rwlock) +{ + int result, result1; + pthread_rwlock_t rwl; + + if (rwlock == NULL || *rwlock == NULL) + { + return EINVAL; + } + + /* + * We do a quick check to see if we need to do more work + * to initialise a static rwlock. We check + * again inside the guarded section of ptw32_rwlock_check_need_init() + * to avoid race conditions. + */ + if (*rwlock == PTHREAD_RWLOCK_INITIALIZER) + { + result = ptw32_rwlock_check_need_init (rwlock); + + if (result != 0 && result != EBUSY) + { + return result; + } + } + + rwl = *rwlock; + + if (rwl->nMagic != PTW32_RWLOCK_MAGIC) + { + return EINVAL; + } + + if ((result = pthread_mutex_trylock (&(rwl->mtxExclusiveAccess))) != 0) + { + return result; + } + + if ((result = + pthread_mutex_trylock (&(rwl->mtxSharedAccessCompleted))) != 0) + { + result1 = pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + return ((result1 != 0) ? result1 : result); + } + + if (rwl->nExclusiveAccessCount == 0) + { + if (rwl->nCompletedSharedAccessCount > 0) + { + rwl->nSharedAccessCount -= rwl->nCompletedSharedAccessCount; + rwl->nCompletedSharedAccessCount = 0; + } + + if (rwl->nSharedAccessCount > 0) + { + if ((result = + pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted))) != 0) + { + (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + return result; + } + + if ((result = + pthread_mutex_unlock (&(rwl->mtxExclusiveAccess))) == 0) + { + result = EBUSY; + } + } + else + { + rwl->nExclusiveAccessCount = 1; + } + } + else + { + result = EBUSY; + } + + return result; +} diff --git a/w32-pthreads/pthread_rwlock_unlock.c b/w32-pthreads/pthread_rwlock_unlock.c new file mode 100644 index 000000000..d48d18705 --- /dev/null +++ b/w32-pthreads/pthread_rwlock_unlock.c @@ -0,0 +1,93 @@ +/* + * pthread_rwlock_unlock.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlock_unlock (pthread_rwlock_t * rwlock) +{ + int result, result1; + pthread_rwlock_t rwl; + + if (rwlock == NULL || *rwlock == NULL) + { + return (EINVAL); + } + + if (*rwlock == PTHREAD_RWLOCK_INITIALIZER) + { + /* + * Assume any race condition here is harmless. + */ + return 0; + } + + rwl = *rwlock; + + if (rwl->nMagic != PTW32_RWLOCK_MAGIC) + { + return EINVAL; + } + + if (rwl->nExclusiveAccessCount == 0) + { + if ((result = + pthread_mutex_lock (&(rwl->mtxSharedAccessCompleted))) != 0) + { + return result; + } + + if (++rwl->nCompletedSharedAccessCount == 0) + { + result = pthread_cond_signal (&(rwl->cndSharedAccessCompleted)); + } + + result1 = pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted)); + } + else + { + rwl->nExclusiveAccessCount--; + + result = pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted)); + result1 = pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + + } + + return ((result != 0) ? result : result1); +} diff --git a/w32-pthreads/pthread_rwlock_wrlock.c b/w32-pthreads/pthread_rwlock_wrlock.c new file mode 100644 index 000000000..e8b4fbb30 --- /dev/null +++ b/w32-pthreads/pthread_rwlock_wrlock.c @@ -0,0 +1,133 @@ +/* + * pthread_rwlock_wrlock.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlock_wrlock (pthread_rwlock_t * rwlock) +{ + int result; + pthread_rwlock_t rwl; + + if (rwlock == NULL || *rwlock == NULL) + { + return EINVAL; + } + + /* + * We do a quick check to see if we need to do more work + * to initialise a static rwlock. We check + * again inside the guarded section of ptw32_rwlock_check_need_init() + * to avoid race conditions. + */ + if (*rwlock == PTHREAD_RWLOCK_INITIALIZER) + { + result = ptw32_rwlock_check_need_init (rwlock); + + if (result != 0 && result != EBUSY) + { + return result; + } + } + + rwl = *rwlock; + + if (rwl->nMagic != PTW32_RWLOCK_MAGIC) + { + return EINVAL; + } + + if ((result = pthread_mutex_lock (&(rwl->mtxExclusiveAccess))) != 0) + { + return result; + } + + if ((result = pthread_mutex_lock (&(rwl->mtxSharedAccessCompleted))) != 0) + { + (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + return result; + } + + if (rwl->nExclusiveAccessCount == 0) + { + if (rwl->nCompletedSharedAccessCount > 0) + { + rwl->nSharedAccessCount -= rwl->nCompletedSharedAccessCount; + rwl->nCompletedSharedAccessCount = 0; + } + + if (rwl->nSharedAccessCount > 0) + { + rwl->nCompletedSharedAccessCount = -rwl->nSharedAccessCount; + + /* + * This routine may be a cancelation point + * according to POSIX 1003.1j section 18.1.2. + */ +#if defined(_MSC_VER) && _MSC_VER < 1400 +#pragma inline_depth(0) +#endif + pthread_cleanup_push (ptw32_rwlock_cancelwrwait, (void *) rwl); + + do + { + result = pthread_cond_wait (&(rwl->cndSharedAccessCompleted), + &(rwl->mtxSharedAccessCompleted)); + } + while (result == 0 && rwl->nCompletedSharedAccessCount < 0); + + pthread_cleanup_pop ((result != 0) ? 1 : 0); +#if defined(_MSC_VER) && _MSC_VER < 1400 +#pragma inline_depth() +#endif + + if (result == 0) + { + rwl->nSharedAccessCount = 0; + } + } + } + + if (result == 0) + { + rwl->nExclusiveAccessCount++; + } + + return result; +} diff --git a/w32-pthreads/pthread_rwlockattr_destroy.c b/w32-pthreads/pthread_rwlockattr_destroy.c new file mode 100644 index 000000000..868e727d3 --- /dev/null +++ b/w32-pthreads/pthread_rwlockattr_destroy.c @@ -0,0 +1,84 @@ +/* + * pthread_rwlockattr_destroy.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlockattr_destroy (pthread_rwlockattr_t * attr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Destroys a rwlock attributes object. The object can + * no longer be used. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_rwlockattr_t + * + * + * DESCRIPTION + * Destroys a rwlock attributes object. The object can + * no longer be used. + * + * NOTES: + * 1) Does not affect rwlockss created using 'attr' + * + * RESULTS + * 0 successfully released attr, + * EINVAL 'attr' is invalid. + * + * ------------------------------------------------------ + */ +{ + int result = 0; + + if (attr == NULL || *attr == NULL) + { + result = EINVAL; + } + else + { + pthread_rwlockattr_t rwa = *attr; + + *attr = NULL; + free (rwa); + } + + return (result); +} /* pthread_rwlockattr_destroy */ diff --git a/w32-pthreads/pthread_rwlockattr_getpshared.c b/w32-pthreads/pthread_rwlockattr_getpshared.c new file mode 100644 index 000000000..eeace207f --- /dev/null +++ b/w32-pthreads/pthread_rwlockattr_getpshared.c @@ -0,0 +1,97 @@ +/* + * pthread_rwlockattr_getpshared.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlockattr_getpshared (const pthread_rwlockattr_t * attr, + int *pshared) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Determine whether rwlocks created with 'attr' can be + * shared between processes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_rwlockattr_t + * + * pshared + * will be set to one of: + * + * PTHREAD_PROCESS_SHARED + * May be shared if in shared memory + * + * PTHREAD_PROCESS_PRIVATE + * Cannot be shared. + * + * + * DESCRIPTION + * Rwlocks creatd with 'attr' can be shared between + * processes if pthread_rwlock_t variable is allocated + * in memory shared by these processes. + * NOTES: + * 1) pshared rwlocks MUST be allocated in shared + * memory. + * 2) The following macro is defined if shared rwlocks + * are supported: + * _POSIX_THREAD_PROCESS_SHARED + * + * RESULTS + * 0 successfully retrieved attribute, + * EINVAL 'attr' is invalid, + * + * ------------------------------------------------------ + */ +{ + int result; + + if ((attr != NULL && *attr != NULL) && (pshared != NULL)) + { + *pshared = (*attr)->pshared; + result = 0; + } + else + { + result = EINVAL; + } + + return (result); + +} /* pthread_rwlockattr_getpshared */ diff --git a/w32-pthreads/pthread_rwlockattr_init.c b/w32-pthreads/pthread_rwlockattr_init.c new file mode 100644 index 000000000..a2d2b945f --- /dev/null +++ b/w32-pthreads/pthread_rwlockattr_init.c @@ -0,0 +1,83 @@ +/* + * pthread_rwlockattr_init.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlockattr_init (pthread_rwlockattr_t * attr) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Initializes a rwlock attributes object with default + * attributes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_rwlockattr_t + * + * + * DESCRIPTION + * Initializes a rwlock attributes object with default + * attributes. + * + * RESULTS + * 0 successfully initialized attr, + * ENOMEM insufficient memory for attr. + * + * ------------------------------------------------------ + */ +{ + int result = 0; + pthread_rwlockattr_t rwa; + + rwa = (pthread_rwlockattr_t) calloc (1, sizeof (*rwa)); + + if (rwa == NULL) + { + result = ENOMEM; + } + else + { + rwa->pshared = PTHREAD_PROCESS_PRIVATE; + } + + *attr = rwa; + + return (result); +} /* pthread_rwlockattr_init */ diff --git a/w32-pthreads/pthread_rwlockattr_setpshared.c b/w32-pthreads/pthread_rwlockattr_setpshared.c new file mode 100644 index 000000000..a83dd70a4 --- /dev/null +++ b/w32-pthreads/pthread_rwlockattr_setpshared.c @@ -0,0 +1,120 @@ +/* + * pthread_rwlockattr_setpshared.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlockattr_setpshared (pthread_rwlockattr_t * attr, int pshared) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Rwlocks created with 'attr' can be shared between + * processes if pthread_rwlock_t variable is allocated + * in memory shared by these processes. + * + * PARAMETERS + * attr + * pointer to an instance of pthread_rwlockattr_t + * + * pshared + * must be one of: + * + * PTHREAD_PROCESS_SHARED + * May be shared if in shared memory + * + * PTHREAD_PROCESS_PRIVATE + * Cannot be shared. + * + * DESCRIPTION + * Rwlocks creatd with 'attr' can be shared between + * processes if pthread_rwlock_t variable is allocated + * in memory shared by these processes. + * + * NOTES: + * 1) pshared rwlocks MUST be allocated in shared + * memory. + * + * 2) The following macro is defined if shared rwlocks + * are supported: + * _POSIX_THREAD_PROCESS_SHARED + * + * RESULTS + * 0 successfully set attribute, + * EINVAL 'attr' or pshared is invalid, + * ENOSYS PTHREAD_PROCESS_SHARED not supported, + * + * ------------------------------------------------------ + */ +{ + int result; + + if ((attr != NULL && *attr != NULL) && + ((pshared == PTHREAD_PROCESS_SHARED) || + (pshared == PTHREAD_PROCESS_PRIVATE))) + { + if (pshared == PTHREAD_PROCESS_SHARED) + { + +#if !defined( _POSIX_THREAD_PROCESS_SHARED ) + + result = ENOSYS; + pshared = PTHREAD_PROCESS_PRIVATE; + +#else + + result = 0; + +#endif /* _POSIX_THREAD_PROCESS_SHARED */ + + } + else + { + result = 0; + } + + (*attr)->pshared = pshared; + } + else + { + result = EINVAL; + } + + return (result); + +} /* pthread_rwlockattr_setpshared */ diff --git a/w32-pthreads/pthread_self.c b/w32-pthreads/pthread_self.c new file mode 100644 index 000000000..9a1765f82 --- /dev/null +++ b/w32-pthreads/pthread_self.c @@ -0,0 +1,141 @@ +/* + * pthread_self.c + * + * Description: + * This translation unit implements miscellaneous thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +pthread_t +pthread_self (void) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function returns a reference to the current running + * thread. + * + * PARAMETERS + * N/A + * + * + * DESCRIPTION + * This function returns a reference to the current running + * thread. + * + * RESULTS + * pthread_t reference to the current thread + * + * ------------------------------------------------------ + */ +{ + pthread_t self; + pthread_t nil = {NULL, 0}; + ptw32_thread_t * sp; + +#if defined(_UWIN) + if (!ptw32_selfThreadKey) + return nil; +#endif + + sp = (ptw32_thread_t *) pthread_getspecific (ptw32_selfThreadKey); + + if (sp != NULL) + { + self = sp->ptHandle; + } + else + { + /* + * Need to create an implicit 'self' for the currently + * executing thread. + */ + self = ptw32_new (); + sp = (ptw32_thread_t *) self.p; + + if (sp != NULL) + { + /* + * This is a non-POSIX thread which has chosen to call + * a POSIX threads function for some reason. We assume that + * it isn't joinable, but we do assume that it's + * (deferred) cancelable. + */ + sp->implicit = 1; + sp->detachState = PTHREAD_CREATE_DETACHED; + sp->thread = GetCurrentThreadId (); + +#if defined(NEED_DUPLICATEHANDLE) + /* + * DuplicateHandle does not exist on WinCE. + * + * NOTE: + * GetCurrentThread only returns a pseudo-handle + * which is only valid in the current thread context. + * Therefore, you should not pass the handle to + * other threads for whatever purpose. + */ + sp->threadH = GetCurrentThread (); +#else + if (!DuplicateHandle (GetCurrentProcess (), + GetCurrentThread (), + GetCurrentProcess (), + &sp->threadH, + 0, FALSE, DUPLICATE_SAME_ACCESS)) + { + /* + * Should not do this, but we have no alternative if + * we can't get a Win32 thread handle. + * Thread structs are never freed. + */ + ptw32_threadReusePush (self); + /* + * As this is a win32 thread calling us and we have failed, + * return a value that makes sense to win32. + */ + return nil; + } +#endif + + /* + * No need to explicitly serialise access to sched_priority + * because the new handle is not yet public. + */ + sp->sched_priority = GetThreadPriority (sp->threadH); + pthread_setspecific (ptw32_selfThreadKey, (void *) sp); + } + } + + return (self); + +} /* pthread_self */ diff --git a/w32-pthreads/pthread_setcancelstate.c b/w32-pthreads/pthread_setcancelstate.c new file mode 100644 index 000000000..bbcd624af --- /dev/null +++ b/w32-pthreads/pthread_setcancelstate.c @@ -0,0 +1,125 @@ +/* + * pthread_setcancelstate.c + * + * Description: + * POSIX thread functions related to thread cancellation. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_setcancelstate (int state, int *oldstate) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function atomically sets the calling thread's + * cancelability state to 'state' and returns the previous + * cancelability state at the location referenced by + * 'oldstate' + * + * PARAMETERS + * state, + * oldstate + * PTHREAD_CANCEL_ENABLE + * cancellation is enabled, + * + * PTHREAD_CANCEL_DISABLE + * cancellation is disabled + * + * + * DESCRIPTION + * This function atomically sets the calling thread's + * cancelability state to 'state' and returns the previous + * cancelability state at the location referenced by + * 'oldstate'. + * + * NOTES: + * 1) Use to disable cancellation around 'atomic' code that + * includes cancellation points + * + * COMPATIBILITY ADDITIONS + * If 'oldstate' is NULL then the previous state is not returned + * but the function still succeeds. (Solaris) + * + * RESULTS + * 0 successfully set cancelability type, + * EINVAL 'state' is invalid + * + * ------------------------------------------------------ + */ +{ + ptw32_mcs_local_node_t stateLock; + int result = 0; + pthread_t self = pthread_self (); + ptw32_thread_t * sp = (ptw32_thread_t *) self.p; + + if (sp == NULL + || (state != PTHREAD_CANCEL_ENABLE && state != PTHREAD_CANCEL_DISABLE)) + { + return EINVAL; + } + + /* + * Lock for async-cancel safety. + */ + ptw32_mcs_lock_acquire (&sp->stateLock, &stateLock); + + if (oldstate != NULL) + { + *oldstate = sp->cancelState; + } + + sp->cancelState = state; + + /* + * Check if there is a pending asynchronous cancel + */ + if (state == PTHREAD_CANCEL_ENABLE + && sp->cancelType == PTHREAD_CANCEL_ASYNCHRONOUS + && WaitForSingleObject (sp->cancelEvent, 0) == WAIT_OBJECT_0) + { + sp->state = PThreadStateCanceling; + sp->cancelState = PTHREAD_CANCEL_DISABLE; + ResetEvent (sp->cancelEvent); + ptw32_mcs_lock_release (&stateLock); + ptw32_throw (PTW32_EPS_CANCEL); + + /* Never reached */ + } + + ptw32_mcs_lock_release (&stateLock); + + return (result); + +} /* pthread_setcancelstate */ diff --git a/w32-pthreads/pthread_setcanceltype.c b/w32-pthreads/pthread_setcanceltype.c new file mode 100644 index 000000000..72b0af5bb --- /dev/null +++ b/w32-pthreads/pthread_setcanceltype.c @@ -0,0 +1,126 @@ +/* + * pthread_setcanceltype.c + * + * Description: + * POSIX thread functions related to thread cancellation. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_setcanceltype (int type, int *oldtype) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function atomically sets the calling thread's + * cancelability type to 'type' and returns the previous + * cancelability type at the location referenced by + * 'oldtype' + * + * PARAMETERS + * type, + * oldtype + * PTHREAD_CANCEL_DEFERRED + * only deferred cancelation is allowed, + * + * PTHREAD_CANCEL_ASYNCHRONOUS + * Asynchronous cancellation is allowed + * + * + * DESCRIPTION + * This function atomically sets the calling thread's + * cancelability type to 'type' and returns the previous + * cancelability type at the location referenced by + * 'oldtype' + * + * NOTES: + * 1) Use with caution; most code is not safe for use + * with asynchronous cancelability. + * + * COMPATIBILITY ADDITIONS + * If 'oldtype' is NULL then the previous type is not returned + * but the function still succeeds. (Solaris) + * + * RESULTS + * 0 successfully set cancelability type, + * EINVAL 'type' is invalid + * + * ------------------------------------------------------ + */ +{ + ptw32_mcs_local_node_t stateLock; + int result = 0; + pthread_t self = pthread_self (); + ptw32_thread_t * sp = (ptw32_thread_t *) self.p; + + if (sp == NULL + || (type != PTHREAD_CANCEL_DEFERRED + && type != PTHREAD_CANCEL_ASYNCHRONOUS)) + { + return EINVAL; + } + + /* + * Lock for async-cancel safety. + */ + ptw32_mcs_lock_acquire (&sp->stateLock, &stateLock); + + if (oldtype != NULL) + { + *oldtype = sp->cancelType; + } + + sp->cancelType = type; + + /* + * Check if there is a pending asynchronous cancel + */ + if (sp->cancelState == PTHREAD_CANCEL_ENABLE + && type == PTHREAD_CANCEL_ASYNCHRONOUS + && WaitForSingleObject (sp->cancelEvent, 0) == WAIT_OBJECT_0) + { + sp->state = PThreadStateCanceling; + sp->cancelState = PTHREAD_CANCEL_DISABLE; + ResetEvent (sp->cancelEvent); + ptw32_mcs_lock_release (&stateLock); + ptw32_throw (PTW32_EPS_CANCEL); + + /* Never reached */ + } + + ptw32_mcs_lock_release (&stateLock); + + return (result); + +} /* pthread_setcanceltype */ diff --git a/w32-pthreads/pthread_setconcurrency.c b/w32-pthreads/pthread_setconcurrency.c new file mode 100644 index 000000000..f62346f8e --- /dev/null +++ b/w32-pthreads/pthread_setconcurrency.c @@ -0,0 +1,53 @@ +/* + * pthread_setconcurrency.c + * + * Description: + * This translation unit implements miscellaneous thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_setconcurrency (int level) +{ + if (level < 0) + { + return EINVAL; + } + else + { + ptw32_concurrency = level; + return 0; + } +} diff --git a/w32-pthreads/pthread_setschedparam.c b/w32-pthreads/pthread_setschedparam.c new file mode 100644 index 000000000..b762753cd --- /dev/null +++ b/w32-pthreads/pthread_setschedparam.c @@ -0,0 +1,123 @@ +/* + * sched_setschedparam.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +int +pthread_setschedparam (pthread_t thread, int policy, + const struct sched_param *param) +{ + int result; + + /* Validate the thread id. */ + result = pthread_kill (thread, 0); + if (0 != result) + { + return result; + } + + /* Validate the scheduling policy. */ + if (policy < SCHED_MIN || policy > SCHED_MAX) + { + return EINVAL; + } + + /* Ensure the policy is SCHED_OTHER. */ + if (policy != SCHED_OTHER) + { + return ENOTSUP; + } + + return (ptw32_setthreadpriority (thread, policy, param->sched_priority)); +} + + +int +ptw32_setthreadpriority (pthread_t thread, int policy, int priority) +{ + int prio; + ptw32_mcs_local_node_t threadLock; + int result = 0; + ptw32_thread_t * tp = (ptw32_thread_t *) thread.p; + + prio = priority; + + /* Validate priority level. */ + if (prio < sched_get_priority_min (policy) || + prio > sched_get_priority_max (policy)) + { + return EINVAL; + } + +#if (THREAD_PRIORITY_LOWEST > THREAD_PRIORITY_NORMAL) +/* WinCE */ +#else +/* Everything else */ + + if (THREAD_PRIORITY_IDLE < prio && THREAD_PRIORITY_LOWEST > prio) + { + prio = THREAD_PRIORITY_LOWEST; + } + else if (THREAD_PRIORITY_TIME_CRITICAL > prio + && THREAD_PRIORITY_HIGHEST < prio) + { + prio = THREAD_PRIORITY_HIGHEST; + } + +#endif + + ptw32_mcs_lock_acquire (&tp->threadLock, &threadLock); + + /* If this fails, the current priority is unchanged. */ + if (0 == SetThreadPriority (tp->threadH, prio)) + { + result = EINVAL; + } + else + { + /* + * Must record the thread's sched_priority as given, + * not as finally adjusted. + */ + tp->sched_priority = priority; + } + + ptw32_mcs_lock_release (&threadLock); + + return result; +} diff --git a/w32-pthreads/pthread_setspecific.c b/w32-pthreads/pthread_setspecific.c new file mode 100644 index 000000000..0f29e704a --- /dev/null +++ b/w32-pthreads/pthread_setspecific.c @@ -0,0 +1,167 @@ +/* + * pthread_setspecific.c + * + * Description: + * POSIX thread functions which implement thread-specific data (TSD). + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_setspecific (pthread_key_t key, const void *value) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function sets the value of the thread specific + * key in the calling thread. + * + * PARAMETERS + * key + * an instance of pthread_key_t + * value + * the value to set key to + * + * + * DESCRIPTION + * This function sets the value of the thread specific + * key in the calling thread. + * + * RESULTS + * 0 successfully set value + * EAGAIN could not set value + * ENOENT SERIOUS!! + * + * ------------------------------------------------------ + */ +{ + pthread_t self; + int result = 0; + + if (key != ptw32_selfThreadKey) + { + /* + * Using pthread_self will implicitly create + * an instance of pthread_t for the current + * thread if one wasn't explicitly created + */ + self = pthread_self (); + if (self.p == NULL) + { + return ENOENT; + } + } + else + { + /* + * Resolve catch-22 of registering thread with selfThread + * key + */ + ptw32_thread_t * sp = (ptw32_thread_t *) pthread_getspecific (ptw32_selfThreadKey); + + if (sp == NULL) + { + if (value == NULL) + { + return ENOENT; + } + self = *((pthread_t *) value); + } + else + { + self = sp->ptHandle; + } + } + + result = 0; + + if (key != NULL) + { + if (self.p != NULL && key->destructor != NULL && value != NULL) + { + ptw32_mcs_local_node_t keyLock; + ptw32_mcs_local_node_t threadLock; + ptw32_thread_t * sp = (ptw32_thread_t *) self.p; + /* + * Only require associations if we have to + * call user destroy routine. + * Don't need to locate an existing association + * when setting data to NULL for WIN32 since the + * data is stored with the operating system; not + * on the association; setting assoc to NULL short + * circuits the search. + */ + ThreadKeyAssoc *assoc; + + ptw32_mcs_lock_acquire(&(key->keyLock), &keyLock); + ptw32_mcs_lock_acquire(&(sp->threadLock), &threadLock); + + assoc = (ThreadKeyAssoc *) sp->keys; + /* + * Locate existing association + */ + while (assoc != NULL) + { + if (assoc->key == key) + { + /* + * Association already exists + */ + break; + } + assoc = assoc->nextKey; + } + + /* + * create an association if not found + */ + if (assoc == NULL) + { + result = ptw32_tkAssocCreate (sp, key); + } + + ptw32_mcs_lock_release(&threadLock); + ptw32_mcs_lock_release(&keyLock); + } + + if (result == 0) + { + if (!TlsSetValue (key->key, (LPVOID) value)) + { + result = EAGAIN; + } + } + } + + return (result); +} /* pthread_setspecific */ diff --git a/w32-pthreads/pthread_spin_destroy.c b/w32-pthreads/pthread_spin_destroy.c new file mode 100644 index 000000000..786c4e34c --- /dev/null +++ b/w32-pthreads/pthread_spin_destroy.c @@ -0,0 +1,111 @@ +/* + * pthread_spin_destroy.c + * + * Description: + * This translation unit implements spin lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_spin_destroy (pthread_spinlock_t * lock) +{ + register pthread_spinlock_t s; + int result = 0; + + if (lock == NULL || *lock == NULL) + { + return EINVAL; + } + + if ((s = *lock) != PTHREAD_SPINLOCK_INITIALIZER) + { + if (s->interlock == PTW32_SPIN_USE_MUTEX) + { + result = pthread_mutex_destroy (&(s->u.mutex)); + } + else if ((PTW32_INTERLOCKED_LONG) PTW32_SPIN_UNLOCKED != + PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG ((PTW32_INTERLOCKED_LONGPTR) &s->interlock, + (PTW32_INTERLOCKED_LONG) PTW32_SPIN_INVALID, + (PTW32_INTERLOCKED_LONG) PTW32_SPIN_UNLOCKED)) + { + result = EINVAL; + } + + if (0 == result) + { + /* + * We are relying on the application to ensure that all other threads + * have finished with the spinlock before destroying it. + */ + *lock = NULL; + (void) free (s); + } + } + else + { + /* + * See notes in ptw32_spinlock_check_need_init() above also. + */ + ptw32_mcs_local_node_t node; + + ptw32_mcs_lock_acquire(&ptw32_spinlock_test_init_lock, &node); + + /* + * Check again. + */ + if (*lock == PTHREAD_SPINLOCK_INITIALIZER) + { + /* + * This is all we need to do to destroy a statically + * initialised spinlock that has not yet been used (initialised). + * If we get to here, another thread + * waiting to initialise this mutex will get an EINVAL. + */ + *lock = NULL; + } + else + { + /* + * The spinlock has been initialised while we were waiting + * so assume it's in use. + */ + result = EBUSY; + } + + ptw32_mcs_lock_release(&node); + } + + return (result); +} diff --git a/w32-pthreads/pthread_spin_init.c b/w32-pthreads/pthread_spin_init.c new file mode 100644 index 000000000..553af7eac --- /dev/null +++ b/w32-pthreads/pthread_spin_init.c @@ -0,0 +1,123 @@ +/* + * pthread_spin_init.c + * + * Description: + * This translation unit implements spin lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_spin_init (pthread_spinlock_t * lock, int pshared) +{ + pthread_spinlock_t s; + int cpus = 0; + int result = 0; + + if (lock == NULL) + { + return EINVAL; + } + + if (0 != ptw32_getprocessors (&cpus)) + { + cpus = 1; + } + + if (cpus > 1) + { + if (pshared == PTHREAD_PROCESS_SHARED) + { + /* + * Creating spinlock that can be shared between + * processes. + */ +#if _POSIX_THREAD_PROCESS_SHARED >= 0 + + /* + * Not implemented yet. + */ + +#error ERROR [__FILE__, line __LINE__]: Process shared spin locks are not supported yet. + +#else + + return ENOSYS; + +#endif /* _POSIX_THREAD_PROCESS_SHARED */ + + } + } + + s = (pthread_spinlock_t) calloc (1, sizeof (*s)); + + if (s == NULL) + { + return ENOMEM; + } + + if (cpus > 1) + { + s->u.cpus = cpus; + s->interlock = PTW32_SPIN_UNLOCKED; + } + else + { + pthread_mutexattr_t ma; + result = pthread_mutexattr_init (&ma); + + if (0 == result) + { + ma->pshared = pshared; + result = pthread_mutex_init (&(s->u.mutex), &ma); + if (0 == result) + { + s->interlock = PTW32_SPIN_USE_MUTEX; + } + } + (void) pthread_mutexattr_destroy (&ma); + } + + if (0 == result) + { + *lock = s; + } + else + { + (void) free (s); + *lock = NULL; + } + + return (result); +} diff --git a/w32-pthreads/pthread_spin_lock.c b/w32-pthreads/pthread_spin_lock.c new file mode 100644 index 000000000..b560e1489 --- /dev/null +++ b/w32-pthreads/pthread_spin_lock.c @@ -0,0 +1,80 @@ +/* + * pthread_spin_lock.c + * + * Description: + * This translation unit implements spin lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_spin_lock (pthread_spinlock_t * lock) +{ + register pthread_spinlock_t s; + + if (NULL == lock || NULL == *lock) + { + return (EINVAL); + } + + if (*lock == PTHREAD_SPINLOCK_INITIALIZER) + { + int result; + + if ((result = ptw32_spinlock_check_need_init (lock)) != 0) + { + return (result); + } + } + + s = *lock; + + while ((PTW32_INTERLOCKED_LONG) PTW32_SPIN_LOCKED == + PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG ((PTW32_INTERLOCKED_LONGPTR) &s->interlock, + (PTW32_INTERLOCKED_LONG) PTW32_SPIN_LOCKED, + (PTW32_INTERLOCKED_LONG) PTW32_SPIN_UNLOCKED)) + { + } + + if (s->interlock == PTW32_SPIN_LOCKED) + { + return 0; + } + else if (s->interlock == PTW32_SPIN_USE_MUTEX) + { + return pthread_mutex_lock (&(s->u.mutex)); + } + + return EINVAL; +} diff --git a/w32-pthreads/pthread_spin_trylock.c b/w32-pthreads/pthread_spin_trylock.c new file mode 100644 index 000000000..a6c65aff6 --- /dev/null +++ b/w32-pthreads/pthread_spin_trylock.c @@ -0,0 +1,77 @@ +/* + * pthread_spin_trylock.c + * + * Description: + * This translation unit implements spin lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_spin_trylock (pthread_spinlock_t * lock) +{ + register pthread_spinlock_t s; + + if (NULL == lock || NULL == *lock) + { + return (EINVAL); + } + + if (*lock == PTHREAD_SPINLOCK_INITIALIZER) + { + int result; + + if ((result = ptw32_spinlock_check_need_init (lock)) != 0) + { + return (result); + } + } + + s = *lock; + + switch ((long) + PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG ((PTW32_INTERLOCKED_LONGPTR) &s->interlock, + (PTW32_INTERLOCKED_LONG) PTW32_SPIN_LOCKED, + (PTW32_INTERLOCKED_LONG) PTW32_SPIN_UNLOCKED)) + { + case PTW32_SPIN_UNLOCKED: + return 0; + case PTW32_SPIN_LOCKED: + return EBUSY; + case PTW32_SPIN_USE_MUTEX: + return pthread_mutex_trylock (&(s->u.mutex)); + } + + return EINVAL; +} diff --git a/w32-pthreads/pthread_spin_unlock.c b/w32-pthreads/pthread_spin_unlock.c new file mode 100644 index 000000000..3a6932aef --- /dev/null +++ b/w32-pthreads/pthread_spin_unlock.c @@ -0,0 +1,71 @@ +/* + * pthread_spin_unlock.c + * + * Description: + * This translation unit implements spin lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +pthread_spin_unlock (pthread_spinlock_t * lock) +{ + register pthread_spinlock_t s; + + if (NULL == lock || NULL == *lock) + { + return (EINVAL); + } + + s = *lock; + + if (s == PTHREAD_SPINLOCK_INITIALIZER) + { + return EPERM; + } + + switch ((long) + PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG ((PTW32_INTERLOCKED_LONGPTR) &s->interlock, + (PTW32_INTERLOCKED_LONG) PTW32_SPIN_UNLOCKED, + (PTW32_INTERLOCKED_LONG) PTW32_SPIN_LOCKED)) + { + case PTW32_SPIN_LOCKED: + case PTW32_SPIN_UNLOCKED: + return 0; + case PTW32_SPIN_USE_MUTEX: + return pthread_mutex_unlock (&(s->u.mutex)); + } + + return EINVAL; +} diff --git a/w32-pthreads/pthread_testcancel.c b/w32-pthreads/pthread_testcancel.c new file mode 100644 index 000000000..665865000 --- /dev/null +++ b/w32-pthreads/pthread_testcancel.c @@ -0,0 +1,103 @@ +/* + * pthread_testcancel.c + * + * Description: + * POSIX thread functions related to thread cancellation. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +void +pthread_testcancel (void) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function creates a deferred cancellation point + * in the calling thread. The call has no effect if the + * current cancelability state is + * PTHREAD_CANCEL_DISABLE + * + * PARAMETERS + * N/A + * + * + * DESCRIPTION + * This function creates a deferred cancellation point + * in the calling thread. The call has no effect if the + * current cancelability state is + * PTHREAD_CANCEL_DISABLE + * + * NOTES: + * 1) Cancellation is asynchronous. Use pthread_join + * to wait for termination of thread if necessary + * + * RESULTS + * N/A + * + * ------------------------------------------------------ + */ +{ + ptw32_mcs_local_node_t stateLock; + pthread_t self = pthread_self (); + ptw32_thread_t * sp = (ptw32_thread_t *) self.p; + + if (sp == NULL) + { + return; + } + + /* + * Pthread_cancel() will have set sp->state to PThreadStateCancelPending + * and set an event, so no need to enter kernel space if + * sp->state != PThreadStateCancelPending - that only slows us down. + */ + if (sp->state != PThreadStateCancelPending) + { + return; + } + + ptw32_mcs_lock_acquire (&sp->stateLock, &stateLock); + + if (sp->cancelState != PTHREAD_CANCEL_DISABLE) + { + ResetEvent(sp->cancelEvent); + sp->state = PThreadStateCanceling; + sp->cancelState = PTHREAD_CANCEL_DISABLE; + ptw32_mcs_lock_release (&stateLock); + ptw32_throw (PTW32_EPS_CANCEL); + /* Never returns here */ + } + + ptw32_mcs_lock_release (&stateLock); +} /* pthread_testcancel */ diff --git a/w32-pthreads/pthread_timechange_handler_np.c b/w32-pthreads/pthread_timechange_handler_np.c new file mode 100644 index 000000000..0f97e74f1 --- /dev/null +++ b/w32-pthreads/pthread_timechange_handler_np.c @@ -0,0 +1,108 @@ +/* + * pthread_timechange_handler_np.c + * + * Description: + * This translation unit implements miscellaneous thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* + * Notes on handling system time adjustments (especially negative ones). + * --------------------------------------------------------------------- + * + * This solution was suggested by Alexander Terekhov, but any errors + * in the implementation are mine - [Ross Johnson] + * + * 1) The problem: threads doing a timedwait on a CV may expect to timeout + * at a specific absolute time according to a system timer. If the + * system clock is adjusted backwards then those threads sleep longer than + * expected. Also, pthreads-win32 converts absolute times to intervals in + * order to make use of the underlying Win32, and so waiting threads may + * awake before their proper abstimes. + * + * 2) We aren't able to distinquish between threads on timed or untimed waits, + * so we wake them all at the time of the adjustment so that they can + * re-evaluate their conditions and re-compute their timeouts. + * + * 3) We rely on correctly written applications for this to work. Specifically, + * they must be able to deal properly with spurious wakeups. That is, + * they must re-test their condition upon wakeup and wait again if + * the condition is not satisfied. + */ + +void * +pthread_timechange_handler_np (void *arg) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * Broadcasts all CVs to force re-evaluation and + * new timeouts if required. + * + * PARAMETERS + * NONE + * + * + * DESCRIPTION + * Broadcasts all CVs to force re-evaluation and + * new timeouts if required. + * + * This routine may be passed directly to pthread_create() + * as a new thread in order to run asynchronously. + * + * + * RESULTS + * 0 successfully broadcast all CVs + * EAGAIN Not all CVs were broadcast + * + * ------------------------------------------------------ + */ +{ + int result = 0; + pthread_cond_t cv; + ptw32_mcs_local_node_t node; + + ptw32_mcs_lock_acquire(&ptw32_cond_list_lock, &node); + + cv = ptw32_cond_list_head; + + while (cv != NULL && 0 == result) + { + result = pthread_cond_broadcast (&cv); + cv = cv->next; + } + + ptw32_mcs_lock_release(&node); + + return (void *) (size_t) (result != 0 ? EAGAIN : 0); +} diff --git a/w32-pthreads/pthread_win32_attach_detach_np.c b/w32-pthreads/pthread_win32_attach_detach_np.c new file mode 100644 index 000000000..bfad45065 --- /dev/null +++ b/w32-pthreads/pthread_win32_attach_detach_np.c @@ -0,0 +1,256 @@ +/* + * pthread_win32_attach_detach_np.c + * + * Description: + * This translation unit implements non-portable thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +/* + * Handle to quserex.dll + */ +static HINSTANCE ptw32_h_quserex; + +BOOL +pthread_win32_process_attach_np () +{ + TCHAR QuserExDLLPathBuf[1024]; + BOOL result = TRUE; + + result = ptw32_processInitialize (); + +#if defined(_UWIN) + pthread_count++; +#endif + +#if defined(__GNUC__) + ptw32_features = 0; +#else + /* + * This is obsolete now. + */ + ptw32_features = PTW32_SYSTEM_INTERLOCKED_COMPARE_EXCHANGE; +#endif + + /* + * Load QUSEREX.DLL and try to get address of QueueUserAPCEx. + * Because QUSEREX.DLL requires a driver to be installed we will + * assume the DLL is in the system directory. + * + * This should take care of any security issues. + */ +#if defined(__GNUC__) || _MSC_VER < 1400 + if(GetSystemDirectory(QuserExDLLPathBuf, sizeof(QuserExDLLPathBuf))) + { + (void) strncat(QuserExDLLPathBuf, + "\\QUSEREX.DLL", + sizeof(QuserExDLLPathBuf) - strlen(QuserExDLLPathBuf) - 1); + ptw32_h_quserex = LoadLibrary(QuserExDLLPathBuf); + } +#else + /* strncat is secure - this is just to avoid a warning */ + if(GetSystemDirectory(QuserExDLLPathBuf, sizeof(QuserExDLLPathBuf)) && + 0 == strncat_s(QuserExDLLPathBuf, sizeof(QuserExDLLPathBuf), "\\QUSEREX.DLL", 12)) + { + ptw32_h_quserex = LoadLibrary(QuserExDLLPathBuf); + } +#endif + + if (ptw32_h_quserex != NULL) + { + ptw32_register_cancelation = (DWORD (*)(PAPCFUNC, HANDLE, DWORD)) +#if defined(NEED_UNICODE_CONSTS) + GetProcAddress (ptw32_h_quserex, + (const TCHAR *) TEXT ("QueueUserAPCEx")); +#else + GetProcAddress (ptw32_h_quserex, (LPCSTR) "QueueUserAPCEx"); +#endif + } + + if (NULL == ptw32_register_cancelation) + { + ptw32_register_cancelation = ptw32_RegisterCancelation; + + if (ptw32_h_quserex != NULL) + { + (void) FreeLibrary (ptw32_h_quserex); + } + ptw32_h_quserex = 0; + } + else + { + /* Initialise QueueUserAPCEx */ + BOOL (*queue_user_apc_ex_init) (VOID); + + queue_user_apc_ex_init = (BOOL (*)(VOID)) +#if defined(NEED_UNICODE_CONSTS) + GetProcAddress (ptw32_h_quserex, + (const TCHAR *) TEXT ("QueueUserAPCEx_Init")); +#else + GetProcAddress (ptw32_h_quserex, (LPCSTR) "QueueUserAPCEx_Init"); +#endif + + if (queue_user_apc_ex_init == NULL || !queue_user_apc_ex_init ()) + { + ptw32_register_cancelation = ptw32_RegisterCancelation; + + (void) FreeLibrary (ptw32_h_quserex); + ptw32_h_quserex = 0; + } + } + + if (ptw32_h_quserex) + { + ptw32_features |= PTW32_ALERTABLE_ASYNC_CANCEL; + } + + return result; +} + + +BOOL +pthread_win32_process_detach_np () +{ + if (ptw32_processInitialized) + { + ptw32_thread_t * sp = (ptw32_thread_t *) pthread_getspecific (ptw32_selfThreadKey); + + if (sp != NULL) + { + /* + * Detached threads have their resources automatically + * cleaned up upon exit (others must be 'joined'). + */ + if (sp->detachState == PTHREAD_CREATE_DETACHED) + { + ptw32_threadDestroy (sp->ptHandle); + TlsSetValue (ptw32_selfThreadKey->key, NULL); + } + } + + /* + * The DLL is being unmapped from the process's address space + */ + ptw32_processTerminate (); + + if (ptw32_h_quserex) + { + /* Close QueueUserAPCEx */ + BOOL (*queue_user_apc_ex_fini) (VOID); + + queue_user_apc_ex_fini = (BOOL (*)(VOID)) +#if defined(NEED_UNICODE_CONSTS) + GetProcAddress (ptw32_h_quserex, + (const TCHAR *) TEXT ("QueueUserAPCEx_Fini")); +#else + GetProcAddress (ptw32_h_quserex, (LPCSTR) "QueueUserAPCEx_Fini"); +#endif + + if (queue_user_apc_ex_fini != NULL) + { + (void) queue_user_apc_ex_fini (); + } + (void) FreeLibrary (ptw32_h_quserex); + } + } + + return TRUE; +} + +BOOL +pthread_win32_thread_attach_np () +{ + return TRUE; +} + +BOOL +pthread_win32_thread_detach_np () +{ + if (ptw32_processInitialized) + { + /* + * Don't use pthread_self() - to avoid creating an implicit POSIX thread handle + * unnecessarily. + */ + ptw32_thread_t * sp = (ptw32_thread_t *) pthread_getspecific (ptw32_selfThreadKey); + + if (sp != NULL) // otherwise Win32 thread with no implicit POSIX handle. + { + ptw32_mcs_local_node_t stateLock; + ptw32_callUserDestroyRoutines (sp->ptHandle); + + ptw32_mcs_lock_acquire (&sp->stateLock, &stateLock); + sp->state = PThreadStateLast; + /* + * If the thread is joinable at this point then it MUST be joined + * or detached explicitly by the application. + */ + ptw32_mcs_lock_release (&stateLock); + + /* + * Robust Mutexes + */ + while (sp->robustMxList != NULL) + { + pthread_mutex_t mx = sp->robustMxList->mx; + ptw32_robust_mutex_remove(&mx, sp); + (void) PTW32_INTERLOCKED_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR)&mx->robustNode->stateInconsistent, + (PTW32_INTERLOCKED_LONG)-1); + /* + * If there are no waiters then the next thread to block will + * sleep, wakeup immediately and then go back to sleep. + * See pthread_mutex_lock.c. + */ + SetEvent(mx->event); + } + + + if (sp->detachState == PTHREAD_CREATE_DETACHED) + { + ptw32_threadDestroy (sp->ptHandle); + + TlsSetValue (ptw32_selfThreadKey->key, NULL); + } + } + } + + return TRUE; +} + +BOOL +pthread_win32_test_features_np (int feature_mask) +{ + return ((ptw32_features & feature_mask) == feature_mask); +} diff --git a/w32-pthreads/ptw32_MCS_lock.c b/w32-pthreads/ptw32_MCS_lock.c new file mode 100644 index 000000000..659cda60d --- /dev/null +++ b/w32-pthreads/ptw32_MCS_lock.c @@ -0,0 +1,278 @@ +/* + * ptw32_MCS_lock.c + * + * Description: + * This translation unit implements queue-based locks. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +/* + * About MCS locks: + * + * MCS locks are queue-based locks, where the queue nodes are local to the + * thread. The 'lock' is nothing more than a global pointer that points to + * the last node in the queue, or is NULL if the queue is empty. + * + * Originally designed for use as spin locks requiring no kernel resources + * for synchronisation or blocking, the implementation below has adapted + * the MCS spin lock for use as a general mutex that will suspend threads + * when there is lock contention. + * + * Because the queue nodes are thread-local, most of the memory read/write + * operations required to add or remove nodes from the queue do not trigger + * cache-coherence updates. + * + * Like 'named' mutexes, MCS locks consume system resources transiently - + * they are able to acquire and free resources automatically - but MCS + * locks do not require any unique 'name' to identify the lock to all + * threads using it. + * + * Usage of MCS locks: + * + * - you need a global ptw32_mcs_lock_t instance initialised to 0 or NULL. + * - you need a local thread-scope ptw32_mcs_local_node_t instance, which + * may serve several different locks but you need at least one node for + * every lock held concurrently by a thread. + * + * E.g.: + * + * ptw32_mcs_lock_t lock1 = 0; + * ptw32_mcs_lock_t lock2 = 0; + * + * void *mythread(void *arg) + * { + * ptw32_mcs_local_node_t node; + * + * ptw32_mcs_acquire (&lock1, &node); + * ptw32_mcs_lock_release (&node); + * + * ptw32_mcs_lock_acquire (&lock2, &node); + * ptw32_mcs_lock_release (&node); + * { + * ptw32_mcs_local_node_t nodex; + * + * ptw32_mcs_lock_acquire (&lock1, &node); + * ptw32_mcs_lock_acquire (&lock2, &nodex); + * + * ptw32_mcs_lock_release (&nodex); + * ptw32_mcs_lock_release (&node); + * } + * return (void *)0; + * } + */ + +#include "pthread.h" +#include "sched.h" +#include "implement.h" + +/* + * ptw32_mcs_flag_set -- notify another thread about an event. + * + * Set event if an event handle has been stored in the flag, and + * set flag to -1 otherwise. Note that -1 cannot be a valid handle value. + */ +INLINE void +ptw32_mcs_flag_set (HANDLE * flag) +{ + HANDLE e = (HANDLE)(PTW32_INTERLOCKED_SIZE)PTW32_INTERLOCKED_COMPARE_EXCHANGE_SIZE( + (PTW32_INTERLOCKED_SIZEPTR)flag, + (PTW32_INTERLOCKED_SIZE)-1, + (PTW32_INTERLOCKED_SIZE)0); + if ((HANDLE)0 != e) + { + /* another thread has already stored an event handle in the flag */ + SetEvent(e); + } +} + +/* + * ptw32_mcs_flag_set -- wait for notification from another. + * + * Store an event handle in the flag and wait on it if the flag has not been + * set, and proceed without creating an event otherwise. + */ +INLINE void +ptw32_mcs_flag_wait (HANDLE * flag) +{ + if ((PTW32_INTERLOCKED_LONG)0 == + PTW32_INTERLOCKED_EXCHANGE_ADD_SIZE((PTW32_INTERLOCKED_SIZEPTR)flag, + (PTW32_INTERLOCKED_SIZE)0)) /* MBR fence */ + { + /* the flag is not set. create event. */ + + HANDLE e = CreateEvent(NULL, PTW32_FALSE, PTW32_FALSE, NULL); + + if ((PTW32_INTERLOCKED_SIZE)0 == PTW32_INTERLOCKED_COMPARE_EXCHANGE_SIZE( + (PTW32_INTERLOCKED_SIZEPTR)flag, + (PTW32_INTERLOCKED_SIZE)e, + (PTW32_INTERLOCKED_SIZE)0)) + { + /* stored handle in the flag. wait on it now. */ + WaitForSingleObject(e, INFINITE); + } + + CloseHandle(e); + } +} + +/* + * ptw32_mcs_lock_acquire -- acquire an MCS lock. + * + * See: + * J. M. Mellor-Crummey and M. L. Scott. + * Algorithms for Scalable Synchronization on Shared-Memory Multiprocessors. + * ACM Transactions on Computer Systems, 9(1):21-65, Feb. 1991. + */ +#if defined(PTW32_BUILD_INLINED) +INLINE +#endif /* PTW32_BUILD_INLINED */ +void +ptw32_mcs_lock_acquire (ptw32_mcs_lock_t * lock, ptw32_mcs_local_node_t * node) +{ + ptw32_mcs_local_node_t *pred; + + node->lock = lock; + node->nextFlag = 0; + node->readyFlag = 0; + node->next = 0; /* initially, no successor */ + + /* queue for the lock */ + pred = (ptw32_mcs_local_node_t *)PTW32_INTERLOCKED_EXCHANGE_PTR((PTW32_INTERLOCKED_PVOID_PTR)lock, + (PTW32_INTERLOCKED_PVOID)node); + + if (0 != pred) + { + /* the lock was not free. link behind predecessor. */ + pred->next = node; + ptw32_mcs_flag_set(&pred->nextFlag); + ptw32_mcs_flag_wait(&node->readyFlag); + } +} + +/* + * ptw32_mcs_lock_release -- release an MCS lock. + * + * See: + * J. M. Mellor-Crummey and M. L. Scott. + * Algorithms for Scalable Synchronization on Shared-Memory Multiprocessors. + * ACM Transactions on Computer Systems, 9(1):21-65, Feb. 1991. + */ +#if defined(PTW32_BUILD_INLINED) +INLINE +#endif /* PTW32_BUILD_INLINED */ +void +ptw32_mcs_lock_release (ptw32_mcs_local_node_t * node) +{ + ptw32_mcs_lock_t *lock = node->lock; + ptw32_mcs_local_node_t *next = + (ptw32_mcs_local_node_t *) + PTW32_INTERLOCKED_EXCHANGE_ADD_SIZE((PTW32_INTERLOCKED_SIZEPTR)&node->next, (PTW32_INTERLOCKED_SIZE)0); /* MBR fence */ + + if (0 == next) + { + /* no known successor */ + + if (node == (ptw32_mcs_local_node_t *) + PTW32_INTERLOCKED_COMPARE_EXCHANGE_PTR((PTW32_INTERLOCKED_PVOID_PTR)lock, + (PTW32_INTERLOCKED_PVOID)0, + (PTW32_INTERLOCKED_PVOID)node)) + { + /* no successor, lock is free now */ + return; + } + + /* A successor has started enqueueing behind us so wait for them to link to us */ + ptw32_mcs_flag_wait(&node->nextFlag); + next = (ptw32_mcs_local_node_t *) + PTW32_INTERLOCKED_EXCHANGE_ADD_SIZE((PTW32_INTERLOCKED_SIZEPTR)&node->next, (PTW32_INTERLOCKED_SIZE)0); /* MBR fence */ + } + + /* pass the lock */ + ptw32_mcs_flag_set(&next->readyFlag); +} + +/* + * ptw32_mcs_lock_try_acquire + */ +#if defined(PTW32_BUILD_INLINED) +INLINE +#endif /* PTW32_BUILD_INLINED */ +int +ptw32_mcs_lock_try_acquire (ptw32_mcs_lock_t * lock, ptw32_mcs_local_node_t * node) +{ + node->lock = lock; + node->nextFlag = 0; + node->readyFlag = 0; + node->next = 0; /* initially, no successor */ + + return ((PTW32_INTERLOCKED_PVOID)PTW32_INTERLOCKED_COMPARE_EXCHANGE_PTR((PTW32_INTERLOCKED_PVOID_PTR)lock, + (PTW32_INTERLOCKED_PVOID)node, + (PTW32_INTERLOCKED_PVOID)0) + == (PTW32_INTERLOCKED_PVOID)0) ? 0 : EBUSY; +} + +/* + * ptw32_mcs_node_transfer -- move an MCS lock local node, usually from thread + * space to, for example, global space so that another thread can release + * the lock on behalf of the current lock owner. + * + * Example: used in pthread_barrier_wait where we want the last thread out of + * the barrier to release the lock owned by the last thread to enter the barrier + * (the one that releases all threads but not necessarily the last to leave). + * + * Should only be called by the thread that has the lock. + */ +#if defined(PTW32_BUILD_INLINED) +INLINE +#endif /* PTW32_BUILD_INLINED */ +void +ptw32_mcs_node_transfer (ptw32_mcs_local_node_t * new_node, ptw32_mcs_local_node_t * old_node) +{ + new_node->lock = old_node->lock; + new_node->nextFlag = 0; /* Not needed - used only in initial Acquire */ + new_node->readyFlag = 0; /* Not needed - we were waiting on this */ + new_node->next = 0; + + if ((ptw32_mcs_local_node_t *)PTW32_INTERLOCKED_COMPARE_EXCHANGE_PTR((PTW32_INTERLOCKED_PVOID_PTR)new_node->lock, + (PTW32_INTERLOCKED_PVOID)new_node, + (PTW32_INTERLOCKED_PVOID)old_node) + != old_node) + { + /* + * A successor has queued after us, so wait for them to link to us + */ + while (old_node->next == 0) + { + sched_yield(); + } + new_node->next = old_node->next; + } +} diff --git a/w32-pthreads/ptw32_OLL_lock.c b/w32-pthreads/ptw32_OLL_lock.c new file mode 100644 index 000000000..789d0ad8c --- /dev/null +++ b/w32-pthreads/ptw32_OLL_lock.c @@ -0,0 +1,734 @@ +/* + * ptw32_OLL_lock.c + * + * Description: + * This translation unit implements extended reader/writer queue-based locks. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +/* + * About the OLL lock (Scalable Reader-Writer Lock): + * + * OLL locks are queue-based locks similar to the MCS queue lock, where the queue + * nodes are local to the thread but where reader threads can enter the critical + * section immediately without going through a central guard lock if there are + * already readers holding the lock. + * + * Covered by United States Patent Application 20100241774 (Oracle) + */ + +#include "pthread.h" +#include "sched.h" +#include "implement.h" + +/* + * C-SNZI support + */ +typedef union ptw32_oll_counter_t_ ptw32_oll_counter_t; +typedef struct ptw32_oll_snziRoot_t_ ptw32_oll_snziRoot_t; +typedef struct ptw32_oll_snziNode_t_ ptw32_oll_snziNode_t; +typedef union ptw32_oll_snziNodeOrRoot_t_ ptw32_oll_snziNodeOrRoot_t; +typedef struct ptw32_oll_queryResult_t_ ptw32_oll_queryResult_t; +typedef struct ptw32_oll_ticket_t_ ptw32_oll_ticket_t; +typedef struct ptw32_oll_csnzi_t_ ptw32_oll_csnzi_t; + +enum +{ + ptw32_archWidth = sizeof(size_t)*8, + ptw32_oll_countWidth = ptw32_archWidth-2 +}; + +#define PTW32_OLL_MAXREADERS (((size_t)2<<(ptw32_oll_countWidth-1))-1) + +union ptw32_oll_counter_t_ +{ + size_t word : ptw32_archWidth; + struct + { + /* + * This needs to be a single word + * + * ------------------------------------ + * | STATE | ROOT | COUNT (readers) | + * ------------------------------------ + * 63 / 31 62 / 30 61 / 29 .. 0 + */ + size_t count : ptw32_oll_countWidth; + size_t root : 1; /* ROOT or NODE */ + size_t state : 1; /* OPEN or CLOSED (root only) */ + } internal; +}; + +struct ptw32_oll_snziRoot_t_ +{ + /* + * "counter" must be at same offset in both + * ptw32_oll_snziNode_t and ptw32_oll_snziRoot_t + */ + ptw32_oll_counter_t counter; +}; + +enum +{ + ptw32_oll_snziRoot_open = 0, + ptw32_oll_snziRoot_closed = 1 +}; + +enum +{ + ptw32_oll_snzi_root = 0, + ptw32_oll_snzi_node = 1 +}; + +/* + * Some common SNZI root whole-word states that can be used to set or compare + * root words with a single operation. + */ +ptw32_oll_snziRoot_t ptw32_oll_snziRoot_openAndZero = {.counter.internal.count = 0, + .counter.internal.root = ptw32_oll_snzi_root, + .counter.internal.state = ptw32_oll_snziRoot_open}; +ptw32_oll_snziRoot_t ptw32_oll_snziRoot_closedAndZero = {.counter.internal.count = 0, + .counter.internal.root = ptw32_oll_snzi_root, + .counter.internal.state = ptw32_oll_snziRoot_closed}; + +struct ptw32_oll_queryResult_t_ +{ + BOOL nonZero; + BOOL open; +}; + +union ptw32_oll_snziNodeOrRoot_t_ +{ + ptw32_oll_snziRoot_t* rootPtr; + ptw32_oll_snziNode_t* nodePtr; +}; + +struct ptw32_oll_snziNode_t_ +{ + /* "counter" must be at same offset in both + * ptw32_oll_snziNode_t and ptw32_oll_snziRoot_t + */ + ptw32_oll_counter_t counter; + ptw32_oll_snziNodeOrRoot_t parentPtr; +}; + +struct ptw32_oll_ticket_t_ +{ + ptw32_oll_snziNodeOrRoot_t snziNodeOrRoot; +}; + +ptw32_oll_ticket_t ptw32_oll_ticket_null = {NULL}; + +struct ptw32_oll_csnzi_t_ +{ + ptw32_oll_snziRoot_t proxyRoot; + ptw32_oll_snziNode_t leafs[]; +}; + +/* + * FOLL lock support + */ + +typedef struct ptw32_foll_node_t_ ptw32_foll_node_t; +typedef struct ptw32_foll_local_t_ ptw32_foll_local_t; +typedef struct ptw32_foll_rwlock_t_ ptw32_foll_rwlock_t; + +enum +{ + ptw32_srwl_reader, + ptw32_srwl_writer +}; + +enum +{ + ptw32_srwl_free, + ptw32_srwl_in_use +}; + +struct ptw32_foll_node_t_ +{ + ptw32_foll_node_t* qNextPtr; + ptw32_oll_csnzi_t* csnziPtr; + ptw32_foll_node_t* nextPtr; + int kind; + int allocState; + BOOL spin; +}; + +struct ptw32_foll_local_t_ +{ + ptw32_foll_node_t* rNodePtr; // Default read node. Immutable + ptw32_foll_node_t* wNodePtr; // Write node. Immutable. + ptw32_foll_node_t* departFromPtr; // List node we last arrived at. + ptw32_oll_ticket_t ticket; // C-SNZI ticket +}; + +struct ptw32_foll_rwlock_t_ +{ + ptw32_foll_node_t* tailPtr; + ptw32_foll_node_t* rNodesPtr; // Head of reader node +}; + +/* + * ShouldArriveAtTree() returns true if: + * the compare_exchange in Arrive() fails too often under read access; or + * ?? + * Note that this is measured across all access to + * this lock, not just this attempt, so that highly + * read-contended locks will use C-SNZI. Lightly + * read-contended locks can reduce memory usage and some + * processing by using the root directly. + */ +BOOL +ptw32_oll_ShouldArriveAtTree() +{ + return PTW32_FALSE; +} + +size_t +ptw32_oll_GetLeafForThread() +{ + return 0; +} + +/* + * Only readers call ptw32_oll_Arrive() + * + * Checks whether the C-SNZI state is OPEN, and if so, + * increments the surplus of the C-SNZI by either directly + * arriving at the root node, or calling TreeArrive on one + * of the leaf nodes. Returns a ticket pointing to the node + * that was arrived at. If the state is CLOSED, makes no + * change and returns a ticket that contains no pointer. + */ +ptw32_oll_ticket_t +ptw32_oll_Arrive(ptw32_oll_csnzi_t* csnzi) +{ + for (;;) + { + ptw32_oll_ticket_t ticket; + ptw32_oll_snziRoot_t oldProxy = csnzi->proxyRoot; + if (oldProxy.counter.internal.state != ptw32_oll_snziRoot_open) + { + ticket.snziNodeOrRoot.rootPtr = (ptw32_oll_snziRoot_t*)NULL; + return ticket; + } + if (!ptw32_oll_ShouldArriveAtTree()) + { + ptw32_oll_snziRoot_t newProxy = oldProxy; + newProxy.counter.internal.count++; + if (PTW32_INTERLOCKED_COMPARE_EXCHANGE_SIZE( + (PTW32_INTERLOCKED_SIZEPTR)&csnzi->proxyRoot.counter, + (PTW32_INTERLOCKED_SIZE)newProxy.counter.word, + (PTW32_INTERLOCKED_SIZE)oldProxy.counter.word) + == (PTW32_INTERLOCKED_SIZE)oldProxy.counter.word) + { + /* Exchange successful */ + ticket.snziNodeOrRoot.rootPtr = &csnzi->proxyRoot; + return ticket; + } + } + else + { + ptw32_oll_snziNode_t* leafPtr = &csnzi->leafs[ptw32_oll_GetLeafForThread()]; + ticket.snziNodeOrRoot.nodePtr = (ptw32_oll_TreeArrive(leafPtr) ? leafPtr : (ptw32_oll_snziNode_t*)NULL); + return ticket; + } + } +} + +/* + * Decrements the C-SNZI surplus. Returns false iff the + * resulting state is CLOSED and the surplus is zero. + * Ticket must have been returned by an arrival. Must have + * received this ticket from Arrive more times than Depart + * has been called with the ticket. (Thus, the surplus + * must be greater than zero.) + */ +BOOL +ptw32_oll_Depart(ptw32_oll_ticket_t ticket) +{ + return ptw32_oll_TreeDepart(ticket.snziNodeOrRoot); +} + +/* + * Increments the C-SNZI surplus and returns true if the + * C-SNZI is open or has a surplus. Calls TreeArrive + * recursively on the nodeā€™s parent if needed. + * Otherwise, returns false without making any changes. + */ +BOOL +ptw32_oll_TreeArrive(ptw32_oll_snziNodeOrRoot_t snziNodeOrRoot) +{ + if (snziNodeOrRoot.nodePtr->counter.internal.root != ptw32_oll_snzi_root) + { + /* Non-root node */ + ptw32_oll_counter_t newCounter, oldCounter; + BOOL arrivedAtParent = PTW32_FALSE; + do + { + oldCounter = snziNodeOrRoot.nodePtr->counter; + if (0 == oldCounter.internal.count && !arrivedAtParent) + { + if (ptw32_oll_TreeArrive(snziNodeOrRoot.nodePtr->parentPtr)) + arrivedAtParent = PTW32_TRUE; + else + return PTW32_FALSE; + } + newCounter = oldCounter; + newCounter.internal.count++; + } while (PTW32_INTERLOCKED_COMPARE_EXCHANGE_SIZE( + (PTW32_INTERLOCKED_SIZEPTR)&snziNodeOrRoot.nodePtr->counter, + (PTW32_INTERLOCKED_SIZE)newCounter.word, + (PTW32_INTERLOCKED_SIZE)oldCounter.word) + != (PTW32_INTERLOCKED_SIZE)oldCounter.word); + if (newCounter.internal.count != 0 && arrivedAtParent) + ptw32_oll_TreeDepart(snziNodeOrRoot.nodePtr->parentPtr); + return PTW32_TRUE; + } + else + { + /* Root node */ + ptw32_oll_snziRoot_t newRoot, oldRoot; + do + { + oldRoot = *(ptw32_oll_snziRoot_t*)snziNodeOrRoot.rootPtr; + if (oldRoot.counter.word == ptw32_oll_snziRoot_closedAndZero.counter.word) + return PTW32_FALSE; + newRoot = oldRoot; + newRoot.counter.internal.count++; + } while (PTW32_INTERLOCKED_COMPARE_EXCHANGE_SIZE( + (PTW32_INTERLOCKED_SIZEPTR)&snziNodeOrRoot.rootPtr->counter, + (PTW32_INTERLOCKED_SIZE)newRoot.counter.word, + (PTW32_INTERLOCKED_SIZE)oldRoot.counter.word) + != (PTW32_INTERLOCKED_SIZE)oldRoot.counter.word); + return PTW32_TRUE; + } +} + +/* + * Decrements the C-SNZI surplus, calling TreeDepart + * recursively on the nodeā€™s parent if needed. Returns + * false iff the resulting state of the C-SNZI is CLOSED + * and the surplus is zero. Otherwise, returns true. + */ +BOOL +ptw32_oll_TreeDepart(ptw32_oll_snziNodeOrRoot_t snziNodeOrRoot) +{ + if (snziNodeOrRoot.nodePtr->counter.internal.root != ptw32_oll_snzi_root) + { + /* Non-root node */ + ptw32_oll_counter_t newCounter, oldCounter; + do + { + newCounter = oldCounter = snziNodeOrRoot.nodePtr->counter; + newCounter.internal.count--; + } while (PTW32_INTERLOCKED_COMPARE_EXCHANGE_SIZE( + (PTW32_INTERLOCKED_SIZEPTR)&snziNodeOrRoot.nodePtr->counter, + (PTW32_INTERLOCKED_SIZE)newCounter.word, + (PTW32_INTERLOCKED_SIZE)oldCounter.word) + != (PTW32_INTERLOCKED_SIZE)oldCounter.word); + return (0 == newCounter.internal.count) + ? ptw32_oll_TreeDepart(snziNodeOrRoot.nodePtr->parentPtr) + : PTW32_TRUE; + } + else + { + /* Root node */ + ptw32_oll_snziRoot_t newRoot, oldRoot; + do + { + newRoot = oldRoot = *(ptw32_oll_snziRoot_t*)snziNodeOrRoot.rootPtr; + newRoot.counter.internal.count--; + } while (PTW32_INTERLOCKED_COMPARE_EXCHANGE_SIZE( + (PTW32_INTERLOCKED_SIZEPTR)&snziNodeOrRoot.rootPtr->counter, + (PTW32_INTERLOCKED_SIZE)newRoot.counter.word, + (PTW32_INTERLOCKED_SIZE)oldRoot.counter.word) + != (PTW32_INTERLOCKED_SIZE)oldRoot.counter.word); + return (newRoot.counter.word != ptw32_oll_snziRoot_closedAndZero.counter.word); + } +} + +/* + * Opens a C-SNZI object. Requires C-SNZI state to be + * CLOSED and the surplus to be zero. + */ +void +ptw32_oll_Open(ptw32_oll_csnzi_t* csnziPtr) +{ + csnziPtr->proxyRoot = ptw32_oll_snziRoot_openAndZero; +} + +/* + * Opens a C-SNZI object while atomically performing count + * arrivals. Requires C-SNZI state to be CLOSED and + * the surplus to be zero. + */ +void +ptw32_oll_OpenWithArrivals(ptw32_oll_csnzi_t* csnziPtr, size_t count, BOOL close) +{ + csnziPtr->proxyRoot.counter.internal.count = count; + csnziPtr->proxyRoot.counter.internal.state = (close ? ptw32_oll_snziRoot_closed : ptw32_oll_snziRoot_open); +} + +/* + * Closes a C-SNZI object. Returns true iff the C-SNZI + * state changed from OPEN to CLOSED and the surplus is + * zero. + */ +BOOL +ptw32_oll_Close(ptw32_oll_csnzi_t* csnziPtr) +{ + ptw32_oll_snziRoot_t newProxy, oldProxy; + do + { + oldProxy = csnziPtr->proxyRoot; + if (oldProxy.counter.internal.state != ptw32_oll_snziRoot_open) + { + return PTW32_FALSE; + } + newProxy = oldProxy; + newProxy.counter.internal.state = ptw32_oll_snziRoot_closed; + } while (PTW32_INTERLOCKED_COMPARE_EXCHANGE_SIZE( + (PTW32_INTERLOCKED_SIZEPTR)&csnziPtr->proxyRoot.counter, + (PTW32_INTERLOCKED_SIZE)newProxy.counter.word, + (PTW32_INTERLOCKED_SIZE)oldProxy.counter.word) + != (PTW32_INTERLOCKED_SIZE)oldProxy.counter.word); + return (newProxy.counter.word == ptw32_oll_snziRoot_closedAndZero.counter.word); +} + +/* + * Closes a C-SNZI if its surplus is zero. Otherwise, does + * nothing. Returns true iff C-SNZI state changed from + * OPEN to CLOSED. + */ +BOOL +ptw32_oll_CloseIfEmpty(ptw32_oll_csnzi_t* csnziPtr) +{ + ptw32_oll_snziRoot_t newProxy, oldProxy; + do + { + oldProxy = csnziPtr->proxyRoot; + if (oldProxy.counter.word != ptw32_oll_snziRoot_openAndZero.counter.word) + { + return PTW32_FALSE; + } + newProxy = ptw32_oll_snziRoot_closedAndZero; + } while (PTW32_INTERLOCKED_COMPARE_EXCHANGE_SIZE( + (PTW32_INTERLOCKED_SIZEPTR)&csnziPtr->proxyRoot.counter, + (PTW32_INTERLOCKED_SIZE)newProxy.counter.word, + (PTW32_INTERLOCKED_SIZE)oldProxy.counter.word) + != (PTW32_INTERLOCKED_SIZE)oldProxy.counter.word); + return PTW32_TRUE; +} + +/* + * Returns whether the C-SNZI has a nonzero surplus and + * whether the C-SNZI is open. + * "nonZero" doesn't appear to be used anywhere in the algorithms. + */ +ptw32_oll_queryResult_t +ptw32_oll_Query(ptw32_oll_csnzi_t* csnziPtr) +{ + ptw32_oll_queryResult_t query; + ptw32_oll_snziRoot_t proxy = csnziPtr->proxyRoot; + + query.nonZero = (proxy.counter.internal.count > 0); + query.open = (proxy.counter.internal.state == ptw32_oll_snziRoot_open); + return query; +} + +/* + * Returns whether the Arrive operation that returned + * the ticket succeeded. + */ +BOOL +ptw32_oll_Arrived(ptw32_oll_ticket_t t) +{ + return (t.snziNodeOrRoot.nodePtr != NULL); +} + +/* + * Constructs and returns a ticket that can be used to + * depart from the root node. + */ +ptw32_oll_ticket_t +ptw32_oll_DirectTicket(ptw32_oll_csnzi_t* csnziPtr) +{ + ptw32_oll_ticket_t ticket; + ticket.snziNodeOrRoot.rootPtr = &csnziPtr->proxyRoot; + return ticket; +} + +/* Scalable RW Locks */ + +typedef struct ptw32_srwl_rwlock_t_ ptw32_srwl_rwlock_t; +typedef struct ptw32_srwl_node_t_ ptw32_srwl_node_t; +typedef struct ptw32_srwl_local_t_ ptw32_srwl_local_t; + +enum +{ + ptw32_srwl_reader = 0, + ptw32_srwl_writer = 1 +}; + +enum +{ + ptw32_srwl_free = 0, + ptw32_srwl_in_use = 1 +}; + +struct ptw32_srwl_rwlock_t_ +{ + ptw32_srwl_node_t* tailPtr; + ptw32_srwl_node_t* readerNodePtr; +}; + +struct ptw32_srwl_node_t_ +{ + ptw32_srwl_node_t* qNextPtr; + ptw32_oll_csnzi_t* csnziPtr; + ptw32_srwl_node_t* nextReaderPtr; + int kind; /* ptw32_srwl_reader, ptw32_srwl_writer */ + int allocState; /* ptw32_srwl_free, ptw32_srwl_in_use */ + BOOL spin; +}; + +/* + * When a ptw32_srwl_local_t is instantiated the "kind" of each of + * rNode and wNode must be set as appropriate. This is the only + * time "kind" is set. + */ +struct ptw32_srwl_local_t_ +{ + ptw32_srwl_node_t* rNodePtr; + ptw32_srwl_node_t* wNodePtr; + ptw32_srwl_node_t* departFromPtr; + ptw32_oll_ticket_t ticket; +}; + +/* Allocates a new reader node. */ +ptw32_srwl_node_t* +ptw32_srwl_AllocReaderNode(ptw32_srwl_local_t* local) +{ + ptw32_srwl_node_t* currNodePtr = local->rNodePtr; + for (;;) + { + if (currNodePtr->allocState == ptw32_srwl_free) + { + if (PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG( + (PTW32_INTERLOCKED_LONGPTR)&currNodePtr->allocState, + (PTW32_INTERLOCKED_LONG)ptw32_srwl_in_use, + (PTW32_INTERLOCKED_LONG)ptw32_srwl_free) + == (PTW32_INTERLOCKED_LONG)ptw32_srwl_in_use) + { + return currNodePtr; + } + } + currNodePtr = currNodePtr->next; + } +} + +/* + * Frees a reader node. Requires that its allocState + * is ptw32_srwl_in_use. + */ +void +ptw32_srwl_FreeReaderNode(ptw32_srwl_node_t* nodePtr) +{ + nodePtr->allocState := ptw32_srwl_free; +} + +void +ptw32_srwl_WriterLock(ptw32_srwl_rwlock_t* lockPtr, ptw32_srwl_local_t* localPtr) +{ + oldTailPtr = (ptw32_srwl_rwlock_t*)PTW32_INTERLOCKED_EXCHANGE_PTR( + (PTW32_INTERLOCKED_PVOID_PTR)&lockPtr->tailPtr, + (PTW32_INTERLOCKED_PVOID)localPtr->wNodePtr); + if (oldTailPtr != NULL) + { + localPtr->wNodePtr->spin := PTW32_TRUE; + oldTailPtr->qNextPtr = localPtr->wNodePtr; + if (oldTailPtr->kind == ptw32_srwl_writer) + { + while (localPtr->wNodePtr->spin); + } + else + { + /* Wait until node is properly recycled */ + while (ptw32_oll_Query(oldTailPtr->csnzi).open); + /* + * Close C-SNZI of previous reader node. + * If there are no readers to signal us, spin on + * previous node and free it before entering + * critical section. + */ + if (ptw32_oll_Close(oldTailPtr->csnzi)) + { + while (oldTailPtr->spin); + ptw32_srwl_FreeReaderNode(oldTailPtr); + } + else + { + while (localPtr->wNodePtr->spin); + } + } + } +} + +void +ptw32_srwl_WriterUnlock(ptw32_srwl_rwlock_t* lockPtr, ptw32_srwl_local_t* localPtr) +{ + if (localPtr->wNodePtr->qNextPtr == NULL) + { + if (PTW32_INTERLOCKED_COMPARE_EXCHANGE_PTR( + (PTW32_INTERLOCKED_PVOIDPTR)&lockPtr->tailPtr, + (PTW32_INTERLOCKED_PVOID)NULL, + (PTW32_INTERLOCKED_PVOID)localPtr->wNodePtr) + == (PTW32_INTERLOCKED_PVOID)NULL) + { + return; + } + else + { + while (localPtr->wNodePtr->qNextPtr == NULL); + } + } + /* Clean up */ + localPtr->wNodePtr->qNextPtr->spin = PTW32_FALSE; + localPtr->wNodePtr->qNextPtr = NULL; +} + +void +ptw32_srwl_ReaderLock(ptw32_srwl_rwlock_t* lockPtr, ptw32_srwl_local_t* localPtr) +{ + ptw32_srwl_node_t* rNodePtr = NULL; + for (;;) + { + ptw32_srwl_node_t* tailPtr = lockPtr->tailPtr; + /* If no nodes are in the queue */ + if (tailPtr == NULL) + { + if (rNodePtr == NULL) + { + rNodePtr = ptw32_srwl_AllocReaderNode(localPtr); + } + rNodePtr->spin = PTW32_FALSE; + if (PTW32_INTERLOCKED_COMPARE_EXCHANGE_PTR( + (PTW32_INTERLOCKED_PVOIDPTR)&lockPtr->tailPtr, + (PTW32_INTERLOCKED_PVOID)rNodePtr, + (PTW32_INTERLOCKED_PVOID)NULL) + == (PTW32_INTERLOCKED_PVOID)rNodePtr) + { + ptw32_oll_Open(rNodePtr->csnzi); + localPtr->ticket = ptw32_oll_Arrive(rNodePtr->csnzi); + if (ptw32_oll_Arrived(localPtr->ticket)) + { + localPtr->departFromPtr = rNodePtr; + return; + } + /* Avoid reusing inserted node */ + rNodePtr = NULL; + } + } + /* Otherwise, there is a node in the queue */ + else + { + /* Is last node a writer node? */ + if (tailPtr->kind == ptw32_srwl_writer) + { + if (rNodePtr == NULL) + { + rNodePtr = ptw32_srwl_AllocReaderNode(localPtr); + } + rNodePtr->spin = PTW32_TRUE; + if (PTW32_INTERLOCKED_COMPARE_EXCHANGE_PTR( + (PTW32_INTERLOCKED_PVOIDPTR)&lockPtr->tailPtr, + (PTW32_INTERLOCKED_PVOID)rNodePtr, + (PTW32_INTERLOCKED_PVOID)tailPtr) + == (PTW32_INTERLOCKED_PVOID)rNodePtr) + { + tailPtr->qNextPtr = rNodePtr; + localPtr->ticket = ptw32_oll_Arrive(rNodePtr->csnzi); + if (ptw32_oll_Arrived(localPtr->ticket)) + { + localPtr->departFromPtr = rNodePtr; + while (rNodePtr->spin); + return; + } + /* Avoid reusing inserted node */ + rNodePtr = NULL; + } + } + /* + * Otherwise, last node is a reader node. + * (tailPtr->kind == ptw32_srwl_reader) + */ + else + { + localPtr->ticket = ptw32_oll_Arrive(tailPtr->csnzi); + if (ptw32_oll_Arrived(localPtr->ticket)) + { + if (rNodePtr != NULL) + { + ptw32_srwl_FreeReaderNode(rNodePtr); + } + localPtr->departFromPtr = tailPtr; + while (tailPtr->spin); + return; + } + } + } + } +} + +void +ptw32_srwl_ReaderUnlock(ptw32_srwl_rwlock_t* lockPtr, ptw32_srwl_local_t* localPtr) +{ + if (ptw32_oll_Depart(localPtr->departFromPtr->csnzi, localPtr->ticket)) + { + return; + } + /* Clean up */ + localPtr->departFromPtr->qNextPtr->spin = PTW32_FALSE; + localPtr->departFromPtr->qNextPtr = NULL; + ptw32_srwl_FreeReaderNode(localPtr->departFromPtr); +} + + +#include + +int main() +{ + printf("%lx\n", PTW32_OLL_MAXREADERS); + return 0; +} + diff --git a/w32-pthreads/ptw32_callUserDestroyRoutines.c b/w32-pthreads/ptw32_callUserDestroyRoutines.c new file mode 100644 index 000000000..f290f7ba5 --- /dev/null +++ b/w32-pthreads/ptw32_callUserDestroyRoutines.c @@ -0,0 +1,232 @@ +/* + * ptw32_callUserDestroyRoutines.c + * + * Description: + * This translation unit implements routines which are private to + * the implementation and may be used throughout it. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +#if defined(__CLEANUP_CXX) +# if defined(_MSC_VER) +# include +# elif defined(__WATCOMC__) +# include +# include +# else +# if defined(__GNUC__) && __GNUC__ < 3 +# include +# else +# include + using + std::terminate; +# endif +# endif +#endif + +void +ptw32_callUserDestroyRoutines (pthread_t thread) + /* + * ------------------------------------------------------------------- + * DOCPRIVATE + * + * This the routine runs through all thread keys and calls + * the destroy routines on the user's data for the current thread. + * It simulates the behaviour of POSIX Threads. + * + * PARAMETERS + * thread + * an instance of pthread_t + * + * RETURNS + * N/A + * ------------------------------------------------------------------- + */ +{ + ThreadKeyAssoc * assoc; + + if (thread.p != NULL) + { + ptw32_mcs_local_node_t threadLock; + ptw32_mcs_local_node_t keyLock; + int assocsRemaining; + int iterations = 0; + ptw32_thread_t * sp = (ptw32_thread_t *) thread.p; + + /* + * Run through all Thread<-->Key associations + * for the current thread. + * + * Do this process at most PTHREAD_DESTRUCTOR_ITERATIONS times. + */ + do + { + assocsRemaining = 0; + iterations++; + + ptw32_mcs_lock_acquire(&(sp->threadLock), &threadLock); + /* + * The pointer to the next assoc is stored in the thread struct so that + * the assoc destructor in pthread_key_delete can adjust it + * if it deletes this assoc. This can happen if we fail to acquire + * both locks below, and are forced to release all of our locks, + * leaving open the opportunity for pthread_key_delete to get in + * before us. + */ + sp->nextAssoc = sp->keys; + ptw32_mcs_lock_release(&threadLock); + + for (;;) + { + void * value; + pthread_key_t k; + void (*destructor) (void *); + + /* + * First we need to serialise with pthread_key_delete by locking + * both assoc guards, but in the reverse order to our convention, + * so we must be careful to avoid deadlock. + */ + ptw32_mcs_lock_acquire(&(sp->threadLock), &threadLock); + + if ((assoc = (ThreadKeyAssoc *)sp->nextAssoc) == NULL) + { + /* Finished */ + ptw32_mcs_lock_release(&threadLock); + break; + } + else + { + /* + * assoc->key must be valid because assoc can't change or be + * removed from our chain while we hold at least one lock. If + * the assoc was on our key chain then the key has not been + * deleted yet. + * + * Now try to acquire the second lock without deadlocking. + * If we fail, we need to relinquish the first lock and the + * processor and then try to acquire them all again. + */ + if (ptw32_mcs_lock_try_acquire(&(assoc->key->keyLock), &keyLock) == EBUSY) + { + ptw32_mcs_lock_release(&threadLock); + Sleep(0); + /* + * Go around again. + * If pthread_key_delete has removed this assoc in the meantime, + * sp->nextAssoc will point to a new assoc. + */ + continue; + } + } + + /* We now hold both locks */ + + sp->nextAssoc = assoc->nextKey; + + /* + * Key still active; pthread_key_delete + * will block on these same mutexes before + * it can release actual key; therefore, + * key is valid and we can call the destroy + * routine; + */ + k = assoc->key; + destructor = k->destructor; + value = TlsGetValue(k->key); + TlsSetValue (k->key, NULL); + + // Every assoc->key exists and has a destructor + if (value != NULL && iterations <= PTHREAD_DESTRUCTOR_ITERATIONS) + { + /* + * Unlock both locks before the destructor runs. + * POSIX says pthread_key_delete can be run from destructors, + * and that probably includes with this key as target. + * pthread_setspecific can also be run from destructors and + * also needs to be able to access the assocs. + */ + ptw32_mcs_lock_release(&threadLock); + ptw32_mcs_lock_release(&keyLock); + + assocsRemaining++; + +#if defined(__cplusplus) + + try + { + /* + * Run the caller's cleanup routine. + */ + destructor (value); + } + catch (...) + { + /* + * A system unexpected exception has occurred + * running the user's destructor. + * We get control back within this block in case + * the application has set up it's own terminate + * handler. Since we are leaving the thread we + * should not get any internal pthreads + * exceptions. + */ + terminate (); + } + +#else /* __cplusplus */ + + /* + * Run the caller's cleanup routine. + */ + destructor (value); + +#endif /* __cplusplus */ + + } + else + { + /* + * Remove association from both the key and thread chains + * and reclaim it's memory resources. + */ + ptw32_tkAssocDestroy (assoc); + ptw32_mcs_lock_release(&threadLock); + ptw32_mcs_lock_release(&keyLock); + } + } + } + while (assocsRemaining); + } +} /* ptw32_callUserDestroyRoutines */ diff --git a/w32-pthreads/ptw32_calloc.c b/w32-pthreads/ptw32_calloc.c new file mode 100644 index 000000000..e7b9e64fe --- /dev/null +++ b/w32-pthreads/ptw32_calloc.c @@ -0,0 +1,56 @@ +/* + * ptw32_calloc.c + * + * Description: + * This translation unit implements miscellaneous thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +#if defined(NEED_CALLOC) +void * +ptw32_calloc (size_t n, size_t s) +{ + unsigned int m = n * s; + void *p; + + p = malloc (m); + if (p == NULL) + return NULL; + + memset (p, 0, m); + + return p; +} +#endif diff --git a/w32-pthreads/ptw32_cond_check_need_init.c b/w32-pthreads/ptw32_cond_check_need_init.c new file mode 100644 index 000000000..ec3e8bbd6 --- /dev/null +++ b/w32-pthreads/ptw32_cond_check_need_init.c @@ -0,0 +1,78 @@ +/* + * ptw32_cond_check_need_init.c + * + * Description: + * This translation unit implements condition variables and their primitives. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +INLINE int +ptw32_cond_check_need_init (pthread_cond_t * cond) +{ + int result = 0; + ptw32_mcs_local_node_t node; + + /* + * The following guarded test is specifically for statically + * initialised condition variables (via PTHREAD_OBJECT_INITIALIZER). + */ + ptw32_mcs_lock_acquire(&ptw32_cond_test_init_lock, &node); + + /* + * We got here possibly under race + * conditions. Check again inside the critical section. + * If a static cv has been destroyed, the application can + * re-initialise it only by calling pthread_cond_init() + * explicitly. + */ + if (*cond == PTHREAD_COND_INITIALIZER) + { + result = pthread_cond_init (cond, NULL); + } + else if (*cond == NULL) + { + /* + * The cv has been destroyed while we were waiting to + * initialise it, so the operation that caused the + * auto-initialisation should fail. + */ + result = EINVAL; + } + + ptw32_mcs_lock_release(&node); + + return result; +} diff --git a/w32-pthreads/ptw32_getprocessors.c b/w32-pthreads/ptw32_getprocessors.c new file mode 100644 index 000000000..e60c3143f --- /dev/null +++ b/w32-pthreads/ptw32_getprocessors.c @@ -0,0 +1,91 @@ +/* + * ptw32_getprocessors.c + * + * Description: + * This translation unit implements routines which are private to + * the implementation and may be used throughout it. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +/* + * ptw32_getprocessors() + * + * Get the number of CPUs available to the process. + * + * If the available number of CPUs is 1 then pthread_spin_lock() + * will block rather than spin if the lock is already owned. + * + * pthread_spin_init() calls this routine when initialising + * a spinlock. If the number of available processors changes + * (after a call to SetProcessAffinityMask()) then only + * newly initialised spinlocks will notice. + */ +int +ptw32_getprocessors (int *count) +{ + DWORD_PTR vProcessCPUs; + DWORD_PTR vSystemCPUs; + int result = 0; + +#if defined(NEED_PROCESS_AFFINITY_MASK) + + *count = 1; + +#else + + if (GetProcessAffinityMask (GetCurrentProcess (), + &vProcessCPUs, &vSystemCPUs)) + { + DWORD_PTR bit; + int CPUs = 0; + + for (bit = 1; bit != 0; bit <<= 1) + { + if (vProcessCPUs & bit) + { + CPUs++; + } + } + *count = CPUs; + } + else + { + result = EAGAIN; + } + +#endif + + return (result); +} diff --git a/w32-pthreads/ptw32_is_attr.c b/w32-pthreads/ptw32_is_attr.c new file mode 100644 index 000000000..36395f81f --- /dev/null +++ b/w32-pthreads/ptw32_is_attr.c @@ -0,0 +1,47 @@ +/* + * ptw32_is_attr.c + * + * Description: + * This translation unit implements operations on thread attribute objects. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +int +ptw32_is_attr (const pthread_attr_t * attr) +{ + /* Return 0 if the attr object is valid, non-zero otherwise. */ + + return (attr == NULL || + *attr == NULL || (*attr)->valid != PTW32_ATTR_VALID); +} diff --git a/w32-pthreads/ptw32_mutex_check_need_init.c b/w32-pthreads/ptw32_mutex_check_need_init.c new file mode 100644 index 000000000..897db3c68 --- /dev/null +++ b/w32-pthreads/ptw32_mutex_check_need_init.c @@ -0,0 +1,92 @@ +/* + * ptw32_mutex_check_need_init.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +static struct pthread_mutexattr_t_ ptw32_recursive_mutexattr_s = + {PTHREAD_PROCESS_PRIVATE, PTHREAD_MUTEX_RECURSIVE}; +static struct pthread_mutexattr_t_ ptw32_errorcheck_mutexattr_s = + {PTHREAD_PROCESS_PRIVATE, PTHREAD_MUTEX_ERRORCHECK}; +static pthread_mutexattr_t ptw32_recursive_mutexattr = &ptw32_recursive_mutexattr_s; +static pthread_mutexattr_t ptw32_errorcheck_mutexattr = &ptw32_errorcheck_mutexattr_s; + + +INLINE int +ptw32_mutex_check_need_init (pthread_mutex_t * mutex) +{ + register int result = 0; + register pthread_mutex_t mtx; + ptw32_mcs_local_node_t node; + + ptw32_mcs_lock_acquire(&ptw32_mutex_test_init_lock, &node); + + /* + * We got here possibly under race + * conditions. Check again inside the critical section + * and only initialise if the mutex is valid (not been destroyed). + * If a static mutex has been destroyed, the application can + * re-initialise it only by calling pthread_mutex_init() + * explicitly. + */ + mtx = *mutex; + + if (mtx == PTHREAD_MUTEX_INITIALIZER) + { + result = pthread_mutex_init (mutex, NULL); + } + else if (mtx == PTHREAD_RECURSIVE_MUTEX_INITIALIZER) + { + result = pthread_mutex_init (mutex, &ptw32_recursive_mutexattr); + } + else if (mtx == PTHREAD_ERRORCHECK_MUTEX_INITIALIZER) + { + result = pthread_mutex_init (mutex, &ptw32_errorcheck_mutexattr); + } + else if (mtx == NULL) + { + /* + * The mutex has been destroyed while we were waiting to + * initialise it, so the operation that caused the + * auto-initialisation should fail. + */ + result = EINVAL; + } + + ptw32_mcs_lock_release(&node); + + return (result); +} diff --git a/w32-pthreads/ptw32_new.c b/w32-pthreads/ptw32_new.c new file mode 100644 index 000000000..ac836ead3 --- /dev/null +++ b/w32-pthreads/ptw32_new.c @@ -0,0 +1,94 @@ +/* + * ptw32_new.c + * + * Description: + * This translation unit implements miscellaneous thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +pthread_t +ptw32_new (void) +{ + pthread_t t; + pthread_t nil = {NULL, 0}; + ptw32_thread_t * tp; + + /* + * If there's a reusable pthread_t then use it. + */ + t = ptw32_threadReusePop (); + + if (NULL != t.p) + { + tp = (ptw32_thread_t *) t.p; + } + else + { + /* No reuse threads available */ + tp = (ptw32_thread_t *) calloc (1, sizeof(ptw32_thread_t)); + + if (tp == NULL) + { + return nil; + } + + /* ptHandle.p needs to point to it's parent ptw32_thread_t. */ + t.p = tp->ptHandle.p = tp; + t.x = tp->ptHandle.x = 0; + } + + /* Set default state. */ + tp->seqNumber = ++ptw32_threadSeqNumber; + tp->sched_priority = THREAD_PRIORITY_NORMAL; + tp->detachState = PTHREAD_CREATE_JOINABLE; + tp->cancelState = PTHREAD_CANCEL_ENABLE; + tp->cancelType = PTHREAD_CANCEL_DEFERRED; + tp->stateLock = 0; + tp->threadLock = 0; + tp->robustMxListLock = 0; + tp->robustMxList = NULL; + tp->cancelEvent = CreateEvent (0, (int) PTW32_TRUE, /* manualReset */ + (int) PTW32_FALSE, /* setSignaled */ + NULL); + + if (tp->cancelEvent == NULL) + { + ptw32_threadReusePush (tp->ptHandle); + return nil; + } + + return t; + +} diff --git a/w32-pthreads/ptw32_processInitialize.c b/w32-pthreads/ptw32_processInitialize.c new file mode 100644 index 000000000..8da3e41fa --- /dev/null +++ b/w32-pthreads/ptw32_processInitialize.c @@ -0,0 +1,92 @@ +/* + * ptw32_processInitialize.c + * + * Description: + * This translation unit implements routines which are private to + * the implementation and may be used throughout it. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +ptw32_processInitialize (void) + /* + * ------------------------------------------------------ + * DOCPRIVATE + * This function performs process wide initialization for + * the pthread library. + * + * PARAMETERS + * N/A + * + * DESCRIPTION + * This function performs process wide initialization for + * the pthread library. + * If successful, this routine sets the global variable + * ptw32_processInitialized to TRUE. + * + * RESULTS + * TRUE if successful, + * FALSE otherwise + * + * ------------------------------------------------------ + */ +{ + if (ptw32_processInitialized) + { + /* + * Ignore if already initialized. this is useful for + * programs that uses a non-dll pthread + * library. Such programs must call ptw32_processInitialize() explicitly, + * since this initialization routine is automatically called only when + * the dll is loaded. + */ + return PTW32_TRUE; + } + + ptw32_processInitialized = PTW32_TRUE; + + /* + * Initialize Keys + */ + if ((pthread_key_create (&ptw32_selfThreadKey, NULL) != 0) || + (pthread_key_create (&ptw32_cleanupKey, NULL) != 0)) + { + + ptw32_processTerminate (); + } + + return (ptw32_processInitialized); + +} /* processInitialize */ diff --git a/w32-pthreads/ptw32_processTerminate.c b/w32-pthreads/ptw32_processTerminate.c new file mode 100644 index 000000000..83f0f23ca --- /dev/null +++ b/w32-pthreads/ptw32_processTerminate.c @@ -0,0 +1,105 @@ +/* + * ptw32_processTerminate.c + * + * Description: + * This translation unit implements routines which are private to + * the implementation and may be used throughout it. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +void +ptw32_processTerminate (void) + /* + * ------------------------------------------------------ + * DOCPRIVATE + * This function performs process wide termination for + * the pthread library. + * + * PARAMETERS + * N/A + * + * DESCRIPTION + * This function performs process wide termination for + * the pthread library. + * This routine sets the global variable + * ptw32_processInitialized to FALSE + * + * RESULTS + * N/A + * + * ------------------------------------------------------ + */ +{ + if (ptw32_processInitialized) + { + ptw32_thread_t * tp, * tpNext; + ptw32_mcs_local_node_t node; + + if (ptw32_selfThreadKey != NULL) + { + /* + * Release ptw32_selfThreadKey + */ + pthread_key_delete (ptw32_selfThreadKey); + + ptw32_selfThreadKey = NULL; + } + + if (ptw32_cleanupKey != NULL) + { + /* + * Release ptw32_cleanupKey + */ + pthread_key_delete (ptw32_cleanupKey); + + ptw32_cleanupKey = NULL; + } + + ptw32_mcs_lock_acquire(&ptw32_thread_reuse_lock, &node); + + tp = ptw32_threadReuseTop; + while (tp != PTW32_THREAD_REUSE_EMPTY) + { + tpNext = tp->prevReuse; + free (tp); + tp = tpNext; + } + + ptw32_mcs_lock_release(&node); + + ptw32_processInitialized = PTW32_FALSE; + } + +} /* processTerminate */ diff --git a/w32-pthreads/ptw32_relmillisecs.c b/w32-pthreads/ptw32_relmillisecs.c new file mode 100644 index 000000000..894d5c9d4 --- /dev/null +++ b/w32-pthreads/ptw32_relmillisecs.c @@ -0,0 +1,132 @@ +/* + * ptw32_relmillisecs.c + * + * Description: + * This translation unit implements miscellaneous thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#if !defined(NEED_FTIME) +#include +#endif + + +#if defined(PTW32_BUILD_INLINED) +INLINE +#endif /* PTW32_BUILD_INLINED */ +DWORD +ptw32_relmillisecs (const struct timespec * abstime) +{ + const int64_t NANOSEC_PER_MILLISEC = 1000000; + const int64_t MILLISEC_PER_SEC = 1000; + DWORD milliseconds; + int64_t tmpAbsMilliseconds; + int64_t tmpCurrMilliseconds; +#if defined(NEED_FTIME) + struct timespec currSysTime; + FILETIME ft; + SYSTEMTIME st; +#else /* ! NEED_FTIME */ +#if ( defined(_MSC_VER) && _MSC_VER >= 1300 ) || \ + ( (defined(__MINGW64__) || defined(__MINGW32__)) && __MSVCRT_VERSION__ >= 0x0601 ) + struct __timeb64 currSysTime; +#else + struct _timeb currSysTime; +#endif +#endif /* NEED_FTIME */ + + + /* + * Calculate timeout as milliseconds from current system time. + */ + + /* + * subtract current system time from abstime in a way that checks + * that abstime is never in the past, or is never equivalent to the + * defined INFINITE value (0xFFFFFFFF). + * + * Assume all integers are unsigned, i.e. cannot test if less than 0. + */ + tmpAbsMilliseconds = (int64_t)abstime->tv_sec * MILLISEC_PER_SEC; + tmpAbsMilliseconds += ((int64_t)abstime->tv_nsec + (NANOSEC_PER_MILLISEC/2)) / NANOSEC_PER_MILLISEC; + + /* get current system time */ + +#if defined(NEED_FTIME) + + GetSystemTime(&st); + SystemTimeToFileTime(&st, &ft); + /* + * GetSystemTimeAsFileTime(&ft); would be faster, + * but it does not exist on WinCE + */ + + ptw32_filetime_to_timespec(&ft, &currSysTime); + + tmpCurrMilliseconds = (int64_t)currSysTime.tv_sec * MILLISEC_PER_SEC; + tmpCurrMilliseconds += ((int64_t)currSysTime.tv_nsec + (NANOSEC_PER_MILLISEC/2)) + / NANOSEC_PER_MILLISEC; + +#else /* ! NEED_FTIME */ + +#if defined(_MSC_VER) && _MSC_VER >= 1400 + _ftime64_s(&currSysTime); +#elif ( defined(_MSC_VER) && _MSC_VER >= 1300 ) || \ + ( (defined(__MINGW64__) || defined(__MINGW32__)) && __MSVCRT_VERSION__ >= 0x0601 ) + _ftime64(&currSysTime); +#else + _ftime(&currSysTime); +#endif + + tmpCurrMilliseconds = (int64_t) currSysTime.time * MILLISEC_PER_SEC; + tmpCurrMilliseconds += (int64_t) currSysTime.millitm; + +#endif /* NEED_FTIME */ + + if (tmpAbsMilliseconds > tmpCurrMilliseconds) + { + milliseconds = (DWORD) (tmpAbsMilliseconds - tmpCurrMilliseconds); + if (milliseconds == INFINITE) + { + /* Timeouts must be finite */ + milliseconds--; + } + } + else + { + /* The abstime given is in the past */ + milliseconds = 0; + } + + return milliseconds; +} diff --git a/w32-pthreads/ptw32_reuse.c b/w32-pthreads/ptw32_reuse.c new file mode 100644 index 000000000..7325857ba --- /dev/null +++ b/w32-pthreads/ptw32_reuse.c @@ -0,0 +1,151 @@ +/* + * ptw32_threadReuse.c + * + * Description: + * This translation unit implements miscellaneous thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +/* + * How it works: + * A pthread_t is a struct (2x32 bit scalar types on IA-32, 2x64 bit on IA-64) + * which is normally passed/returned by value to/from pthreads routines. + * Applications are therefore storing a copy of the struct as it is at that + * time. + * + * The original pthread_t struct plus all copies of it contain the address of + * the thread state struct ptw32_thread_t_ (p), plus a reuse counter (x). Each + * ptw32_thread_t contains the original copy of it's pthread_t. + * Once malloced, a ptw32_thread_t_ struct is not freed until the process exits. + * + * The thread reuse stack is a simple LILO stack managed through a singly + * linked list element in the ptw32_thread_t. + * + * Each time a thread is destroyed, the ptw32_thread_t address is pushed onto the + * reuse stack after it's ptHandle's reuse counter has been incremented. + * + * The following can now be said from this: + * - two pthread_t's are identical if their ptw32_thread_t reference pointers + * are equal and their reuse counters are equal. That is, + * + * equal = (a.p == b.p && a.x == b.x) + * + * - a pthread_t copy refers to a destroyed thread if the reuse counter in + * the copy is not equal to the reuse counter in the original. + * + * threadDestroyed = (copy.x != ((ptw32_thread_t *)copy.p)->ptHandle.x) + * + */ + +/* + * Pop a clean pthread_t struct off the reuse stack. + */ +pthread_t +ptw32_threadReusePop (void) +{ + pthread_t t = {NULL, 0}; + ptw32_mcs_local_node_t node; + + ptw32_mcs_lock_acquire(&ptw32_thread_reuse_lock, &node); + + if (PTW32_THREAD_REUSE_EMPTY != ptw32_threadReuseTop) + { + ptw32_thread_t * tp; + + tp = ptw32_threadReuseTop; + + ptw32_threadReuseTop = tp->prevReuse; + + if (PTW32_THREAD_REUSE_EMPTY == ptw32_threadReuseTop) + { + ptw32_threadReuseBottom = PTW32_THREAD_REUSE_EMPTY; + } + + tp->prevReuse = NULL; + + t = tp->ptHandle; + } + + ptw32_mcs_lock_release(&node); + + return t; + +} + +/* + * Push a clean pthread_t struct onto the reuse stack. + * Must be re-initialised when reused. + * All object elements (mutexes, events etc) must have been either + * detroyed before this, or never initialised. + */ +void +ptw32_threadReusePush (pthread_t thread) +{ + ptw32_thread_t * tp = (ptw32_thread_t *) thread.p; + pthread_t t; + ptw32_mcs_local_node_t node; + + ptw32_mcs_lock_acquire(&ptw32_thread_reuse_lock, &node); + + t = tp->ptHandle; + memset(tp, 0, sizeof(ptw32_thread_t)); + + /* Must restore the original POSIX handle that we just wiped. */ + tp->ptHandle = t; + + /* Bump the reuse counter now */ +#if defined(PTW32_THREAD_ID_REUSE_INCREMENT) + tp->ptHandle.x += PTW32_THREAD_ID_REUSE_INCREMENT; +#else + tp->ptHandle.x++; +#endif + + tp->state = PThreadStateReuse; + + tp->prevReuse = PTW32_THREAD_REUSE_EMPTY; + + if (PTW32_THREAD_REUSE_EMPTY != ptw32_threadReuseBottom) + { + ptw32_threadReuseBottom->prevReuse = tp; + } + else + { + ptw32_threadReuseTop = tp; + } + + ptw32_threadReuseBottom = tp; + + ptw32_mcs_lock_release(&node); +} diff --git a/w32-pthreads/ptw32_rwlock_cancelwrwait.c b/w32-pthreads/ptw32_rwlock_cancelwrwait.c new file mode 100644 index 000000000..a057bd1d7 --- /dev/null +++ b/w32-pthreads/ptw32_rwlock_cancelwrwait.c @@ -0,0 +1,50 @@ +/* + * ptw32_rwlock_cancelwrwait.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +void +ptw32_rwlock_cancelwrwait (void *arg) +{ + pthread_rwlock_t rwl = (pthread_rwlock_t) arg; + + rwl->nSharedAccessCount = -rwl->nCompletedSharedAccessCount; + rwl->nCompletedSharedAccessCount = 0; + + (void) pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted)); + (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); +} diff --git a/w32-pthreads/ptw32_rwlock_check_need_init.c b/w32-pthreads/ptw32_rwlock_check_need_init.c new file mode 100644 index 000000000..858ee271c --- /dev/null +++ b/w32-pthreads/ptw32_rwlock_check_need_init.c @@ -0,0 +1,77 @@ +/* + * pthread_rwlock_check_need_init.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +INLINE int +ptw32_rwlock_check_need_init (pthread_rwlock_t * rwlock) +{ + int result = 0; + ptw32_mcs_local_node_t node; + + /* + * The following guarded test is specifically for statically + * initialised rwlocks (via PTHREAD_RWLOCK_INITIALIZER). + */ + ptw32_mcs_lock_acquire(&ptw32_rwlock_test_init_lock, &node); + + /* + * We got here possibly under race + * conditions. Check again inside the critical section + * and only initialise if the rwlock is valid (not been destroyed). + * If a static rwlock has been destroyed, the application can + * re-initialise it only by calling pthread_rwlock_init() + * explicitly. + */ + if (*rwlock == PTHREAD_RWLOCK_INITIALIZER) + { + result = pthread_rwlock_init (rwlock, NULL); + } + else if (*rwlock == NULL) + { + /* + * The rwlock has been destroyed while we were waiting to + * initialise it, so the operation that caused the + * auto-initialisation should fail. + */ + result = EINVAL; + } + + ptw32_mcs_lock_release(&node); + + return result; +} diff --git a/w32-pthreads/ptw32_semwait.c b/w32-pthreads/ptw32_semwait.c new file mode 100644 index 000000000..c3c4fd0e5 --- /dev/null +++ b/w32-pthreads/ptw32_semwait.c @@ -0,0 +1,135 @@ +/* + * ptw32_semwait.c + * + * Description: + * This translation unit implements mutual exclusion (mutex) primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#if !defined(_UWIN) +/*# include */ +#endif +#include "pthread.h" +#include "implement.h" + + +int +ptw32_semwait (sem_t * sem) + /* + * ------------------------------------------------------ + * DESCRIPTION + * This function waits on a POSIX semaphore. If the + * semaphore value is greater than zero, it decreases + * its value by one. If the semaphore value is zero, then + * the calling thread (or process) is blocked until it can + * successfully decrease the value. + * + * Unlike sem_wait(), this routine is non-cancelable. + * + * RESULTS + * 0 successfully decreased semaphore, + * -1 failed, error in errno. + * ERRNO + * EINVAL 'sem' is not a valid semaphore, + * ENOSYS semaphores are not supported, + * EINTR the function was interrupted by a signal, + * EDEADLK a deadlock condition was detected. + * + * ------------------------------------------------------ + */ +{ + int result = 0; + sem_t s = *sem; + + if (s == NULL) + { + result = EINVAL; + } + else + { + if ((result = pthread_mutex_lock (&s->lock)) == 0) + { + int v; + + /* See sem_destroy.c + */ + if (*sem == NULL) + { + (void) pthread_mutex_unlock (&s->lock); + errno = EINVAL; + return -1; + } + + v = --s->value; + (void) pthread_mutex_unlock (&s->lock); + + if (v < 0) + { + /* Must wait */ + if (WaitForSingleObject (s->sem, INFINITE) == WAIT_OBJECT_0) + { +#if defined(NEED_SEM) + if (pthread_mutex_lock (&s->lock) == 0) + { + if (*sem == NULL) + { + (void) pthread_mutex_unlock (&s->lock); + errno = EINVAL; + return -1; + } + + if (s->leftToUnblock > 0) + { + --s->leftToUnblock; + SetEvent(s->sem); + } + (void) pthread_mutex_unlock (&s->lock); + } +#endif + return 0; + } + } + else + { + return 0; + } + } + } + + if (result != 0) + { + errno = result; + return -1; + } + + return 0; + +} /* ptw32_semwait */ diff --git a/w32-pthreads/ptw32_spinlock_check_need_init.c b/w32-pthreads/ptw32_spinlock_check_need_init.c new file mode 100644 index 000000000..8808454ee --- /dev/null +++ b/w32-pthreads/ptw32_spinlock_check_need_init.c @@ -0,0 +1,78 @@ +/* + * ptw32_spinlock_check_need_init.c + * + * Description: + * This translation unit implements spin lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +INLINE int +ptw32_spinlock_check_need_init (pthread_spinlock_t * lock) +{ + int result = 0; + ptw32_mcs_local_node_t node; + + /* + * The following guarded test is specifically for statically + * initialised spinlocks (via PTHREAD_SPINLOCK_INITIALIZER). + */ + ptw32_mcs_lock_acquire(&ptw32_spinlock_test_init_lock, &node); + + /* + * We got here possibly under race + * conditions. Check again inside the critical section + * and only initialise if the spinlock is valid (not been destroyed). + * If a static spinlock has been destroyed, the application can + * re-initialise it only by calling pthread_spin_init() + * explicitly. + */ + if (*lock == PTHREAD_SPINLOCK_INITIALIZER) + { + result = pthread_spin_init (lock, PTHREAD_PROCESS_PRIVATE); + } + else if (*lock == NULL) + { + /* + * The spinlock has been destroyed while we were waiting to + * initialise it, so the operation that caused the + * auto-initialisation should fail. + */ + result = EINVAL; + } + + ptw32_mcs_lock_release(&node); + + return (result); +} diff --git a/w32-pthreads/ptw32_threadDestroy.c b/w32-pthreads/ptw32_threadDestroy.c new file mode 100644 index 000000000..41499b11b --- /dev/null +++ b/w32-pthreads/ptw32_threadDestroy.c @@ -0,0 +1,79 @@ +/* + * ptw32_threadDestroy.c + * + * Description: + * This translation unit implements routines which are private to + * the implementation and may be used throughout it. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +void +ptw32_threadDestroy (pthread_t thread) +{ + ptw32_thread_t * tp = (ptw32_thread_t *) thread.p; + ptw32_thread_t threadCopy; + + if (tp != NULL) + { + /* + * Copy thread state so that the thread can be atomically NULLed. + */ + memcpy (&threadCopy, tp, sizeof (threadCopy)); + + /* + * Thread ID structs are never freed. They're NULLed and reused. + * This also sets the thread to PThreadStateInitial (invalid). + */ + ptw32_threadReusePush (thread); + + /* Now work on the copy. */ + if (threadCopy.cancelEvent != NULL) + { + CloseHandle (threadCopy.cancelEvent); + } + +#if ! (defined(__MINGW64__) || defined(__MINGW32__)) || defined (__MSVCRT__) || defined (__DMC__) + /* + * See documentation for endthread vs endthreadex. + */ + if (threadCopy.threadH != 0) + { + CloseHandle (threadCopy.threadH); + } +#endif + + } +} /* ptw32_threadDestroy */ + diff --git a/w32-pthreads/ptw32_threadStart.c b/w32-pthreads/ptw32_threadStart.c new file mode 100644 index 000000000..e83ede0ec --- /dev/null +++ b/w32-pthreads/ptw32_threadStart.c @@ -0,0 +1,357 @@ +/* + * ptw32_threadStart.c + * + * Description: + * This translation unit implements routines which are private to + * the implementation and may be used throughout it. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include + +#if defined(__CLEANUP_C) +# include +#endif + +#if defined(__CLEANUP_SEH) + +static DWORD +ExceptionFilter (EXCEPTION_POINTERS * ep, DWORD * ei) +{ + switch (ep->ExceptionRecord->ExceptionCode) + { + case EXCEPTION_PTW32_SERVICES: + { + DWORD param; + DWORD numParams = ep->ExceptionRecord->NumberParameters; + + numParams = (numParams > 3) ? 3 : numParams; + + for (param = 0; param < numParams; param++) + { + ei[param] = ep->ExceptionRecord->ExceptionInformation[param]; + } + + return EXCEPTION_EXECUTE_HANDLER; + break; + } + default: + { + /* + * A system unexpected exception has occurred running the user's + * routine. We need to cleanup before letting the exception + * out of thread scope. + */ + pthread_t self = pthread_self (); + + ptw32_callUserDestroyRoutines (self); + + return EXCEPTION_CONTINUE_SEARCH; + break; + } + } +} + +#elif defined(__CLEANUP_CXX) + +#if defined(_MSC_VER) +# include +#elif defined(__WATCOMC__) +# include +# include +typedef terminate_handler + terminate_function; +#else +# if defined(__GNUC__) && __GNUC__ < 3 +# include +# else +# include +using + std::terminate_handler; +using + std::terminate; +using + std::set_terminate; +# endif +typedef terminate_handler + terminate_function; +#endif + +static terminate_function + ptw32_oldTerminate; + +void +ptw32_terminate () +{ + set_terminate (ptw32_oldTerminate); + (void) pthread_win32_thread_detach_np (); + terminate (); +} + +#endif + +#if ! (defined(__MINGW64__) || defined(__MINGW32__)) || (defined (__MSVCRT__) && ! defined (__DMC__)) +unsigned + __stdcall +#else +void +#endif +ptw32_threadStart (void *vthreadParms) +{ + ThreadParms * threadParms = (ThreadParms *) vthreadParms; + pthread_t self; + ptw32_thread_t * sp; + void * (PTW32_CDECL *start) (void *); + void * arg; + +#if defined(__CLEANUP_SEH) + DWORD + ei[] = { 0, 0, 0 }; +#endif + +#if defined(__CLEANUP_C) + int setjmp_rc; +#endif + + ptw32_mcs_local_node_t stateLock; + void * status = (void *) 0; + + self = threadParms->tid; + sp = (ptw32_thread_t *) self.p; + start = threadParms->start; + arg = threadParms->arg; + + free (threadParms); + +#if (defined(__MINGW64__) || defined(__MINGW32__)) && ! defined (__MSVCRT__) + /* + * beginthread does not return the thread id and is running + * before it returns us the thread handle, and so we do it here. + */ + sp->thread = GetCurrentThreadId (); + /* + * Here we're using stateLock as a general-purpose lock + * to make the new thread wait until the creating thread + * has the new handle. + */ + ptw32_mcs_lock_acquire (&sp->stateLock, &stateLock); + pthread_setspecific (ptw32_selfThreadKey, sp); +#else + pthread_setspecific (ptw32_selfThreadKey, sp); + ptw32_mcs_lock_acquire (&sp->stateLock, &stateLock); +#endif + + sp->state = PThreadStateRunning; + ptw32_mcs_lock_release (&stateLock); + +#if defined(__CLEANUP_SEH) + + __try + { + /* + * Run the caller's routine; + */ + status = sp->exitStatus = (*start) (arg); + sp->state = PThreadStateExiting; + +#if defined(_UWIN) + if (--pthread_count <= 0) + exit (0); +#endif + + } + __except (ExceptionFilter (GetExceptionInformation (), ei)) + { + switch (ei[0]) + { + case PTW32_EPS_CANCEL: + status = sp->exitStatus = PTHREAD_CANCELED; +#if defined(_UWIN) + if (--pthread_count <= 0) + exit (0); +#endif + break; + case PTW32_EPS_EXIT: + status = sp->exitStatus; + break; + default: + status = sp->exitStatus = PTHREAD_CANCELED; + break; + } + } + +#else /* __CLEANUP_SEH */ + +#if defined(__CLEANUP_C) + + setjmp_rc = setjmp (sp->start_mark); + + if (0 == setjmp_rc) + { + + /* + * Run the caller's routine; + */ + status = sp->exitStatus = (*start) (arg); + sp->state = PThreadStateExiting; + } + else + { + switch (setjmp_rc) + { + case PTW32_EPS_CANCEL: + status = sp->exitStatus = PTHREAD_CANCELED; + break; + case PTW32_EPS_EXIT: + status = sp->exitStatus; + break; + default: + status = sp->exitStatus = PTHREAD_CANCELED; + break; + } + } + +#else /* __CLEANUP_C */ + +#if defined(__CLEANUP_CXX) + + ptw32_oldTerminate = set_terminate (&ptw32_terminate); + + try + { + /* + * Run the caller's routine in a nested try block so that we + * can run the user's terminate function, which may call + * pthread_exit() or be canceled. + */ + try + { + status = sp->exitStatus = (*start) (arg); + sp->state = PThreadStateExiting; + } + catch (ptw32_exception &) + { + /* + * Pass these through to the outer block. + */ + throw; + } + catch (...) + { + /* + * We want to run the user's terminate function if supplied. + * That function may call pthread_exit() or be canceled, which will + * be handled by the outer try block. + * + * ptw32_terminate() will be called if there is no user + * supplied function. + */ + terminate_function + term_func = set_terminate (0); + set_terminate (term_func); + + if (term_func != 0) + { + term_func (); + } + throw; + } + } + catch (ptw32_exception_cancel &) + { + /* + * Thread was canceled. + */ + status = sp->exitStatus = PTHREAD_CANCELED; + } + catch (ptw32_exception_exit &) + { + /* + * Thread was exited via pthread_exit(). + */ + status = sp->exitStatus; + } + catch (...) + { + /* + * A system unexpected exception has occurred running the user's + * terminate routine. We get control back within this block + * and exit with a substitute status. If the thread was not + * cancelled then this indicates the unhandled exception. + */ + status = sp->exitStatus = PTHREAD_CANCELED; + } + + (void) set_terminate (ptw32_oldTerminate); + +#else + +#error ERROR [__FILE__, line __LINE__]: Cleanup type undefined. + +#endif /* __CLEANUP_CXX */ +#endif /* __CLEANUP_C */ +#endif /* __CLEANUP_SEH */ + +#if defined(PTW32_STATIC_LIB) + /* + * We need to cleanup the pthread now if we have + * been statically linked, in which case the cleanup + * in dllMain won't get done. Joinable threads will + * only be partially cleaned up and must be fully cleaned + * up by pthread_join() or pthread_detach(). + * + * Note: if this library has been statically linked, + * implicitly created pthreads (those created + * for Win32 threads which have called pthreads routines) + * must be cleaned up explicitly by the application + * (by calling pthread_win32_thread_detach_np()). + * For the dll, dllMain will do the cleanup automatically. + */ + (void) pthread_win32_thread_detach_np (); +#endif + +#if ! (defined(__MINGW64__) || defined(__MINGW32__)) || defined (__MSVCRT__) || defined (__DMC__) + _endthreadex ((unsigned)(size_t) status); +#else + _endthread (); +#endif + + /* + * Never reached. + */ + +#if ! (defined(__MINGW64__) || defined(__MINGW32__)) || defined (__MSVCRT__) || defined (__DMC__) + return (unsigned)(size_t) status; +#endif + +} /* ptw32_threadStart */ diff --git a/w32-pthreads/ptw32_throw.c b/w32-pthreads/ptw32_throw.c new file mode 100644 index 000000000..1404e940f --- /dev/null +++ b/w32-pthreads/ptw32_throw.c @@ -0,0 +1,189 @@ +/* + * ptw32_throw.c + * + * Description: + * This translation unit implements routines which are private to + * the implementation and may be used throughout it. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + +#if defined(__CLEANUP_C) +# include +#endif + +/* + * ptw32_throw + * + * All canceled and explicitly exited POSIX threads go through + * here. This routine knows how to exit both POSIX initiated threads and + * 'implicit' POSIX threads for each of the possible language modes (C, + * C++, and SEH). + */ +#if defined(_MSC_VER) +/* + * Ignore the warning: + * "C++ exception specification ignored except to indicate that + * the function is not __declspec(nothrow)." + */ +#pragma warning(disable:4290) +#endif +void +ptw32_throw (DWORD exception) +#if defined(__CLEANUP_CXX) + throw(ptw32_exception_cancel,ptw32_exception_exit) +#endif +{ + /* + * Don't use pthread_self() to avoid creating an implicit POSIX thread handle + * unnecessarily. + */ + ptw32_thread_t * sp = (ptw32_thread_t *) pthread_getspecific (ptw32_selfThreadKey); + +#if defined(__CLEANUP_SEH) + DWORD exceptionInformation[3]; +#endif + + sp->state = PThreadStateExiting; + + if (exception != PTW32_EPS_CANCEL && exception != PTW32_EPS_EXIT) + { + /* Should never enter here */ + exit (1); + } + + if (NULL == sp || sp->implicit) + { + /* + * We're inside a non-POSIX initialised Win32 thread + * so there is no point to jump or throw back to. Just do an + * explicit thread exit here after cleaning up POSIX + * residue (i.e. cleanup handlers, POSIX thread handle etc). + */ +#if ! (defined(__MINGW64__) || defined(__MINGW32__)) || defined (__MSVCRT__) || defined (__DMC__) + unsigned exitCode = 0; + + switch (exception) + { + case PTW32_EPS_CANCEL: + exitCode = (unsigned)(size_t) PTHREAD_CANCELED; + break; + case PTW32_EPS_EXIT: + if (NULL != sp) + { + exitCode = (unsigned)(size_t) sp->exitStatus; + } + break; + } +#endif + +#if defined(PTW32_STATIC_LIB) + + pthread_win32_thread_detach_np (); + +#endif + +#if ! (defined(__MINGW64__) || defined(__MINGW32__)) || defined (__MSVCRT__) || defined (__DMC__) + _endthreadex (exitCode); +#else + _endthread (); +#endif + + } + +#if defined(__CLEANUP_SEH) + + + exceptionInformation[0] = (DWORD) (exception); + exceptionInformation[1] = (DWORD) (0); + exceptionInformation[2] = (DWORD) (0); + + RaiseException (EXCEPTION_PTW32_SERVICES, 0, 3, exceptionInformation); + +#else /* __CLEANUP_SEH */ + +#if defined(__CLEANUP_C) + + ptw32_pop_cleanup_all (1); + longjmp (sp->start_mark, exception); + +#else /* __CLEANUP_C */ + +#if defined(__CLEANUP_CXX) + + switch (exception) + { + case PTW32_EPS_CANCEL: + throw ptw32_exception_cancel (); + break; + case PTW32_EPS_EXIT: + throw ptw32_exception_exit (); + break; + } + +#else + +#error ERROR [__FILE__, line __LINE__]: Cleanup type undefined. + +#endif /* __CLEANUP_CXX */ + +#endif /* __CLEANUP_C */ + +#endif /* __CLEANUP_SEH */ + + /* Never reached */ +} + + +void +ptw32_pop_cleanup_all (int execute) +{ + while (NULL != ptw32_pop_cleanup (execute)) + { + } +} + + +DWORD +ptw32_get_exception_services_code (void) +{ +#if defined(__CLEANUP_SEH) + + return EXCEPTION_PTW32_SERVICES; + +#else + + return (DWORD)0; + +#endif +} diff --git a/w32-pthreads/ptw32_timespec.c b/w32-pthreads/ptw32_timespec.c new file mode 100644 index 000000000..6318957a8 --- /dev/null +++ b/w32-pthreads/ptw32_timespec.c @@ -0,0 +1,83 @@ +/* + * ptw32_timespec.c + * + * Description: + * This translation unit implements routines which are private to + * the implementation and may be used throughout it. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +#if defined(NEED_FTIME) + +/* + * time between jan 1, 1601 and jan 1, 1970 in units of 100 nanoseconds + */ +#define PTW32_TIMESPEC_TO_FILETIME_OFFSET \ + ( ((int64_t) 27111902 << 32) + (int64_t) 3577643008 ) + +INLINE void +ptw32_timespec_to_filetime (const struct timespec *ts, FILETIME * ft) + /* + * ------------------------------------------------------------------- + * converts struct timespec + * where the time is expressed in seconds and nanoseconds from Jan 1, 1970. + * into FILETIME (as set by GetSystemTimeAsFileTime), where the time is + * expressed in 100 nanoseconds from Jan 1, 1601, + * ------------------------------------------------------------------- + */ +{ + *(int64_t *) ft = ts->tv_sec * 10000000 + + (ts->tv_nsec + 50) / 100 + PTW32_TIMESPEC_TO_FILETIME_OFFSET; +} + +INLINE void +ptw32_filetime_to_timespec (const FILETIME * ft, struct timespec *ts) + /* + * ------------------------------------------------------------------- + * converts FILETIME (as set by GetSystemTimeAsFileTime), where the time is + * expressed in 100 nanoseconds from Jan 1, 1601, + * into struct timespec + * where the time is expressed in seconds and nanoseconds from Jan 1, 1970. + * ------------------------------------------------------------------- + */ +{ + ts->tv_sec = + (int) ((*(int64_t *) ft - PTW32_TIMESPEC_TO_FILETIME_OFFSET) / 10000000); + ts->tv_nsec = + (int) ((*(int64_t *) ft - PTW32_TIMESPEC_TO_FILETIME_OFFSET - + ((int64_t) ts->tv_sec * (int64_t) 10000000)) * 100); +} + +#endif /* NEED_FTIME */ diff --git a/w32-pthreads/ptw32_tkAssocCreate.c b/w32-pthreads/ptw32_tkAssocCreate.c new file mode 100644 index 000000000..50d6c500c --- /dev/null +++ b/w32-pthreads/ptw32_tkAssocCreate.c @@ -0,0 +1,118 @@ +/* + * ptw32_tkAssocCreate.c + * + * Description: + * This translation unit implements routines which are private to + * the implementation and may be used throughout it. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +int +ptw32_tkAssocCreate (ptw32_thread_t * sp, pthread_key_t key) + /* + * ------------------------------------------------------------------- + * This routine creates an association that + * is unique for the given (thread,key) combination.The association + * is referenced by both the thread and the key. + * This association allows us to determine what keys the + * current thread references and what threads a given key + * references. + * See the detailed description + * at the beginning of this file for further details. + * + * Notes: + * 1) New associations are pushed to the beginning of the + * chain so that the internal ptw32_selfThreadKey association + * is always last, thus allowing selfThreadExit to + * be implicitly called last by pthread_exit. + * 2) + * + * Parameters: + * thread + * current running thread. + * key + * key on which to create an association. + * Returns: + * 0 - if successful, + * ENOMEM - not enough memory to create assoc or other object + * EINVAL - an internal error occurred + * ENOSYS - an internal error occurred + * ------------------------------------------------------------------- + */ +{ + ThreadKeyAssoc *assoc; + + /* + * Have to create an association and add it + * to both the key and the thread. + * + * Both key->keyLock and thread->threadLock are locked before + * entry to this routine. + */ + assoc = (ThreadKeyAssoc *) calloc (1, sizeof (*assoc)); + + if (assoc == NULL) + { + return ENOMEM; + } + + assoc->thread = sp; + assoc->key = key; + + /* + * Register assoc with key + */ + assoc->prevThread = NULL; + assoc->nextThread = (ThreadKeyAssoc *) key->threads; + if (assoc->nextThread != NULL) + { + assoc->nextThread->prevThread = assoc; + } + key->threads = (void *) assoc; + + /* + * Register assoc with thread + */ + assoc->prevKey = NULL; + assoc->nextKey = (ThreadKeyAssoc *) sp->keys; + if (assoc->nextKey != NULL) + { + assoc->nextKey->prevKey = assoc; + } + sp->keys = (void *) assoc; + + return (0); + +} /* ptw32_tkAssocCreate */ diff --git a/w32-pthreads/ptw32_tkAssocDestroy.c b/w32-pthreads/ptw32_tkAssocDestroy.c new file mode 100644 index 000000000..fedebf593 --- /dev/null +++ b/w32-pthreads/ptw32_tkAssocDestroy.c @@ -0,0 +1,114 @@ +/* + * ptw32_tkAssocDestroy.c + * + * Description: + * This translation unit implements routines which are private to + * the implementation and may be used throughout it. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +void +ptw32_tkAssocDestroy (ThreadKeyAssoc * assoc) + /* + * ------------------------------------------------------------------- + * This routine releases all resources for the given ThreadKeyAssoc + * once it is no longer being referenced + * ie) either the key or thread has stopped referencing it. + * + * Parameters: + * assoc + * an instance of ThreadKeyAssoc. + * Returns: + * N/A + * ------------------------------------------------------------------- + */ +{ + + /* + * Both key->keyLock and thread->threadLock are locked before + * entry to this routine. + */ + if (assoc != NULL) + { + ThreadKeyAssoc * prev, * next; + + /* Remove assoc from thread's keys chain */ + prev = assoc->prevKey; + next = assoc->nextKey; + if (prev != NULL) + { + prev->nextKey = next; + } + if (next != NULL) + { + next->prevKey = prev; + } + + if (assoc->thread->keys == assoc) + { + /* We're at the head of the thread's keys chain */ + assoc->thread->keys = next; + } + if (assoc->thread->nextAssoc == assoc) + { + /* + * Thread is exiting and we're deleting the assoc to be processed next. + * Hand thread the assoc after this one. + */ + assoc->thread->nextAssoc = next; + } + + /* Remove assoc from key's threads chain */ + prev = assoc->prevThread; + next = assoc->nextThread; + if (prev != NULL) + { + prev->nextThread = next; + } + if (next != NULL) + { + next->prevThread = prev; + } + + if (assoc->key->threads == assoc) + { + /* We're at the head of the key's threads chain */ + assoc->key->threads = next; + } + + free (assoc); + } + +} /* ptw32_tkAssocDestroy */ diff --git a/w32-pthreads/rwlock.c b/w32-pthreads/rwlock.c new file mode 100644 index 000000000..4a3cd2594 --- /dev/null +++ b/w32-pthreads/rwlock.c @@ -0,0 +1,51 @@ +/* + * rwlock.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "ptw32_rwlock_check_need_init.c" +#include "ptw32_rwlock_cancelwrwait.c" +#include "pthread_rwlock_init.c" +#include "pthread_rwlock_destroy.c" +#include "pthread_rwlockattr_init.c" +#include "pthread_rwlockattr_destroy.c" +#include "pthread_rwlockattr_getpshared.c" +#include "pthread_rwlockattr_setpshared.c" +#include "pthread_rwlock_rdlock.c" +#include "pthread_rwlock_timedrdlock.c" +#include "pthread_rwlock_wrlock.c" +#include "pthread_rwlock_timedwrlock.c" +#include "pthread_rwlock_unlock.c" +#include "pthread_rwlock_tryrdlock.c" +#include "pthread_rwlock_trywrlock.c" diff --git a/w32-pthreads/sched.c b/w32-pthreads/sched.c new file mode 100644 index 000000000..ed30ea7b2 --- /dev/null +++ b/w32-pthreads/sched.c @@ -0,0 +1,53 @@ +/* + * sched.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +#include "pthread_attr_setschedpolicy.c" +#include "pthread_attr_getschedpolicy.c" +#include "pthread_attr_setschedparam.c" +#include "pthread_attr_getschedparam.c" +#include "pthread_attr_setinheritsched.c" +#include "pthread_attr_getinheritsched.c" +#include "pthread_setschedparam.c" +#include "pthread_getschedparam.c" +#include "sched_get_priority_max.c" +#include "sched_get_priority_min.c" +#include "sched_setscheduler.c" +#include "sched_getscheduler.c" +#include "sched_yield.c" diff --git a/w32-pthreads/sched.h b/w32-pthreads/sched.h new file mode 100644 index 000000000..9a5483302 --- /dev/null +++ b/w32-pthreads/sched.h @@ -0,0 +1,183 @@ +/* + * Module: sched.h + * + * Purpose: + * Provides an implementation of POSIX realtime extensions + * as defined in + * + * POSIX 1003.1b-1993 (POSIX.1b) + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ +#if !defined(_SCHED_H) +#define _SCHED_H + +#undef PTW32_SCHED_LEVEL + +#if defined(_POSIX_SOURCE) +#define PTW32_SCHED_LEVEL 0 +/* Early POSIX */ +#endif + +#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309 +#undef PTW32_SCHED_LEVEL +#define PTW32_SCHED_LEVEL 1 +/* Include 1b, 1c and 1d */ +#endif + +#if defined(INCLUDE_NP) +#undef PTW32_SCHED_LEVEL +#define PTW32_SCHED_LEVEL 2 +/* Include Non-Portable extensions */ +#endif + +#define PTW32_SCHED_LEVEL_MAX 3 + +#if ( defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112 ) || !defined(PTW32_SCHED_LEVEL) +#define PTW32_SCHED_LEVEL PTW32_SCHED_LEVEL_MAX +/* Include everything */ +#endif + + +#if defined(__GNUC__) && !defined(__declspec) +# error Please upgrade your GNU compiler to one that supports __declspec. +#endif + +/* + * When building the library, you should define PTW32_BUILD so that + * the variables/functions are exported correctly. When using the library, + * do NOT define PTW32_BUILD, and then the variables/functions will + * be imported correctly. + */ +#if !defined(PTW32_STATIC_LIB) +# if defined(PTW32_BUILD) +# define PTW32_DLLPORT __declspec (dllexport) +# else +# define PTW32_DLLPORT +# endif +#else +# define PTW32_DLLPORT +#endif + +/* + * This is a duplicate of what is in the autoconf config.h, + * which is only used when building the pthread-win32 libraries. + */ + +#if !defined(PTW32_CONFIG_H) +# if defined(WINCE) +# define NEED_ERRNO +# define NEED_SEM +# endif +# if defined(__MINGW64__) +# define HAVE_STRUCT_TIMESPEC +# define HAVE_MODE_T +# elif defined(_UWIN) || defined(__MINGW32__) +# define HAVE_MODE_T +# endif +#endif + +/* + * + */ + +#if PTW32_SCHED_LEVEL >= PTW32_SCHED_LEVEL_MAX +#if defined(NEED_ERRNO) +#include "need_errno.h" +#else +#include +#endif +#endif /* PTW32_SCHED_LEVEL >= PTW32_SCHED_LEVEL_MAX */ + +#if (defined(__MINGW64__) || defined(__MINGW32__)) || defined(_UWIN) +# if PTW32_SCHED_LEVEL >= PTW32_SCHED_LEVEL_MAX +/* For pid_t */ +# include +/* Required by Unix 98 */ +# include +# else + typedef int pid_t; +# endif +#else + typedef int pid_t; +#endif + +/* Thread scheduling policies */ + +enum { + SCHED_OTHER = 0, + SCHED_FIFO, + SCHED_RR, + SCHED_MIN = SCHED_OTHER, + SCHED_MAX = SCHED_RR +}; + +struct sched_param { + int sched_priority; +}; + +#if defined(__cplusplus) +extern "C" +{ +#endif /* __cplusplus */ + +PTW32_DLLPORT int __cdecl sched_yield (void); + +PTW32_DLLPORT int __cdecl sched_get_priority_min (int policy); + +PTW32_DLLPORT int __cdecl sched_get_priority_max (int policy); + +PTW32_DLLPORT int __cdecl sched_setscheduler (pid_t pid, int policy); + +PTW32_DLLPORT int __cdecl sched_getscheduler (pid_t pid); + +/* + * Note that this macro returns ENOTSUP rather than + * ENOSYS as might be expected. However, returning ENOSYS + * should mean that sched_get_priority_{min,max} are + * not implemented as well as sched_rr_get_interval. + * This is not the case, since we just don't support + * round-robin scheduling. Therefore I have chosen to + * return the same value as sched_setscheduler when + * SCHED_RR is passed to it. + */ +#define sched_rr_get_interval(_pid, _interval) \ + ( errno = ENOTSUP, (int) -1 ) + + +#if defined(__cplusplus) +} /* End of extern "C" */ +#endif /* __cplusplus */ + +#undef PTW32_SCHED_LEVEL +#undef PTW32_SCHED_LEVEL_MAX + +#endif /* !_SCHED_H */ + diff --git a/w32-pthreads/sched_get_priority_max.c b/w32-pthreads/sched_get_priority_max.c new file mode 100644 index 000000000..cabf2320a --- /dev/null +++ b/w32-pthreads/sched_get_priority_max.c @@ -0,0 +1,134 @@ +/* + * sched_get_priority_max.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +/* + * On Windows98, THREAD_PRIORITY_LOWEST is (-2) and + * THREAD_PRIORITY_HIGHEST is 2, and everything works just fine. + * + * On WinCE 3.0, it so happen that THREAD_PRIORITY_LOWEST is 5 + * and THREAD_PRIORITY_HIGHEST is 1 (yes, I know, it is funny: + * highest priority use smaller numbers) and the following happens: + * + * sched_get_priority_min() returns 5 + * sched_get_priority_max() returns 1 + * + * The following table shows the base priority levels for combinations + * of priority class and priority value in Win32. + * + * Process Priority Class Thread Priority Level + * ----------------------------------------------------------------- + * 1 IDLE_PRIORITY_CLASS THREAD_PRIORITY_IDLE + * 1 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_IDLE + * 1 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_IDLE + * 1 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_IDLE + * 1 HIGH_PRIORITY_CLASS THREAD_PRIORITY_IDLE + * 2 IDLE_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 3 IDLE_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 4 IDLE_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 4 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 5 IDLE_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 5 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 5 Background NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 6 IDLE_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 6 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 6 Background NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 7 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 7 Background NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 7 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 8 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 8 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 8 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 8 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 9 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 9 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 9 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 10 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 10 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 11 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 11 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 11 HIGH_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 12 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 12 HIGH_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 13 HIGH_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 14 HIGH_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 15 HIGH_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 15 HIGH_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + * 15 IDLE_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + * 15 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + * 15 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + * 15 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + * 16 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_IDLE + * 17 REALTIME_PRIORITY_CLASS -7 + * 18 REALTIME_PRIORITY_CLASS -6 + * 19 REALTIME_PRIORITY_CLASS -5 + * 20 REALTIME_PRIORITY_CLASS -4 + * 21 REALTIME_PRIORITY_CLASS -3 + * 22 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 23 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 24 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 25 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 26 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 27 REALTIME_PRIORITY_CLASS 3 + * 28 REALTIME_PRIORITY_CLASS 4 + * 29 REALTIME_PRIORITY_CLASS 5 + * 30 REALTIME_PRIORITY_CLASS 6 + * 31 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + * + * Windows NT: Values -7, -6, -5, -4, -3, 3, 4, 5, and 6 are not supported. + */ + + +int +sched_get_priority_max (int policy) +{ + if (policy < SCHED_MIN || policy > SCHED_MAX) + { + errno = EINVAL; + return -1; + } + +#if (THREAD_PRIORITY_LOWEST > THREAD_PRIORITY_NORMAL) + /* WinCE? */ + return PTW32_MAX (THREAD_PRIORITY_IDLE, THREAD_PRIORITY_TIME_CRITICAL); +#else + /* This is independent of scheduling policy in Win32. */ + return PTW32_MAX (THREAD_PRIORITY_IDLE, THREAD_PRIORITY_TIME_CRITICAL); +#endif +} diff --git a/w32-pthreads/sched_get_priority_min.c b/w32-pthreads/sched_get_priority_min.c new file mode 100644 index 000000000..9c4f8591e --- /dev/null +++ b/w32-pthreads/sched_get_priority_min.c @@ -0,0 +1,135 @@ +/* + * sched_get_priority_min.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +/* + * On Windows98, THREAD_PRIORITY_LOWEST is (-2) and + * THREAD_PRIORITY_HIGHEST is 2, and everything works just fine. + * + * On WinCE 3.0, it so happen that THREAD_PRIORITY_LOWEST is 5 + * and THREAD_PRIORITY_HIGHEST is 1 (yes, I know, it is funny: + * highest priority use smaller numbers) and the following happens: + * + * sched_get_priority_min() returns 5 + * sched_get_priority_max() returns 1 + * + * The following table shows the base priority levels for combinations + * of priority class and priority value in Win32. + * + * Process Priority Class Thread Priority Level + * ----------------------------------------------------------------- + * 1 IDLE_PRIORITY_CLASS THREAD_PRIORITY_IDLE + * 1 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_IDLE + * 1 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_IDLE + * 1 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_IDLE + * 1 HIGH_PRIORITY_CLASS THREAD_PRIORITY_IDLE + * 2 IDLE_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 3 IDLE_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 4 IDLE_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 4 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 5 IDLE_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 5 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 5 Background NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 6 IDLE_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 6 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 6 Background NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 7 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 7 Background NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 7 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 8 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 8 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 8 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 8 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 9 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 9 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 9 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 10 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 10 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 11 Foreground NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 11 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 11 HIGH_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 12 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 12 HIGH_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 13 HIGH_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 14 HIGH_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 15 HIGH_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 15 HIGH_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + * 15 IDLE_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + * 15 BELOW_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + * 15 NORMAL_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + * 15 ABOVE_NORMAL_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + * 16 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_IDLE + * 17 REALTIME_PRIORITY_CLASS -7 + * 18 REALTIME_PRIORITY_CLASS -6 + * 19 REALTIME_PRIORITY_CLASS -5 + * 20 REALTIME_PRIORITY_CLASS -4 + * 21 REALTIME_PRIORITY_CLASS -3 + * 22 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_LOWEST + * 23 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_BELOW_NORMAL + * 24 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_NORMAL + * 25 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_ABOVE_NORMAL + * 26 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_HIGHEST + * 27 REALTIME_PRIORITY_CLASS 3 + * 28 REALTIME_PRIORITY_CLASS 4 + * 29 REALTIME_PRIORITY_CLASS 5 + * 30 REALTIME_PRIORITY_CLASS 6 + * 31 REALTIME_PRIORITY_CLASS THREAD_PRIORITY_TIME_CRITICAL + * + * Windows NT: Values -7, -6, -5, -4, -3, 3, 4, 5, and 6 are not supported. + * + */ + + +int +sched_get_priority_min (int policy) +{ + if (policy < SCHED_MIN || policy > SCHED_MAX) + { + errno = EINVAL; + return -1; + } + +#if (THREAD_PRIORITY_LOWEST > THREAD_PRIORITY_NORMAL) + /* WinCE? */ + return PTW32_MIN (THREAD_PRIORITY_IDLE, THREAD_PRIORITY_TIME_CRITICAL); +#else + /* This is independent of scheduling policy in Win32. */ + return PTW32_MIN (THREAD_PRIORITY_IDLE, THREAD_PRIORITY_TIME_CRITICAL); +#endif +} diff --git a/w32-pthreads/sched_getscheduler.c b/w32-pthreads/sched_getscheduler.c new file mode 100644 index 000000000..8769c15e5 --- /dev/null +++ b/w32-pthreads/sched_getscheduler.c @@ -0,0 +1,71 @@ +/* + * sched_getscheduler.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +int +sched_getscheduler (pid_t pid) +{ + /* + * Win32 only has one policy which we call SCHED_OTHER. + * However, we try to provide other valid side-effects + * such as EPERM and ESRCH errors. + */ + if (0 != pid) + { + int selfPid = (int) GetCurrentProcessId (); + + if (pid != selfPid) + { + HANDLE h = + OpenProcess (PROCESS_QUERY_INFORMATION, PTW32_FALSE, (DWORD) pid); + + if (NULL == h) + { + errno = + (GetLastError () == + (0xFF & ERROR_ACCESS_DENIED)) ? EPERM : ESRCH; + return -1; + } + else + CloseHandle(h); + } + } + + return SCHED_OTHER; +} diff --git a/w32-pthreads/sched_setscheduler.c b/w32-pthreads/sched_setscheduler.c new file mode 100644 index 000000000..869131637 --- /dev/null +++ b/w32-pthreads/sched_setscheduler.c @@ -0,0 +1,83 @@ +/* + * sched_setscheduler.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +int +sched_setscheduler (pid_t pid, int policy) +{ + /* + * Win32 only has one policy which we call SCHED_OTHER. + * However, we try to provide other valid side-effects + * such as EPERM and ESRCH errors. Choosing to check + * for a valid policy last allows us to get the most value out + * of this function. + */ + if (0 != pid) + { + int selfPid = (int) GetCurrentProcessId (); + + if (pid != selfPid) + { + HANDLE h = + OpenProcess (PROCESS_SET_INFORMATION, PTW32_FALSE, (DWORD) pid); + + if (NULL == h) + { + errno = + (GetLastError () == + (0xFF & ERROR_ACCESS_DENIED)) ? EPERM : ESRCH; + return -1; + } + else + CloseHandle(h); + } + } + + if (SCHED_OTHER != policy) + { + errno = ENOSYS; + return -1; + } + + /* + * Don't set anything because there is nothing to set. + * Just return the current (the only possible) value. + */ + return SCHED_OTHER; +} diff --git a/w32-pthreads/sched_yield.c b/w32-pthreads/sched_yield.c new file mode 100644 index 000000000..6ac5ed926 --- /dev/null +++ b/w32-pthreads/sched_yield.c @@ -0,0 +1,71 @@ +/* + * sched_yield.c + * + * Description: + * POSIX thread functions that deal with thread scheduling. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" +#include "sched.h" + +int +sched_yield (void) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function indicates that the calling thread is + * willing to give up some time slices to other threads. + * + * PARAMETERS + * N/A + * + * + * DESCRIPTION + * This function indicates that the calling thread is + * willing to give up some time slices to other threads. + * NOTE: Since this is part of POSIX 1003.1b + * (realtime extensions), it is defined as returning + * -1 if an error occurs and sets errno to the actual + * error. + * + * RESULTS + * 0 successfully created semaphore, + * ENOSYS sched_yield not supported, + * + * ------------------------------------------------------ + */ +{ + Sleep (0); + + return 0; +} diff --git a/w32-pthreads/sem_close.c b/w32-pthreads/sem_close.c new file mode 100644 index 000000000..6d7280f29 --- /dev/null +++ b/w32-pthreads/sem_close.c @@ -0,0 +1,58 @@ +/* + * ------------------------------------------------------------- + * + * Module: sem_close.c + * + * Purpose: + * Semaphores aren't actually part of the PThreads standard. + * They are defined by the POSIX Standard: + * + * POSIX 1003.1b-1993 (POSIX.1b) + * + * ------------------------------------------------------------- + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "semaphore.h" +#include "implement.h" + +/* ignore warning "unreferenced formal parameter" */ +#if defined(_MSC_VER) +#pragma warning( disable : 4100 ) +#endif + +int +sem_close (sem_t * sem) +{ + errno = ENOSYS; + return -1; +} /* sem_close */ diff --git a/w32-pthreads/sem_destroy.c b/w32-pthreads/sem_destroy.c new file mode 100644 index 000000000..6c98e80b9 --- /dev/null +++ b/w32-pthreads/sem_destroy.c @@ -0,0 +1,144 @@ +/* + * ------------------------------------------------------------- + * + * Module: sem_destroy.c + * + * Purpose: + * Semaphores aren't actually part of the PThreads standard. + * They are defined by the POSIX Standard: + * + * POSIX 1003.1b-1993 (POSIX.1b) + * + * ------------------------------------------------------------- + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "semaphore.h" +#include "implement.h" + + +int +sem_destroy (sem_t * sem) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function destroys an unnamed semaphore. + * + * PARAMETERS + * sem + * pointer to an instance of sem_t + * + * DESCRIPTION + * This function destroys an unnamed semaphore. + * + * RESULTS + * 0 successfully destroyed semaphore, + * -1 failed, error in errno + * ERRNO + * EINVAL 'sem' is not a valid semaphore, + * ENOSYS semaphores are not supported, + * EBUSY threads (or processes) are currently + * blocked on 'sem' + * + * ------------------------------------------------------ + */ +{ + int result = 0; + sem_t s = NULL; + + if (sem == NULL || *sem == NULL) + { + result = EINVAL; + } + else + { + s = *sem; + + if ((result = pthread_mutex_lock (&s->lock)) == 0) + { + if (s->value < 0) + { + (void) pthread_mutex_unlock (&s->lock); + result = EBUSY; + } + else + { + /* There are no threads currently blocked on this semaphore. */ + + if (!CloseHandle (s->sem)) + { + (void) pthread_mutex_unlock (&s->lock); + result = EINVAL; + } + else + { + /* + * Invalidate the semaphore handle when we have the lock. + * Other sema operations should test this after acquiring the lock + * to check that the sema is still valid, i.e. before performing any + * operations. This may only be necessary before the sema op routine + * returns so that the routine can return EINVAL - e.g. if setting + * s->value to SEM_VALUE_MAX below does force a fall-through. + */ + *sem = NULL; + + /* Prevent anyone else actually waiting on or posting this sema. + */ + s->value = SEM_VALUE_MAX; + + (void) pthread_mutex_unlock (&s->lock); + + do + { + /* Give other threads a chance to run and exit any sema op + * routines. Due to the SEM_VALUE_MAX value, if sem_post or + * sem_wait were blocked by us they should fall through. + */ + Sleep(0); + } + while (pthread_mutex_destroy (&s->lock) == EBUSY); + } + } + } + } + + if (result != 0) + { + errno = result; + return -1; + } + + free (s); + + return 0; + +} /* sem_destroy */ diff --git a/w32-pthreads/sem_getvalue.c b/w32-pthreads/sem_getvalue.c new file mode 100644 index 000000000..baafb02cf --- /dev/null +++ b/w32-pthreads/sem_getvalue.c @@ -0,0 +1,110 @@ +/* + * ------------------------------------------------------------- + * + * Module: sem_getvalue.c + * + * Purpose: + * Semaphores aren't actually part of PThreads. + * They are defined by the POSIX Standard: + * + * POSIX 1003.1-2001 + * + * ------------------------------------------------------------- + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "semaphore.h" +#include "implement.h" + + +int +sem_getvalue (sem_t * sem, int *sval) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function stores the current count value of the + * semaphore. + * RESULTS + * + * Return value + * + * 0 sval has been set. + * -1 failed, error in errno + * + * in global errno + * + * EINVAL 'sem' is not a valid semaphore, + * ENOSYS this function is not supported, + * + * + * PARAMETERS + * + * sem pointer to an instance of sem_t + * + * sval pointer to int. + * + * DESCRIPTION + * This function stores the current count value of the semaphore + * pointed to by sem in the int pointed to by sval. + */ +{ + if (sem == NULL || *sem == NULL || sval == NULL) + { + errno = EINVAL; + return -1; + } + else + { + long value; + register sem_t s = *sem; + int result = 0; + + if ((result = pthread_mutex_lock(&s->lock)) == 0) + { + /* See sem_destroy.c + */ + if (*sem == NULL) + { + (void) pthread_mutex_unlock (&s->lock); + errno = EINVAL; + return -1; + } + + value = s->value; + (void) pthread_mutex_unlock(&s->lock); + *sval = value; + } + + return result; + } + +} /* sem_getvalue */ diff --git a/w32-pthreads/sem_init.c b/w32-pthreads/sem_init.c new file mode 100644 index 000000000..f682f4b20 --- /dev/null +++ b/w32-pthreads/sem_init.c @@ -0,0 +1,169 @@ +/* + * ------------------------------------------------------------- + * + * Module: sem_init.c + * + * Purpose: + * Semaphores aren't actually part of PThreads. + * They are defined by the POSIX Standard: + * + * POSIX 1003.1-2001 + * + * ------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "semaphore.h" +#include "implement.h" + +int +sem_init (sem_t * sem, int pshared, unsigned int value) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function initializes a semaphore. The + * initial value of the semaphore is 'value' + * + * PARAMETERS + * sem + * pointer to an instance of sem_t + * + * pshared + * if zero, this semaphore may only be shared between + * threads in the same process. + * if nonzero, the semaphore can be shared between + * processes + * + * value + * initial value of the semaphore counter + * + * DESCRIPTION + * This function initializes a semaphore. The + * initial value of the semaphore is set to 'value'. + * + * RESULTS + * 0 successfully created semaphore, + * -1 failed, error in errno + * ERRNO + * EINVAL 'sem' is not a valid semaphore, or + * 'value' >= SEM_VALUE_MAX + * ENOMEM out of memory, + * ENOSPC a required resource has been exhausted, + * ENOSYS semaphores are not supported, + * EPERM the process lacks appropriate privilege + * + * ------------------------------------------------------ + */ +{ + int result = 0; + sem_t s = NULL; + + if (pshared != 0) + { + /* + * Creating a semaphore that can be shared between + * processes + */ + result = EPERM; + } + else if (value > (unsigned int)SEM_VALUE_MAX) + { + result = EINVAL; + } + else + { + s = (sem_t) calloc (1, sizeof (*s)); + + if (NULL == s) + { + result = ENOMEM; + } + else + { + + s->value = value; + if (pthread_mutex_init(&s->lock, NULL) == 0) + { + +#if defined(NEED_SEM) + + s->sem = CreateEvent (NULL, + PTW32_FALSE, /* auto (not manual) reset */ + PTW32_FALSE, /* initial state is unset */ + NULL); + + if (0 == s->sem) + { + free (s); + (void) pthread_mutex_destroy(&s->lock); + result = ENOSPC; + } + else + { + s->leftToUnblock = 0; + } + +#else /* NEED_SEM */ + + if ((s->sem = CreateSemaphore (NULL, /* Always NULL */ + (long) 0, /* Force threads to wait */ + (long) SEM_VALUE_MAX, /* Maximum value */ + NULL)) == 0) /* Name */ + { + (void) pthread_mutex_destroy(&s->lock); + result = ENOSPC; + } + +#endif /* NEED_SEM */ + + } + else + { + result = ENOSPC; + } + + if (result != 0) + { + free(s); + } + } + } + + if (result != 0) + { + errno = result; + return -1; + } + + *sem = s; + + return 0; + +} /* sem_init */ diff --git a/w32-pthreads/sem_open.c b/w32-pthreads/sem_open.c new file mode 100644 index 000000000..fb1cc541f --- /dev/null +++ b/w32-pthreads/sem_open.c @@ -0,0 +1,58 @@ +/* + * ------------------------------------------------------------- + * + * Module: sem_open.c + * + * Purpose: + * Semaphores aren't actually part of the PThreads standard. + * They are defined by the POSIX Standard: + * + * POSIX 1003.1b-1993 (POSIX.1b) + * + * ------------------------------------------------------------- + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "semaphore.h" +#include "implement.h" + +/* ignore warning "unreferenced formal parameter" */ +#if defined(_MSC_VER) +#pragma warning( disable : 4100 ) +#endif + +int +sem_open (const char *name, int oflag, mode_t mode, unsigned int value) +{ + errno = ENOSYS; + return -1; +} /* sem_open */ diff --git a/w32-pthreads/sem_post.c b/w32-pthreads/sem_post.c new file mode 100644 index 000000000..34832527b --- /dev/null +++ b/w32-pthreads/sem_post.c @@ -0,0 +1,128 @@ +/* + * ------------------------------------------------------------- + * + * Module: sem_post.c + * + * Purpose: + * Semaphores aren't actually part of the PThreads standard. + * They are defined by the POSIX Standard: + * + * POSIX 1003.1b-1993 (POSIX.1b) + * + * ------------------------------------------------------------- + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "semaphore.h" +#include "implement.h" + + +int +sem_post (sem_t * sem) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function posts a wakeup to a semaphore. + * + * PARAMETERS + * sem + * pointer to an instance of sem_t + * + * DESCRIPTION + * This function posts a wakeup to a semaphore. If there + * are waiting threads (or processes), one is awakened; + * otherwise, the semaphore value is incremented by one. + * + * RESULTS + * 0 successfully posted semaphore, + * -1 failed, error in errno + * ERRNO + * EINVAL 'sem' is not a valid semaphore, + * ENOSYS semaphores are not supported, + * ERANGE semaphore count is too big + * + * ------------------------------------------------------ + */ +{ + int result = 0; + sem_t s = *sem; + + if (s == NULL) + { + result = EINVAL; + } + else if ((result = pthread_mutex_lock (&s->lock)) == 0) + { + /* See sem_destroy.c + */ + if (*sem == NULL) + { + (void) pthread_mutex_unlock (&s->lock); + result = EINVAL; + return -1; + } + + if (s->value < SEM_VALUE_MAX) + { +#if defined(NEED_SEM) + if (++s->value <= 0 + && !SetEvent(s->sem)) + { + s->value--; + result = EINVAL; + } +#else + if (++s->value <= 0 + && !ReleaseSemaphore (s->sem, 1, NULL)) + { + s->value--; + result = EINVAL; + } +#endif /* NEED_SEM */ + } + else + { + result = ERANGE; + } + + (void) pthread_mutex_unlock (&s->lock); + } + + if (result != 0) + { + errno = result; + return -1; + } + + return 0; + +} /* sem_post */ diff --git a/w32-pthreads/sem_post_multiple.c b/w32-pthreads/sem_post_multiple.c new file mode 100644 index 000000000..44c168c6c --- /dev/null +++ b/w32-pthreads/sem_post_multiple.c @@ -0,0 +1,142 @@ +/* + * ------------------------------------------------------------- + * + * Module: sem_post_multiple.c + * + * Purpose: + * Semaphores aren't actually part of the PThreads standard. + * They are defined by the POSIX Standard: + * + * POSIX 1003.1b-1993 (POSIX.1b) + * + * ------------------------------------------------------------- + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "semaphore.h" +#include "implement.h" + + +int +sem_post_multiple (sem_t * sem, int count) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function posts multiple wakeups to a semaphore. + * + * PARAMETERS + * sem + * pointer to an instance of sem_t + * + * count + * counter, must be greater than zero. + * + * DESCRIPTION + * This function posts multiple wakeups to a semaphore. If there + * are waiting threads (or processes), n <= count are awakened; + * the semaphore value is incremented by count - n. + * + * RESULTS + * 0 successfully posted semaphore, + * -1 failed, error in errno + * ERRNO + * EINVAL 'sem' is not a valid semaphore + * or count is less than or equal to zero. + * ERANGE semaphore count is too big + * + * ------------------------------------------------------ + */ +{ + int result = 0; + long waiters; + sem_t s = *sem; + + if (s == NULL || count <= 0) + { + result = EINVAL; + } + else if ((result = pthread_mutex_lock (&s->lock)) == 0) + { + /* See sem_destroy.c + */ + if (*sem == NULL) + { + (void) pthread_mutex_unlock (&s->lock); + result = EINVAL; + return -1; + } + + if (s->value <= (SEM_VALUE_MAX - count)) + { + waiters = -s->value; + s->value += count; + if (waiters > 0) + { +#if defined(NEED_SEM) + if (SetEvent(s->sem)) + { + waiters--; + s->leftToUnblock += count - 1; + if (s->leftToUnblock > waiters) + { + s->leftToUnblock = waiters; + } + } +#else + if (ReleaseSemaphore (s->sem, (waiters<=count)?waiters:count, 0)) + { + /* No action */ + } +#endif + else + { + s->value -= count; + result = EINVAL; + } + } + } + else + { + result = ERANGE; + } + (void) pthread_mutex_unlock (&s->lock); + } + + if (result != 0) + { + errno = result; + return -1; + } + + return 0; + +} /* sem_post_multiple */ diff --git a/w32-pthreads/sem_timedwait.c b/w32-pthreads/sem_timedwait.c new file mode 100644 index 000000000..638431cf1 --- /dev/null +++ b/w32-pthreads/sem_timedwait.c @@ -0,0 +1,238 @@ +/* + * ------------------------------------------------------------- + * + * Module: sem_timedwait.c + * + * Purpose: + * Semaphores aren't actually part of the PThreads standard. + * They are defined by the POSIX Standard: + * + * POSIX 1003.1b-1993 (POSIX.1b) + * + * ------------------------------------------------------------- + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "semaphore.h" +#include "implement.h" + + +typedef struct { + sem_t sem; + int * resultPtr; +} sem_timedwait_cleanup_args_t; + + +static void PTW32_CDECL +ptw32_sem_timedwait_cleanup (void * args) +{ + sem_timedwait_cleanup_args_t * a = (sem_timedwait_cleanup_args_t *)args; + sem_t s = a->sem; + + if (pthread_mutex_lock (&s->lock) == 0) + { + /* + * We either timed out or were cancelled. + * If someone has posted between then and now we try to take the semaphore. + * Otherwise the semaphore count may be wrong after we + * return. In the case of a cancellation, it is as if we + * were cancelled just before we return (after taking the semaphore) + * which is ok. + */ + if (WaitForSingleObject(s->sem, 0) == WAIT_OBJECT_0) + { + /* We got the semaphore on the second attempt */ + *(a->resultPtr) = 0; + } + else + { + /* Indicate we're no longer waiting */ + s->value++; +#if defined(NEED_SEM) + if (s->value > 0) + { + s->leftToUnblock = 0; + } +#else + /* + * Don't release the W32 sema, it doesn't need adjustment + * because it doesn't record the number of waiters. + */ +#endif + } + (void) pthread_mutex_unlock (&s->lock); + } +} + + +int +sem_timedwait (sem_t * sem, const struct timespec *abstime) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function waits on a semaphore possibly until + * 'abstime' time. + * + * PARAMETERS + * sem + * pointer to an instance of sem_t + * + * abstime + * pointer to an instance of struct timespec + * + * DESCRIPTION + * This function waits on a semaphore. If the + * semaphore value is greater than zero, it decreases + * its value by one. If the semaphore value is zero, then + * the calling thread (or process) is blocked until it can + * successfully decrease the value or until interrupted by + * a signal. + * + * If 'abstime' is a NULL pointer then this function will + * block until it can successfully decrease the value or + * until interrupted by a signal. + * + * RESULTS + * 0 successfully decreased semaphore, + * -1 failed, error in errno + * ERRNO + * EINVAL 'sem' is not a valid semaphore, + * ENOSYS semaphores are not supported, + * EINTR the function was interrupted by a signal, + * EDEADLK a deadlock condition was detected. + * ETIMEDOUT abstime elapsed before success. + * + * ------------------------------------------------------ + */ +{ + int result = 0; + sem_t s = *sem; + + pthread_testcancel(); + + if (sem == NULL) + { + result = EINVAL; + } + else + { + DWORD milliseconds; + + if (abstime == NULL) + { + milliseconds = INFINITE; + } + else + { + /* + * Calculate timeout as milliseconds from current system time. + */ + milliseconds = ptw32_relmillisecs (abstime); + } + + if ((result = pthread_mutex_lock (&s->lock)) == 0) + { + int v; + + /* See sem_destroy.c + */ + if (*sem == NULL) + { + (void) pthread_mutex_unlock (&s->lock); + errno = EINVAL; + return -1; + } + + v = --s->value; + (void) pthread_mutex_unlock (&s->lock); + + if (v < 0) + { +#if defined(NEED_SEM) + int timedout; +#endif + sem_timedwait_cleanup_args_t cleanup_args; + + cleanup_args.sem = s; + cleanup_args.resultPtr = &result; + +#if defined(_MSC_VER) && _MSC_VER < 1400 +#pragma inline_depth(0) +#endif + /* Must wait */ + pthread_cleanup_push(ptw32_sem_timedwait_cleanup, (void *) &cleanup_args); +#if defined(NEED_SEM) + timedout = +#endif + result = pthreadCancelableTimedWait (s->sem, milliseconds); + pthread_cleanup_pop(result); +#if defined(_MSC_VER) && _MSC_VER < 1400 +#pragma inline_depth() +#endif + +#if defined(NEED_SEM) + + if (!timedout && pthread_mutex_lock (&s->lock) == 0) + { + if (*sem == NULL) + { + (void) pthread_mutex_unlock (&s->lock); + errno = EINVAL; + return -1; + } + + if (s->leftToUnblock > 0) + { + --s->leftToUnblock; + SetEvent(s->sem); + } + (void) pthread_mutex_unlock (&s->lock); + } + +#endif /* NEED_SEM */ + + } + } + + } + + if (result != 0) + { + + errno = result; + return -1; + + } + + return 0; + +} /* sem_timedwait */ diff --git a/w32-pthreads/sem_trywait.c b/w32-pthreads/sem_trywait.c new file mode 100644 index 000000000..63614ba2b --- /dev/null +++ b/w32-pthreads/sem_trywait.c @@ -0,0 +1,117 @@ +/* + * ------------------------------------------------------------- + * + * Module: sem_trywait.c + * + * Purpose: + * Semaphores aren't actually part of the PThreads standard. + * They are defined by the POSIX Standard: + * + * POSIX 1003.1b-1993 (POSIX.1b) + * + * ------------------------------------------------------------- + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "semaphore.h" +#include "implement.h" + + +int +sem_trywait (sem_t * sem) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function tries to wait on a semaphore. + * + * PARAMETERS + * sem + * pointer to an instance of sem_t + * + * DESCRIPTION + * This function tries to wait on a semaphore. If the + * semaphore value is greater than zero, it decreases + * its value by one. If the semaphore value is zero, then + * this function returns immediately with the error EAGAIN + * + * RESULTS + * 0 successfully decreased semaphore, + * -1 failed, error in errno + * ERRNO + * EAGAIN the semaphore was already locked, + * EINVAL 'sem' is not a valid semaphore, + * ENOTSUP sem_trywait is not supported, + * EINTR the function was interrupted by a signal, + * EDEADLK a deadlock condition was detected. + * + * ------------------------------------------------------ + */ +{ + int result = 0; + sem_t s = *sem; + + if (s == NULL) + { + result = EINVAL; + } + else if ((result = pthread_mutex_lock (&s->lock)) == 0) + { + /* See sem_destroy.c + */ + if (*sem == NULL) + { + (void) pthread_mutex_unlock (&s->lock); + errno = EINVAL; + return -1; + } + + if (s->value > 0) + { + s->value--; + } + else + { + result = EAGAIN; + } + + (void) pthread_mutex_unlock (&s->lock); + } + + if (result != 0) + { + errno = result; + return -1; + } + + return 0; + +} /* sem_trywait */ diff --git a/w32-pthreads/sem_unlink.c b/w32-pthreads/sem_unlink.c new file mode 100644 index 000000000..fb80569a0 --- /dev/null +++ b/w32-pthreads/sem_unlink.c @@ -0,0 +1,58 @@ +/* + * ------------------------------------------------------------- + * + * Module: sem_unlink.c + * + * Purpose: + * Semaphores aren't actually part of the PThreads standard. + * They are defined by the POSIX Standard: + * + * POSIX 1003.1b-1993 (POSIX.1b) + * + * ------------------------------------------------------------- + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "semaphore.h" +#include "implement.h" + +/* ignore warning "unreferenced formal parameter" */ +#if defined(_MSC_VER) +#pragma warning( disable : 4100 ) +#endif + +int +sem_unlink (const char *name) +{ + errno = ENOSYS; + return -1; +} /* sem_unlink */ diff --git a/w32-pthreads/sem_wait.c b/w32-pthreads/sem_wait.c new file mode 100644 index 000000000..50c11d808 --- /dev/null +++ b/w32-pthreads/sem_wait.c @@ -0,0 +1,187 @@ +/* + * ------------------------------------------------------------- + * + * Module: sem_wait.c + * + * Purpose: + * Semaphores aren't actually part of the PThreads standard. + * They are defined by the POSIX Standard: + * + * POSIX 1003.1b-1993 (POSIX.1b) + * + * ------------------------------------------------------------- + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "semaphore.h" +#include "implement.h" + + +static void PTW32_CDECL +ptw32_sem_wait_cleanup(void * sem) +{ + sem_t s = (sem_t) sem; + + if (pthread_mutex_lock (&s->lock) == 0) + { + /* + * If sema is destroyed do nothing, otherwise:- + * If the sema is posted between us being cancelled and us locking + * the sema again above then we need to consume that post but cancel + * anyway. If we don't get the semaphore we indicate that we're no + * longer waiting. + */ + if (*((sem_t *)sem) != NULL && !(WaitForSingleObject(s->sem, 0) == WAIT_OBJECT_0)) + { + ++s->value; +#if defined(NEED_SEM) + if (s->value > 0) + { + s->leftToUnblock = 0; + } +#else + /* + * Don't release the W32 sema, it doesn't need adjustment + * because it doesn't record the number of waiters. + */ +#endif /* NEED_SEM */ + } + (void) pthread_mutex_unlock (&s->lock); + } +} + +int +sem_wait (sem_t * sem) + /* + * ------------------------------------------------------ + * DOCPUBLIC + * This function waits on a semaphore. + * + * PARAMETERS + * sem + * pointer to an instance of sem_t + * + * DESCRIPTION + * This function waits on a semaphore. If the + * semaphore value is greater than zero, it decreases + * its value by one. If the semaphore value is zero, then + * the calling thread (or process) is blocked until it can + * successfully decrease the value or until interrupted by + * a signal. + * + * RESULTS + * 0 successfully decreased semaphore, + * -1 failed, error in errno + * ERRNO + * EINVAL 'sem' is not a valid semaphore, + * ENOSYS semaphores are not supported, + * EINTR the function was interrupted by a signal, + * EDEADLK a deadlock condition was detected. + * + * ------------------------------------------------------ + */ +{ + int result = 0; + sem_t s = *sem; + + pthread_testcancel(); + + if (s == NULL) + { + result = EINVAL; + } + else + { + if ((result = pthread_mutex_lock (&s->lock)) == 0) + { + int v; + + /* See sem_destroy.c + */ + if (*sem == NULL) + { + (void) pthread_mutex_unlock (&s->lock); + errno = EINVAL; + return -1; + } + + v = --s->value; + (void) pthread_mutex_unlock (&s->lock); + + if (v < 0) + { +#if defined(_MSC_VER) && _MSC_VER < 1400 +#pragma inline_depth(0) +#endif + /* Must wait */ + pthread_cleanup_push(ptw32_sem_wait_cleanup, (void *) s); + result = pthreadCancelableWait (s->sem); + /* Cleanup if we're canceled or on any other error */ + pthread_cleanup_pop(result); +#if defined(_MSC_VER) && _MSC_VER < 1400 +#pragma inline_depth() +#endif + } +#if defined(NEED_SEM) + + if (!result && pthread_mutex_lock (&s->lock) == 0) + { + if (*sem == NULL) + { + (void) pthread_mutex_unlock (&s->lock); + errno = EINVAL; + return -1; + } + + if (s->leftToUnblock > 0) + { + --s->leftToUnblock; + SetEvent(s->sem); + } + (void) pthread_mutex_unlock (&s->lock); + } + +#endif /* NEED_SEM */ + + } + + } + + if (result != 0) + { + errno = result; + return -1; + } + + return 0; + +} /* sem_wait */ diff --git a/w32-pthreads/semaphore.c b/w32-pthreads/semaphore.c new file mode 100644 index 000000000..64fc0e366 --- /dev/null +++ b/w32-pthreads/semaphore.c @@ -0,0 +1,69 @@ +/* + * ------------------------------------------------------------- + * + * Module: semaphore.c + * + * Purpose: + * Concatenated version of separate modules to allow + * inlining optimisation, which it is assumed can only + * be effective within a single module. + * + * Semaphores aren't actually part of the PThreads standard. + * They are defined by the POSIX Standard: + * + * POSIX 1003.1b-1993 (POSIX.1b) + * + * ------------------------------------------------------------- + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#if !defined(NEED_FTIME) +# include +#endif + +#include + +#include "pthread.h" +#include "semaphore.h" +#include "implement.h" + + +#include "sem_init.c" +#include "sem_destroy.c" +#include "sem_trywait.c" +#include "sem_wait.c" +#include "sem_timedwait.c" +#include "sem_post.c" +#include "sem_post_multiple.c" +#include "sem_getvalue.c" +#include "sem_open.c" +#include "sem_close.c" +#include "sem_unlink.c" diff --git a/w32-pthreads/semaphore.h b/w32-pthreads/semaphore.h new file mode 100644 index 000000000..006d6094d --- /dev/null +++ b/w32-pthreads/semaphore.h @@ -0,0 +1,169 @@ +/* + * Module: semaphore.h + * + * Purpose: + * Semaphores aren't actually part of the PThreads standard. + * They are defined by the POSIX Standard: + * + * POSIX 1003.1b-1993 (POSIX.1b) + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ +#if !defined( SEMAPHORE_H ) +#define SEMAPHORE_H + +#undef PTW32_SEMAPHORE_LEVEL + +#if defined(_POSIX_SOURCE) +#define PTW32_SEMAPHORE_LEVEL 0 +/* Early POSIX */ +#endif + +#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309 +#undef PTW32_SEMAPHORE_LEVEL +#define PTW32_SEMAPHORE_LEVEL 1 +/* Include 1b, 1c and 1d */ +#endif + +#if defined(INCLUDE_NP) +#undef PTW32_SEMAPHORE_LEVEL +#define PTW32_SEMAPHORE_LEVEL 2 +/* Include Non-Portable extensions */ +#endif + +#define PTW32_SEMAPHORE_LEVEL_MAX 3 + +#if !defined(PTW32_SEMAPHORE_LEVEL) +#define PTW32_SEMAPHORE_LEVEL PTW32_SEMAPHORE_LEVEL_MAX +/* Include everything */ +#endif + +#if defined(__GNUC__) && ! defined (__declspec) +# error Please upgrade your GNU compiler to one that supports __declspec. +#endif + +/* + * When building the library, you should define PTW32_BUILD so that + * the variables/functions are exported correctly. When using the library, + * do NOT define PTW32_BUILD, and then the variables/functions will + * be imported correctly. + */ +#if !defined(PTW32_STATIC_LIB) +# if defined(PTW32_BUILD) +# define PTW32_DLLPORT __declspec (dllexport) +# else +# define PTW32_DLLPORT +# endif +#else +# define PTW32_DLLPORT +#endif + +/* + * This is a duplicate of what is in the autoconf config.h, + * which is only used when building the pthread-win32 libraries. + */ + +#if !defined(PTW32_CONFIG_H) +# if defined(WINCE) +# define NEED_ERRNO +# define NEED_SEM +# endif +# if defined(__MINGW64__) +# define HAVE_STRUCT_TIMESPEC +# define HAVE_MODE_T +# elif defined(_UWIN) || defined(__MINGW32__) +# define HAVE_MODE_T +# endif +#endif + +/* + * + */ + +#if PTW32_SEMAPHORE_LEVEL >= PTW32_SEMAPHORE_LEVEL_MAX +#if defined(NEED_ERRNO) +#include "need_errno.h" +#else +#include +#endif +#endif /* PTW32_SEMAPHORE_LEVEL >= PTW32_SEMAPHORE_LEVEL_MAX */ + +#define _POSIX_SEMAPHORES + +#if defined(__cplusplus) +extern "C" +{ +#endif /* __cplusplus */ + +#if !defined(HAVE_MODE_T) +typedef unsigned int mode_t; +#endif + + +typedef struct sem_t_ * sem_t; + +PTW32_DLLPORT int __cdecl sem_init (sem_t * sem, + int pshared, + unsigned int value); + +PTW32_DLLPORT int __cdecl sem_destroy (sem_t * sem); + +PTW32_DLLPORT int __cdecl sem_trywait (sem_t * sem); + +PTW32_DLLPORT int __cdecl sem_wait (sem_t * sem); + +PTW32_DLLPORT int __cdecl sem_timedwait (sem_t * sem, + const struct timespec * abstime); + +PTW32_DLLPORT int __cdecl sem_post (sem_t * sem); + +PTW32_DLLPORT int __cdecl sem_post_multiple (sem_t * sem, + int count); + +PTW32_DLLPORT int __cdecl sem_open (const char * name, + int oflag, + mode_t mode, + unsigned int value); + +PTW32_DLLPORT int __cdecl sem_close (sem_t * sem); + +PTW32_DLLPORT int __cdecl sem_unlink (const char * name); + +PTW32_DLLPORT int __cdecl sem_getvalue (sem_t * sem, + int * sval); + +#if defined(__cplusplus) +} /* End of extern "C" */ +#endif /* __cplusplus */ + +#undef PTW32_SEMAPHORE_LEVEL +#undef PTW32_SEMAPHORE_LEVEL_MAX + +#endif /* !SEMAPHORE_H */ diff --git a/w32-pthreads/signal.c b/w32-pthreads/signal.c new file mode 100644 index 000000000..eef466962 --- /dev/null +++ b/w32-pthreads/signal.c @@ -0,0 +1,179 @@ +/* + * signal.c + * + * Description: + * Thread-aware signal functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +/* + * Possible future strategy for implementing pthread_kill() + * ======================================================== + * + * Win32 does not implement signals. + * Signals are simply software interrupts. + * pthread_kill() asks the system to deliver a specified + * signal (interrupt) to a specified thread in the same + * process. + * Signals are always asynchronous (no deferred signals). + * Pthread-win32 has an async cancelation mechanism. + * A similar system can be written to deliver signals + * within the same process (on ix86 processors at least). + * + * Each thread maintains information about which + * signals it will respond to. Handler routines + * are set on a per-process basis - not per-thread. + * When signalled, a thread will check it's sigmask + * and, if the signal is not being ignored, call the + * handler routine associated with the signal. The + * thread must then (except for some signals) return to + * the point where it was interrupted. + * + * Ideally the system itself would check the target thread's + * mask before possibly needlessly bothering the thread + * itself. This could be done by pthread_kill(), that is, + * in the signaling thread since it has access to + * all pthread_t structures. It could also retrieve + * the handler routine address to minimise the target + * threads response overhead. This may also simplify + * serialisation of the access to the per-thread signal + * structures. + * + * pthread_kill() eventually calls a routine similar to + * ptw32_cancel_thread() which manipulates the target + * threads processor context to cause the thread to + * run the handler launcher routine. pthread_kill() must + * save the target threads current context so that the + * handler launcher routine can restore the context after + * the signal handler has returned. Some handlers will not + * return, eg. the default SIGKILL handler may simply + * call pthread_exit(). + * + * The current context is saved in the target threads + * pthread_t structure. + */ + +#include "pthread.h" +#include "implement.h" + +#if defined(HAVE_SIGSET_T) + +static void +ptw32_signal_thread () +{ +} + +static void +ptw32_signal_callhandler () +{ +} + +int +pthread_sigmask (int how, sigset_t const *set, sigset_t * oset) +{ + pthread_t thread = pthread_self (); + + if (thread.p == NULL) + { + return ENOENT; + } + + /* Validate the `how' argument. */ + if (set != NULL) + { + switch (how) + { + case SIG_BLOCK: + break; + case SIG_UNBLOCK: + break; + case SIG_SETMASK: + break; + default: + /* Invalid `how' argument. */ + return EINVAL; + } + } + + /* Copy the old mask before modifying it. */ + if (oset != NULL) + { + memcpy (oset, &(thread.p->sigmask), sizeof (sigset_t)); + } + + if (set != NULL) + { + unsigned int i; + + /* FIXME: this code assumes that sigmask is an even multiple of + the size of a long integer. */ + + unsigned long *src = (unsigned long const *) set; + unsigned long *dest = (unsigned long *) &(thread.p->sigmask); + + switch (how) + { + case SIG_BLOCK: + for (i = 0; i < (sizeof (sigset_t) / sizeof (unsigned long)); i++) + { + /* OR the bit field longword-wise. */ + *dest++ |= *src++; + } + break; + case SIG_UNBLOCK: + for (i = 0; i < (sizeof (sigset_t) / sizeof (unsigned long)); i++) + { + /* XOR the bitfield longword-wise. */ + *dest++ ^= *src++; + } + case SIG_SETMASK: + /* Replace the whole sigmask. */ + memcpy (&(thread.p->sigmask), set, sizeof (sigset_t)); + break; + } + } + + return 0; +} + +int +sigwait (const sigset_t * set, int *sig) +{ + /* This routine is a cancellation point */ + pthread_test_cancel(); +} + +int +sigaction (int signum, const struct sigaction *act, struct sigaction *oldact) +{ +} + +#endif /* HAVE_SIGSET_T */ diff --git a/w32-pthreads/spin.c b/w32-pthreads/spin.c new file mode 100644 index 000000000..41b5aa525 --- /dev/null +++ b/w32-pthreads/spin.c @@ -0,0 +1,46 @@ +/* + * spin.c + * + * Description: + * This translation unit implements spin lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +#include "ptw32_spinlock_check_need_init.c" +#include "pthread_spin_init.c" +#include "pthread_spin_destroy.c" +#include "pthread_spin_lock.c" +#include "pthread_spin_unlock.c" +#include "pthread_spin_trylock.c" diff --git a/w32-pthreads/sync.c b/w32-pthreads/sync.c new file mode 100644 index 000000000..5e56fa9a1 --- /dev/null +++ b/w32-pthreads/sync.c @@ -0,0 +1,43 @@ +/* + * sync.c + * + * Description: + * This translation unit implements functions related to thread + * synchronisation. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +#include "pthread_detach.c" +#include "pthread_join.c" diff --git a/w32-pthreads/tests/Bmakefile b/w32-pthreads/tests/Bmakefile new file mode 100644 index 000000000..df2ac1b1b --- /dev/null +++ b/w32-pthreads/tests/Bmakefile @@ -0,0 +1,358 @@ +# Makefile for the pthreads test suite. +# If all of the .pass files can be created, the test suite has passed. +# +# -------------------------------------------------------------------------- +# +# Pthreads-win32 - POSIX Threads Library for Win32 +# Copyright(C) 1998 John E. Bossom +# Copyright(C) 1999,2005 Pthreads-win32 contributors +# +# Contact Email: rpj@callisto.canberra.edu.au +# +# The current list of contributors is contained +# in the file CONTRIBUTORS included with the source +# code distribution. The list can also be seen at the +# following World Wide Web location: +# http://sources.redhat.com/pthreads-win32/contributors.html +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2 of the License, or (at your option) any later version. +# +# This library 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library in the file COPYING.LIB; +# if not, write to the Free Software Foundation, Inc., +# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA +# + +DLL_VER = 2 + +CP = copy +RM = erase +CAT = type +MKDIR = mkdir +TOUCH = echo Passed > +ECHO = @echo + +# The next path is relative to $BUILD_DIR +QAPC = # ..\QueueUserAPCEx\User\quserex.dll + +CPHDR = pthread.h semaphore.h sched.h + +OPTIM = -O2 + +XXLIBS = cw32mti.lib ws2_32.lib + +# C++ Exceptions +BCEFLAGS = -P -DPtW32NoCatchWarn -D__CLEANUP_CXX +BCELIB = pthreadBCE$(DLL_VER).lib +BCEDLL = pthreadBCE$(DLL_VER).dll +# C cleanup code +BCFLAGS = -D__CLEANUP_C +BCLIB = pthreadBC$(DLL_VER).lib +BCDLL = pthreadBC$(DLL_VER).dll +# C++ Exceptions in application - using VC version of pthreads dll +BCXFLAGS = -D__CLEANUP_C + +# Defaults +CPLIB = $(BCLIB) +CPDLL = $(BCDLL) + +CFLAGS= -q $(OPTIM) /D_WIN32_WINNT=0x400 -w -tWC -tWM -4 -w-aus -w-asc -w-par +LFLAGS= +INCLUDES=-I. +BUILD_DIR=.. + +COPYFILES = $(CPHDR) $(CPLIB) $(CPDLL) $(QAPC) + +EHFLAGS = + +# If a test case returns a non-zero exit code to the shell, make will +# stop. + +PASSES= loadfree.pass \ + errno1.pass \ + self1.pass mutex5.pass \ + mutex1.pass mutex1n.pass mutex1e.pass mutex1r.pass \ + semaphore1.pass semaphore2.pass semaphore3.pass \ + mutex2.pass mutex3.pass \ + mutex2r.pass mutex2e.pass mutex3r.pass mutex3e.pass \ + condvar1.pass condvar1_1.pass condvar1_2.pass condvar2.pass condvar2_1.pass \ + exit1.pass create1.pass create2.pass reuse1.pass reuse2.pass equal1.pass \ + sequence1.pass kill1.pass valid1.pass valid2.pass \ + exit2.pass exit3.pass exit4.pass exit5.pass \ + join0.pass join1.pass detach1.pass join2.pass join3.pass \ + mutex4.pass mutex6.pass mutex6n.pass mutex6e.pass mutex6r.pass \ + mutex6s.pass mutex6es.pass mutex6rs.pass \ + mutex7.pass mutex7n.pass mutex7e.pass mutex7r.pass \ + mutex8.pass mutex8n.pass mutex8e.pass mutex8r.pass \ + robust1.pass robust2.pass robust3.pass robust4.pass robust5.pass \ + count1.pass \ + once1.pass once2.pass once3.pass once4.pass \ + self2.pass \ + cancel1.pass cancel2.pass \ + semaphore4.pass semaphore4t.pass semaphore5.pass \ + barrier1.pass barrier2.pass barrier3.pass barrier4.pass barrier5.pass barrier6.pass \ + tsd1.pass tsd2.pass delay1.pass delay2.pass eyal1.pass \ + condvar3.pass condvar3_1.pass condvar3_2.pass condvar3_3.pass \ + condvar4.pass condvar5.pass condvar6.pass \ + condvar7.pass condvar8.pass condvar9.pass \ + rwlock1.pass rwlock2.pass rwlock3.pass rwlock4.pass \ + rwlock5.pass rwlock6.pass rwlock7.pass rwlock8.pass \ + rwlock2_t.pass rwlock3_t.pass rwlock4_t.pass rwlock5_t.pass rwlock6_t.pass rwlock6_t2.pass \ + context1.pass \ + cancel3.pass cancel4.pass cancel5.pass cancel6a.pass cancel6d.pass \ + cancel7.pass cancel8.pass \ + cleanup0.pass cleanup1.pass cleanup2.pass cleanup3.pass \ + priority1.pass priority2.pass inherit1.pass \ + spin1.pass spin2.pass spin3.pass spin4.pass \ + exception1.pass exception2.pass exception3.pass \ + cancel9.pass stress1.pass + +BENCHRESULTS = \ + benchtest1.bench benchtest2.bench benchtest3.bench benchtest4.bench benchtest5.bench + +help: + @ $(ECHO) Run one of the following command lines: + @ $(ECHO) make clean BC (to test using BC dll with VC (no EH) applications) + @ $(ECHO) make clean BCX (to test using BC dll with VC++ (EH) applications) + @ $(ECHO) make clean BCE (to test using the BCE dll with VC++ EH applications) + @ $(ECHO) make clean BC-bench (to benchtest using BC dll with C bench app) + @ $(ECHO) make clean BCX-bench (to benchtest using BC dll with C++ bench app) + @ $(ECHO) make clean BCE-bench (to benchtest using BCE dll with C++ bench app) + +all: + @ make clean BC + @ make clean BCX + @ make clean BCE + @ make clean BC-bench + +# This allows an individual test application to be made using the default lib. +# e.g. make clean test cancel3.exe +test: $(CPLIB) $(CPDLL) $(CPHDR) $(QAPC) + +tests: $(CPLIB) $(CPDLL) $(CPHDR) $(QAPC) sizes.pass $(PASSES) + @ $(ECHO) ALL TESTS PASSED! Congratulations! + +benchtests: $(CPLIB) $(CPDLL) $(CPHDR) $(BENCHRESULTS) + @ $(ECHO) ALL BENCH TESTS DONE. + +sizes.pass: sizes.exe + @ $(ECHO) ... Running $(TEST) test: $*.exe + @ .\$*.exe > SIZES.$(TEST) + @ $(CAT) SIZES.$(TEST) + @ $(ECHO) ...... Passed + @ $(TOUCH) $*.pass + +BCE: + @ make -f Bmakefile TEST="$@" CPLIB="$(BCELIB)" CPDLL="$(BCEDLL)" EHFLAGS="$(BCEFLAGS)" tests + +BC: + @ make -f Bmakefile TEST="$@" CPLIB="$(BCLIB)" CPDLL="$(BCDLL)" EHFLAGS="$(BCFLAGS)" tests + +BCX: + @ make -f Bmakefile TEST="$@" CPLIB="$(BCLIB)" CPDLL="$(BCDLL)" EHFLAGS="$(BCXFLAGS)" tests + +BCE-bench: + @ make -f Bmakefile TEST="$@" CPLIB="$(BCELIB)" CPDLL="$(BCEDLL)" EHFLAGS="$(BCEFLAGS)" XXLIBS="benchlib.o" benchtests + +BC-bench: + @ make -f Bmakefile TEST="$@" CPLIB="$(BCLIB)" CPDLL="$(BCDLL)" EHFLAGS="$(BCFLAGS)" XXLIBS="benchlib.o" benchtests + +BCX-bench: + @ make -f Bmakefile TEST="$@" CPLIB="$(BCLIB)" CPDLL="$(BCDLL)" EHFLAGS="$(BCXFLAGS)" XXLIBS="benchlib.o" benchtests + +.exe.pass: + @ $(ECHO) ... Running $(TEST) test: $< + @ .\$< + @ $(ECHO) ...... Passed + @ $(TOUCH) $@ + +.exe.bench: + @ $(ECHO) ... Running $(TEST) benchtest: $< + @ .\$< + @ $(ECHO) ...... Done + @ $(TOUCH) $@ + +.c.exe: + @ $(ECHO) $(CC) $(EHFLAGS) $(CFLAGS) $(INCLUDES) $< -e$@ $(LFLAGS) $(CPLIB) $(XXLIBS) + @ $(CC) $(EHFLAGS) $(CFLAGS) $(INCLUDES) $< -e$@ $(LFLAGS) $(CPLIB) $(XXLIBS) + +.c.o: + @ $(ECHO) $(CC) $(EHFLAGS) -c $(CFLAGS) $(INCLUDES) $< -o$@ + @ $(CC) $(EHFLAGS) $(CFLAGS) -c $(INCLUDES) $< -o$@ + + +.c.i: + @ $(CC) /P $(EHFLAGS) $(CFLAGS) $(INCLUDES) $< + +$(COPYFILES): + @ $(ECHO) Copying $(BUILD_DIR)\$@ + @ $(CP) $(BUILD_DIR)\$@ . + +pthread.dll: $(CPDLL) + @ $(CP) $(CPDLL) pthread.dll + @ $(CP) $(CPLIB) pthread.lib + +clean: + - $(RM) *.dll + - $(RM) *.lib + - $(RM) pthread.h + - $(RM) semaphore.h + - $(RM) sched.h + - $(RM) *.e + - $(RM) *.i + - $(RM) *.obj + - $(RM) *.tds + - $(RM) *.pdb + - $(RM) *.o + - $(RM) *.asm + - $(RM) *.exe + - $(RM) *.pass + - $(RM) *.bench + - $(RM) *.log + +benchtest1.bench: +benchtest2.bench: +benchtest3.bench: +benchtest4.bench: +benchtest5.bench: +barrier1.pass: semaphore4.pass +barrier2.pass: barrier1.pass +barrier3.pass: barrier2.pass +barrier4.pass: barrier3.pass +barrier5.pass: barrier4.pass +barrier6.pass: barrier5.pass +cancel1.pass: create1.pass +cancel2.pass: cancel1.pass +cancel3.pass: context1.pass +cancel4.pass: cancel3.pass +cancel5.pass: cancel3.pass +cancel6a.pass: cancel3.pass +cancel6d.pass: cancel3.pass +cancel7.pass: kill1.pass +cancel8.pass: cancel7.pass +cancel9.pass: cancel8.pass +cleanup0.pass: cancel5.pass +cleanup1.pass: cleanup0.pass +cleanup2.pass: cleanup1.pass +cleanup3.pass: cleanup2.pass +condvar1.pass: +condvar1_1.pass: condvar1.pass +condvar1_2.pass: join2.pass +condvar2.pass: condvar1.pass +condvar2_1.pass: condvar2.pass join2.pass +condvar3.pass: create1.pass condvar2.pass +condvar3_1.pass: condvar3.pass join2.pass +condvar3_2.pass: condvar3_1.pass +condvar3_3.pass: condvar3_2.pass +condvar4.pass: create1.pass +condvar5.pass: condvar4.pass +condvar6.pass: condvar5.pass +condvar7.pass: condvar6.pass cleanup1.pass +condvar8.pass: condvar7.pass +condvar9.pass: condvar8.pass +context1.pass: cancel1.pass +count1.pass: join1.pass +create1.pass: mutex2.pass +create2.pass: create1.pass +delay1.pass: +delay2.pass: delay1.pass +detach1.pass: join0.pass +equal1.pass: create1.pass +errno1.pass: mutex3.pass +exception1.pass: cancel4.pass +exception2.pass: exception1.pass +exception3.pass: exception2.pass +exit1.pass: +exit2.pass: create1.pass +exit3.pass: create1.pass +exit4.pass: +exit5.pass: kill1.pass +eyal1.pass: tsd1.pass +inherit1.pass: join1.pass priority1.pass +join0.pass: create1.pass +join1.pass: create1.pass +join2.pass: create1.pass +join3.pass: join2.pass +kill1.pass: +loadfree.pass: pthread.dll +mutex1.pass: self1.pass +mutex1n.pass: mutex1.pass +mutex1e.pass: mutex1.pass +mutex1r.pass: mutex1.pass +mutex2.pass: mutex1.pass +mutex2r.pass: mutex2.pass +mutex2e.pass: mutex2.pass +mutex3.pass: create1.pass +mutex3r.pass: mutex3.pass +mutex3e.pass: mutex3.pass +mutex4.pass: mutex3.pass +mutex5.pass: +mutex6.pass: mutex4.pass +mutex6n.pass: mutex4.pass +mutex6e.pass: mutex4.pass +mutex6r.pass: mutex4.pass +mutex6s.pass: mutex6.pass +mutex6rs.pass: mutex6r.pass +mutex6es.pass: mutex6e.pass +mutex7.pass: mutex6.pass +mutex7n.pass: mutex6n.pass +mutex7e.pass: mutex6e.pass +mutex7r.pass: mutex6r.pass +mutex8.pass: mutex7.pass +mutex8n.pass: mutex7n.pass +mutex8e.pass: mutex7e.pass +mutex8r.pass: mutex7r.pass +once1.pass: create1.pass +once2.pass: once1.pass +once3.pass: once2.pass +once4.pass: once3.pass +priority1.pass: join1.pass +priority2.pass: priority1.pass barrier3.pass +reuse1.pass: create2.pass +reuse2.pass: reuse1.pass +robust1.pass: mutex8r.pass +robust2.pass: mutex8r.pass +robust3.pass: robust2.pass +robust4.pass: robust3.pass +robust5.pass: robust4.pass +rwlock1.pass: condvar6.pass +rwlock2.pass: rwlock1.pass +rwlock3.pass: rwlock2.pass join2.pass +rwlock4.pass: rwlock3.pass +rwlock5.pass: rwlock4.pass +rwlock6.pass: rwlock5.pass +rwlock7.pass: rwlock6.pass +rwlock8.pass: rwlock7.pass +rwlock2_t.pass: rwlock2.pass +rwlock3_t.pass: rwlock2_t.pass +rwlock4_t.pass: rwlock3_t.pass +rwlock5_t.pass: rwlock4_t.pass +rwlock6_t.pass: rwlock5_t.pass +rwlock6_t2.pass: rwlock6_t.pass +self1.pass: +self2.pass: create1.pass +semaphore1.pass: +semaphore2.pass: +semaphore3.pass: semaphore2.pass +semaphore4.pass: semaphore3.pass cancel1.pass +semaphore4t.pass: semaphore4.pass +semaphore5.pass: semaphore4.pass +sequence1.pass: reuse2.pass +sizes.pass: +spin1.pass: +spin2.pass: spin1.pass +spin3.pass: spin2.pass +spin4.pass: spin3.pass +stress1.pass: +tsd1.pass: barrier5.pass join1.pass +tsd2.pass: tsd1.pass +valid1.pass: join1.pass +valid2.pass: valid1.pass diff --git a/w32-pthreads/tests/ChangeLog b/w32-pthreads/tests/ChangeLog new file mode 100644 index 000000000..dfb4f4555 --- /dev/null +++ b/w32-pthreads/tests/ChangeLog @@ -0,0 +1,1000 @@ +2011-07-03 Ross Johnson + + * create3.c: Removed; testing a condition that is not in the library's + scope and was more trouble than it was worth. + * cancel2.c: Ensure this test only runs for Structured or C++ EH. + * exit2.c: Shorten Sleep() time. + * exit3.c: Likewise. + * cancel1.c: Likewise. + * cancel3.c: Likewise. + * exception3.c: Likewise; make terminate routine consistent for all + build environments. + +2011-07-02 Ross Johnson + + * spin3.c: Unlock the unlocked spinlock now returns success. + * rwlock3.c: Join the thread to ensure it's completed. + * rwlock4.c: Likewise. + * rwlock5.c: Likewise. + * Makefile: Adjust prerequisites. + * GNUmakefile: Likewise. + * Bmakefile: Likewise. + * Wmakefile: Likewise. + +2011-07-02 Daniel Richard G. + + * *.[ch]: Cleanups around timeb struct, mainly centralising + macro definitions in test.h. + * Makefile: Fix annoying nmake warning. + +2011-06-30 Ross Johnson + + * sequence1.c: Fix loop overrun. + +2011-05-11 Ross Johnson + + * GNUmakefile (GCE-debug): New target; expects pthreadGCE2d.dll. + +2011-05-05 Ross Johnson + + * openmp1.c: Add missing test; used to comfirm that this + library works with libgomp; if this test produces a segfault + then try upgrading your version of libgomp/gcc; gcc version + 4.5.2 passes this test. + +2011-03-26 Ross Johnson + + * sequence1.c: New test for new pthread_getsequence_np(). + +2011-03-24 Ross Johnson + + * mutex*.c: Include tests for robust mutexes wherever + appropriate. + * benchtest*.c: Include comparisons for robust mutexes. + * robust1.c: New test for robust mutex handling. + * robust2.c: Likewise. + * robust3.c: Likewise. + * robust4.c: Likewise. + * robust5.c: Likewise. + * GNUmakefile: Include new tests. + * Makefile: Likewise. + * Bmakefile: Likewise (not tested). + * Wmakefile: Likewise (not tested). + +2011-03-06 Ross Johnson + + * several (MINGW64): Cast and call fixups for 64 bit compatibility; + clean build via x86_64-w64-mingw32 cross toolchain on Linux + i686 targeting x86_64 win64. + +2011-03-04 Ross Johnson + + * condvar3_2.c: abstime.tv_sec operation warning fixed. + * several: Use correct casting on pthread_join result arg + and associated declaration and usage; assumed that 64 bit + gcc gave some warnings for it. + +2011-02-28 Ross Johnson + + * test.h: Define FTIME to be _ftime64_s or _ftime64 or _ftime + in that order of preference where supported. + * several: Replace calls to _ftime with the FTIME macro. + +2010-06-19 Ross Johnson + + * Makefile (STATICRESULTS): Add all tests into suite for static + library. + * GNUmakefile (STATICTESTS): Likewise, except for openmp1.c which + has a DLL dependency. + +2010-02-04 Ross Johnson + + * openmp1.c: New; for libgomp compatibility (OpenMP). + * barrier5.c: Rewrite after changes to barriers. + * barrier6.c: New. + * benchtest6.c: New; timing barriers. + * GNUMakefile: Update for new tests. + * Makefile: Ditto. + * BMakefile: Ditto. + * once3.c: Improve cancelation testing. + * stress1.c: Fix comment. + +2007-01-04 Ross Johnson + + * context1.c: Include context.h from library sources and remove + x86 dependence in main(). + +2005-06-12 Ross Johnson + + * stress1.c (millisecondsFromNow): Remove limit 0 <= millisecs < 1000; + now works for -INT_MAX <= millisecs <= INT_MAX; not needed for + stress1.c but should be general anyway. + +2005-05-18 Ross Johnson + + * reuse2.c (main): Must use a read with memory barrier semantics + when polling 'done' to force the cache into coherence on MP systems. + +2005-05-15 Ross Johnson + + * detach1.c: New test. + * join1.c: Reduce sleep times. + * join0.c: Remove MSVCRT conditional compile - join should always + return the thread exit code. + * join1.c: Likewise. + * join2.c: Likewise. + * join3.c: Likewise. + +2005-04-18 Ross Johnson + + * condvar3.c: Remove locks from around signalling calls - should not + be required for normal operation and only serve to mask deficiencies; + ensure that CV destruction is not premature after removing guards. + * condvar3_1.c: Likewise. + * condvar3_2.c: Likewise. + * condvar3_3.c: Likewise. + * condvar4.c: Likewise. + * condvar5.c: Likewise. + * condvar6.c: Likewise. + * condvar7.c: Likewise. + * condvar8.c: Likewise. + * condvar9.c: Likewise. + +2005-04-11 Ross Johnson + + * once4.c: New test; tries to test priority adjustments + in pthread_once(); set priority class to realtime so that + any failures can be seen. + +2005-04-06 Ross Johnson + + * cleanup0.c: Fix unguarded global variable accesses. + * cleanup1.c: Likewise. + * cleanup2.c: Likewise. + * cleanup3.c: Likewise. + * once2.c: Likewise. + * once3.c: Likewise. + +2005-04-01 Ross Johnson + + * GNUmakefile: Add target to test linking static link library. + * Makefile: Likewise. + * self1.c: Run process attach/detach routines when static linked. + +2005-03-16 Ross Johnson + + * mutex5.c: Prevent optimiser from removing asserts. + +2005-03-12 Ross Johnson + + * once3.c: New test. + +2005-03-08 Ross Johnson + + * once2.c: New test. + +2004-11-19 Ross Johnson + + * Bmakefile: New makefile for Borland. + * Makefile (DLL_VER): Added. + * GNUmakefile (DLL_VER): Added. + * Wmakefile (DLL_VER): Added. + +2004-10-29 Ross Johnson + + * semaphore4.c: New test. + * semaphore4t.c: New test. + * Debug.dsp (et al): Created MSVC Workspace project to aid debugging. + * All: Many tests have been modified to work with the new pthread + ID type; some other corrections were made after some library + functions were semantically strengthened. For example, + pthread_cond_destroy() no longer destroys a busy CV, which + required minor redesigns of some tests, including some where + the mutex associated with the CV was not locked during + signaling and broadcasting. + +2004-10-23 Ross Johnson + + * condvar3.c: Fixed mutex operations that were incorrectly + placed in relation to their condition variable operations. + The error became evident after sem_destroy() was rewritten + and conditions for destroing the semaphore were tightened. + As a result, pthread_cond_destroy() was not able to + destroy the cv queueing sempahore. + * condvar3_1.c: Likewise. + * condvar3_2.c: Likewise. + * condvar4.c: Likewise. + * condvar5.c: Likewise. + * condvar6.c: Likewise. + * condvar7.c: Likewise. + * condvar8.c: Likewise. + * condvar9.c: Likewise. + +2004-10-19 Ross Johnson + + * semaphore3.c: New test. + +2004-10-14 Ross Johnson + + * rwlock7.c (main): Tidy up statistics reporting; randomise + update accesses. + * rwlock8.c: New test. + +2004-09-08 Alexandre Girao + + * cancel7.c (main): Win98 wants a valid (non-NULL) location + for the last arg of _beginthreadex(). + * cancel8.c (main): Likewise. + * exit4.c (main): Likewise. + * exit5.c (main): Likewise. + +2004-08-26 Ross Johnson + + * create3.c: New test. + +2004-06-21 Ross Johnson + + * mutex2r.c: New test. + * mutex2e.c: New test. + * mutex3r.c: New test. + * mutex3e.c: New test. + * mutex6s.c: New test. + * mutex6rs.c: New test. + * mutex6es.c: New test. + +2004-05-21 Ross Johnson + + * join3.c: New test. + +2004-05-16 Ross Johnson + + * condvar2.c (WIN32_WINNT): Define to avoid redefinition warning + from inclusion of implement.h. + * convar2_1.c: Likewise. + * condvar3_1.c: Likewise. + * condvar3_2.c: Likewise. + * context1.c: Likewise. + * sizes.c: Likewise. + * Makefile: Don't define _WIN32_WINNT on compiler command line. + * GNUmakefile: Likewise. + * priority1.c (main): Add column to output for actual win32 + priority. + +2004-05-16 Ross Johnson + + * cancel9.c: New test. + * cancel3.c: Remove inappropriate conditional compilation; + GNU C version of test suite no longer quietly skips this test. + * cancel5.c: Likewise. + * GNUmakefile: Can now build individual test app using default + C version of library using 'make clean testname.c'. + * Makefile: Likewise for VC using 'nmake clean test testname.c'. + +2003-10-14 Ross Johnson + + * Wmakefile: New makefile for Watcom testing. + +2003-09-18 Ross Johnson + + * benchtest.h: Move old mutex code into benchlib.c. + * benchlib.c: New statically linked module to ensure that + bench apps don't inline the code and therefore have an unfair + advantage over the pthreads lib routines. Made little or no + difference. + * benchtest1.c: Minor change to avoid compiler warnings. + * benchtest5.c: Likewise. + * benchtest2.c: Fix misinformation in output report. + * README.BENCH: Add comments on results. + +2003-09-14 Ross Johnson + + * priority1.c: Reworked to comply with modified priority + management and provide additional output. + * priority2.c: Likewise. + * inherit1.c: Likewise. + +2003-09-03 Ross Johnson + + * exit4.c: New test. + * exit5.c: New test. + * cancel7.c: New test. + * cancel8.c: New test. + +2003-08-13 Ross Johnson + + * reuse1.c: New test. + * reuse1.c: New test. + * valid1.c: New test. + * valid2.c: New test. + * kill1.c: New test. + * create2.c: Now included in test regime. + +2003-07-19 Ross Johnson + + * eyal1.c (waste_time): Make threads do more work to ensure that + all threads get to do some work. + * semaphore1.c: Make it clear that certain errors are expected. + * exception2.c (non_MSVC code sections): Change to include + C++ standard include file, i.e. change to . + * exception3.c (non_MSVC code sections): Likewise; qualify std:: + namespace entities where necessary. + * GNUmakefile: modified to work in the MsysDTK (newer MinGW) + environment; define CC as gcc or g++ as appropriate because + using gcc -x c++ doesn't link with required c++ libs by default, + but g++ does. + +2002-12-11 Ross Johnson + + * mutex7e.c: Assert EBUSY return instead of EDEADLK. + +2002-06-03 Ross Johnson + + * semaphore2.c: New test. + +2002-03-02 Ross Johnson + + * Makefile (CFLAGS): Changed /MT to /MD to link with + the correct library MSVCRT.LIB. Otherwise errno doesn't + work. + +2002-02-28 Ross Johnson + + * exception3.c: Correct recent change. + + * semaphore1.c: New test. + + * Makefile: Add rule to generate pre-processor output. + +2002-02-28 Ross Johnson + + * exception3.c (terminateFunction): For MSVC++, call + exit() rather than pthread_exit(). Add comments to explain + why. + * Notes from the MSVC++ manual: + * 1) A term_func() should call exit(), otherwise + * abort() will be called on return to the caller. + * abort() raises SIGABRT. The default signal handler + * for all signals terminates the calling program with + * exit code 3. + * 2) A term_func() must not throw an exception. Therefore + * term_func() should not call pthread_exit() if an + * an exception-using version of pthreads-win32 library + * is being used (i.e. either pthreadVCE or pthreadVSE). + + +2002-02-23 Ross Johnson + + * rwlock2_t.c: New test. + * rwlock3_t.c: New test. + * rwlock4_t.c: New test. + * rwlock5_t.c: New test. + * rwlock6_t.c: New test. + * rwlock6_t2.c: New test. + * rwlock6.c (main): Swap thread and result variables + to correspond to actual thread functions. + * rwlock1.c: Change test description comment to correspond + to the actual test. + + * condvar1_2.c: Loop over the test many times in the hope + of detecting any intermittent deadlocks. This is to + test a fixed problem in pthread_cond_destroy.c. + + * spin4.c: Remove unused variable. + +2002-02-17 Ross Johnson + + * condvar1_1.c: New test. + * condvar1_2.c: New test. + +2002-02-07 Ross Johnson + + * delay1.c: New test. + * delay2.c: New test. + * exit4.c: New test. + +2002-02-02 Ross Johnson + + * mutex8: New test. + * mutex8n: New test. + * mutex8e: New test. + * mutex8r: New test. + * cancel6a: New test. + * cancel6d: New test. + * cleanup0.c: Add pragmas for inline optimisation control. + * cleanup1.c: Add pragmas for inline optimisation control. + * cleanup2.c: Add pragmas for inline optimisation control. + * cleanup3.c: Add pragmas for inline optimisation control. + * condvar7.c: Add pragmas for inline optimisation control. + * condvar8.c: Add pragmas for inline optimisation control. + * condvar9.c: Add pragmas for inline optimisation control. + +2002-01-30 Ross Johnson + + * cleanup1.c (): Must be declared __cdecl when compiled + as C++ AND testing the standard C library version. + +2002-01-16 Ross Johnson + + * spin4.c (main): Fix renamed function call. + +2002-01-14 Ross Johnson + + * exception3.c (main): Shorten wait time. + +2002-01-09 Ross Johnson + + * mutex7.c: New test. + * mutex7n.c: New test. + * mutex7e.c: New test. + * mutex7r.c: New test. + * mutex6.c: Modified to avoid leaving the locked mutex + around on exit. + +2001-10-25 Ross Johnson + + * condvar2.c: Remove reference to cv->nWaitersUnblocked. + * condvar2_1.c: Likewise; lower NUMTHREADS from 60 to 30. + * condvar3_1.c: Likewise. + * condvar3_2.c: Likewise. + * count1.c: lower NUMTHREADS from 60 to 30. + * inherit1.c: Determine valid priority values and then + assert values returned by POSIX routines are the same. + * priority1.c: Likewise. + * priority2.c: Likewise. + +2001-07-12 Ross Johnson + + * barrier5.c: Assert that precisely one thread receives + PTHREAD_BARRIER_SERIAL_THREAD at each barrier. + +2001-07-09 Ross Johnson + + * barrier3.c: Fixed. + * barrier4.c: Fixed. + * barrier5.c: New; proves that all threads in the group + reaching the barrier wait and then resume together. Repeats the test + using groups of 1 to 16 threads. Each group of threads must negotiate + a large number of barriers (10000). + * spin4.c: Fixed. + * test.h (error_string): Modified the success (0) value. + +2001-07-07 Ross Johnson + + * spin3.c: Changed test and fixed. + * spin4.c: Fixed. + * barrier3.c: Fixed. + * barrier4.c: Fixed. + +2001-07-05 Ross Johnson + + * spin1.c: New; testing spinlocks. + * spin2.c: New; testing spinlocks. + * spin3.c: New; testing spinlocks. + * spin4.c: New; testing spinlocks. + * barrier1.c: New; testing barriers. + * barrier2.c: New; testing barriers. + * barrier3.c: New; testing barriers. + * barrier4.c: New; testing barriers. + * GNUmakefile: Add new tests. + * Makefile: Add new tests. + +2001-07-01 Ross Johnson + + * benchtest3.c: New; timing mutexes. + * benchtest4.c: New; time mutexes. + * condvar3_1.c: Fixed bug - Alexander Terekhov + * condvar3_3.c: New test. + +2001-06-25 Ross Johnson + + * priority1.c: New test. + * priority2.c: New test. + * inherit1.c: New test. + * benchtest1.c: New; timing mutexes. + * benchtest2.c: New; timing mutexes. + * mutex4.c: Modified to test all mutex types. + +2001-06-8 Ross Johnson + + * mutex5.c: Insert inert change to quell compiler warnings. + * condvar3_2.c: Remove unused variable. + +2001-06-3 Ross Johnson + + * condvar2_1.c: New test. + * condvar3_1.c: New test. + * condvar3_2.c: New test. + +2001-05-30 Ross Johnson + + * mutex1n.c: New test. + * mutex1e.c: New test. + * mutex1r.c: New test. + * mutex4.c: Now locks and unlocks a mutex. + * mutex5.c: New test. + * mutex6.c: New test. + * mutex6n.c: New test. + * mutex6e.c: New test. + * mutex6r.c: New test. + * Makefile: Added new tests; reorganised. + * GNUmakefile: Likewise. + * rwlock6.c: Fix to properly prove read-while-write locking + and single writer locking. + +2001-05-29 Ross Johnson + + * Makefile: Reorganisation. + * GNUmakefile: Likewise. + - Thomas Pfaff + + * exception1.c: Add stdio.h include to define fprintf and stderr + in non-exception C version of main(). + * exception2.c: Likewise. + * exception3.c: Likewise. + + * Makefile (rwlock7): Add new test. + * GNUmakefile (rwlock7): Add new test. + * rwlock7.c: New test. + * rwlock6.c: Changed to test that writer has priority. + + * eyal1.c (main): Unlock each mutex_start lock before destroying + it. + +2000-12-29 Ross Johnson + + * GNUmakefile: Add mutex4 test; ensure libpthreadw32.a is + removed for "clean" target. + * Makefile: Add mutex4 test. + + * exception3.c: Remove SEH code; automatically pass the test + under SEH (which is an N/A environment). + + * mutex4.c: New test. + + * eyal1.c (do_work_unit): Add a dummy "if" to force the + optimiser to retain code; reduce thread work loads. + + * condvar8.c (main): Add an additional "assert" for debugging; + increase pthread_cond_signal timeout. + +2000-12-28 Ross Johnson + + * eyal1.c: Increase thread work loads. + * exception2.c: New test. + * exception3.c: New test. + * Makefile: Add new tests exception2.c and exception3.c. + * GNUmakefile: Likewise. + +2000-12-11 Ross Johnson + + * cleanup3.c: Remove unused variable. + * cleanup2.c: Likewise. + * exception1.c: Throw an exception rather than use + a deliberate zero divide so that catch(...) will + handle it under Mingw32. Mingw32 now builds the + library correctly to pass all tests - see Thomas + Pfaff's detailed instructions re needed changes + to Mingw32 in the Pthreads-Win32 FAQ. + +2000-09-08 Ross Johnson + + * cancel5.c: New; tests calling pthread_cancel() + from the main thread without first creating a + POSIX thread struct for the non-POSIX main thread + - this forces pthread_cancel() to create one via + pthread_self(). + * Makefile (cancel5): Add new test. + * GNUmakefile (cancel5): Likewise. + +2000-08-17 Ross Johnson + + * create2.c: New; Test that pthread_t contains + the W32 HANDLE before it calls the thread routine + proper. + +2000-08-13 Ross Johnson + + * condvar3.c: Minor change to eliminate compiler + warning. + + * condvar4.c: ditto. + + * condvar5.c: ditto. + + * condvar6.c: ditto. + + * condvar7.c: ditto. + + * condvar8.c: ditto. + + * condvar9.c: ditto. + + * exit1.c: Function needed return statement. + + * cleanup1.c: Remove unnecessary printf arg. + + * cleanup2.c: Fix cast. + + * rwlock6.c: Fix casts. + + * exception1.c (PtW32CatchAll): Had the wrong name; + fix casts. + + * cancel3.c: Remove unused waitLock variable. + + * GNUmakefile: Change library/dll naming; add new tests; + general minor changes. + + * Makefile: Change library/dll naming; add targets for + testing each of the two VC++ EH scheme versions; + default target now issues help message; compile warnings + now interpreted as errors to stop the make; add new + tests; restructure to remove prerequisites needed + otherwise. + + * README: Updated. + + +2000-08-10 Ross Johnson + + * eyal1.c (main): Change implicit cast to explicit + cast when passing "print_server" function pointer; + G++ no longer allows implicit func parameter casts. + + * cleanup1.c: Remove unused "waitLock". + (main): Fix implicit parameter cast. + + * cancel2.c (main): Fix implicit parameter cast. + + * cancel4.c (main): Fix implicit parameter cast. + + * cancel3.c (main): Fix implicit parameter cast. + + * GNUmakefile: Renamed from Makefile; Add missing + cancel1 and cancel2 test targets. + + * Makefile: Converted for use with MS nmake. + +2000-08-06 Ross Johnson + + * ccl.bat: Add /nologo to remove extraneous output. + + * exception1.c (exceptionedThread): Init 'dummy'; + put expression into if condition to prevent optimising away; + remove unused variable. + + * cancel4.c (mythread): Cast return value to avoid warnings. + + * cancel2.c (mythread): Missing #endif. + + * condvar9.c (mythread): Cast return value to avoid warnings. + + * condvar8.c (mythread): Cast return value to avoid warnings. + + * condvar7.c (mythread): Cast return value to avoid warnings. + + * cleanup3.c (mythread): Cast return value to avoid warnings. + + * cleanup2.c (mythread): Cast return value to avoid warnings. + + * cleanup1.c (mythread): Cast return value to avoid warnings. + + * condvar5.c (mythread): Cast return value to avoid warnings. + + * condvar3.c (mythread): Cast return value to avoid warnings. + + * condvar6.c (mythread): Cast return value to avoid warnings. + + * condvar4.c (mythread): Cast return value to avoid warnings. + +2000-08-05 Ross Johnson + + * cancel2.c: Use PtW32CatchAll macro if defined. + + * exception1.c: Use PtW32CatchAll macro if defined. + +2000-08-02 Ross Johnson + + * tsd1.c: Fix typecasts of &result [g++ is now very fussy]. + + * test.h (assert): Return 0's explicitly to allay + g++ errors. + + * join2.c: Add explicit typecasts. + + * join1.c: Add explicit typecasts. + + * join0.c: Add explicit typecasts. + + * eyal1.c: Add explicit typecasts. + + * count1.c (main): Add type cast to remove g++ parse warning + [gcc-2.95.2 seems to have tightened up on this]. + + * Makefile (GLANG): Use c++ explicitly. + Remove MSVC sections (was commented out). + Add target to generate cpp output. + +2000-07-25 Ross Johnson + + * runtest.bat: modified to work under W98. + + * runall.bat: Add new tests; modified to work under W98. + It was ok under NT. + + * Makefile: Add new tests. + + * exception1.c: New; Test passing exceptions back to the + application and retaining library internal exceptions. + + * join0.c: New; Test a single join. + +2000-01-06 Ross Johnson + + * cleanup1.c: New; Test cleanup handler executes (when thread is + canceled). + + * cleanup2.c: New; Test cleanup handler executes (when thread is + not canceled). + + * cleanup3.c: New; Test cleanup handler does not execute + (when thread is not canceled). + +2000-01-04 Ross Johnson + + * cancel4.c: New; Test cancelation does not occur in deferred + cancelation threads with no cancelation points. + + * cancel3.c: New; Test asynchronous cancelation. + + * context1.c: New; Test context switching method for async + cancelation. + +1999-11-23 Ross Johnson + + * test.h: Add header includes; include local header versions rather + than system versions; rearrange the assert macro defines. + +1999-11-07 Ross Johnson + + * loadfree.c: New. Test loading and freeing the library (DLL). + +1999-10-30 Ross Johnson + + * cancel1.c: New. Test pthread_setcancelstate and + pthread_setcanceltype functions. + * eyal1.c (waste_time): Change calculation to avoid FP exception + on Aplhas + - Rich Peters + +Oct 14 1999 Ross Johnson + + * condvar7.c: New. Test broadcast after waiting thread is canceled. + * condvar8.c: New. Test multiple broadcasts. + * condvar9.c: New. Test multiple broadcasts with thread + cancelation. + +Sep 16 1999 Ross Johnson + + * rwlock6.c: New test. + +Sep 15 1999 Ross Johnson + + * rwlock1.c: New test. + * rwlock2.c: New test. + * rwlock3.c: New test. + * rwlock4.c: New test. + * rwlock5.c: New test. + +Aug 22 1999 Ross Johnson + + * runall.bat (join2): Add test. + +Aug 19 1999 Ross Johnson + + * join2.c: New test. + +Wed Aug 12 1999 Ross Johnson + + * Makefile (LIBS): Add -L. + +Mon May 31 10:25:01 1999 Ross Johnson + + * Makefile (GLANG): Add GCC language option. + +Sat May 29 23:29:04 1999 Ross Johnson + + * runall.bat (condvar5): Add new test. + + * runall.bat (condvar6): Add new test. + + * Makefile (condvar5) : Add new test. + + * Makefile (condvar6) : Add new test. + + * condvar5.c: New test for pthread_cond_broadcast(). + + * condvar6.c: New test for pthread_cond_broadcast(). + +Sun Apr 4 12:04:28 1999 Ross Johnson + + * tsd1.c (mythread): Change Sleep(0) to sched_yield(). + (sched.h): Include. + + * condvar3.c (mythread): Remove redundant Sleep(). + + * runtest.bat: Re-organised to make more informative. + +Fri Mar 19 1999 Ross Johnson + + * *.bat: redirect unwanted output to nul: + + * runall.bat: new. + + * cancel1.c: new. Not part of suite yet. + +Mon Mar 15 00:17:55 1999 Ross Johnson + + * mutex1.c: only test mutex init and destroy; add assertions. + + * count1.c: raise number of spawned threads to 60 (appears to + be the limit under Win98). + +Sun Mar 14 21:31:02 1999 Ross Johnson + + * test.h (assert): add assertion trace option. + Use: + "#define ASSERT_TRACE 1" to turn it on, + "#define ASSERT_TRACE 0" to turn it off (default). + + * condvar3.c (main): add more assertions. + + * condvar4.c (main): add more assertions. + + * condvar1.c (main): add more assertions. + +Fri Mar 12 08:34:15 1999 Ross Johnson + + * condvar4.c (cvthing): switch the order of the INITIALIZERs. + + * eyal1.c (main): Fix trylock loop; was not waiting for thread to lock + the "started" mutex. + +Wed Mar 10 10:41:52 1999 Ross Johnson + + * tryentercs.c: Apply typo patch from bje. + + * tryentercs2.c: Ditto. + +Sun Mar 7 10:41:52 1999 Ross Johnson + + * Makefile (condvar3, condvar4): Add tests. + + * condvar4.c (General): Reduce to simple test case; prerequisite + is condvar3.c; add description. + + * condvar3.c (General): Reduce to simple test case; prerequisite + is condvar2.c; add description. + + * condvar2.c (General): Reduce to simple test case; prerequisite + is condvar1.c; add description. + + * condvar1.c (General): Reduce to simple test case; add + description. + + * Template.c (Comments): Add generic test detail. + +1999-02-23 Ross Johnson + + * Template.c: Revamp. + + * condvar1.c: Add. + + * condvar2.c: Add. + + * Makefile: Add condvar1 condvar2 tests. + + * exit1.c, exit2.c, exit3.c: Cosmetic changes. + +1999-02-23 Ross Johnson + + * Makefile: Some refinement. + + * *.c: More exhaustive checking through assertions; clean up; + add some more tests. + + * Makefile: Now actually runs the tests. + + * tests.h: Define our own assert macro. The Mingw32 + version pops up a dialog but we want to run non-interactively. + + * equal1.c: use assert a little more directly so that it + prints the actual call statement. + + * exit1.c: Modify to return 0 on success, 1 on failure. + +1999-02-22 Ross Johnson + + * self2.c: Bring up to date. + + * self3.c: Ditto. + +1999-02-21 Ben Elliston + + * README: Update. + + * Makefile: New file. Run all tests automatically. Primitive tests + are run first; more complex tests are run last. + + * count1.c: New test. Validate the thread count. + + * exit2.c: Perform a simpler test. + + * exit3.c: New test. Replaces exit2.c, since exit2.c needs to + perform simpler checking first. + + * create1.c: Update to use the new testsuite exiting convention. + + * equal1.c: Likewise. + + * mutex1.c: Likewise. + + * mutex2.c: Likewise. + + * once1.c: Likewise. + + * self2.c: Likewise. + + * self3.c: Likewise. + + * tsd1.c: Likewise. + +1999-02-20 Ross Johnson + + * mutex2.c: Test static mutex initialisation. + + * test.h: New. Declares a table mapping error numbers to + error names. + +1999-01-17 Ross Johnson + + * runtest: New script to build and run a test in the tests directory. + +Wed Dec 30 11:22:44 1998 Ross Johnson + + * tsd1.c: Re-written. See comments at start of file. + * Template.c: New. Contains skeleton code and comment template + intended to fully document the test. + +Fri Oct 16 17:59:49 1998 Ross Johnson + + * tsd1.c (destroy_key): Add function. Change diagnostics. + +Thu Oct 15 17:42:37 1998 Ross Johnson + + * tsd1.c (mythread): Fix some casts and add some message + output. Fix inverted conditional. + +Mon Oct 12 02:12:29 1998 Ross Johnson + + * tsd1.c: New. Test TSD using 1 key and 2 threads. + +1998-09-13 Ben Elliston + + * eyal1.c: New file; contributed by Eyal Lebedinsky + . + +1998-09-12 Ben Elliston + + * exit2.c (func): Return a value. + (main): Call the right thread entry function. + +1998-07-22 Ben Elliston + + * exit2.c (main): Fix size of pthread_t array. + +1998-07-10 Ben Elliston + + * exit2.c: New file; test pthread_exit() harder. + + * exit1.c: New file; test pthread_exit(). diff --git a/w32-pthreads/tests/Debug.dsp b/w32-pthreads/tests/Debug.dsp new file mode 100644 index 000000000..191b97862 --- /dev/null +++ b/w32-pthreads/tests/Debug.dsp @@ -0,0 +1,93 @@ +# Microsoft Developer Studio Project File - Name="Debug" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=Debug - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "Debug.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "Debug.mak" CFG="Debug - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "Debug - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "Debug - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "Debug - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0xc09 /d "NDEBUG" +# ADD RSC /l 0xc09 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "Debug - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /MDd /W3 /WX /Gm /ZI /Od /I ".." /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "CLEANUP_C" /FR /YX /FD /GZ /c +# ADD BASE RSC /l 0xc09 /d "_DEBUG" +# ADD RSC /l 0xc09 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib pthreadVC2d.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:".." + +!ENDIF + +# Begin Target + +# Name "Debug - Win32 Release" +# Name "Debug - Win32 Debug" +# Begin Source File + +SOURCE=.\Debug.txt +# End Source File +# Begin Source File + +SOURCE=.\semaphore1.c +# End Source File +# End Target +# End Project diff --git a/w32-pthreads/tests/Debug.dsw b/w32-pthreads/tests/Debug.dsw new file mode 100644 index 000000000..5fd6af3e5 --- /dev/null +++ b/w32-pthreads/tests/Debug.dsw @@ -0,0 +1,29 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "Debug"=.\Debug.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/w32-pthreads/tests/Debug.plg b/w32-pthreads/tests/Debug.plg new file mode 100644 index 000000000..22ce672ce --- /dev/null +++ b/w32-pthreads/tests/Debug.plg @@ -0,0 +1,32 @@ + + +
+

Build Log

+

+--------------------Configuration: Debug - Win32 Debug-------------------- +

+

Command Lines

+Creating temporary file "C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\RSP9.tmp" with contents +[ +/nologo /MDd /W3 /WX /Gm /ZI /Od /I ".." /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "CLEANUP_C" /FR"Debug/" /Fp"Debug/Debug.pch" /YX /Fo"Debug/" /Fd"Debug/" /FD /GZ /c +"E:\PTHREADS\pthreads.2\tests\semaphore1.c" +] +Creating command line "cl.exe @C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\RSP9.tmp" +Creating temporary file "C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\RSPA.tmp" with contents +[ +kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib pthreadVC2d.lib /nologo /subsystem:console /incremental:yes /pdb:"Debug/Debug.pdb" /debug /machine:I386 /out:"Debug/Debug.exe" /pdbtype:sept /libpath:".." +.\Debug\semaphore1.obj +] +Creating command line "link.exe @C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\RSPA.tmp" +

Output Window

+Compiling... +semaphore1.c +Linking... + + + +

Results

+Debug.exe - 0 error(s), 0 warning(s) +
+ + diff --git a/w32-pthreads/tests/Debug.txt b/w32-pthreads/tests/Debug.txt new file mode 100644 index 000000000..5323874f4 --- /dev/null +++ b/w32-pthreads/tests/Debug.txt @@ -0,0 +1,6 @@ +This project is used to debug individual test case programs. + +To build and debug a test case: +- add the .c file to this project; +- remove any .c files from other test cases from this project. +- build and debug as usual. \ No newline at end of file diff --git a/w32-pthreads/tests/GNUmakefile b/w32-pthreads/tests/GNUmakefile new file mode 100644 index 000000000..4b586ecad --- /dev/null +++ b/w32-pthreads/tests/GNUmakefile @@ -0,0 +1,447 @@ +# Makefile for the pthreads test suite. +# If all of the .pass files can be created, the test suite has passed. +# +# -------------------------------------------------------------------------- +# +# Pthreads-win32 - POSIX Threads Library for Win32 +# Copyright(C) 1998 John E. Bossom +# Copyright(C) 1999,2005 Pthreads-win32 contributors +# +# Contact Email: rpj@callisto.canberra.edu.au +# +# The current list of contributors is contained +# in the file CONTRIBUTORS included with the source +# code distribution. The list can also be seen at the +# following World Wide Web location: +# http://sources.redhat.com/pthreads-win32/contributors.html +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2 of the License, or (at your option) any later version. +# +# This library 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library in the file COPYING.LIB; +# if not, write to the Free Software Foundation, Inc., +# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA +# + +DLL_VER = 2 + +CP = cp -f +MV = mv -f +RM = rm -f +CAT = cat +MKDIR = mkdir +TOUCH = echo Passed > +ECHO = @echo +MAKE = make -k + +# For cross compiling use e.g. +# # make CROSS=i386-mingw32msvc- clean GC +CROSS = + +# For cross testing use e.g. +# # make RUN=wine CROSS=i386-mingw32msvc- clean GC +RUN = + +AR = $(CROSS)ar +DLLTOOL = $(CROSS)dlltool +CC = $(CROSS)gcc +CXX = $(CROSS)g++ +RANLIB = $(CROSS)ranlib + +# +# Mingw32 +# +XXCFLAGS = +XXLIBS = -lws2_32 -lgomp +OPT = -O3 +DOPT = -g -O0 +#CFLAGS = -O3 -UNDEBUG -Wall $(XXCFLAGS) +CFLAGS = ${OPT} -UNDEBUG -Wall $(XXCFLAGS) +BUILD_DIR = .. +INCLUDES = -I. + +.INTERMEDIATE: %.exe %.pass +.SECONDARY: %.exe %.pass +.PRECIOUS: %.exe %.pass + +TEST = GC + +# Default lib version +GCX = $(TEST)$(DLL_VER) + +# Files we need to run the tests +# - paths are relative to pthreads build dir. +HDR = pthread.h semaphore.h sched.h +LIB = libpthread$(GCX).a +DLL = pthread$(GCX).dll +# The next path is relative to $BUILD_DIR +QAPC = # ../QueueUserAPCEx/User/quserex.dll + +COPYFILES = $(HDR) $(LIB) $(DLL) $(QAPC) + +# If a test case returns a non-zero exit code to the shell, make will +# stop. + +TESTS = \ + sizes loadfree \ + self1 mutex5 mutex1 mutex1e mutex1n mutex1r \ + semaphore1 semaphore2 semaphore3 \ + condvar1 condvar1_1 condvar1_2 condvar2 condvar2_1 exit1 \ + create1 create2 create3 reuse1 reuse2 equal1 \ + sequence1 kill1 valid1 valid2 \ + exit2 exit3 exit4 exit5 \ + join0 join1 detach1 join2 join3 \ + mutex2 mutex2r mutex2e mutex3 mutex3r mutex3e \ + mutex4 mutex6 mutex6n mutex6e mutex6r \ + mutex6s mutex6es mutex6rs \ + mutex7 mutex7n mutex7e mutex7r mutex8 mutex8n mutex8e mutex8r \ + robust1 robust2 robust3 robust4 robust5 \ + count1 \ + once1 once2 once3 once4 self2 \ + cancel1 cancel2 \ + semaphore4 semaphore4t semaphore5 \ + barrier1 barrier2 barrier3 barrier4 barrier5 barrier6 \ + tsd1 tsd2 openmp1 delay1 delay2 eyal1 \ + condvar3 condvar3_1 condvar3_2 condvar3_3 \ + condvar4 condvar5 condvar6 condvar7 condvar8 condvar9 \ + errno1 \ + rwlock1 rwlock2 rwlock3 rwlock4 rwlock5 rwlock6 rwlock7 rwlock8 \ + rwlock2_t rwlock3_t rwlock4_t rwlock5_t rwlock6_t rwlock6_t2 \ + context1 cancel3 cancel4 cancel5 cancel6a cancel6d \ + cancel7 cancel8 \ + cleanup0 cleanup1 cleanup2 cleanup3 \ + priority1 priority2 inherit1 \ + spin1 spin2 spin3 spin4 \ + exception1 exception2 exception3 \ + cancel9 stress1 + +STRESSTESTS = \ + stress1 + +BENCHTESTS = \ + benchtest1 benchtest2 benchtest3 benchtest4 benchtest5 + +STATICTESTS = \ + sizes \ + self1 mutex5 mutex1 mutex1e mutex1n mutex1r \ + semaphore1 semaphore2 semaphore3 \ + condvar1 condvar1_1 condvar1_2 condvar2 condvar2_1 exit1 \ + create1 create2 create3 reuse1 reuse2 equal1 \ + sequence1 kill1 valid1 valid2 \ + exit2 exit3 exit4 exit5 \ + join0 join1 detach1 join2 join3 \ + mutex2 mutex2r mutex2e mutex3 mutex3r mutex3e \ + mutex4 mutex6 mutex6n mutex6e mutex6r \ + mutex6s mutex6es mutex6rs \ + mutex7 mutex7n mutex7e mutex7r mutex8 mutex8n mutex8e mutex8r \ + robust1 robust2 robust3 robust4 robust5 \ + count1 \ + once1 once2 once3 once4 self2 \ + cancel1 cancel2 \ + semaphore4 semaphore4t semaphore5 \ + barrier1 barrier2 barrier3 barrier4 barrier5 barrier6 \ + tsd1 tsd2 delay1 delay2 eyal1 \ + condvar3 condvar3_1 condvar3_2 condvar3_3 \ + condvar4 condvar5 condvar6 condvar7 condvar8 condvar9 \ + errno1 \ + rwlock1 rwlock2 rwlock3 rwlock4 rwlock5 rwlock6 rwlock7 rwlock8 \ + rwlock2_t rwlock3_t rwlock4_t rwlock5_t rwlock6_t rwlock6_t2 \ + context1 cancel3 cancel4 cancel5 cancel6a cancel6d \ + cancel7 cancel8 \ + cleanup0 cleanup1 cleanup2 cleanup3 \ + priority1 priority2 inherit1 \ + spin1 spin2 spin3 spin4 \ + exception1 exception2 exception3 \ + cancel9 stress1 + +ALLTESTS = $(TESTS) $(BENCHTESTS) + +ASM = $(ALLTESTS:%=%.s) +PASSES = $(TESTS:%=%.pass) +BENCHRESULTS = $(BENCHTESTS:%=%.bench) +STRESSRESULTS = $(STRESSTESTS:%=%.pass) +STATICRESULTS = $(STATICTESTS:%=%.pass) + +help: + @ $(ECHO) "Run one of the following command lines:" + @ $(ECHO) "make clean GC (to test using GC dll with C (no EH) applications)" + @ $(ECHO) "make clean GCX (to test using GC dll with C++ (EH) applications)" + @ $(ECHO) "make clean GCE (to test using GCE dll with C++ (EH) applications)" + @ $(ECHO) "make clean GC-bench (to benchtest using GNU C dll with C cleanup code)" + @ $(ECHO) "make clean GCE-bench (to benchtest using GNU C dll with C++ exception handling)" + @ $(ECHO) "make clean GC-stress (to stresstest using GNU C dll with C cleanup code)" + @ $(ECHO) "make clean GCE-stress (to stresstest using GNU C dll with C++ exception handling)" + @ $(ECHO) "make clean GC-static (to test using GC static lib with C (no EH) applications)" + @ $(ECHO) "make clean GC-debug (to test using GC dll with C (no EH) applications)" + +all: + @ $(MAKE) clean GC + @ $(MAKE) clean GCX + @ $(MAKE) clean GCE + +GC: + $(MAKE) TEST=GC CC=$(CC) XXCFLAGS="-fopenmp -D__CLEANUP_C" all-pass + +GC-asm: + $(MAKE) TEST=GC CC=$(CC) XXCFLAGS="-fopenmp -D__CLEANUP_C" all-asm + +GCE: + $(MAKE) TEST=GCE CC=$(CXX) XXCFLAGS="-fopenmp -mthreads -D__CLEANUP_CXX" all-pass + +GCX: + $(MAKE) TEST=GC CC=$(CXX) XXCFLAGS="-fopenmp -mthreads -D__CLEANUP_C" all-pass + +GC-bench: + $(MAKE) TEST=GC CC=$(CC) XXCFLAGS="-D__CLEANUP_C" XXLIBS="benchlib.o" all-bench + +GCE-bench: + $(MAKE) TEST=GCE CC=$(CXX) XXCFLAGS="-mthreads -D__CLEANUP_CXX" XXLIBS="benchlib." all-bench + +GC-debug: + $(MAKE) TEST=GC CC=$(CC) XXCFLAGS="-fopenmp -D__CLEANUP_C" OPT="${DOPT}" DLL_VER="$(DLL_VER)d" all-pass + +GCE-debug: + $(MAKE) TEST=GCE CC=$(CXX) XXCFLAGS="-fopenmp -D__CLEANUP_CXX" OPT="${DOPT}" DLL_VER="$(DLL_VER)d" all-pass + +GC-bench-debug: + $(MAKE) TEST=GC CC=$(CC) XXCFLAGS="-D__CLEANUP_C" XXLIBS="benchlib.o" OPT="${OPT}" DLL_VER="$(DLL_VER)d" all-bench + +GC-static: + $(MAKE) TEST=GC CC=$(CC) XXCFLAGS="-D__CLEANUP_C -DPTW32_STATIC_LIB" XXLIBS="-lws2_32" DLL="" all-static + +GC-stress: + $(ECHO) Stress tests can take a long time since they are trying to + $(ECHO) expose weaknesses that may be intermittant or statistically rare. + $(ECHO) A pass does not prove correctness, but may give greater confidence. + $(MAKE) TEST=GC CC=$(CC) XXCFLAGS="-D__CLEANUP_C" XXLIBS="" all-stress + +GCE-stress: + $(MAKE) TEST=GCE CC=$(CXX) XXCFLAGS="-mthreads -D__CLEANUP_CXX" XXLIBS="" all-stress + +all-asm: $(ASM) + @ $(ECHO) ALL TESTS PASSED! Congratulations! + +all-pass: $(PASSES) + @ $(ECHO) ALL TESTS PASSED! Congratulations! + +all-bench: $(BENCHRESULTS) + @ $(ECHO) BENCH TESTS COMPLETED. + +all-stress: $(STRESSRESULTS) + @ $(ECHO) STRESS TESTS COMPLETED. + +all-static: $(STATICRESULTS) + @ $(ECHO) ALL STATIC TESTS PASSED! Congratulations! + +benchtest1.bench: +benchtest2.bench: +benchtest3.bench: +benchtest4.bench: +benchtest5.bench: + +barrier1.pass: semaphore4.pass +barrier2.pass: barrier1.pass +barrier3.pass: barrier2.pass +barrier4.pass: barrier3.pass +barrier5.pass: barrier4.pass +barrier6.pass: barrier5.pass +cancel1.pass: create1.pass +cancel2.pass: cancel1.pass +cancel3.pass: context1.pass +cancel4.pass: cancel3.pass +cancel5.pass: cancel3.pass +cancel6a.pass: cancel3.pass +cancel6d.pass: cancel3.pass +cancel7.pass: kill1.pass +cancel8.pass: cancel7.pass +cancel9.pass: cancel8.pass +cleanup0.pass: cancel5.pass +cleanup1.pass: cleanup0.pass +cleanup2.pass: cleanup1.pass +cleanup3.pass: cleanup2.pass +condvar1.pass: +condvar1_1.pass: condvar1.pass +condvar1_2.pass: join2.pass +condvar2.pass: condvar1.pass +condvar2_1.pass: condvar2.pass join2.pass +condvar3.pass: create1.pass condvar2.pass +condvar3_1.pass: condvar3.pass join2.pass +condvar3_2.pass: condvar3_1.pass +condvar3_3.pass: condvar3_2.pass +condvar4.pass: create1.pass +condvar5.pass: condvar4.pass +condvar6.pass: condvar5.pass +condvar7.pass: condvar6.pass cleanup1.pass +condvar8.pass: condvar7.pass +condvar9.pass: condvar8.pass +context1.pass: cancel1.pass +count1.pass: join1.pass +create1.pass: mutex2.pass +create2.pass: create1.pass +create3.pass: create2.pass +delay1.pass: +delay2.pass: delay1.pass +detach1.pass: join0.pass +equal1.pass: create1.pass +errno1.pass: mutex3.pass +exception1.pass: cancel4.pass +exception2.pass: exception1.pass +exception3.pass: exception2.pass +exit1.pass: +exit2.pass: create1.pass +exit3.pass: create1.pass +exit4.pass: +exit5.pass: exit4.pass kill1.pass +eyal1.pass: tsd1.pass +inherit1.pass: join1.pass priority1.pass +join0.pass: create1.pass +join1.pass: create1.pass +join2.pass: create1.pass +join3.pass: join2.pass +kill1.pass: +loadfree.pass: pthread.dll +mutex1.pass: self1.pass +mutex1n.pass: mutex1.pass +mutex1e.pass: mutex1.pass +mutex1r.pass: mutex1.pass +mutex2.pass: mutex1.pass +mutex2r.pass: mutex2.pass +mutex2e.pass: mutex2.pass +mutex3.pass: create1.pass +mutex3r.pass: mutex3.pass +mutex3e.pass: mutex3.pass +mutex4.pass: mutex3.pass +mutex5.pass: +mutex6.pass: mutex4.pass +mutex6n.pass: mutex4.pass +mutex6e.pass: mutex4.pass +mutex6r.pass: mutex4.pass +mutex6s.pass: mutex6.pass +mutex6rs.pass: mutex6r.pass +mutex6es.pass: mutex6e.pass +mutex7.pass: mutex6.pass +mutex7n.pass: mutex6n.pass +mutex7e.pass: mutex6e.pass +mutex7r.pass: mutex6r.pass +mutex8.pass: mutex7.pass +mutex8n.pass: mutex7n.pass +mutex8e.pass: mutex7e.pass +mutex8r.pass: mutex7r.pass +once1.pass: create1.pass +once2.pass: once1.pass +once3.pass: once2.pass +once4.pass: once3.pass +openmp1.pass: tsd2.pass +priority1.pass: join1.pass +priority2.pass: priority1.pass barrier3.pass +reuse1.pass: create3.pass +reuse2.pass: reuse1.pass +robust1.pass: mutex8r.pass +robust2.pass: mutex8r.pass +robust3.pass: robust2.pass +robust4.pass: robust3.pass +robust5.pass: robust4.pass +rwlock1.pass: condvar6.pass +rwlock2.pass: rwlock1.pass +rwlock3.pass: rwlock2.pass join2.pass +rwlock4.pass: rwlock3.pass +rwlock5.pass: rwlock4.pass +rwlock6.pass: rwlock5.pass +rwlock7.pass: rwlock6.pass +rwlock8.pass: rwlock7.pass +rwlock2_t.pass: rwlock2.pass +rwlock3_t.pass: rwlock2_t.pass +rwlock4_t.pass: rwlock3_t.pass +rwlock5_t.pass: rwlock4_t.pass +rwlock6_t.pass: rwlock5_t.pass +rwlock6_t2.pass: rwlock6_t.pass +self1.pass: +self2.pass: create1.pass +semaphore1.pass: +semaphore2.pass: +semaphore3.pass: semaphore2.pass +semaphore4.pass: semaphore3.pass cancel1.pass +semaphore4t.pass: semaphore4.pass +semaphore5.pass: semaphore4.pass +sequence1.pass: reuse2.pass +sizes.pass: +spin1.pass: +spin2.pass: spin1.pass +spin3.pass: spin2.pass +spin4.pass: spin3.pass +stress1.pass: +tsd1.pass: barrier5.pass join1.pass +tsd2.pass: tsd1.pass +valid1.pass: join1.pass +valid2.pass: valid1.pass + +sizes.pass: sizes.exe + @ $(ECHO) Running $* + @ $(RUN) ./$< > SIZES.$(TEST) + @ $(CAT) SIZES.$(TEST) + @ $(ECHO) Passed + @ $(TOUCH) $@ + +%.pass: %.exe + @ $(ECHO) Running $* + @ $(RUN) ./$* + @ $(ECHO) Passed + @ $(TOUCH) $@ + +%.bench: $(LIB) $(DLL) $(HDR) $(QAPC) $(XXLIBS) %.exe + @ $(ECHO) Running $* + @ $(RUN) ./$* + @ $(ECHO) Done + @ $(TOUCH) $@ + +%.exe: %.c $(LIB) $(DLL) $(HDR) $(QAPC) + @ $(ECHO) Compiling $@ + @ $(ECHO) $(CC) $(CFLAGS) -o $@ $< $(INCLUDES) -L. -lpthread$(GCX) -lsupc++ $(XXLIBS) + @ $(CC) $(CFLAGS) -o $@ $< $(INCLUDES) -L. -lpthread$(GCX) -lsupc++ $(XXLIBS) + +%.pre: %.c $(HDR) + @ $(CC) -E $(CFLAGS) -o $@ $< $(INCLUDES) + +%.s: %.c $(HDR) + @ $(ECHO) Compiling $@ + @ $(CC) -S $(CFLAGS) -o $@ $< $(INCLUDES) + +$(COPYFILES): + @ $(ECHO) Copying $(BUILD_DIR)/$@ + @ $(CP) $(BUILD_DIR)/$@ . + +benchlib.o: benchlib.c + @ $(ECHO) Compiling $@ + @ $(ECHO) $(CC) -c $(CFLAGS) $< $(INCLUDES) + @ $(CC) -c $(CFLAGS) $< $(INCLUDES) + +pthread.dll: $(DLL) + @ $(CP) $(DLL) $@ + +clean: + - $(RM) *.dll + - $(RM) *.lib + - $(RM) pthread.h + - $(RM) semaphore.h + - $(RM) sched.h + - $(RM) *.a + - $(RM) *.e + - $(RM) *.i + - $(RM) *.o + - $(RM) *.s + - $(RM) *.so + - $(RM) *.obj + - $(RM) *.pdb + - $(RM) *.exe + - $(RM) *.pass + - $(RM) *.bench + - $(RM) *.static + - $(RM) *.log diff --git a/w32-pthreads/tests/Makefile b/w32-pthreads/tests/Makefile new file mode 100644 index 000000000..b2163d8a6 --- /dev/null +++ b/w32-pthreads/tests/Makefile @@ -0,0 +1,450 @@ +# Makefile for the pthreads test suite. +# If all of the .pass files can be created, the test suite has passed. +# +# -------------------------------------------------------------------------- +# +# Pthreads-win32 - POSIX Threads Library for Win32 +# Copyright(C) 1998 John E. Bossom +# Copyright(C) 1999,2005 Pthreads-win32 contributors +# +# Contact Email: rpj@callisto.canberra.edu.au +# +# The current list of contributors is contained +# in the file CONTRIBUTORS included with the source +# code distribution. The list can also be seen at the +# following World Wide Web location: +# http://sources.redhat.com/pthreads-win32/contributors.html +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2 of the License, or (at your option) any later version. +# +# This library 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library in the file COPYING.LIB; +# if not, write to the Free Software Foundation, Inc., +# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA +# + +DLL_VER = 2 + +CP = copy +RM = erase +CAT = type +MKDIR = mkdir +TOUCH = echo Passed > +ECHO = echo + +# The next path is relative to $BUILD_DIR +QAPC = # ..\QueueUserAPCEx\User\quserex.dll + +CPHDR = pthread.h semaphore.h sched.h + +OPTIM = /O2 /Ob0 + +XXLIBS = ws2_32.lib + +# C++ Exceptions +VCEFLAGS = /EHsc /TP /DPtW32NoCatchWarn /D__CLEANUP_CXX +VCELIB = pthreadVCE$(DLL_VER).lib +VCEDLL = pthreadVCE$(DLL_VER).dll +# Structured Exceptions +VSEFLAGS = /D__CLEANUP_SEH +VSELIB = pthreadVSE$(DLL_VER).lib +VSEDLL = pthreadVSE$(DLL_VER).dll +# C cleanup code +VCFLAGS = /D__CLEANUP_C +VCLIB = pthreadVC$(DLL_VER).lib +VCDLL = pthreadVC$(DLL_VER).dll +# C++ Exceptions in application - using VC version of pthreads dll +VCXFLAGS = /EHsc /TP /D__CLEANUP_C + +# Defaults +CPLIB = $(VCLIB) +CPDLL = $(VCDLL) + +CFLAGS= $(OPTIM) /W3 /MD /nologo /Z7 +LFLAGS= /INCREMENTAL:NO +INCLUDES=-I. +BUILD_DIR=.. + +COPYFILES = $(CPHDR) $(CPLIB) $(CPDLL) $(QAPC) + +TEST = +EHFLAGS = + +# If a test case returns a non-zero exit code to the shell, make will +# stop. + +PASSES = sizes.pass $(REGULAR_PASSES) + +REGULAR_PASSES = loadfree.pass \ + self1.pass mutex5.pass \ + mutex1.pass mutex1n.pass mutex1e.pass mutex1r.pass \ + semaphore1.pass semaphore2.pass semaphore3.pass \ + mutex2.pass mutex3.pass \ + mutex2r.pass mutex2e.pass mutex3r.pass mutex3e.pass \ + condvar1.pass condvar1_1.pass condvar1_2.pass condvar2.pass condvar2_1.pass \ + exit1.pass create1.pass create2.pass create3.pass reuse1.pass reuse2.pass equal1.pass \ + sequence1.pass kill1.pass valid1.pass valid2.pass \ + exit2.pass exit3.pass exit4.pass exit5.pass \ + join0.pass join1.pass detach1.pass join2.pass join3.pass \ + mutex4.pass mutex6.pass mutex6n.pass mutex6e.pass mutex6r.pass \ + mutex6s.pass mutex6es.pass mutex6rs.pass \ + mutex7.pass mutex7n.pass mutex7e.pass mutex7r.pass \ + mutex8.pass mutex8n.pass mutex8e.pass mutex8r.pass \ + robust1.pass robust2.pass robust3.pass robust4.pass robust5.pass \ + count1.pass \ + once1.pass once2.pass once3.pass once4.pass \ + self2.pass \ + cancel1.pass cancel2.pass \ + semaphore4.pass semaphore4t.pass semaphore5.pass \ + barrier1.pass barrier2.pass barrier3.pass barrier4.pass barrier5.pass barrier6.pass \ + tsd1.pass tsd2.pass delay1.pass delay2.pass eyal1.pass \ + condvar3.pass condvar3_1.pass condvar3_2.pass condvar3_3.pass \ + condvar4.pass condvar5.pass condvar6.pass \ + condvar7.pass condvar8.pass condvar9.pass \ + errno1.pass \ + rwlock1.pass rwlock2.pass rwlock3.pass rwlock4.pass \ + rwlock5.pass rwlock6.pass rwlock7.pass rwlock8.pass \ + rwlock2_t.pass rwlock3_t.pass rwlock4_t.pass rwlock5_t.pass rwlock6_t.pass rwlock6_t2.pass \ + context1.pass \ + cancel3.pass cancel4.pass cancel5.pass cancel6a.pass cancel6d.pass \ + cancel7.pass cancel8.pass \ + cleanup0.pass cleanup1.pass cleanup2.pass cleanup3.pass \ + priority1.pass priority2.pass inherit1.pass \ + spin1.pass spin2.pass spin3.pass spin4.pass \ + exception1.pass exception2.pass exception3.pass \ + cancel9.pass stress1.pass + +BENCHRESULTS = \ + benchtest1.bench benchtest2.bench benchtest3.bench benchtest4.bench benchtest5.bench + +STRESSRESULTS = \ + stress1.stress + +STATICRESULTS = \ + sizes.pass \ + self1.pass mutex5.pass \ + mutex1.pass mutex1n.pass mutex1e.pass mutex1r.pass \ + semaphore1.pass semaphore2.pass semaphore3.pass \ + mutex2.pass mutex3.pass \ + mutex2r.pass mutex2e.pass mutex3r.pass mutex3e.pass \ + condvar1.pass condvar1_1.pass condvar1_2.pass condvar2.pass condvar2_1.pass \ + exit1.pass create1.pass create2.pass create3.pass reuse1.pass reuse2.pass equal1.pass \ + sequence1.pass kill1.pass valid1.pass valid2.pass \ + exit2.pass exit3.pass exit4.pass exit5.pass \ + join0.pass join1.pass detach1.pass join2.pass join3.pass \ + mutex4.pass mutex6.pass mutex6n.pass mutex6e.pass mutex6r.pass \ + mutex6s.pass mutex6es.pass mutex6rs.pass \ + mutex7.pass mutex7n.pass mutex7e.pass mutex7r.pass \ + mutex8.pass mutex8n.pass mutex8e.pass mutex8r.pass \ + robust1.pass robust2.pass robust3.pass robust4.pass robust5.pass \ + count1.pass \ + once1.pass once2.pass once3.pass once4.pass \ + self2.pass \ + cancel1.pass cancel2.pass \ + semaphore4.pass semaphore4t.pass semaphore5.pass \ + barrier1.pass barrier2.pass barrier3.pass barrier4.pass barrier5.pass barrier6.pass \ + tsd1.pass tsd2.pass delay1.pass delay2.pass eyal1.pass \ + condvar3.pass condvar3_1.pass condvar3_2.pass condvar3_3.pass \ + condvar4.pass condvar5.pass condvar6.pass \ + condvar7.pass condvar8.pass condvar9.pass \ + errno1.pass \ + rwlock1.pass rwlock2.pass rwlock3.pass rwlock4.pass \ + rwlock5.pass rwlock6.pass rwlock7.pass rwlock8.pass \ + rwlock2_t.pass rwlock3_t.pass rwlock4_t.pass rwlock5_t.pass rwlock6_t.pass rwlock6_t2.pass \ + context1.pass \ + cancel3.pass cancel4.pass cancel5.pass cancel6a.pass cancel6d.pass \ + cancel7.pass cancel8.pass \ + cleanup0.pass cleanup1.pass cleanup2.pass cleanup3.pass \ + priority1.pass priority2.pass inherit1.pass \ + spin1.pass spin2.pass spin3.pass spin4.pass \ + exception1.pass exception2.pass exception3.pass \ + cancel9.pass stress1.pass + +help: + @ $(ECHO) Run one of the following command lines: + @ $(ECHO) nmake clean VC (to test using VC dll with VC (no EH) apps) + @ $(ECHO) nmake clean VC-bench (to benchtest using VC dll with C bench apps) + @ $(ECHO) nmake clean VC-stress (to stresstest using VC dll with C stress apps) + @ $(ECHO) nmake clean VC-static (to test using VC static lib with VC (no EH) apps) + @ $(ECHO) nmake clean VCX (to test using VC dll with VC++ (EH) applications) + @ $(ECHO) nmake clean VCX-bench (to benchtest using VC dll with C++ bench apps) + @ $(ECHO) nmake clean VCX-stress (to stresstest using VC dll with C++ stress apps) + @ $(ECHO) nmake clean VCE (to test using the VCE dll with VC++ EH applications) + @ $(ECHO) nmake clean VCE-bench (to benchtest using VCE dll with C++ bench apps) + @ $(ECHO) nmake clean VCE-stress (to stresstest using VCE dll with C++ stress apps) + @ $(ECHO) nmake clean VSE (to test using VSE dll with VC (SEH) apps) + @ $(ECHO) nmake clean VSE-bench (to benchtest using VSE dll with SEH bench apps) + @ $(ECHO) nmake clean VSE-stress (to stresstest using VSE dll with SEH stress apps) + +all: + @ $(MAKE) /E clean VC + @ $(MAKE) /E clean VCX + @ $(MAKE) /E clean VCE + @ $(MAKE) /E clean VSE + @ $(MAKE) /E clean VC-bench + @ $(MAKE) /E clean VC-stress + +# This allows an individual test application to be made using the default lib. +# e.g. nmake clean test cancel3.exe +test: $(CPLIB) $(CPDLL) $(CPHDR) $(QAPC) + +tests: $(CPLIB) $(CPDLL) $(CPHDR) $(QAPC) $(PASSES) + @ $(ECHO) ALL TESTS PASSED! Congratulations! + +benchtests: $(CPLIB) $(CPDLL) $(CPHDR) $(XXLIBS) $(BENCHRESULTS) + @ $(ECHO) ALL BENCH TESTS DONE. + +stresstests: $(CPLIB) $(CPDLL) $(CPHDR) $(STRESSRESULTS) + @ $(ECHO) ALL STRESS TESTS DONE. + +statictests: $(CPLIB) $(CPDLL) $(CPHDR) $(STATICRESULTS) + @ $(ECHO) ALL STATIC TESTS DONE. + +sizes.pass: sizes.exe + @ $(ECHO) ... Running $(TEST)$(DLL_VER) test: $*.exe + @ .\$*.exe > SIZES.$(TEST) + @ $(CAT) SIZES.$(TEST) + @ $(ECHO) ...... Passed + @ $(TOUCH) $*.pass + +$(REGULAR_PASSES): $*.exe + @ $(ECHO) ... Running $(TEST) test: $*.exe + @ .\$*.exe + @ $(ECHO) ...... Passed + @ $(TOUCH) $*.pass + +$(BENCHRESULTS): $*.exe + @ $(ECHO) ... Running $(TEST) benchtest: $*.exe + @ .\$*.exe + @ $(ECHO) ...... Done + @ $(TOUCH) $*.bench + +$(STRESSRESULTS): $*.exe + @ $(ECHO) ... Running $(TEST) stresstest: $*.exe + @ .\$*.exe + @ $(ECHO) ...... Done + @ $(TOUCH) $*.pass + +VC: + @ $(MAKE) /E TEST="$@" CPLIB="$(VCLIB)" CPDLL="$(VCDLL)" EHFLAGS="$(VCFLAGS)" tests + +VCE: + @ $(MAKE) /E TEST="$@" CPLIB="$(VCELIB)" CPDLL="$(VCEDLL)" EHFLAGS="$(VCEFLAGS)" tests + +VSE: + @ $(MAKE) /E TEST="$@" CPLIB="$(VSELIB)" CPDLL="$(VSEDLL)" EHFLAGS="$(VSEFLAGS)" tests + +VCX: + @ $(MAKE) /E TEST="$@" CPLIB="$(VCLIB)" CPDLL="$(VCDLL)" EHFLAGS="$(VCXFLAGS)" tests + +VC-bench: + @ $(MAKE) /E TEST="$@" CPLIB="$(VCLIB)" CPDLL="$(VCDLL)" EHFLAGS="$(VCFLAGS)" XXLIBS="benchlib.o" benchtests + +VCE-bench: + @ $(MAKE) /E TEST="$@" CPLIB="$(VCELIB)" CPDLL="$(VCEDLL)" EHFLAGS="$(VCEFLAGS)" XXLIBS="benchlib.o" benchtests + +VSE-bench: + @ $(MAKE) /E TEST="$@" CPLIB="$(VSELIB)" CPDLL="$(VSEDLL)" EHFLAGS="$(VSEFLAGS)" XXLIBS="benchlib.o" benchtests + +VCX-bench: + @ $(MAKE) /E TEST="$@" CPLIB="$(VCLIB)" CPDLL="$(VCDLL)" EHFLAGS="$(VCXFLAGS)" XXLIBS="benchlib.o" benchtests + +VC-stress: + @ $(MAKE) /E TEST="$@" CPLIB="$(VCLIB)" CPDLL="$(VCDLL)" EHFLAGS="$(VCFLAGS)" stresstests + +VCE-stress: + @ $(MAKE) /E TEST="$@" CPLIB="$(VCELIB)" CPDLL="$(VCEDLL)" EHFLAGS="$(VCEFLAGS)" stresstests + +VSE-stress: + @ $(MAKE) /E TEST="$@" CPLIB="$(VSELIB)" CPDLL="$(VSEDLL)" EHFLAGS="$(VSEFLAGS)" stresstests + +VCX-stress: + @ $(MAKE) /E TEST="$@" CPLIB="$(VCLIB)" CPDLL="$(VCDLL)" EHFLAGS="$(VCXFLAGS)" stresstests + +VC-static: + @ $(MAKE) /E TEST="$@" CPLIB="$(VCLIB)" CPDLL="" EHFLAGS="$(VCFLAGS) /DPTW32_STATIC_LIB" statictests + +.c.exe: + @ $(ECHO) $(CC) $(EHFLAGS) $(CFLAGS) $(INCLUDES) $< /Fe$@ /link $(LFLAGS) $(CPLIB) $(XXLIBS) + @ $(CC) $(EHFLAGS) $(CFLAGS) $(INCLUDES) $< /Fe$@ /link $(LFLAGS) $(CPLIB) $(XXLIBS) + +.c.o: + @ $(ECHO) $(CC) $(EHFLAGS) /c $(CFLAGS) $(INCLUDES) $< /Fo$@ + @ $(CC) $(EHFLAGS) $(CFLAGS) /c $(INCLUDES) $< /Fo$@ + +.c.i: + @ $(CC) /P $(EHFLAGS) $(CFLAGS) $(INCLUDES) $< + +$(COPYFILES): + @ $(ECHO) Copying $(BUILD_DIR)\$@ + @ $(CP) $(BUILD_DIR)\$@ . + +pthread.dll: $(CPDLL) + @ $(CP) $(CPDLL) pthread.dll + @ $(CP) $(CPLIB) pthread.lib + +clean: + - $(RM) *.dll + - $(RM) *.lib + - $(RM) pthread.h + - $(RM) semaphore.h + - $(RM) sched.h + - $(RM) *.e + - $(RM) *.i + - $(RM) *.obj + - $(RM) *.pdb + - $(RM) *.o + - $(RM) *.asm + - $(RM) *.exe + - $(RM) *.pass + - $(RM) *.bench + - $(RM) *.log + +benchtest1.bench: +benchtest2.bench: +benchtest3.bench: +benchtest4.bench: +benchtest5.bench: + +barrier1.pass: semaphore4.pass +barrier2.pass: barrier1.pass +barrier3.pass: barrier2.pass +barrier4.pass: barrier3.pass +barrier5.pass: barrier4.pass +barrier6.pass: barrier5.pass +cancel1.pass: create1.pass +cancel2.pass: cancel1.pass +cancel3.pass: context1.pass +cancel4.pass: cancel3.pass +cancel5.pass: cancel3.pass +cancel6a.pass: cancel3.pass +cancel6d.pass: cancel3.pass +cancel7.pass: kill1.pass +cancel8.pass: cancel7.pass +cancel9.pass: cancel8.pass +cleanup0.pass: cancel5.pass +cleanup1.pass: cleanup0.pass +cleanup2.pass: cleanup1.pass +cleanup3.pass: cleanup2.pass +condvar1.pass: +condvar1_1.pass: condvar1.pass +condvar1_2.pass: join2.pass +condvar2.pass: condvar1.pass +condvar2_1.pass: condvar2.pass join2.pass +condvar3.pass: create1.pass condvar2.pass +condvar3_1.pass: condvar3.pass join2.pass +condvar3_2.pass: condvar3_1.pass +condvar3_3.pass: condvar3_2.pass +condvar4.pass: create1.pass +condvar5.pass: condvar4.pass +condvar6.pass: condvar5.pass +condvar7.pass: condvar6.pass cleanup1.pass +condvar8.pass: condvar7.pass +condvar9.pass: condvar8.pass +context1.pass: cancel1.pass +count1.pass: join1.pass +create1.pass: mutex2.pass +create2.pass: create1.pass +create3.pass: create2.pass +delay1.pass: +delay2.pass: delay1.pass +detach1.pass: join0.pass +equal1.pass: create1.pass +errno1.pass: mutex3.pass +exception1.pass: cancel4.pass +exception2.pass: exception1.pass +exception3.pass: exception2.pass +exit1.pass: +exit2.pass: create1.pass +exit3.pass: create1.pass +exit4.pass: +exit5.pass: kill1.pass +eyal1.pass: tsd1.pass +inherit1.pass: join1.pass priority1.pass +join0.pass: create1.pass +join1.pass: create1.pass +join2.pass: create1.pass +join3.pass: join2.pass +kill1.pass: +loadfree.pass: pthread.dll +mutex1.pass: self1.pass +mutex1n.pass: mutex1.pass +mutex1e.pass: mutex1.pass +mutex1r.pass: mutex1.pass +mutex2.pass: mutex1.pass +mutex2r.pass: mutex2.pass +mutex2e.pass: mutex2.pass +mutex3.pass: create1.pass +mutex3r.pass: mutex3.pass +mutex3e.pass: mutex3.pass +mutex4.pass: mutex3.pass +mutex5.pass: +mutex6.pass: mutex4.pass +mutex6n.pass: mutex4.pass +mutex6e.pass: mutex4.pass +mutex6r.pass: mutex4.pass +mutex6s.pass: mutex6.pass +mutex6rs.pass: mutex6r.pass +mutex6es.pass: mutex6e.pass +mutex7.pass: mutex6.pass +mutex7n.pass: mutex6n.pass +mutex7e.pass: mutex6e.pass +mutex7r.pass: mutex6r.pass +mutex8.pass: mutex7.pass +mutex8n.pass: mutex7n.pass +mutex8e.pass: mutex7e.pass +mutex8r.pass: mutex7r.pass +once1.pass: create1.pass +once2.pass: once1.pass +once3.pass: once2.pass +once4.pass: once3.pass +priority1.pass: join1.pass +priority2.pass: priority1.pass barrier3.pass +reuse1.pass: create3.pass +reuse2.pass: reuse1.pass +robust1.pass: mutex8r.pass +robust2.pass: mutex8r.pass +robust3.pass: robust2.pass +robust4.pass: robust3.pass +robust5.pass: robust4.pass +rwlock1.pass: condvar6.pass +rwlock2.pass: rwlock1.pass +rwlock3.pass: rwlock2.pass join2.pass +rwlock4.pass: rwlock3.pass +rwlock5.pass: rwlock4.pass +rwlock6.pass: rwlock5.pass +rwlock7.pass: rwlock6.pass +rwlock8.pass: rwlock7.pass +rwlock2_t.pass: rwlock2.pass +rwlock3_t.pass: rwlock2_t.pass +rwlock4_t.pass: rwlock3_t.pass +rwlock5_t.pass: rwlock4_t.pass +rwlock6_t.pass: rwlock5_t.pass +rwlock6_t2.pass: rwlock6_t.pass +self1.pass: +self2.pass: create1.pass +semaphore1.pass: +semaphore2.pass: +semaphore3.pass: semaphore2.pass +semaphore4.pass: semaphore3.pass cancel1.pass +semaphore4t.pass: semaphore4.pass +semaphore5.pass: semaphore4.pass +sequence1.pass: reuse2.pass +sizes.pass: +spin1.pass: +spin2.pass: spin1.pass +spin3.pass: spin2.pass +spin4.pass: spin3.pass +stress1.pass: condvar9.pass barrier5.pass +tsd1.pass: barrier5.pass join1.pass +tsd2.pass: tsd1.pass +valid1.pass: join1.pass +valid2.pass: valid1.pass diff --git a/w32-pthreads/tests/README b/w32-pthreads/tests/README new file mode 100644 index 000000000..a1b5646b9 --- /dev/null +++ b/w32-pthreads/tests/README @@ -0,0 +1,44 @@ +Running test cases in this directory +------------------------------------ + +These make scripts expect to be able to copy the dll, library +and header files from this directory's parent directory, +which should be the pthreads-win32 source directory. + +MS VC nmake +------------- + +Run the target corresponding to the DLL version being tested: + +nmake clean VC + +or: + +nmake clean VS + + +GNU GCC make +------------ + +Run "make clean" and then "make". See the "Known bugs" section +in ..\README. + + +Writing Test Cases +------------------ + +Tests written in this test suite should behave in the following manner: + + * If a test fails, leave main() with a result of 1. + + * If a test succeeds, leave main() with a result of 0. + + * No diagnostic output should appear when the test is succeeding. + Diagnostic output may be emitted if something in the test + fails, to help determine the cause of the test failure. + +Notes: +------ + +Many test cases use knowledge of implementation internals which are supposed +to be opaque to portable applications. diff --git a/w32-pthreads/tests/README.BENCHTESTS b/w32-pthreads/tests/README.BENCHTESTS new file mode 100644 index 000000000..448570c1f --- /dev/null +++ b/w32-pthreads/tests/README.BENCHTESTS @@ -0,0 +1,74 @@ + +------------ +Benchmarking +------------ +There is a set a benchmarking programs in the +"tests" directory. These should be runnable using the +following command-lines corresponding to each of the possible +library builds: + +MSVC: +nmake clean VC-bench +nmake clean VCE-bench +nmake clean VSE-bench + +Mingw32: +make clean GC-bench +make clean GCE-bench + +UWIN: +The benchtests are run as part of the testsuite. + + +Mutex benchtests +---------------- + +benchtest1 - Lock plus unlock on an unlocked mutex. +benchtest2 - Lock plus unlock on a locked mutex. +benchtest3 - Trylock on a locked mutex. +benchtest4 - Trylock plus unlock on an unlocked mutex. + + +Each test times up to three alternate synchronisation +implementations as a reference, and then times each of +the four mutex types provided by the library. Each is +described below: + +Simple Critical Section +- uses a simple Win32 critical section. There is no +additional overhead for this case as there is in the +remaining cases. + +POSIX mutex implemented using a Critical Section +- The old implementation which uses runtime adaptation +depending on the Windows variant being run on. When +the pthreads DLL was run on WinNT or higher then +POSIX mutexes would use Win32 Critical Sections. + +POSIX mutex implemented using a Win32 Mutex +- The old implementation which uses runtime adaptation +depending on the Windows variant being run on. When +the pthreads DLL was run on Win9x then POSIX mutexes +would use Win32 Mutexes (because TryEnterCriticalSection +is not implemented on Win9x). + +PTHREAD_MUTEX_DEFAULT +PTHREAD_MUTEX_NORMAL +PTHREAD_MUTEX_ERRORCHECK +PTHREAD_MUTEX_RECURSIVE +- The current implementation supports these mutex types. +The underlying basis of POSIX mutexes is now the same +irrespective of the Windows variant, and should therefore +have consistent performance. + + +Semaphore benchtests +-------------------- + +benchtest5 - Timing for various uncontended cases. + + +In all benchtests, the operation is repeated a large +number of times and an average is calculated. Loop +overhead is measured and subtracted from all test times. + diff --git a/w32-pthreads/tests/SIZES.GC b/w32-pthreads/tests/SIZES.GC new file mode 100644 index 000000000..4a575cb84 --- /dev/null +++ b/w32-pthreads/tests/SIZES.GC @@ -0,0 +1,21 @@ +Sizes of pthreads-win32 structs +------------------------------- + pthread_t 8 + ptw32_thread_t 160 + pthread_attr_t_ 28 + sem_t_ 12 + pthread_mutex_t_ 28 + pthread_mutexattr_t_ 12 + pthread_spinlock_t_ 8 + pthread_barrier_t_ 36 + pthread_barrierattr_t_ 4 + pthread_key_t_ 16 + pthread_cond_t_ 32 + pthread_condattr_t_ 4 + pthread_rwlock_t_ 28 + pthread_rwlockattr_t_ 4 + pthread_once_t_ 16 + ptw32_cleanup_t 12 + ptw32_mcs_node_t_ 16 + sched_param 4 +------------------------------- diff --git a/w32-pthreads/tests/SIZES.GCE b/w32-pthreads/tests/SIZES.GCE new file mode 100644 index 000000000..048b3ab93 --- /dev/null +++ b/w32-pthreads/tests/SIZES.GCE @@ -0,0 +1,21 @@ +Sizes of pthreads-win32 structs +------------------------------- + pthread_t 8 + ptw32_thread_t 96 + pthread_attr_t_ 28 + sem_t_ 12 + pthread_mutex_t_ 28 + pthread_mutexattr_t_ 12 + pthread_spinlock_t_ 8 + pthread_barrier_t_ 36 + pthread_barrierattr_t_ 4 + pthread_key_t_ 16 + pthread_cond_t_ 32 + pthread_condattr_t_ 4 + pthread_rwlock_t_ 28 + pthread_rwlockattr_t_ 4 + pthread_once_t_ 16 + ptw32_cleanup_t 12 + ptw32_mcs_node_t_ 16 + sched_param 4 +------------------------------- diff --git a/w32-pthreads/tests/SIZES.VC b/w32-pthreads/tests/SIZES.VC new file mode 100644 index 000000000..a73236de4 --- /dev/null +++ b/w32-pthreads/tests/SIZES.VC @@ -0,0 +1,21 @@ +Sizes of pthreads-win32 structs +------------------------------- + pthread_t 16 + ptw32_thread_t 432 + pthread_attr_t_ 40 + sem_t_ 24 + pthread_mutex_t_ 48 + pthread_mutexattr_t_ 12 + pthread_spinlock_t_ 16 + pthread_barrier_t_ 64 + pthread_barrierattr_t_ 4 + pthread_key_t_ 32 + pthread_cond_t_ 56 + pthread_condattr_t_ 4 + pthread_rwlock_t_ 40 + pthread_rwlockattr_t_ 4 + pthread_once_t_ 24 + ptw32_cleanup_t 24 + ptw32_mcs_node_t_ 32 + sched_param 4 +------------------------------- diff --git a/w32-pthreads/tests/SIZES.VCE b/w32-pthreads/tests/SIZES.VCE new file mode 100644 index 000000000..048b3ab93 --- /dev/null +++ b/w32-pthreads/tests/SIZES.VCE @@ -0,0 +1,21 @@ +Sizes of pthreads-win32 structs +------------------------------- + pthread_t 8 + ptw32_thread_t 96 + pthread_attr_t_ 28 + sem_t_ 12 + pthread_mutex_t_ 28 + pthread_mutexattr_t_ 12 + pthread_spinlock_t_ 8 + pthread_barrier_t_ 36 + pthread_barrierattr_t_ 4 + pthread_key_t_ 16 + pthread_cond_t_ 32 + pthread_condattr_t_ 4 + pthread_rwlock_t_ 28 + pthread_rwlockattr_t_ 4 + pthread_once_t_ 16 + ptw32_cleanup_t 12 + ptw32_mcs_node_t_ 16 + sched_param 4 +------------------------------- diff --git a/w32-pthreads/tests/SIZES.VSE b/w32-pthreads/tests/SIZES.VSE new file mode 100644 index 000000000..048b3ab93 --- /dev/null +++ b/w32-pthreads/tests/SIZES.VSE @@ -0,0 +1,21 @@ +Sizes of pthreads-win32 structs +------------------------------- + pthread_t 8 + ptw32_thread_t 96 + pthread_attr_t_ 28 + sem_t_ 12 + pthread_mutex_t_ 28 + pthread_mutexattr_t_ 12 + pthread_spinlock_t_ 8 + pthread_barrier_t_ 36 + pthread_barrierattr_t_ 4 + pthread_key_t_ 16 + pthread_cond_t_ 32 + pthread_condattr_t_ 4 + pthread_rwlock_t_ 28 + pthread_rwlockattr_t_ 4 + pthread_once_t_ 16 + ptw32_cleanup_t 12 + ptw32_mcs_node_t_ 16 + sched_param 4 +------------------------------- diff --git a/w32-pthreads/tests/Wmakefile b/w32-pthreads/tests/Wmakefile new file mode 100644 index 000000000..2b37c4691 --- /dev/null +++ b/w32-pthreads/tests/Wmakefile @@ -0,0 +1,355 @@ +# Watcom makefile for the pthreads test suite. +# If all of the .pass files can be created, the test suite has passed. +# +# -------------------------------------------------------------------------- +# +# Pthreads-win32 - POSIX Threads Library for Win32 +# Copyright(C) 1998 John E. Bossom +# Copyright(C) 1999,2005 Pthreads-win32 contributors +# +# Contact Email: rpj@callisto.canberra.edu.au +# +# The current list of contributors is contained +# in the file CONTRIBUTORS included with the source +# code distribution. The list can also be seen at the +# following World Wide Web location: +# http://sources.redhat.com/pthreads-win32/contributors.html +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2 of the License, or (at your option) any later version. +# +# This library 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 +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library in the file COPYING.LIB; +# if not, write to the Free Software Foundation, Inc., +# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA +# + + +DLL_VER = 2 + +.EXTENSIONS: + +.EXTENSIONS: .pass .exe .obj .i .c + +CP = copy +RM = erase +CAT = type +MKDIR = mkdir +TOUCH = echo Passed > +ECHO = @echo + +CPHDR = pthread.h semaphore.h sched.h + +OPTIM = -od + +XXLIBS = + +# C++ Exceptions +WCEFLAGS = -xs -dPtW32NoCatchWarn -d__CLEANUP_CXX +WCELIB = pthreadWCE$(DLL_VER).lib +WCEDLL = pthreadWCE$(DLL_VER).dll +# C cleanup code +WCFLAGS = -d__CLEANUP_C +WCLIB = pthreadWC$(DLL_VER).lib +WCDLL = pthreadWC$(DLL_VER).dll +# C++ Exceptions in application - using WC version of pthreads dll +WCXFLAGS = -xs -d__CLEANUP_C + +CFLAGS= -w4 -e25 -d_WIN32_WINNT=0x400 -d_REENTRANT -zq -bm $(OPTIM) -5r -bt=nt -mf -d2 + +LFLAGS= +INCLUDES= -i=. +BUILD_DIR=.. + +# The next path is relative to $BUILD_DIR +QAPC = # ..\QueueUserAPCEx\User\quserex.dll + +COPYFILES = $(CPHDR) $(CPLIB) $(CPDLL) $(QAPC) + +TEST = +EHFLAGS = + +# If a test case returns a non-zero exit code to the shell, make will +# stop. + +PASSES = sizes.pass loadfree.pass & + self1.pass mutex5.pass & + mutex1.pass mutex1n.pass mutex1e.pass mutex1r.pass & + semaphore1.pass semaphore2.pass semaphore3.pass & + mutex2.pass mutex3.pass & + mutex2r.pass mutex2e.pass mutex3r.pass mutex3e.pass & + condvar1.pass condvar1_1.pass condvar1_2.pass condvar2.pass condvar2_1.pass & + exit1.pass create1.pass create2.pass reuse1.pass reuse2.pass equal1.pass & + sequence1.pass kill1.pass valid1.pass valid2.pass & + exit2.pass exit3.pass exit4 exit5 & + join0.pass join1.pass detach1.pass join2.pass join3.pass & + mutex4.pass mutex6.pass mutex6n.pass mutex6e.pass mutex6r.pass & + mutex6s.pass mutex6es.pass mutex6rs.pass & + mutex7.pass mutex7n.pass mutex7e.pass mutex7r.pass & + mutex8.pass mutex8n.pass mutex8e.pass mutex8r.pass & + robust1.pass robust2.pass robust3.pass robust4.pass robust5.pass & + count1.pass & + once1.pass once2.pass once3.pass once4.pass tsd1.pass & + self2.pass & + cancel1.pass cancel2.pass & + semaphore4.pass semaphore4t.pass semaphore5.pass & + delay1.pass delay2.pass eyal1.pass & + condvar3.pass condvar3_1.pass condvar3_2.pass condvar3_3.pass & + condvar4.pass condvar5.pass condvar6.pass & + condvar7.pass condvar8.pass condvar9.pass & + errno1.pass & + rwlock1.pass rwlock2.pass rwlock3.pass rwlock4.pass rwlock5.pass & + rwlock6.pass rwlock7.pass rwlock8.pass & + rwlock2_t.pass rwlock3_t.pass rwlock4_t.pass rwlock5_t.pass rwlock6_t.pass rwlock6_t2.pass & + context1.pass & + cancel3.pass cancel4.pass cancel5.pass cancel6a.pass cancel6d.pass & + cancel7 cancel8 & + cleanup0.pass cleanup1.pass cleanup2.pass cleanup3.pass & + priority1.pass priority2.pass inherit1.pass & + spin1.pass spin2.pass spin3.pass spin4.pass & + barrier1.pass barrier2.pass barrier3.pass barrier4.pass barrier5.pass & + exception1.pass exception2.pass exception3.pass & + cancel9.pass stress1.pass + +BENCHRESULTS = & + benchtest1.bench benchtest2.bench benchtest3.bench benchtest4.bench benchtest5.bench + +help: .SYMBOLIC + @ $(ECHO) Run one of the following command lines: + @ $(ECHO) wmake /f Wmakefile clean WC (to test using WC dll with wcc386 (no EH) applications) + @ $(ECHO) wmake /f Wmakefile clean WCX (to test using WC dll with wpp386 (EH) applications) + @ $(ECHO) wmake /f Wmakefile clean WCE (to test using the WCE dll with wpp386 EH applications) + @ $(ECHO) wmake /f Wmakefile clean WC-bench (to benchtest using WC dll with C bench app) + @ $(ECHO) wmake /f Wmakefile clean WCX-bench (to benchtest using WC dll with C++ bench app) + @ $(ECHO) wmake /f Wmakefile clean WCE-bench (to benchtest using WCE dll with C++ bench app) + +all: .SYMBOLIC + @ wmake /f Wmakefile clean WC + @ wmake /f Wmakefile clean WCX + @ wmake /f Wmakefile clean WCE + @ wmake /f Wmakefile clean WSE + @ wmake /f Wmakefile clean WC-bench + +tests: $(CPLIB) $(CPDLL) $(CPHDR) $(PASSES) .SYMBOLIC + @ $(ECHO) ALL TESTS PASSED! Congratulations! + +benchtests: $(CPLIB) $(CPDLL) $(CPHDR) $(XXLIBS) $(BENCHRESULTS) .SYMBOLIC + @ $(ECHO) ALL BENCH TESTS DONE. + +$(BENCHRESULTS): ($[*).exe + @ $(ECHO) ... Running $(TEST) benchtest: ($[*).exe + @ .\($[*).exe + @ $(ECHO) ...... Done + @ $(TOUCH) ($[*).bench + +WCE: .SYMBOLIC + @ wmake /f Wmakefile CC=wpp386 TEST="$@" CPLIB="$(WCELIB)" CPDLL="$(WCEDLL)" EHFLAGS="$(WCEFLAGS)" tests + +WC: .SYMBOLIC + @ wmake /f Wmakefile CC=wcc386 TEST="$@" CPLIB="$(WCLIB)" CPDLL="$(WCDLL)" EHFLAGS="$(WCFLAGS)" tests + +WCX: .SYMBOLIC + @ wmake /f Wmakefile CC=wpp386 TEST="$@" CPLIB="$(WCLIB)" CPDLL="$(WCDLL)" EHFLAGS="$(WCXFLAGS)" tests + +WCE-bench: .SYMBOLIC + @ wmake /f Wmakefile CC=wpp386 TEST="$@" CPLIB="$(WCELIB)" CPDLL="$(WCEDLL)" EHFLAGS="$(WCEFLAGS)" XXLIBS="benchlib.o" benchtests + +WC-bench: .SYMBOLIC + @ wmake /f Wmakefile CC=wcc386 TEST="$@" CPLIB="$(WCLIB)" CPDLL="$(WCDLL)" EHFLAGS="$(WCFLAGS)" XXLIBS="benchlib.o" benchtests + +WCX-bench: .SYMBOLIC + @ wmake /f Wmakefile CC=wpp386 TEST="$@" CPLIB="$(WCLIB)" CPDLL="$(WCDLL)" EHFLAGS="$(WCXFLAGS)" XXLIBS="benchlib.o" benchtests + +sizes.pass: sizes.exe + @ $(ECHO) ... Running $(TEST) test: $^* + @ $[@ > SIZES.$(TEST) + @ $(CAT) SIZES.$(TEST) + @ $(ECHO) ...... Passed + @ $(TOUCH) $^@ + +.exe.pass: + @ $(ECHO) ... Running $(TEST) test: $^* + @ $[@ + @ $(ECHO) ...... Passed + @ $(TOUCH) $^@ + +.obj.exe: + @ $(ECHO) wlink NAME $^@ FILE $[@ LIBRARY $(CPLIB) OPTION quiet + @ wlink NAME $^@ FILE $[@ LIBRARY $(CPLIB) OPTION quiet + +.c.obj: + @ $(ECHO) $(CC) $^* $(EHFLAGS) $(CFLAGS) $(INCLUDES) + @ $(CC) $^* $(EHFLAGS) $(CFLAGS) $(INCLUDES) + +.c.i: + @ $(CC) /P $(EHFLAGS) $(CFLAGS) $(INCLUDES) $< + +$(COPYFILES): .SYMBOLIC + @ $(ECHO) Copying $(BUILD_DIR)\$@ + @ $(CP) $(BUILD_DIR)\$@ . + +pthread.dll: + @ $(CP) $(CPDLL) $*.dll + @ $(CP) $(CPLIB) $*.lib + +clean: .SYMBOLIC + @ if exist *.dll $(RM) *.dll + @ if exist *.lib $(RM) *.lib + @ if exist *.err $(RM) *.err + @ if exist pthread.h $(RM) pthread.h + @ if exist semaphore.h $(RM) semaphore.h + @ if exist sched.h $(RM) sched.h + @ if exist *.e $(RM) *.e + @ if exist *.i $(RM) *.i + @ if exist *.obj $(RM) *.obj + @ if exist *.pdb $(RM) *.pdb + @ if exist *.o $(RM) *.o + @ if exist *.asm $(RM) *.asm + @ if exist *.exe $(RM) *.exe + @ if exist *.pass $(RM) *.pass + @ if exist *.bench $(RM) *.bench + @ if exist *.log $(RM) *.log + @ $(ECHO) Clean completed. + +benchtest1.bench: +benchtest2.bench: +benchtest3.bench: +benchtest4.bench: +benchtest5.bench: +barrier1.pass: +barrier2.pass: barrier1.pass +barrier3.pass: barrier2.pass +barrier4.pass: barrier3.pass +barrier5.pass: barrier4.pass +cancel1.pass: create1.pass +cancel2.pass: cancel1.pass +cancel3.pass: context1.pass +cancel4.pass: cancel3.pass +cancel5.pass: cancel3.pass +cancel6a.pass: cancel3.pass +cancel6d.pass: cancel3.pass +cancel7.pass: kill1.pass +cancel8.pass: cancel7.pass +cleanup0.pass: cancel5.pass +cleanup1.pass: cleanup0.pass +cleanup2.pass: cleanup1.pass +cleanup3.pass: cleanup2.pass +condvar1.pass: +condvar1_1.pass: condvar1.pass +condvar1_2.pass: join2.pass +condvar2.pass: condvar1.pass +condvar2_1.pass: condvar2.pass join2.pass +condvar3.pass: create1.pass condvar2.pass +condvar3_1.pass: condvar3.pass join2.pass +condvar3_2.pass: condvar3_1.pass +condvar3_3.pass: condvar3_2.pass +condvar4.pass: create1.pass +condvar5.pass: condvar4.pass +condvar6.pass: condvar5.pass +condvar7.pass: condvar6.pass cleanup1.pass +condvar8.pass: condvar7.pass +condvar9.pass: condvar8.pass +context1.pass: cancel1.pass +count1.pass: join1.pass +create1.pass: mutex2.pass +create2.pass: create1.pass +delay1.pass: +delay2.pass: delay1.pass +detach1.pass: join0.pass +equal1.pass: create1.pass +errno1.pass: mutex3.pass +exception1.pass: cancel4.pass +exception2.pass: exception1.pass +exception3.pass: exception2.pass +exit1.pass: +exit2.pass: create1.pass +exit3.pass: create1.pass +exit4.pass: +exit5.pass: kill1.pass +eyal1.pass: tsd1.pass +inherit1.pass: join1.pass priority1.pass +join0.pass: create1.pass +join1.pass: create1.pass +join2.pass: create1.pass +join3.pass: join2.pass +kill1.pass: +loadfree.pass: pthread.dll +mutex1.pass: self1.pass +mutex1n.pass: mutex1.pass +mutex1e.pass: mutex1.pass +mutex1r.pass: mutex1.pass +mutex2.pass: mutex1.pass +mutex2r.pass: mutex2.pass +mutex2e.pass: mutex2.pass +mutex3.pass: create1.pass +mutex3r.pass: mutex3.pass +mutex3e.pass: mutex3.pass +mutex4.pass: mutex3.pass +mutex5.pass: +mutex6.pass: mutex4.pass +mutex6n.pass: mutex4.pass +mutex6e.pass: mutex4.pass +mutex6r.pass: mutex4.pass +mutex6s.pass: mutex6.pass +mutex6rs.pass: mutex6r.pass +mutex6es.pass: mutex6e.pass +mutex7.pass: mutex6.pass +mutex7n.pass: mutex6n.pass +mutex7e.pass: mutex6e.pass +mutex7r.pass: mutex6r.pass +mutex8.pass: mutex7.pass +mutex8n.pass: mutex7n.pass +mutex8e.pass: mutex7e.pass +mutex8r.pass: mutex7r.pass +once1.pass: create1.pass +once2.pass: once1.pass +once3.pass: once2.pass +once4.pass: once3.pass +priority1.pass: join1.pass +priority2.pass: priority1.pass barrier3.pass +reuse1.pass: create2.pass +reuse2.pass: reuse1.pass +robust1.pass: mutex8r.pass +robust2.pass: mutex8r.pass +robust3.pass: robust2.pass +robust4.pass: robust3.pass +robust5.pass: robust4.pass +rwlock1.pass: condvar6.pass +rwlock2.pass: rwlock1.pass +rwlock3.pass: rwlock2.pass join2.pass +rwlock4.pass: rwlock3.pass +rwlock5.pass: rwlock4.pass +rwlock6.pass: rwlock5.pass +rwlock7.pass: rwlock6.pass +rwlock2_t.pass: rwlock2.pass +rwlock3_t.pass: rwlock2_t.pass +rwlock4_t.pass: rwlock3_t.pass +rwlock5_t.pass: rwlock4_t.pass +rwlock6_t.pass: rwlock5_t.pass +rwlock6_t2.pass: rwlock6_t.pass +self1.pass: +self2.pass: create1.pass +semaphore1.pass: +semaphore2.pass: +semaphore3.pass: semaphore2.pass +semaphore4.pass: semaphore3.pass cancel1.pass +semaphore4t.pass: semaphore4.pass +semaphore5.pass: semaphore4.pass +sequence1.pass: reuse2.pass +sizes.pass: +spin1.pass: +spin2.pass: spin1.pass +spin3.pass: spin2.pass +spin4.pass: spin3.pass +stress1.pass: +tsd1.pass: join1.pass +valid1.pass: join1.pass +valid2.pass: valid1.pass +cancel9.pass: cancel8.pass diff --git a/w32-pthreads/tests/barrier1.c b/w32-pthreads/tests/barrier1.c new file mode 100644 index 000000000..76f78df66 --- /dev/null +++ b/w32-pthreads/tests/barrier1.c @@ -0,0 +1,58 @@ +/* + * barrier1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Create a barrier object and then destroy it. + * + */ + +#include "test.h" + +pthread_barrier_t barrier = NULL; + +int +main() +{ + assert(barrier == NULL); + + assert(pthread_barrier_init(&barrier, NULL, 1) == 0); + + assert(barrier != NULL); + + assert(pthread_barrier_destroy(&barrier) == 0); + + assert(barrier == NULL); + + return 0; +} diff --git a/w32-pthreads/tests/barrier2.c b/w32-pthreads/tests/barrier2.c new file mode 100644 index 000000000..28aa238c5 --- /dev/null +++ b/w32-pthreads/tests/barrier2.c @@ -0,0 +1,55 @@ +/* + * barrier2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a single barrier object, wait on it, + * and then destroy it. + * + */ + +#include "test.h" + +pthread_barrier_t barrier = NULL; + +int +main() +{ + assert(pthread_barrier_init(&barrier, NULL, 1) == 0); + + assert(pthread_barrier_wait(&barrier) == PTHREAD_BARRIER_SERIAL_THREAD); + + assert(pthread_barrier_destroy(&barrier) == 0); + + return 0; +} diff --git a/w32-pthreads/tests/barrier3.c b/w32-pthreads/tests/barrier3.c new file mode 100644 index 000000000..dece77068 --- /dev/null +++ b/w32-pthreads/tests/barrier3.c @@ -0,0 +1,71 @@ +/* + * barrier3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a single barrier object with barrier attribute, wait on it, + * and then destroy it. + * + */ + +#include "test.h" + +pthread_barrier_t barrier = NULL; +static void* result = (void*)1; + +void * func(void * arg) +{ + return (void *) (size_t)pthread_barrier_wait(&barrier); +} + +int +main() +{ + pthread_t t; + pthread_barrierattr_t ba; + + assert(pthread_barrierattr_init(&ba) == 0); + assert(pthread_barrierattr_setpshared(&ba, PTHREAD_PROCESS_PRIVATE) == 0); + assert(pthread_barrier_init(&barrier, &ba, 1) == 0); + + assert(pthread_create(&t, NULL, func, NULL) == 0); + + assert(pthread_join(t, &result) == 0); + + assert((int)(size_t)result == PTHREAD_BARRIER_SERIAL_THREAD); + + assert(pthread_barrier_destroy(&barrier) == 0); + assert(pthread_barrierattr_destroy(&ba) == 0); + + return 0; +} diff --git a/w32-pthreads/tests/barrier4.c b/w32-pthreads/tests/barrier4.c new file mode 100644 index 000000000..042992dfd --- /dev/null +++ b/w32-pthreads/tests/barrier4.c @@ -0,0 +1,110 @@ +/* + * barrier4.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a single barrier object, multiple wait on it, + * and then destroy it. + * + */ + +#include "test.h" + +enum { + NUMTHREADS = 16 +}; + +pthread_barrier_t barrier = NULL; +pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER; +static int serialThreadCount = 0; +static int otherThreadCount = 0; + +void * +func(void * arg) +{ + int result = pthread_barrier_wait(&barrier); + + assert(pthread_mutex_lock(&mx) == 0); + + if (result == PTHREAD_BARRIER_SERIAL_THREAD) + { + serialThreadCount++; + } + else if (0 == result) + { + otherThreadCount++; + } + else + { + printf("Barrier wait failed: error = %s\n", error_string[result]); + fflush(stdout); + return NULL; + } + assert(pthread_mutex_unlock(&mx) == 0); + + return NULL; +} + +int +main() +{ + int i, j; + pthread_t t[NUMTHREADS + 1]; + + for (j = 1; j <= NUMTHREADS; j++) + { + printf("Barrier height = %d\n", j); + + serialThreadCount = 0; + + assert(pthread_barrier_init(&barrier, NULL, j) == 0); + + for (i = 1; i <= j; i++) + { + assert(pthread_create(&t[i], NULL, func, NULL) == 0); + } + + for (i = 1; i <= j; i++) + { + assert(pthread_join(t[i], NULL) == 0); + } + + assert(serialThreadCount == 1); + + assert(pthread_barrier_destroy(&barrier) == 0); + } + + assert(pthread_mutex_destroy(&mx) == 0); + + return 0; +} diff --git a/w32-pthreads/tests/barrier5.c b/w32-pthreads/tests/barrier5.c new file mode 100644 index 000000000..353384081 --- /dev/null +++ b/w32-pthreads/tests/barrier5.c @@ -0,0 +1,118 @@ +/* + * barrier5.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Set up a series of barriers at different heights and test various numbers + * of threads accessing, especially cases where there are more threads than the + * barrier height (count), i.e. test contention when the barrier is released. + */ + +#include "test.h" + +enum { + NUMTHREADS = 15, + HEIGHT = 10, + BARRIERMULTIPLE = 1000 +}; + +pthread_barrier_t barrier = NULL; +pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER; +LONG totalThreadCrossings; + +void * +func(void * crossings) +{ + int result; + int serialThreads = 0; + + while ((LONG)(size_t)crossings >= (LONG)InterlockedIncrement((LPLONG)&totalThreadCrossings)) + { + result = pthread_barrier_wait(&barrier); + + if (result == PTHREAD_BARRIER_SERIAL_THREAD) + { + serialThreads++; + } + else if (result != 0) + { + printf("Barrier failed: result = %s\n", error_string[result]); + fflush(stdout); + return NULL; + } + } + + return (void*)(size_t)serialThreads; +} + +int +main() +{ + int i, j; + void* result; + int serialThreadsTotal; + LONG Crossings; + pthread_t t[NUMTHREADS + 1]; + + for (j = 1; j <= NUMTHREADS; j++) + { + int height = j +#include + +#ifdef __GNUC__ +#include +#endif + +#include "benchtest.h" + +int old_mutex_use = OLD_WIN32CS; + +BOOL (WINAPI *ptw32_try_enter_critical_section)(LPCRITICAL_SECTION) = NULL; +HINSTANCE ptw32_h_kernel32; + +void +dummy_call(int * a) +{ +} + +void +interlocked_inc_with_conditionals(int * a) +{ + if (a != NULL) + if (InterlockedIncrement((long *) a) == -1) + { + *a = 0; + } +} + +void +interlocked_dec_with_conditionals(int * a) +{ + if (a != NULL) + if (InterlockedDecrement((long *) a) == -1) + { + *a = 0; + } +} + +int +old_mutex_init(old_mutex_t *mutex, const old_mutexattr_t *attr) +{ + int result = 0; + old_mutex_t mx; + + if (mutex == NULL) + { + return EINVAL; + } + + mx = (old_mutex_t) calloc(1, sizeof(*mx)); + + if (mx == NULL) + { + result = ENOMEM; + goto FAIL0; + } + + mx->mutex = 0; + + if (attr != NULL + && *attr != NULL + && (*attr)->pshared == PTHREAD_PROCESS_SHARED + ) + { + result = ENOSYS; + } + else + { + CRITICAL_SECTION cs; + + /* + * Load KERNEL32 and try to get address of TryEnterCriticalSection + */ + ptw32_h_kernel32 = LoadLibrary(TEXT("KERNEL32.DLL")); + ptw32_try_enter_critical_section = (BOOL (WINAPI *)(LPCRITICAL_SECTION)) + +#if defined(NEED_UNICODE_CONSTS) + GetProcAddress(ptw32_h_kernel32, + (const TCHAR *)TEXT("TryEnterCriticalSection")); +#else + GetProcAddress(ptw32_h_kernel32, + (LPCSTR) "TryEnterCriticalSection"); +#endif + + if (ptw32_try_enter_critical_section != NULL) + { + InitializeCriticalSection(&cs); + if ((*ptw32_try_enter_critical_section)(&cs)) + { + LeaveCriticalSection(&cs); + } + else + { + /* + * Not really supported (Win98?). + */ + ptw32_try_enter_critical_section = NULL; + } + DeleteCriticalSection(&cs); + } + + if (ptw32_try_enter_critical_section == NULL) + { + (void) FreeLibrary(ptw32_h_kernel32); + ptw32_h_kernel32 = 0; + } + + if (old_mutex_use == OLD_WIN32CS) + { + InitializeCriticalSection(&mx->cs); + } + else if (old_mutex_use == OLD_WIN32MUTEX) + { + mx->mutex = CreateMutex (NULL, + FALSE, + NULL); + + if (mx->mutex == 0) + { + result = EAGAIN; + } + } + else + { + result = EINVAL; + } + } + + if (result != 0 && mx != NULL) + { + free(mx); + mx = NULL; + } + +FAIL0: + *mutex = mx; + + return(result); +} + + +int +old_mutex_lock(old_mutex_t *mutex) +{ + int result = 0; + old_mutex_t mx; + + if (mutex == NULL || *mutex == NULL) + { + return EINVAL; + } + + if (*mutex == (old_mutex_t) PTW32_OBJECT_AUTO_INIT) + { + /* + * Don't use initialisers when benchtesting. + */ + result = EINVAL; + } + + mx = *mutex; + + if (result == 0) + { + if (mx->mutex == 0) + { + EnterCriticalSection(&mx->cs); + } + else + { + result = (WaitForSingleObject(mx->mutex, INFINITE) + == WAIT_OBJECT_0) + ? 0 + : EINVAL; + } + } + + return(result); +} + +int +old_mutex_unlock(old_mutex_t *mutex) +{ + int result = 0; + old_mutex_t mx; + + if (mutex == NULL || *mutex == NULL) + { + return EINVAL; + } + + mx = *mutex; + + if (mx != (old_mutex_t) PTW32_OBJECT_AUTO_INIT) + { + if (mx->mutex == 0) + { + LeaveCriticalSection(&mx->cs); + } + else + { + result = (ReleaseMutex (mx->mutex) ? 0 : EINVAL); + } + } + else + { + result = EINVAL; + } + + return(result); +} + + +int +old_mutex_trylock(old_mutex_t *mutex) +{ + int result = 0; + old_mutex_t mx; + + if (mutex == NULL || *mutex == NULL) + { + return EINVAL; + } + + if (*mutex == (old_mutex_t) PTW32_OBJECT_AUTO_INIT) + { + /* + * Don't use initialisers when benchtesting. + */ + result = EINVAL; + } + + mx = *mutex; + + if (result == 0) + { + if (mx->mutex == 0) + { + if (ptw32_try_enter_critical_section == NULL) + { + result = 0; + } + else if ((*ptw32_try_enter_critical_section)(&mx->cs) != TRUE) + { + result = EBUSY; + } + } + else + { + DWORD status; + + status = WaitForSingleObject (mx->mutex, 0); + + if (status != WAIT_OBJECT_0) + { + result = ((status == WAIT_TIMEOUT) + ? EBUSY + : EINVAL); + } + } + } + + return(result); +} + + +int +old_mutex_destroy(old_mutex_t *mutex) +{ + int result = 0; + old_mutex_t mx; + + if (mutex == NULL + || *mutex == NULL) + { + return EINVAL; + } + + if (*mutex != (old_mutex_t) PTW32_OBJECT_AUTO_INIT) + { + mx = *mutex; + + if ((result = old_mutex_trylock(&mx)) == 0) + { + *mutex = NULL; + + (void) old_mutex_unlock(&mx); + + if (mx->mutex == 0) + { + DeleteCriticalSection(&mx->cs); + } + else + { + result = (CloseHandle (mx->mutex) ? 0 : EINVAL); + } + + if (result == 0) + { + mx->mutex = 0; + free(mx); + } + else + { + *mutex = mx; + } + } + } + else + { + result = EINVAL; + } + + if (ptw32_try_enter_critical_section != NULL) + { + (void) FreeLibrary(ptw32_h_kernel32); + ptw32_h_kernel32 = 0; + } + + return(result); +} + +/****************************************************************************************/ diff --git a/w32-pthreads/tests/benchtest.h b/w32-pthreads/tests/benchtest.h new file mode 100644 index 000000000..809057810 --- /dev/null +++ b/w32-pthreads/tests/benchtest.h @@ -0,0 +1,70 @@ +/* + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + */ + +#include "../config.h" + +enum { + OLD_WIN32CS, + OLD_WIN32MUTEX +}; + +extern int old_mutex_use; + +struct old_mutex_t_ { + HANDLE mutex; + CRITICAL_SECTION cs; +}; + +typedef struct old_mutex_t_ * old_mutex_t; + +struct old_mutexattr_t_ { + int pshared; +}; + +typedef struct old_mutexattr_t_ * old_mutexattr_t; + +extern BOOL (WINAPI *ptw32_try_enter_critical_section)(LPCRITICAL_SECTION); +extern HINSTANCE ptw32_h_kernel32; + +#define PTW32_OBJECT_AUTO_INIT ((void *) -1) + +void dummy_call(int * a); +void interlocked_inc_with_conditionals(int *a); +void interlocked_dec_with_conditionals(int *a); +int old_mutex_init(old_mutex_t *mutex, const old_mutexattr_t *attr); +int old_mutex_lock(old_mutex_t *mutex); +int old_mutex_unlock(old_mutex_t *mutex); +int old_mutex_trylock(old_mutex_t *mutex); +int old_mutex_destroy(old_mutex_t *mutex); +/****************************************************************************************/ diff --git a/w32-pthreads/tests/benchtest1.c b/w32-pthreads/tests/benchtest1.c new file mode 100644 index 000000000..191f98636 --- /dev/null +++ b/w32-pthreads/tests/benchtest1.c @@ -0,0 +1,266 @@ +/* + * benchtest1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Measure time taken to complete an elementary operation. + * + * - Mutex + * Single thread iteration over lock/unlock for each mutex type. + */ + +#include "test.h" +#include + +#ifdef __GNUC__ +#include +#endif + +#include "benchtest.h" + +#define PTW32_MUTEX_TYPES +#define ITERATIONS 10000000L + +pthread_mutex_t mx; +pthread_mutexattr_t ma; +PTW32_STRUCT_TIMEB currSysTimeStart; +PTW32_STRUCT_TIMEB currSysTimeStop; +long durationMilliSecs; +long overHeadMilliSecs = 0; +int two = 2; +int one = 1; +int zero = 0; +int iter; + +#define GetDurationMilliSecs(_TStart, _TStop) ((long)((_TStop.time*1000+_TStop.millitm) \ + - (_TStart.time*1000+_TStart.millitm))) + +/* + * Dummy use of j, otherwise the loop may be removed by the optimiser + * when doing the overhead timing with an empty loop. + */ +#define TESTSTART \ + { int i, j = 0, k = 0; PTW32_FTIME(&currSysTimeStart); for (i = 0; i < ITERATIONS; i++) { j++; + +#define TESTSTOP \ + }; PTW32_FTIME(&currSysTimeStop); if (j + k == i) j++; } + + +void +runTest (char * testNameString, int mType) +{ +#ifdef PTW32_MUTEX_TYPES + assert(pthread_mutexattr_settype(&ma, mType) == 0); +#endif + assert(pthread_mutex_init(&mx, &ma) == 0); + + TESTSTART + assert((pthread_mutex_lock(&mx),1) == one); + assert((pthread_mutex_unlock(&mx),2) == two); + TESTSTOP + + assert(pthread_mutex_destroy(&mx) == 0); + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + testNameString, + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); +} + + +int +main (int argc, char *argv[]) +{ + int i = 0; + CRITICAL_SECTION cs; + old_mutex_t ox; + pthread_mutexattr_init(&ma); + + printf( "=============================================================================\n"); + printf( "\nLock plus unlock on an unlocked mutex.\n%ld iterations\n\n", + ITERATIONS); + printf( "%-45s %15s %15s\n", + "Test", + "Total(msec)", + "average(usec)"); + printf( "-----------------------------------------------------------------------------\n"); + + /* + * Time the loop overhead so we can subtract it from the actual test times. + */ + TESTSTART + assert(1 == one); + assert(2 == two); + TESTSTOP + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + overHeadMilliSecs = durationMilliSecs; + + + TESTSTART + assert((dummy_call(&i), 1) == one); + assert((dummy_call(&i), 2) == two); + TESTSTOP + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + "Dummy call x 2", + durationMilliSecs, + (float) (durationMilliSecs * 1E3 / ITERATIONS)); + + + TESTSTART + assert((interlocked_inc_with_conditionals(&i), 1) == one); + assert((interlocked_dec_with_conditionals(&i), 2) == two); + TESTSTOP + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + "Dummy call -> Interlocked with cond x 2", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); + + + TESTSTART + assert((InterlockedIncrement((LPLONG)&i), 1) == (LONG)one); + assert((InterlockedDecrement((LPLONG)&i), 2) == (LONG)two); + TESTSTOP + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + "InterlockedOp x 2", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); + + + InitializeCriticalSection(&cs); + + TESTSTART + assert((EnterCriticalSection(&cs), 1) == one); + assert((LeaveCriticalSection(&cs), 2) == two); + TESTSTOP + + DeleteCriticalSection(&cs); + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + "Simple Critical Section", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); + + + old_mutex_use = OLD_WIN32CS; + assert(old_mutex_init(&ox, NULL) == 0); + + TESTSTART + assert(old_mutex_lock(&ox) == zero); + assert(old_mutex_unlock(&ox) == zero); + TESTSTOP + + assert(old_mutex_destroy(&ox) == 0); + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + "Old PT Mutex using a Critical Section (WNT)", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); + + + old_mutex_use = OLD_WIN32MUTEX; + assert(old_mutex_init(&ox, NULL) == 0); + + TESTSTART + assert(old_mutex_lock(&ox) == zero); + assert(old_mutex_unlock(&ox) == zero); + TESTSTOP + + assert(old_mutex_destroy(&ox) == 0); + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + "Old PT Mutex using a Win32 Mutex (W9x)", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); + + printf( ".............................................................................\n"); + + /* + * Now we can start the actual tests + */ +#ifdef PTW32_MUTEX_TYPES + runTest("PTHREAD_MUTEX_DEFAULT", PTHREAD_MUTEX_DEFAULT); + + runTest("PTHREAD_MUTEX_NORMAL", PTHREAD_MUTEX_NORMAL); + + runTest("PTHREAD_MUTEX_ERRORCHECK", PTHREAD_MUTEX_ERRORCHECK); + + runTest("PTHREAD_MUTEX_RECURSIVE", PTHREAD_MUTEX_RECURSIVE); +#else + runTest("Non-blocking lock", 0); +#endif + + printf( ".............................................................................\n"); + + pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST); + +#ifdef PTW32_MUTEX_TYPES + runTest("PTHREAD_MUTEX_DEFAULT (Robust)", PTHREAD_MUTEX_DEFAULT); + + runTest("PTHREAD_MUTEX_NORMAL (Robust)", PTHREAD_MUTEX_NORMAL); + + runTest("PTHREAD_MUTEX_ERRORCHECK (Robust)", PTHREAD_MUTEX_ERRORCHECK); + + runTest("PTHREAD_MUTEX_RECURSIVE (Robust)", PTHREAD_MUTEX_RECURSIVE); +#else + runTest("Non-blocking lock", 0); +#endif + + printf( "=============================================================================\n"); + + /* + * End of tests. + */ + + pthread_mutexattr_destroy(&ma); + + one = i; /* Dummy assignment to avoid 'variable unused' warning */ + return 0; +} diff --git a/w32-pthreads/tests/benchtest2.c b/w32-pthreads/tests/benchtest2.c new file mode 100644 index 000000000..10f3d0ee8 --- /dev/null +++ b/w32-pthreads/tests/benchtest2.c @@ -0,0 +1,327 @@ +/* + * benchtest1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Measure time taken to complete an elementary operation. + * + * - Mutex + * Two threads iterate over lock/unlock for each mutex type. + * The two threads are forced into lock-step using two mutexes, + * forcing the threads to block on each lock operation. The + * time measured is therefore the worst case senario. + */ + +#include "test.h" +#include + +#ifdef __GNUC__ +#include +#endif + +#include "benchtest.h" + +#define PTW32_MUTEX_TYPES +#define ITERATIONS 100000L + +pthread_mutex_t gate1, gate2; +old_mutex_t ox1, ox2; +CRITICAL_SECTION cs1, cs2; +pthread_mutexattr_t ma; +long durationMilliSecs; +long overHeadMilliSecs = 0; +PTW32_STRUCT_TIMEB currSysTimeStart; +PTW32_STRUCT_TIMEB currSysTimeStop; +pthread_t worker; +int running = 0; + +#define GetDurationMilliSecs(_TStart, _TStop) ((long)((_TStop.time*1000+_TStop.millitm) \ + - (_TStart.time*1000+_TStart.millitm))) + +/* + * Dummy use of j, otherwise the loop may be removed by the optimiser + * when doing the overhead timing with an empty loop. + */ +#define TESTSTART \ + { int i, j = 0, k = 0; PTW32_FTIME(&currSysTimeStart); for (i = 0; i < ITERATIONS; i++) { j++; + +#define TESTSTOP \ + }; PTW32_FTIME(&currSysTimeStop); if (j + k == i) j++; } + + +void * +overheadThread(void * arg) +{ + do + { + sched_yield(); + } + while (running); + + return NULL; +} + + +void * +oldThread(void * arg) +{ + do + { + (void) old_mutex_lock(&ox1); + (void) old_mutex_lock(&ox2); + (void) old_mutex_unlock(&ox1); + sched_yield(); + (void) old_mutex_unlock(&ox2); + } + while (running); + + return NULL; +} + +void * +workerThread(void * arg) +{ + do + { + (void) pthread_mutex_lock(&gate1); + (void) pthread_mutex_lock(&gate2); + (void) pthread_mutex_unlock(&gate1); + sched_yield(); + (void) pthread_mutex_unlock(&gate2); + } + while (running); + + return NULL; +} + +void * +CSThread(void * arg) +{ + do + { + EnterCriticalSection(&cs1); + EnterCriticalSection(&cs2); + LeaveCriticalSection(&cs1); + sched_yield(); + LeaveCriticalSection(&cs2); + } + while (running); + + return NULL; +} + +void +runTest (char * testNameString, int mType) +{ +#ifdef PTW32_MUTEX_TYPES + assert(pthread_mutexattr_settype(&ma, mType) == 0); +#endif + assert(pthread_mutex_init(&gate1, &ma) == 0); + assert(pthread_mutex_init(&gate2, &ma) == 0); + assert(pthread_mutex_lock(&gate1) == 0); + assert(pthread_mutex_lock(&gate2) == 0); + running = 1; + assert(pthread_create(&worker, NULL, workerThread, NULL) == 0); + TESTSTART + (void) pthread_mutex_unlock(&gate1); + sched_yield(); + (void) pthread_mutex_unlock(&gate2); + (void) pthread_mutex_lock(&gate1); + (void) pthread_mutex_lock(&gate2); + TESTSTOP + running = 0; + assert(pthread_mutex_unlock(&gate2) == 0); + assert(pthread_mutex_unlock(&gate1) == 0); + assert(pthread_join(worker, NULL) == 0); + assert(pthread_mutex_destroy(&gate2) == 0); + assert(pthread_mutex_destroy(&gate1) == 0); + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + printf( "%-45s %15ld %15.3f\n", + testNameString, + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS / 4 /* Four locks/unlocks per iteration */); +} + + +int +main (int argc, char *argv[]) +{ + assert(pthread_mutexattr_init(&ma) == 0); + + printf( "=============================================================================\n"); + printf( "\nLock plus unlock on a locked mutex.\n"); + printf("%ld iterations, four locks/unlocks per iteration.\n\n", ITERATIONS); + + printf( "%-45s %15s %15s\n", + "Test", + "Total(msec)", + "average(usec)"); + printf( "-----------------------------------------------------------------------------\n"); + + /* + * Time the loop overhead so we can subtract it from the actual test times. + */ + + running = 1; + assert(pthread_create(&worker, NULL, overheadThread, NULL) == 0); + TESTSTART + sched_yield(); + sched_yield(); + TESTSTOP + running = 0; + assert(pthread_join(worker, NULL) == 0); + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + overHeadMilliSecs = durationMilliSecs; + + + InitializeCriticalSection(&cs1); + InitializeCriticalSection(&cs2); + EnterCriticalSection(&cs1); + EnterCriticalSection(&cs2); + running = 1; + assert(pthread_create(&worker, NULL, CSThread, NULL) == 0); + TESTSTART + LeaveCriticalSection(&cs1); + sched_yield(); + LeaveCriticalSection(&cs2); + EnterCriticalSection(&cs1); + EnterCriticalSection(&cs2); + TESTSTOP + running = 0; + LeaveCriticalSection(&cs2); + LeaveCriticalSection(&cs1); + assert(pthread_join(worker, NULL) == 0); + DeleteCriticalSection(&cs2); + DeleteCriticalSection(&cs1); + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + printf( "%-45s %15ld %15.3f\n", + "Simple Critical Section", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS / 4 ); + + + old_mutex_use = OLD_WIN32CS; + assert(old_mutex_init(&ox1, NULL) == 0); + assert(old_mutex_init(&ox2, NULL) == 0); + assert(old_mutex_lock(&ox1) == 0); + assert(old_mutex_lock(&ox2) == 0); + running = 1; + assert(pthread_create(&worker, NULL, oldThread, NULL) == 0); + TESTSTART + (void) old_mutex_unlock(&ox1); + sched_yield(); + (void) old_mutex_unlock(&ox2); + (void) old_mutex_lock(&ox1); + (void) old_mutex_lock(&ox2); + TESTSTOP + running = 0; + assert(old_mutex_unlock(&ox1) == 0); + assert(old_mutex_unlock(&ox2) == 0); + assert(pthread_join(worker, NULL) == 0); + assert(old_mutex_destroy(&ox2) == 0); + assert(old_mutex_destroy(&ox1) == 0); + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + printf( "%-45s %15ld %15.3f\n", + "Old PT Mutex using a Critical Section (WNT)", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS / 4); + + + old_mutex_use = OLD_WIN32MUTEX; + assert(old_mutex_init(&ox1, NULL) == 0); + assert(old_mutex_init(&ox2, NULL) == 0); + assert(old_mutex_lock(&ox1) == 0); + assert(old_mutex_lock(&ox2) == 0); + running = 1; + assert(pthread_create(&worker, NULL, oldThread, NULL) == 0); + TESTSTART + (void) old_mutex_unlock(&ox1); + sched_yield(); + (void) old_mutex_unlock(&ox2); + (void) old_mutex_lock(&ox1); + (void) old_mutex_lock(&ox2); + TESTSTOP + running = 0; + assert(old_mutex_unlock(&ox1) == 0); + assert(old_mutex_unlock(&ox2) == 0); + assert(pthread_join(worker, NULL) == 0); + assert(old_mutex_destroy(&ox2) == 0); + assert(old_mutex_destroy(&ox1) == 0); + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + printf( "%-45s %15ld %15.3f\n", + "Old PT Mutex using a Win32 Mutex (W9x)", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS / 4); + + printf( ".............................................................................\n"); + + /* + * Now we can start the actual tests + */ +#ifdef PTW32_MUTEX_TYPES + runTest("PTHREAD_MUTEX_DEFAULT", PTHREAD_MUTEX_DEFAULT); + + runTest("PTHREAD_MUTEX_NORMAL", PTHREAD_MUTEX_NORMAL); + + runTest("PTHREAD_MUTEX_ERRORCHECK", PTHREAD_MUTEX_ERRORCHECK); + + runTest("PTHREAD_MUTEX_RECURSIVE", PTHREAD_MUTEX_RECURSIVE); +#else + runTest("Non-blocking lock", 0); +#endif + + printf( ".............................................................................\n"); + + pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST); + +#ifdef PTW32_MUTEX_TYPES + runTest("PTHREAD_MUTEX_DEFAULT (Robust)", PTHREAD_MUTEX_DEFAULT); + + runTest("PTHREAD_MUTEX_NORMAL (Robust)", PTHREAD_MUTEX_NORMAL); + + runTest("PTHREAD_MUTEX_ERRORCHECK (Robust)", PTHREAD_MUTEX_ERRORCHECK); + + runTest("PTHREAD_MUTEX_RECURSIVE (Robust)", PTHREAD_MUTEX_RECURSIVE); +#else + runTest("Non-blocking lock", 0); +#endif + + printf( "=============================================================================\n"); + /* + * End of tests. + */ + + pthread_mutexattr_destroy(&ma); + + return 0; +} diff --git a/w32-pthreads/tests/benchtest3.c b/w32-pthreads/tests/benchtest3.c new file mode 100644 index 000000000..7d03ed884 --- /dev/null +++ b/w32-pthreads/tests/benchtest3.c @@ -0,0 +1,217 @@ +/* + * benchtest3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Measure time taken to complete an elementary operation. + * + * - Mutex + * Single thread iteration over a trylock on a locked mutex for each mutex type. + */ + +#include "test.h" +#include + +#ifdef __GNUC__ +#include +#endif + +#include "benchtest.h" + +#define PTW32_MUTEX_TYPES +#define ITERATIONS 10000000L + +pthread_mutex_t mx; +old_mutex_t ox; +pthread_mutexattr_t ma; +PTW32_STRUCT_TIMEB currSysTimeStart; +PTW32_STRUCT_TIMEB currSysTimeStop; +long durationMilliSecs; +long overHeadMilliSecs = 0; + +#define GetDurationMilliSecs(_TStart, _TStop) ((long)((_TStop.time*1000+_TStop.millitm) \ + - (_TStart.time*1000+_TStart.millitm))) + +/* + * Dummy use of j, otherwise the loop may be removed by the optimiser + * when doing the overhead timing with an empty loop. + */ +#define TESTSTART \ + { int i, j = 0, k = 0; PTW32_FTIME(&currSysTimeStart); for (i = 0; i < ITERATIONS; i++) { j++; + +#define TESTSTOP \ + }; PTW32_FTIME(&currSysTimeStop); if (j + k == i) j++; } + + +void * +trylockThread (void * arg) +{ + TESTSTART + (void) pthread_mutex_trylock(&mx); + TESTSTOP + + return NULL; +} + + +void * +oldTrylockThread (void * arg) +{ + TESTSTART + (void) old_mutex_trylock(&ox); + TESTSTOP + + return NULL; +} + + +void +runTest (char * testNameString, int mType) +{ + pthread_t t; + +#ifdef PTW32_MUTEX_TYPES + (void) pthread_mutexattr_settype(&ma, mType); +#endif + assert(pthread_mutex_init(&mx, &ma) == 0); + assert(pthread_mutex_lock(&mx) == 0); + assert(pthread_create(&t, NULL, trylockThread, 0) == 0); + assert(pthread_join(t, NULL) == 0); + assert(pthread_mutex_unlock(&mx) == 0); + assert(pthread_mutex_destroy(&mx) == 0); + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + testNameString, + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); +} + + +int +main (int argc, char *argv[]) +{ + pthread_t t; + + assert(pthread_mutexattr_init(&ma) == 0); + + printf( "=============================================================================\n"); + printf( "\nTrylock on a locked mutex.\n"); + printf( "%ld iterations.\n\n", ITERATIONS); + printf( "%-45s %15s %15s\n", + "Test", + "Total(msec)", + "average(usec)"); + printf( "-----------------------------------------------------------------------------\n"); + + /* + * Time the loop overhead so we can subtract it from the actual test times. + */ + + TESTSTART + TESTSTOP + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + overHeadMilliSecs = durationMilliSecs; + + + old_mutex_use = OLD_WIN32CS; + assert(old_mutex_init(&ox, NULL) == 0); + assert(old_mutex_lock(&ox) == 0); + assert(pthread_create(&t, NULL, oldTrylockThread, 0) == 0); + assert(pthread_join(t, NULL) == 0); + assert(old_mutex_unlock(&ox) == 0); + assert(old_mutex_destroy(&ox) == 0); + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + printf( "%-45s %15ld %15.3f\n", + "Old PT Mutex using a Critical Section (WNT)", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); + + old_mutex_use = OLD_WIN32MUTEX; + assert(old_mutex_init(&ox, NULL) == 0); + assert(old_mutex_lock(&ox) == 0); + assert(pthread_create(&t, NULL, oldTrylockThread, 0) == 0); + assert(pthread_join(t, NULL) == 0); + assert(old_mutex_unlock(&ox) == 0); + assert(old_mutex_destroy(&ox) == 0); + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + printf( "%-45s %15ld %15.3f\n", + "Old PT Mutex using a Win32 Mutex (W9x)", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); + + printf( ".............................................................................\n"); + + /* + * Now we can start the actual tests + */ +#ifdef PTW32_MUTEX_TYPES + runTest("PTHREAD_MUTEX_DEFAULT", PTHREAD_MUTEX_DEFAULT); + + runTest("PTHREAD_MUTEX_NORMAL", PTHREAD_MUTEX_NORMAL); + + runTest("PTHREAD_MUTEX_ERRORCHECK", PTHREAD_MUTEX_ERRORCHECK); + + runTest("PTHREAD_MUTEX_RECURSIVE", PTHREAD_MUTEX_RECURSIVE); +#else + runTest("Non-blocking lock", 0); +#endif + + printf( ".............................................................................\n"); + + pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST); + +#ifdef PTW32_MUTEX_TYPES + runTest("PTHREAD_MUTEX_DEFAULT (Robust)", PTHREAD_MUTEX_DEFAULT); + + runTest("PTHREAD_MUTEX_NORMAL (Robust)", PTHREAD_MUTEX_NORMAL); + + runTest("PTHREAD_MUTEX_ERRORCHECK (Robust)", PTHREAD_MUTEX_ERRORCHECK); + + runTest("PTHREAD_MUTEX_RECURSIVE (Robust)", PTHREAD_MUTEX_RECURSIVE); +#else + runTest("Non-blocking lock", 0); +#endif + + printf( "=============================================================================\n"); + + /* + * End of tests. + */ + + pthread_mutexattr_destroy(&ma); + + return 0; +} diff --git a/w32-pthreads/tests/benchtest4.c b/w32-pthreads/tests/benchtest4.c new file mode 100644 index 000000000..d7cf47c3b --- /dev/null +++ b/w32-pthreads/tests/benchtest4.c @@ -0,0 +1,198 @@ +/* + * benchtest4.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Measure time taken to complete an elementary operation. + * + * - Mutex + * Single thread iteration over trylock/unlock for each mutex type. + */ + +#include "test.h" +#include + +#ifdef __GNUC__ +#include +#endif + +#include "benchtest.h" + +#define PTW32_MUTEX_TYPES +#define ITERATIONS 10000000L + +pthread_mutex_t mx; +old_mutex_t ox; +pthread_mutexattr_t ma; +PTW32_STRUCT_TIMEB currSysTimeStart; +PTW32_STRUCT_TIMEB currSysTimeStop; +long durationMilliSecs; +long overHeadMilliSecs = 0; + +#define GetDurationMilliSecs(_TStart, _TStop) ((long)((_TStop.time*1000+_TStop.millitm) \ + - (_TStart.time*1000+_TStart.millitm))) + +/* + * Dummy use of j, otherwise the loop may be removed by the optimiser + * when doing the overhead timing with an empty loop. + */ +#define TESTSTART \ + { int i, j = 0, k = 0; PTW32_FTIME(&currSysTimeStart); for (i = 0; i < ITERATIONS; i++) { j++; + +#define TESTSTOP \ + }; PTW32_FTIME(&currSysTimeStop); if (j + k == i) j++; } + + +void +oldRunTest (char * testNameString, int mType) +{ +} + + +void +runTest (char * testNameString, int mType) +{ +#ifdef PTW32_MUTEX_TYPES + pthread_mutexattr_settype(&ma, mType); +#endif + pthread_mutex_init(&mx, &ma); + + TESTSTART + (void) pthread_mutex_trylock(&mx); + (void) pthread_mutex_unlock(&mx); + TESTSTOP + + pthread_mutex_destroy(&mx); + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + testNameString, + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); +} + + +int +main (int argc, char *argv[]) +{ + pthread_mutexattr_init(&ma); + + printf( "=============================================================================\n"); + printf( "Trylock plus unlock on an unlocked mutex.\n"); + printf( "%ld iterations.\n\n", ITERATIONS); + printf( "%-45s %15s %15s\n", + "Test", + "Total(msec)", + "average(usec)"); + printf( "-----------------------------------------------------------------------------\n"); + + /* + * Time the loop overhead so we can subtract it from the actual test times. + */ + + TESTSTART + TESTSTOP + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + overHeadMilliSecs = durationMilliSecs; + + old_mutex_use = OLD_WIN32CS; + assert(old_mutex_init(&ox, NULL) == 0); + TESTSTART + (void) old_mutex_trylock(&ox); + (void) old_mutex_unlock(&ox); + TESTSTOP + assert(old_mutex_destroy(&ox) == 0); + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + printf( "%-45s %15ld %15.3f\n", + "Old PT Mutex using a Critical Section (WNT)", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); + + old_mutex_use = OLD_WIN32MUTEX; + assert(old_mutex_init(&ox, NULL) == 0); + TESTSTART + (void) old_mutex_trylock(&ox); + (void) old_mutex_unlock(&ox); + TESTSTOP + assert(old_mutex_destroy(&ox) == 0); + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + printf( "%-45s %15ld %15.3f\n", + "Old PT Mutex using a Win32 Mutex (W9x)", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); + + printf( ".............................................................................\n"); + + /* + * Now we can start the actual tests + */ +#ifdef PTW32_MUTEX_TYPES + runTest("PTHREAD_MUTEX_DEFAULT", PTHREAD_MUTEX_DEFAULT); + + runTest("PTHREAD_MUTEX_NORMAL", PTHREAD_MUTEX_NORMAL); + + runTest("PTHREAD_MUTEX_ERRORCHECK", PTHREAD_MUTEX_ERRORCHECK); + + runTest("PTHREAD_MUTEX_RECURSIVE", PTHREAD_MUTEX_RECURSIVE); +#else + runTest("Non-blocking lock", 0); +#endif + + printf( ".............................................................................\n"); + + pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST); + +#ifdef PTW32_MUTEX_TYPES + runTest("PTHREAD_MUTEX_DEFAULT (Robust)", PTHREAD_MUTEX_DEFAULT); + + runTest("PTHREAD_MUTEX_NORMAL (Robust)", PTHREAD_MUTEX_NORMAL); + + runTest("PTHREAD_MUTEX_ERRORCHECK (Robust)", PTHREAD_MUTEX_ERRORCHECK); + + runTest("PTHREAD_MUTEX_RECURSIVE (Robust)", PTHREAD_MUTEX_RECURSIVE); +#else + runTest("Non-blocking lock", 0); +#endif + + printf( "=============================================================================\n"); + + /* + * End of tests. + */ + + pthread_mutexattr_destroy(&ma); + + return 0; +} diff --git a/w32-pthreads/tests/benchtest5.c b/w32-pthreads/tests/benchtest5.c new file mode 100644 index 000000000..d262baf11 --- /dev/null +++ b/w32-pthreads/tests/benchtest5.c @@ -0,0 +1,159 @@ +/* + * benchtest5.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Measure time taken to complete an elementary operation. + * + * - Semaphore + * Single thread iteration over post/wait for a semaphore. + */ + +#include "test.h" +#include + +#ifdef __GNUC__ +#include +#endif + +#include "benchtest.h" + +#define ITERATIONS 1000000L + +sem_t sema; +HANDLE w32sema; + +PTW32_STRUCT_TIMEB currSysTimeStart; +PTW32_STRUCT_TIMEB currSysTimeStop; +long durationMilliSecs; +long overHeadMilliSecs = 0; +int one = 1; +int zero = 0; + +#define GetDurationMilliSecs(_TStart, _TStop) ((long)((_TStop.time*1000+_TStop.millitm) \ + - (_TStart.time*1000+_TStart.millitm))) + +/* + * Dummy use of j, otherwise the loop may be removed by the optimiser + * when doing the overhead timing with an empty loop. + */ +#define TESTSTART \ + { int i, j = 0, k = 0; PTW32_FTIME(&currSysTimeStart); for (i = 0; i < ITERATIONS; i++) { j++; + +#define TESTSTOP \ + }; PTW32_FTIME(&currSysTimeStop); if (j + k == i) j++; } + + +void +reportTest (char * testNameString) +{ + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + testNameString, + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); +} + + +int +main (int argc, char *argv[]) +{ + printf( "=============================================================================\n"); + printf( "\nOperations on a semaphore.\n%ld iterations\n\n", + ITERATIONS); + printf( "%-45s %15s %15s\n", + "Test", + "Total(msec)", + "average(usec)"); + printf( "-----------------------------------------------------------------------------\n"); + + /* + * Time the loop overhead so we can subtract it from the actual test times. + */ + + TESTSTART + assert(1 == one); + TESTSTOP + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + overHeadMilliSecs = durationMilliSecs; + + + /* + * Now we can start the actual tests + */ + assert((w32sema = CreateSemaphore(NULL, (long) 0, (long) ITERATIONS, NULL)) != 0); + TESTSTART + assert((ReleaseSemaphore(w32sema, 1, NULL),1) == one); + TESTSTOP + assert(CloseHandle(w32sema) != 0); + + reportTest("W32 Post with no waiters"); + + + assert((w32sema = CreateSemaphore(NULL, (long) ITERATIONS, (long) ITERATIONS, NULL)) != 0); + TESTSTART + assert((WaitForSingleObject(w32sema, INFINITE),1) == one); + TESTSTOP + assert(CloseHandle(w32sema) != 0); + + reportTest("W32 Wait without blocking"); + + + assert(sem_init(&sema, 0, 0) == 0); + TESTSTART + assert((sem_post(&sema),1) == one); + TESTSTOP + assert(sem_destroy(&sema) == 0); + + reportTest("POSIX Post with no waiters"); + + + assert(sem_init(&sema, 0, ITERATIONS) == 0); + TESTSTART + assert((sem_wait(&sema),1) == one); + TESTSTOP + assert(sem_destroy(&sema) == 0); + + reportTest("POSIX Wait without blocking"); + + + printf( "=============================================================================\n"); + + /* + * End of tests. + */ + + return 0; +} diff --git a/w32-pthreads/tests/cancel1.c b/w32-pthreads/tests/cancel1.c new file mode 100644 index 000000000..23d2726a2 --- /dev/null +++ b/w32-pthreads/tests/cancel1.c @@ -0,0 +1,179 @@ +/* + * File: cancel1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test setting cancel state and cancel type. + * - + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - pthread_setcancelstate function + * - pthread_setcanceltype function + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - pthread_create, pthread_self work. + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 2 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +void * +mythread(void * arg) +{ + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + /* ... */ + { + int oldstate; + int oldtype; + + assert(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate) == 0); + assert(oldstate == PTHREAD_CANCEL_ENABLE); /* Check default */ + assert(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) == 0); + assert(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) == 0); + assert(pthread_setcancelstate(oldstate, &oldstate) == 0); + assert(oldstate == PTHREAD_CANCEL_DISABLE); /* Check setting */ + + assert(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype) == 0); + assert(oldtype == PTHREAD_CANCEL_DEFERRED); /* Check default */ + assert(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) == 0); + assert(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL) == 0); + assert(pthread_setcanceltype(oldtype, &oldtype) == 0); + assert(oldtype == PTHREAD_CANCEL_ASYNCHRONOUS); /* Check setting */ + } + + return 0; +} + +int +main() +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + assert((t[0] = pthread_self()).p != NULL); + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + + /* + * Give threads time to run. + */ + Sleep(NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + failed = !threadbag[i].started; + + if (failed) + { + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print ouput on failure. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + /* ... */ + } + + assert(!failed); + + /* + * Success. + */ + return 0; +} diff --git a/w32-pthreads/tests/cancel2.c b/w32-pthreads/tests/cancel2.c new file mode 100644 index 000000000..2ee596abb --- /dev/null +++ b/w32-pthreads/tests/cancel2.c @@ -0,0 +1,258 @@ +/* + * File: cancel2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test SEH or C++ cancel exception handling within + * application exception blocks. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel, pthread_join + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +/* + * Don't know how to identify if we are using SEH so it's only C++ for now + */ +#if defined(__cplusplus) + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 4 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +static pthread_mutex_t waitLock = PTHREAD_MUTEX_INITIALIZER; + +void * +mythread(void * arg) +{ + int result = 0; + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + /* Set to known state and type */ + + assert(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) == 0); + + switch (bag->threadnum % 2) + { + case 0: + assert(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL) == 0); + result = 0; + break; + case 1: + assert(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) == 0); + result = 1; + break; + } + +#if !defined(__cplusplus) + __try +#else + try +#endif + { + /* Wait for go from main */ + assert(pthread_mutex_lock(&waitLock) == 0); + assert(pthread_mutex_unlock(&waitLock) == 0); + sched_yield(); + + for (;;) + { + pthread_testcancel(); + } + } +#if !defined(__cplusplus) + __except(EXCEPTION_EXECUTE_HANDLER) +#else +#if defined(PtW32CatchAll) + PtW32CatchAll +#else + catch(...) +#endif +#endif + { + /* + * Should not get into here. + */ + result += 100; + } + + /* + * Should not get to here either. + */ + result += 1000; + + return (void *) (size_t)result; +} + +int +main() +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + assert((t[0] = pthread_self()).p != NULL); + assert(pthread_mutex_lock(&waitLock) == 0); + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(500); + + assert(pthread_mutex_unlock(&waitLock) == 0); + + Sleep(500); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_cancel(t[i]) == 0); + } + + /* + * Give threads time to run. + */ + Sleep(NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + void* result = (void*)0; + + assert(pthread_join(t[i], &result) == 0); + fail = ((int)(size_t)result != (int) PTHREAD_CANCELED); + if (fail) + { + fprintf(stderr, "Thread %d: started %d: location %d: cancel type %s\n", + i, + threadbag[i].started, + (int)(size_t)result, + (((int)(size_t)result % 2) == 0) ? "ASYNCHRONOUS" : "DEFERRED"); + } + failed |= fail; + } + + assert(!failed); + + /* + * Success. + */ + return 0; +} + +#else /* defined(__cplusplus) */ + +#include + +int +main() +{ + fprintf(stderr, "Test N/A for this compiler environment.\n"); + return 0; +} + +#endif /* defined(__cplusplus) */ + diff --git a/w32-pthreads/tests/cancel3.c b/w32-pthreads/tests/cancel3.c new file mode 100644 index 000000000..5020648a6 --- /dev/null +++ b/w32-pthreads/tests/cancel3.c @@ -0,0 +1,201 @@ +/* + * File: cancel3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test asynchronous cancelation (alertable or non-alertable). + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - Async cancel if thread is not blocked (i.e. voluntarily resumes if blocked). + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel, pthread_join. + * - quserex.dll and alertdrv.sys are not available. + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum +{ + NUMTHREADS = 4 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ +{ + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +void * +mythread (void *arg) +{ + void* result = (void*)((int)(size_t)PTHREAD_CANCELED + 1); + bag_t *bag = (bag_t *) arg; + + assert (bag == &threadbag[bag->threadnum]); + assert (bag->started == 0); + bag->started = 1; + + /* Set to known state and type */ + + assert (pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL) == 0); + + assert (pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL) == 0); + + /* + * We wait up to 10 seconds, waking every 0.1 seconds, + * for a cancelation to be applied to us. + */ + for (bag->count = 0; bag->count < 100; bag->count++) + Sleep (100); + + return result; +} + +int +main () +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + assert ((t[0] = pthread_self ()).p != NULL); + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert (pthread_create (&t[i], NULL, mythread, (void *) &threadbag[i]) + == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep (NUMTHREADS * 100); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert (pthread_cancel (t[i]) == 0); + } + + /* + * Give threads time to complete. + */ + Sleep (NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf (stderr, "Thread %d: started %d\n", i, + threadbag[i].started); + } + } + + assert (!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + void* result = (void*)0; + + /* + * The thread does not contain any cancelation points, so + * a return value of PTHREAD_CANCELED confirms that async + * cancelation succeeded. + */ + assert (pthread_join (t[i], &result) == 0); + + fail = (result != PTHREAD_CANCELED); + + if (fail) + { + fprintf (stderr, "Thread %d: started %d: count %d\n", + i, threadbag[i].started, threadbag[i].count); + } + failed = (failed || fail); + } + + assert (!failed); + + /* + * Success. + */ + return 0; +} diff --git a/w32-pthreads/tests/cancel4.c b/w32-pthreads/tests/cancel4.c new file mode 100644 index 000000000..893f33b12 --- /dev/null +++ b/w32-pthreads/tests/cancel4.c @@ -0,0 +1,203 @@ +/* + * File: cancel4.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test cancelation does not occur in deferred + * cancelation threads with no cancelation points. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - pthread_create + * pthread_self + * pthread_cancel + * pthread_join + * pthread_setcancelstate + * pthread_setcanceltype + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 4 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +void * +mythread(void * arg) +{ + void* result = (void*)((int)(size_t)PTHREAD_CANCELED + 1); + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + /* Set to known state and type */ + + assert(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) == 0); + + assert(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) == 0); + + /* + * We wait up to 2 seconds, waking every 0.1 seconds, + * for a cancelation to be applied to us. + */ + for (bag->count = 0; bag->count < 20; bag->count++) + Sleep(100); + + return result; +} + +int +main() +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + assert((t[0] = pthread_self()).p != NULL); + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(500); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_cancel(t[i]) == 0); + } + + /* + * Give threads time to run. + */ + Sleep(NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + void* result = (void*)0; + + /* + * The thread does not contain any cancelation points, so + * a return value of PTHREAD_CANCELED indicates that async + * cancelation occurred. + */ + assert(pthread_join(t[i], &result) == 0); + + fail = (result == PTHREAD_CANCELED); + + if (fail) + { + fprintf(stderr, "Thread %d: started %d: count %d\n", + i, + threadbag[i].started, + threadbag[i].count); + } + failed = (failed || fail); + } + + assert(!failed); + + /* + * Success. + */ + return 0; +} diff --git a/w32-pthreads/tests/cancel5.c b/w32-pthreads/tests/cancel5.c new file mode 100644 index 000000000..6c3951634 --- /dev/null +++ b/w32-pthreads/tests/cancel5.c @@ -0,0 +1,199 @@ +/* + * File: cancel5.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test calling pthread_cancel from the main thread + * without calling pthread_self() in main. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel, pthread_join + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum +{ + NUMTHREADS = 4 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ +{ + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +void * +mythread (void *arg) +{ + void* result = (void*)((int)(size_t)PTHREAD_CANCELED + 1); + bag_t *bag = (bag_t *) arg; + + assert (bag == &threadbag[bag->threadnum]); + assert (bag->started == 0); + bag->started = 1; + + /* Set to known state and type */ + + assert (pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL) == 0); + + assert (pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL) == 0); + + /* + * We wait up to 10 seconds, waking every 0.1 seconds, + * for a cancelation to be applied to us. + */ + for (bag->count = 0; bag->count < 100; bag->count++) + Sleep (100); + + return result; +} + +int +main () +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert (pthread_create (&t[i], NULL, mythread, (void *) &threadbag[i]) + == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep (500); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert (pthread_cancel (t[i]) == 0); + } + + /* + * Give threads time to run. + */ + Sleep (NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf (stderr, "Thread %d: started %d\n", i, + threadbag[i].started); + } + } + + assert (!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + void* result = (void*)((int)(size_t)PTHREAD_CANCELED + 1); + + /* + * The thread does not contain any cancelation points, so + * a return value of PTHREAD_CANCELED confirms that async + * cancelation succeeded. + */ + assert (pthread_join (t[i], &result) == 0); + + fail = (result != PTHREAD_CANCELED); + + if (fail) + { + fprintf (stderr, "Thread %d: started %d: count %d\n", + i, threadbag[i].started, threadbag[i].count); + } + failed = (failed || fail); + } + + assert (!failed); + + /* + * Success. + */ + return 0; +} diff --git a/w32-pthreads/tests/cancel6a.c b/w32-pthreads/tests/cancel6a.c new file mode 100644 index 000000000..58063d573 --- /dev/null +++ b/w32-pthreads/tests/cancel6a.c @@ -0,0 +1,191 @@ +/* + * File: cancel6a.c + * + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright (C) 1998 Ben Elliston and Ross Johnson + * Copyright (C) 1999,2000,2001 Ross Johnson + * + * Contact Email: rpj@ise.canberra.edu.au + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test double cancelation - asynchronous. + * Second attempt should fail (ESRCH). + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel, pthread_join + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 4 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +void * +mythread(void * arg) +{ + void* result = (void*)((int)(size_t)PTHREAD_CANCELED + 1); + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + /* Set to known state and type */ + + assert(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) == 0); + + assert(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL) == 0); + + /* + * We wait up to 10 seconds, waking every 0.1 seconds, + * for a cancelation to be applied to us. + */ + for (bag->count = 0; bag->count < 100; bag->count++) + Sleep(100); + + return result; +} + +int +main() +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + assert((t[0] = pthread_self()).p != NULL); + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(500); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_cancel(t[i]) == 0); + assert(pthread_cancel(t[i]) == ESRCH); + } + + /* + * Give threads time to run. + */ + Sleep(NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + void* result = (void*)0; + + /* + * The thread does not contain any cancelation points, so + * a return value of PTHREAD_CANCELED confirms that async + * cancelation succeeded. + */ + assert(pthread_join(t[i], &result) == 0); + + fail = (result != PTHREAD_CANCELED); + + if (fail) + { + fprintf(stderr, "Thread %d: started %d: count %d\n", + i, + threadbag[i].started, + threadbag[i].count); + } + failed = (failed || fail); + } + + assert(!failed); + + /* + * Success. + */ + return 0; +} diff --git a/w32-pthreads/tests/cancel6d.c b/w32-pthreads/tests/cancel6d.c new file mode 100644 index 000000000..37f9ca5f3 --- /dev/null +++ b/w32-pthreads/tests/cancel6d.c @@ -0,0 +1,193 @@ +/* + * File: cancel6d.c + * + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright (C) 1998 Ben Elliston and Ross Johnson + * Copyright (C) 1999,2000,2001 Ross Johnson + * + * Contact Email: rpj@ise.canberra.edu.au + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test double cancelation - deferred. + * Second attempt should succeed (unless the canceled thread has started + * cancelation already - not tested here). + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel, pthread_join + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 4 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +void * +mythread(void * arg) +{ + void* result = (void*)((int)(size_t)PTHREAD_CANCELED + 1); + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + /* Set to known state and type */ + + assert(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) == 0); + + assert(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) == 0); + + /* + * We wait up to 10 seconds, waking every 0.1 seconds, + * for a cancelation to be applied to us. + */ + for (bag->count = 0; bag->count < 100; bag->count++) + { + Sleep(100); + pthread_testcancel(); + } + + return result; +} + +int +main() +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + assert((t[0] = pthread_self()).p != NULL); + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *)(size_t) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(500); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_cancel(t[i]) == 0); + if (pthread_cancel(t[i]) != 0) + { + printf("Second cancelation failed but this is expected sometimes.\n"); + } + } + + /* + * Give threads time to run. + */ + Sleep(NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + void* result = (void*)0; + + assert(pthread_join(t[i], &result) == 0); + + fail = (result != PTHREAD_CANCELED); + + if (fail) + { + fprintf(stderr, "Thread %d: started %d: count %d\n", + i, + threadbag[i].started, + threadbag[i].count); + } + failed = (failed || fail); + } + + assert(!failed); + + /* + * Success. + */ + return 0; +} diff --git a/w32-pthreads/tests/cancel7.c b/w32-pthreads/tests/cancel7.c new file mode 100644 index 000000000..5f1390f7b --- /dev/null +++ b/w32-pthreads/tests/cancel7.c @@ -0,0 +1,218 @@ +/* + * File: cancel7.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test canceling a Win32 thread having created an + * implicit POSIX handle for it. + * + * Test Method (Validation or Falsification): + * - Validate return value and that POSIX handle is created and destroyed. + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" +#ifndef _UWIN +#include +#endif + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 4 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; + pthread_t self; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +#if ! defined (__MINGW32__) || defined (__MSVCRT__) +unsigned __stdcall +#else +void +#endif +Win32thread(void * arg) +{ + int i; + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + assert((bag->self = pthread_self()).p != NULL); + assert(pthread_kill(bag->self, 0) == 0); + + for (i = 0; i < 100; i++) + { + Sleep(100); + pthread_testcancel(); + } + +#if ! defined (__MINGW32__) || defined (__MSVCRT__) + return 0; +#endif +} + +int +main() +{ + int failed = 0; + int i; + HANDLE h[NUMTHREADS + 1]; + unsigned thrAddr; /* Dummy variable to pass a valid location to _beginthreadex (Win98). */ + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; +#if ! defined (__MINGW32__) || defined (__MSVCRT__) + h[i] = (HANDLE) _beginthreadex(NULL, 0, Win32thread, (void *) &threadbag[i], 0, &thrAddr); +#else + h[i] = (HANDLE) _beginthread(Win32thread, 0, (void *) &threadbag[i]); +#endif + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(500); + + /* + * Cancel all threads. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_kill(threadbag[i].self, 0) == 0); + assert(pthread_cancel(threadbag[i].self) == 0); + } + + /* + * Give threads time to run. + */ + Sleep(NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + int result = 0; + +#if ! defined (__MINGW32__) || defined (__MSVCRT__) + assert(GetExitCodeThread(h[i], (LPDWORD) &result) == TRUE); +#else + /* + * Can't get a result code. + */ + result = (int)(size_t)PTHREAD_CANCELED; +#endif + + assert(threadbag[i].self.p != NULL); + assert(pthread_kill(threadbag[i].self, 0) == ESRCH); + + fail = (result != (int)(size_t)PTHREAD_CANCELED); + + if (fail) + { + fprintf(stderr, "Thread %d: started %d: count %d\n", + i, + threadbag[i].started, + threadbag[i].count); + } + failed = (failed || fail); + } + + assert(!failed); + + /* + * Success. + */ + return 0; +} + diff --git a/w32-pthreads/tests/cancel8.c b/w32-pthreads/tests/cancel8.c new file mode 100644 index 000000000..7204d19b1 --- /dev/null +++ b/w32-pthreads/tests/cancel8.c @@ -0,0 +1,219 @@ +/* + * File: cancel8.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test cancelling a blocked Win32 thread having created an + * implicit POSIX handle for it. + * + * Test Method (Validation or Falsification): + * - Validate return value and that POSIX handle is created and destroyed. + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" +#ifndef _UWIN +#include +#endif + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 4 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; + pthread_t self; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +pthread_cond_t CV = PTHREAD_COND_INITIALIZER; +pthread_mutex_t CVLock = PTHREAD_MUTEX_INITIALIZER; + +#if ! defined (__MINGW32__) || defined (__MSVCRT__) +unsigned __stdcall +#else +void +#endif +Win32thread(void * arg) +{ + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + assert((bag->self = pthread_self()).p != NULL); + assert(pthread_kill(bag->self, 0) == 0); + + assert(pthread_mutex_lock(&CVLock) == 0); + pthread_cleanup_push(pthread_mutex_unlock, &CVLock); + pthread_cond_wait(&CV, &CVLock); + pthread_cleanup_pop(1); + +#if ! defined (__MINGW32__) || defined (__MSVCRT__) + return 0; +#endif +} + +int +main() +{ + int failed = 0; + int i; + HANDLE h[NUMTHREADS + 1]; + unsigned thrAddr; /* Dummy variable to pass a valid location to _beginthreadex (Win98). */ + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; +#if ! defined (__MINGW32__) || defined (__MSVCRT__) + h[i] = (HANDLE) _beginthreadex(NULL, 0, Win32thread, (void *) &threadbag[i], 0, &thrAddr); +#else + h[i] = (HANDLE) _beginthread(Win32thread, 0, (void *) &threadbag[i]); +#endif + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(500); + + /* + * Cancel all threads. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_kill(threadbag[i].self, 0) == 0); + assert(pthread_cancel(threadbag[i].self) == 0); + } + + /* + * Give threads time to run. + */ + Sleep(NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + int result = 0; + +#if ! defined (__MINGW32__) || defined (__MSVCRT__) + assert(GetExitCodeThread(h[i], (LPDWORD) &result) == TRUE); +#else + /* + * Can't get a result code. + */ + result = (int)(size_t)PTHREAD_CANCELED; +#endif + + assert(threadbag[i].self.p != NULL); + assert(pthread_kill(threadbag[i].self, 0) == ESRCH); + + fail = (result != (int)(size_t)PTHREAD_CANCELED); + + if (fail) + { + fprintf(stderr, "Thread %d: started %d: count %d\n", + i, + threadbag[i].started, + threadbag[i].count); + } + failed = (failed || fail); + } + + assert(!failed); + + /* + * Success. + */ + return 0; +} + diff --git a/w32-pthreads/tests/cancel9.c b/w32-pthreads/tests/cancel9.c new file mode 100644 index 000000000..b0091614a --- /dev/null +++ b/w32-pthreads/tests/cancel9.c @@ -0,0 +1,202 @@ +/* + * File: cancel9.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test true asynchronous cancelation with Alert driver. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - Cancel threads, including those blocked on system recources + * such as network I/O. + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel, pthread_join + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" +#include + + +void * +test_udp (void *arg) +{ + struct sockaddr_in serverAddress; + struct sockaddr_in clientAddress; + SOCKET UDPSocket; + int addr_len; + int nbyte, bytes; + char buffer[4096]; + WORD wsaVersion = MAKEWORD (2, 2); + WSADATA wsaData; + + pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL); + pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL); + + if (WSAStartup (wsaVersion, &wsaData) != 0) + { + return NULL; + } + + UDPSocket = socket (AF_INET, SOCK_DGRAM, 0); + if ((int)UDPSocket == -1) + { + printf ("Server: socket ERROR \n"); + exit (-1); + } + + serverAddress.sin_family = AF_INET; + serverAddress.sin_addr.s_addr = INADDR_ANY; + serverAddress.sin_port = htons (9003); + + if (bind + (UDPSocket, (struct sockaddr *) &serverAddress, + sizeof (struct sockaddr_in))) + { + printf ("Server: ERROR can't bind UDPSocket"); + exit (-1); + } + + addr_len = sizeof (struct sockaddr); + + nbyte = 512; + + bytes = + recvfrom (UDPSocket, (char *) buffer, nbyte, 0, + (struct sockaddr *) &clientAddress, &addr_len); + + closesocket (UDPSocket); + WSACleanup (); + + return NULL; +} + + +void * +test_sleep (void *arg) +{ + pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL); + pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL); + + Sleep (1000); + return NULL; + +} + +void * +test_wait (void *arg) +{ + HANDLE hEvent; + DWORD dwEvent; + + pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL); + pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL); + + hEvent = CreateEvent (NULL, FALSE, FALSE, NULL); + + dwEvent = WaitForSingleObject (hEvent, 1000); /* WAIT_IO_COMPLETION */ + + return NULL; +} + + +int +main () +{ + pthread_t t; + void *result; + + if (pthread_win32_test_features_np (PTW32_ALERTABLE_ASYNC_CANCEL)) + { + printf ("Cancel sleeping thread.\n"); + assert (pthread_create (&t, NULL, test_sleep, NULL) == 0); + /* Sleep for a while; then cancel */ + Sleep (100); + assert (pthread_cancel (t) == 0); + assert (pthread_join (t, &result) == 0); + assert (result == PTHREAD_CANCELED && "test_sleep" != NULL); + + printf ("Cancel waiting thread.\n"); + assert (pthread_create (&t, NULL, test_wait, NULL) == 0); + /* Sleep for a while; then cancel. */ + Sleep (100); + assert (pthread_cancel (t) == 0); + assert (pthread_join (t, &result) == 0); + assert (result == PTHREAD_CANCELED && "test_wait"); + + printf ("Cancel blocked thread (blocked on network I/O).\n"); + assert (pthread_create (&t, NULL, test_udp, NULL) == 0); + /* Sleep for a while; then cancel. */ + Sleep (100); + assert (pthread_cancel (t) == 0); + assert (pthread_join (t, &result) == 0); + assert (result == PTHREAD_CANCELED && "test_udp" != NULL); + } + else + { + printf ("Alertable async cancel not available.\n"); + } + + /* + * Success. + */ + return 0; +} diff --git a/w32-pthreads/tests/cleanup0.c b/w32-pthreads/tests/cleanup0.c new file mode 100644 index 000000000..d9fbedccc --- /dev/null +++ b/w32-pthreads/tests/cleanup0.c @@ -0,0 +1,229 @@ +/* + * File: cleanup1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test cleanup handler executes (when thread is not canceled). + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel, pthread_join + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#if defined(_MSC_VER) || defined(__cplusplus) + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 10 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +typedef struct { + int i; + CRITICAL_SECTION cs; +} sharedInt_t; + +static sharedInt_t pop_count = {0, {0}}; + +static void +increment_pop_count(void * arg) +{ + sharedInt_t * sI = (sharedInt_t *) arg; + + EnterCriticalSection(&sI->cs); + sI->i++; + LeaveCriticalSection(&sI->cs); +} + +void * +mythread(void * arg) +{ + int result = 0; + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + /* Set to known state and type */ + + assert(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) == 0); + + assert(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL) == 0); + +#ifdef _MSC_VER +#pragma inline_depth(0) +#endif + pthread_cleanup_push(increment_pop_count, (void *) &pop_count); + + Sleep(100); + + pthread_cleanup_pop(1); +#ifdef _MSC_VER +#pragma inline_depth() +#endif + + return (void *) (size_t)result; +} + +int +main() +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + InitializeCriticalSection(&pop_count.cs); + + assert((t[0] = pthread_self()).p != NULL); + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(500); + + /* + * Give threads time to run. + */ + Sleep(NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + void* result = (void*)0; + + assert(pthread_join(t[i], &result) == 0); + + fail = ((int)(size_t)result == (int) PTHREAD_CANCELED); + + if (fail) + { + fprintf(stderr, "Thread %d: started %d: result %d\n", + i, + threadbag[i].started, + (int)(size_t)result); + fflush(stderr); + } + failed = (failed || fail); + } + + assert(!failed); + + assert(pop_count.i == NUMTHREADS); + + DeleteCriticalSection(&pop_count.cs); + + /* + * Success. + */ + return 0; +} + +#else /* defined(_MSC_VER) || defined(__cplusplus) */ + +int +main() +{ + return 0; +} + +#endif /* defined(_MSC_VER) || defined(__cplusplus) */ diff --git a/w32-pthreads/tests/cleanup1.c b/w32-pthreads/tests/cleanup1.c new file mode 100644 index 000000000..30d4940b7 --- /dev/null +++ b/w32-pthreads/tests/cleanup1.c @@ -0,0 +1,242 @@ +/* + * File: cleanup1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test cleanup handler executes (when thread is canceled). + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel, pthread_join + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#if defined(_MSC_VER) || defined(__cplusplus) + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 10 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +typedef struct { + int i; + CRITICAL_SECTION cs; +} sharedInt_t; + +static sharedInt_t pop_count = {0, {0}}; + +static void +#ifdef __CLEANUP_C +__cdecl +#endif +increment_pop_count(void * arg) +{ + sharedInt_t * sI = (sharedInt_t *) arg; + + EnterCriticalSection(&sI->cs); + sI->i++; + LeaveCriticalSection(&sI->cs); +} + +void * +mythread(void * arg) +{ + int result = 0; + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + /* Set to known state and type */ + + assert(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) == 0); + + assert(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL) == 0); + +#ifdef _MSC_VER +#pragma inline_depth(0) +#endif + pthread_cleanup_push(increment_pop_count, (void *) &pop_count); + /* + * We don't have true async cancelation - it relies on the thread + * at least re-entering the run state at some point. + * We wait up to 10 seconds, waking every 0.1 seconds, + * for a cancelation to be applied to us. + */ + for (bag->count = 0; bag->count < 100; bag->count++) + Sleep(100); + + pthread_cleanup_pop(0); +#ifdef _MSC_VER +#pragma inline_depth() +#endif + + return (void *) (size_t)result; +} + +int +main() +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + InitializeCriticalSection(&pop_count.cs); + + assert((t[0] = pthread_self()).p != NULL); + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(500); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_cancel(t[i]) == 0); + } + + /* + * Give threads time to run. + */ + Sleep(NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + void* result = (void*)0; + + assert(pthread_join(t[i], &result) == 0); + + fail = ((int)(size_t)result != (int) PTHREAD_CANCELED); + + if (fail) + { + fprintf(stderr, "Thread %d: started %d: result %d\n", + i, + threadbag[i].started, + (int)(size_t)result); + } + failed = (failed || fail); + } + + assert(!failed); + + assert(pop_count.i == NUMTHREADS); + + DeleteCriticalSection(&pop_count.cs); + + /* + * Success. + */ + return 0; +} + +#else /* defined(_MSC_VER) || defined(__cplusplus) */ + +int +main() +{ + return 0; +} + +#endif /* defined(_MSC_VER) || defined(__cplusplus) */ diff --git a/w32-pthreads/tests/cleanup2.c b/w32-pthreads/tests/cleanup2.c new file mode 100644 index 000000000..67037c255 --- /dev/null +++ b/w32-pthreads/tests/cleanup2.c @@ -0,0 +1,217 @@ +/* + * File: cleanup2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test cleanup handler executes (when thread is not canceled). + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel, pthread_join + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#if defined(_MSC_VER) || defined(__cplusplus) + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 10 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +typedef struct { + int i; + CRITICAL_SECTION cs; +} sharedInt_t; + +static sharedInt_t pop_count = {0, {0}}; + +static void +increment_pop_count(void * arg) +{ + sharedInt_t * sI = (sharedInt_t *) arg; + + EnterCriticalSection(&sI->cs); + sI->i++; + LeaveCriticalSection(&sI->cs); +} + +void * +mythread(void * arg) +{ + int result = 0; + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + +#ifdef _MSC_VER +#pragma inline_depth(0) +#endif + pthread_cleanup_push(increment_pop_count, (void *) &pop_count); + + sched_yield(); + + pthread_cleanup_pop(1); +#ifdef _MSC_VER +#pragma inline_depth() +#endif + + return (void *) (size_t)result; +} + +int +main() +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + InitializeCriticalSection(&pop_count.cs); + + assert((t[0] = pthread_self()).p != NULL); + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(1000); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + void* result = (void*)0; + + assert(pthread_join(t[i], &result) == 0); + + fail = ((int)(size_t)result != 0); + + if (fail) + { + fprintf(stderr, "Thread %d: started %d: result: %d\n", + i, + threadbag[i].started, + (int)(size_t)result); + } + failed = (failed || fail); + } + + assert(!failed); + + assert(pop_count.i == NUMTHREADS); + + DeleteCriticalSection(&pop_count.cs); + + /* + * Success. + */ + return 0; +} + +#else /* defined(_MSC_VER) || defined(__cplusplus) */ + +int +main() +{ + return 0; +} + +#endif /* defined(_MSC_VER) || defined(__cplusplus) */ diff --git a/w32-pthreads/tests/cleanup3.c b/w32-pthreads/tests/cleanup3.c new file mode 100644 index 000000000..62317b3b0 --- /dev/null +++ b/w32-pthreads/tests/cleanup3.c @@ -0,0 +1,222 @@ +/* + * File: cleanup3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test cleanup handler does not execute (when thread is + * not canceled). + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel, pthread_join + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#if defined(_MSC_VER) || defined(__cplusplus) + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 10 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +typedef struct { + int i; + CRITICAL_SECTION cs; +} sharedInt_t; + +static sharedInt_t pop_count = {0, {0}}; + +static void +increment_pop_count(void * arg) +{ + sharedInt_t * sI = (sharedInt_t *) arg; + + EnterCriticalSection(&sI->cs); + sI->i++; + LeaveCriticalSection(&sI->cs); +} + +void * +mythread(void * arg) +{ + int result = 0; + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + +#ifdef _MSC_VER +#pragma inline_depth(0) +#endif + pthread_cleanup_push(increment_pop_count, (void *) &pop_count); + + sched_yield(); + + EnterCriticalSection(&pop_count.cs); + pop_count.i--; + LeaveCriticalSection(&pop_count.cs); + + pthread_cleanup_pop(0); +#ifdef _MSC_VER +#pragma inline_depth() +#endif + + return (void *) (size_t)result; +} + +int +main() +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + InitializeCriticalSection(&pop_count.cs); + + assert((t[0] = pthread_self()).p != NULL); + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(1000); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + void* result = (void*)0; + + assert(pthread_join(t[i], &result) == 0); + + fail = ((int)(size_t)result != 0); + + if (fail) + { + fprintf(stderr, "Thread %d: started %d: result: %d\n", + i, + threadbag[i].started, + (int)(size_t)result); + } + failed = (failed || fail); + } + + assert(!failed); + + assert(pop_count.i == -(NUMTHREADS)); + + DeleteCriticalSection(&pop_count.cs); + + /* + * Success. + */ + return 0; +} + +#else /* defined(_MSC_VER) || defined(__cplusplus) */ + +int +main() +{ + return 0; +} + +#endif /* defined(_MSC_VER) || defined(__cplusplus) */ diff --git a/w32-pthreads/tests/condvar1.c b/w32-pthreads/tests/condvar1.c new file mode 100644 index 000000000..380ab1aff --- /dev/null +++ b/w32-pthreads/tests/condvar1.c @@ -0,0 +1,97 @@ +/* + * File: condvar1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test initialisation and destruction of a CV. + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - Creates and then imediately destroys a CV. Does not + * test the CV. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - pthread_cond_init returns 0, and + * - pthread_cond_destroy returns 0. + * - Process returns zero exit status. + * + * Fail Criteria: + * - pthread_cond_init returns non-zero, or + * - pthread_cond_destroy returns non-zero. + * - Process returns non-zero exit status. + */ + +#include "test.h" + +static pthread_cond_t cv = NULL; + +int +main() +{ + assert(cv == NULL); + + assert(pthread_cond_init(&cv, NULL) == 0); + + assert(cv != NULL); + + assert(pthread_cond_destroy(&cv) == 0); + + assert(cv == NULL); + + return 0; +} diff --git a/w32-pthreads/tests/condvar1_1.c b/w32-pthreads/tests/condvar1_1.c new file mode 100644 index 000000000..a05e113b9 --- /dev/null +++ b/w32-pthreads/tests/condvar1_1.c @@ -0,0 +1,115 @@ +/* + * File: condvar1_1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test CV linked list management. + * + * Test Method (Validation or Falsification): + * - Validation: + * Initiate and destroy several CVs in random order. + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - Creates and then imediately destroys a CV. Does not + * test the CV. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - All initialised CVs destroyed without segfault. + * - Successfully broadcasts all remaining CVs after + * each CV is removed. + * + * Fail Criteria: + */ + +#include +#include "test.h" + +enum { + NUM_CV = 100 +}; + +static pthread_cond_t cv[NUM_CV]; + +int +main() +{ + int i, j; + + for (i = 0; i < NUM_CV; i++) + { + /* Traverse the list before every init of a CV. */ + assert(pthread_timechange_handler_np(NULL) == (void *) 0); + assert(pthread_cond_init(&cv[i], NULL) == 0); + } + + j = NUM_CV; + (void) srand((unsigned)time(NULL)); + + do + { + i = (NUM_CV - 1) * rand() / RAND_MAX; + if (cv[i] != NULL) + { + j--; + assert(pthread_cond_destroy(&cv[i]) == 0); + /* Traverse the list every time we remove a CV. */ + assert(pthread_timechange_handler_np(NULL) == (void *) 0); + } + } + while (j > 0); + + return 0; +} diff --git a/w32-pthreads/tests/condvar1_2.c b/w32-pthreads/tests/condvar1_2.c new file mode 100644 index 000000000..3d961f06d --- /dev/null +++ b/w32-pthreads/tests/condvar1_2.c @@ -0,0 +1,124 @@ +/* + * File: condvar1_2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test CV linked list management and serialisation. + * + * Test Method (Validation or Falsification): + * - Validation: + * Initiate and destroy several CVs in random order. + * Asynchronously traverse the CV list and broadcast. + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - Creates and then imediately destroys a CV. Does not + * test the CV. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - All initialised CVs destroyed without segfault. + * - Successfully broadcasts all remaining CVs after + * each CV is removed. + * + * Fail Criteria: + */ + +#include +#include "test.h" + +enum { + NUM_CV = 5, + NUM_LOOPS = 5 +}; + +static pthread_cond_t cv[NUM_CV]; + +int +main() +{ + int i, j, k; + void* result = (void*)-1; + pthread_t t; + + for (k = 0; k < NUM_LOOPS; k++) + { + for (i = 0; i < NUM_CV; i++) + { + assert(pthread_cond_init(&cv[i], NULL) == 0); + } + + j = NUM_CV; + (void) srand((unsigned)time(NULL)); + + /* Traverse the list asynchronously. */ + assert(pthread_create(&t, NULL, pthread_timechange_handler_np, NULL) == 0); + + do + { + i = (NUM_CV - 1) * rand() / RAND_MAX; + if (cv[i] != NULL) + { + j--; + assert(pthread_cond_destroy(&cv[i]) == 0); + } + } + while (j > 0); + + assert(pthread_join(t, &result) == 0); + assert ((int)(size_t)result == 0); + } + + return 0; +} diff --git a/w32-pthreads/tests/condvar2.c b/w32-pthreads/tests/condvar2.c new file mode 100644 index 000000000..6e2fa52d2 --- /dev/null +++ b/w32-pthreads/tests/condvar2.c @@ -0,0 +1,125 @@ +/* + * File: condvar2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test timed wait on a CV. + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - Because the CV is never signaled, we expect the wait to time out. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - pthread_cond_timedwait returns ETIMEDOUT. + * - Process returns zero exit status. + * + * Fail Criteria: + * - pthread_cond_timedwait does not return ETIMEDOUT. + * - Process returns non-zero exit status. + */ + +#define _WIN32_WINNT 0x400 + +#include "test.h" +#include + +pthread_cond_t cv; +pthread_mutex_t mutex; + +#include "../implement.h" + +int +main() +{ + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + assert(pthread_cond_init(&cv, NULL) == 0); + + assert(pthread_mutex_init(&mutex, NULL) == 0); + + assert(pthread_mutex_lock(&mutex) == 0); + + /* get current system time */ + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 1; + + assert(pthread_cond_timedwait(&cv, &mutex, &abstime) == ETIMEDOUT); + + assert(pthread_mutex_unlock(&mutex) == 0); + + { + int result = pthread_cond_destroy(&cv); + if (result != 0) + { + fprintf(stderr, "Result = %s\n", error_string[result]); + fprintf(stderr, "\tWaitersBlocked = %ld\n", cv->nWaitersBlocked); + fprintf(stderr, "\tWaitersGone = %ld\n", cv->nWaitersGone); + fprintf(stderr, "\tWaitersToUnblock = %ld\n", cv->nWaitersToUnblock); + fflush(stderr); + } + assert(result == 0); + } + + return 0; +} diff --git a/w32-pthreads/tests/condvar2_1.c b/w32-pthreads/tests/condvar2_1.c new file mode 100644 index 000000000..3486d2110 --- /dev/null +++ b/w32-pthreads/tests/condvar2_1.c @@ -0,0 +1,153 @@ +/* + * File: condvar2_1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test timeout of multiple waits on a CV with no signal/broadcast. + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - Because the CV is never signaled, we expect the waits to time out. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - pthread_cond_timedwait returns ETIMEDOUT. + * - Process returns zero exit status. + * + * Fail Criteria: + * - pthread_cond_timedwait does not return ETIMEDOUT. + * - Process returns non-zero exit status. + */ + +#define _WIN32_WINNT 0x400 + +#include "test.h" +#include + +static pthread_cond_t cv; +static pthread_mutex_t mutex; +static struct timespec abstime = { 0, 0 }; + +enum { + NUMTHREADS = 30 +}; + +void * +mythread(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + + assert(pthread_cond_timedwait(&cv, &mutex, &abstime) == ETIMEDOUT); + + assert(pthread_mutex_unlock(&mutex) == 0); + + return arg; +} + +#include "../implement.h" + +int +main() +{ + int i; + pthread_t t[NUMTHREADS + 1]; + void* result = (void*)0; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + assert(pthread_cond_init(&cv, NULL) == 0); + + assert(pthread_mutex_init(&mutex, NULL) == 0); + + /* get current system time */ + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 5; + + assert(pthread_mutex_lock(&mutex) == 0); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_create(&t[i], NULL, mythread, (void *)(size_t)i) == 0); + } + + assert(pthread_mutex_unlock(&mutex) == 0); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_join(t[i], &result) == 0); + assert((int)(size_t)result == i); + } + + { + int result = pthread_cond_destroy(&cv); + if (result != 0) + { + fprintf(stderr, "Result = %s\n", error_string[result]); + fprintf(stderr, "\tWaitersBlocked = %ld\n", cv->nWaitersBlocked); + fprintf(stderr, "\tWaitersGone = %ld\n", cv->nWaitersGone); + fprintf(stderr, "\tWaitersToUnblock = %ld\n", cv->nWaitersToUnblock); + fflush(stderr); + } + assert(result == 0); + } + + return 0; +} diff --git a/w32-pthreads/tests/condvar3.c b/w32-pthreads/tests/condvar3.c new file mode 100644 index 000000000..056334b37 --- /dev/null +++ b/w32-pthreads/tests/condvar3.c @@ -0,0 +1,148 @@ +/* + * File: condvar3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test basic function of a CV + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - The primary thread takes the lock before creating any threads. + * The secondary thread blocks on the lock allowing the primary + * thread to enter the cv wait state which releases the lock. + * The secondary thread then takes the lock and signals the waiting + * primary thread. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - pthread_cond_timedwait returns 0. + * - Process returns zero exit status. + * + * Fail Criteria: + * - pthread_cond_timedwait returns ETIMEDOUT. + * - Process returns non-zero exit status. + */ + +#include "test.h" +#include + +static pthread_cond_t cv; +static pthread_mutex_t mutex; +static int shared = 0; + +enum { + NUMTHREADS = 2 /* Including the primary thread. */ +}; + +void * +mythread(void * arg) +{ + int result = 0; + + assert(pthread_mutex_lock(&mutex) == 0); + shared++; + assert(pthread_mutex_unlock(&mutex) == 0); + + if ((result = pthread_cond_signal(&cv)) != 0) + { + printf("Error = %s\n", error_string[result]); + } + assert(result == 0); + + + return (void *) 0; +} + +int +main() +{ + pthread_t t[NUMTHREADS]; + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + assert((t[0] = pthread_self()).p != NULL); + + assert(pthread_cond_init(&cv, NULL) == 0); + + assert(pthread_mutex_init(&mutex, NULL) == 0); + + assert(pthread_mutex_lock(&mutex) == 0); + + /* get current system time */ + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + assert(pthread_create(&t[1], NULL, mythread, (void *) 1) == 0); + + abstime.tv_sec += 5; + + while (! (shared > 0)) + assert(pthread_cond_timedwait(&cv, &mutex, &abstime) == 0); + + assert(shared > 0); + + assert(pthread_mutex_unlock(&mutex) == 0); + + assert(pthread_join(t[1], NULL) == 0); + + assert(pthread_cond_destroy(&cv) == 0); + + return 0; +} diff --git a/w32-pthreads/tests/condvar3_1.c b/w32-pthreads/tests/condvar3_1.c new file mode 100644 index 000000000..33baeb14d --- /dev/null +++ b/w32-pthreads/tests/condvar3_1.c @@ -0,0 +1,201 @@ +/* + * File: condvar3_1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test timeout of multiple waits on a CV with some signaled. + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - Because some CVs are never signaled, we expect their waits to time out. + * Some are signaled, the rest time out. Pthread_cond_destroy() will fail + * unless all are accounted for, either signaled or timedout. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - pthread_cond_timedwait returns ETIMEDOUT. + * - Process returns zero exit status. + * + * Fail Criteria: + * - pthread_cond_timedwait does not return ETIMEDOUT. + * - Process returns non-zero exit status. + */ + +#define _WIN32_WINNT 0x400 + +#include "test.h" +#include + +static pthread_cond_t cv; +static pthread_cond_t cv1; +static pthread_mutex_t mutex; +static pthread_mutex_t mutex1; +static struct timespec abstime = { 0, 0 }; +static int timedout = 0; +static int signaled = 0; +static int awoken = 0; +static int waiting = 0; + +enum { + NUMTHREADS = 30 +}; + +void * +mythread(void * arg) +{ + int result; + + assert(pthread_mutex_lock(&mutex1) == 0); + ++waiting; + assert(pthread_mutex_unlock(&mutex1) == 0); + assert(pthread_cond_signal(&cv1) == 0); + + assert(pthread_mutex_lock(&mutex) == 0); + result = pthread_cond_timedwait(&cv, &mutex, &abstime); + if (result == ETIMEDOUT) + { + timedout++; + } + else + { + awoken++; + } + assert(pthread_mutex_unlock(&mutex) == 0); + + return arg; +} + +#include "../implement.h" + +int +main() +{ + int i; + pthread_t t[NUMTHREADS + 1]; + void* result = (void*)0; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + assert(pthread_cond_init(&cv, NULL) == 0); + assert(pthread_cond_init(&cv1, NULL) == 0); + + assert(pthread_mutex_init(&mutex, NULL) == 0); + assert(pthread_mutex_init(&mutex1, NULL) == 0); + + /* get current system time */ + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 5; + + assert(pthread_mutex_lock(&mutex1) == 0); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_create(&t[i], NULL, mythread, (void *)(size_t)i) == 0); + } + + do { + assert(pthread_cond_wait(&cv1,&mutex1) == 0); + } while ( NUMTHREADS > waiting ); + + assert(pthread_mutex_unlock(&mutex1) == 0); + + for (i = NUMTHREADS/3; i <= 2*NUMTHREADS/3; i++) + { +// assert(pthread_mutex_lock(&mutex) == 0); + assert(pthread_cond_signal(&cv) == 0); +// assert(pthread_mutex_unlock(&mutex) == 0); + + signaled++; + } + + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_join(t[i], &result) == 0); + assert((int)(size_t)result == i); + } + + fprintf(stderr, "awk = %d\n", awoken); + fprintf(stderr, "sig = %d\n", signaled); + fprintf(stderr, "tot = %d\n", timedout); + + assert(signaled == awoken); + assert(timedout == NUMTHREADS - signaled); + + assert(pthread_cond_destroy(&cv1) == 0); + + { + int result = pthread_cond_destroy(&cv); + if (result != 0) + { + fprintf(stderr, "Result = %s\n", error_string[result]); + fprintf(stderr, "\tWaitersBlocked = %ld\n", cv->nWaitersBlocked); + fprintf(stderr, "\tWaitersGone = %ld\n", cv->nWaitersGone); + fprintf(stderr, "\tWaitersToUnblock = %ld\n", cv->nWaitersToUnblock); + fflush(stderr); + } + assert(result == 0); + } + + assert(pthread_mutex_destroy(&mutex1) == 0); + assert(pthread_mutex_destroy(&mutex) == 0); + + return 0; +} diff --git a/w32-pthreads/tests/condvar3_2.c b/w32-pthreads/tests/condvar3_2.c new file mode 100644 index 000000000..4c3580152 --- /dev/null +++ b/w32-pthreads/tests/condvar3_2.c @@ -0,0 +1,193 @@ +/* + * File: condvar3_2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test timeout of multiple waits on a CV with remainder broadcast awoken. + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - Because some CVs are never signaled, we expect their waits to time out. + * Some time out, the rest are broadcast signaled. Pthread_cond_destroy() will fail + * unless all are accounted for, either signaled or timedout. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - pthread_cond_timedwait returns ETIMEDOUT. + * - Process returns zero exit status. + * + * Fail Criteria: + * - pthread_cond_timedwait does not return ETIMEDOUT. + * - Process returns non-zero exit status. + */ + +#define _WIN32_WINNT 0x400 + +#include "test.h" +#include + +static pthread_cond_t cv; +static pthread_mutex_t mutex; +static struct timespec abstime = { 0, 0 }; +static struct timespec abstime2 = { 0, 0 }; +static int timedout = 0; +static int awoken = 0; + +enum { + NUMTHREADS = 30 +}; + +void * +mythread(void * arg) +{ + int result; + + assert(pthread_mutex_lock(&mutex) == 0); + + abstime2.tv_sec = abstime.tv_sec; + + if ((int) (size_t)arg % 3 == 0) + { + abstime2.tv_sec += 2; + } + + result = pthread_cond_timedwait(&cv, &mutex, &abstime2); + assert(pthread_mutex_unlock(&mutex) == 0); + if (result == ETIMEDOUT) + { + InterlockedIncrement((LPLONG)&timedout); + } + else + { + InterlockedIncrement((LPLONG)&awoken); + } + + + return arg; +} + +#include "../implement.h" + +int +main() +{ + int i; + pthread_t t[NUMTHREADS + 1]; + void* result = (void*)0; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + assert(pthread_cond_init(&cv, NULL) == 0); + + assert(pthread_mutex_init(&mutex, NULL) == 0); + + /* get current system time */ + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = abstime2.tv_sec = (long)currSysTime.time + 5; + abstime.tv_nsec = abstime2.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + assert(pthread_mutex_lock(&mutex) == 0); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_create(&t[i], NULL, mythread, (void *)(size_t)i) == 0); + } + + assert(pthread_mutex_unlock(&mutex) == 0); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_join(t[i], &result) == 0); + assert((int)(size_t)result == i); + /* + * Approximately 2/3rds of the threads are expected to time out. + * Signal the remainder after some threads have woken up and exited + * and while some are still waking up after timeout. + * Also tests that redundant broadcasts don't return errors. + */ + +// assert(pthread_mutex_lock(&mutex) == 0); + + if (InterlockedExchangeAdd((LPLONG)&awoken, 0L) > NUMTHREADS/3) + { + assert(pthread_cond_broadcast(&cv) == 0); + } + +// assert(pthread_mutex_unlock(&mutex) == 0); + + } + + assert(awoken == NUMTHREADS - timedout); + + { + int result = pthread_cond_destroy(&cv); + if (result != 0) + { + fprintf(stderr, "Result = %s\n", error_string[result]); + fprintf(stderr, "\tWaitersBlocked = %ld\n", cv->nWaitersBlocked); + fprintf(stderr, "\tWaitersGone = %ld\n", cv->nWaitersGone); + fprintf(stderr, "\tWaitersToUnblock = %ld\n", cv->nWaitersToUnblock); + fflush(stderr); + } + assert(result == 0); + } + + assert(pthread_mutex_destroy(&mutex) == 0); + + return 0; +} diff --git a/w32-pthreads/tests/condvar3_3.c b/w32-pthreads/tests/condvar3_3.c new file mode 100644 index 000000000..f842440a1 --- /dev/null +++ b/w32-pthreads/tests/condvar3_3.c @@ -0,0 +1,132 @@ +/* + * File: condvar3_3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test timeouts and lost signals on a CV. + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - pthread_cond_timedwait returns ETIMEDOUT. + * - Process returns zero exit status. + * + * Fail Criteria: + * - pthread_cond_timedwait does not return ETIMEDOUT. + * - Process returns non-zero exit status. + */ + +/* Timur Aydin (taydin@snet.net) */ + +#include "test.h" + +#include + +pthread_cond_t cnd; +pthread_mutex_t mtx; + +int main() +{ + int rc; + + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + assert(pthread_cond_init(&cnd, 0) == 0); + assert(pthread_mutex_init(&mtx, 0) == 0); + + /* get current system time */ + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + abstime.tv_sec += 1; + + /* Here pthread_cond_timedwait should time out after one second. */ + + assert(pthread_mutex_lock(&mtx) == 0); + + assert((rc = pthread_cond_timedwait(&cnd, &mtx, &abstime)) == ETIMEDOUT); + + assert(pthread_mutex_unlock(&mtx) == 0); + + /* Here, the condition variable is signaled, but there are no + threads waiting on it. The signal should be lost and + the next pthread_cond_timedwait should time out too. */ + +// assert(pthread_mutex_lock(&mtx) == 0); + + assert((rc = pthread_cond_signal(&cnd)) == 0); + +// assert(pthread_mutex_unlock(&mtx) == 0); + + assert(pthread_mutex_lock(&mtx) == 0); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + abstime.tv_sec += 1; + + assert((rc = pthread_cond_timedwait(&cnd, &mtx, &abstime)) == ETIMEDOUT); + + assert(pthread_mutex_unlock(&mtx) == 0); + + return 0; +} diff --git a/w32-pthreads/tests/condvar4.c b/w32-pthreads/tests/condvar4.c new file mode 100644 index 000000000..3f6879b0a --- /dev/null +++ b/w32-pthreads/tests/condvar4.c @@ -0,0 +1,169 @@ +/* + * File: condvar4.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test PTHREAD_COND_INITIALIZER. + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - Test basic CV function but starting with a static initialised + * CV. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - pthread_cond_timedwait returns 0. + * - Process returns zero exit status. + * + * Fail Criteria: + * - pthread_cond_timedwait returns ETIMEDOUT. + * - Process returns non-zero exit status. + */ + +#include "test.h" +#include + +typedef struct cvthing_t_ cvthing_t; + +struct cvthing_t_ { + pthread_cond_t notbusy; + pthread_mutex_t lock; + int shared; +}; + +static cvthing_t cvthing = { + PTHREAD_COND_INITIALIZER, + PTHREAD_MUTEX_INITIALIZER, + 0 +}; + +enum { + NUMTHREADS = 2 +}; + +void * +mythread(void * arg) +{ + assert(pthread_mutex_lock(&cvthing.lock) == 0); + cvthing.shared++; + assert(pthread_mutex_unlock(&cvthing.lock) == 0); + + assert(pthread_cond_signal(&cvthing.notbusy) == 0); + + return (void *) 0; +} + +int +main() +{ + pthread_t t[NUMTHREADS]; + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + cvthing.shared = 0; + + assert((t[0] = pthread_self()).p != NULL); + + assert(cvthing.notbusy == PTHREAD_COND_INITIALIZER); + + assert(cvthing.lock == PTHREAD_MUTEX_INITIALIZER); + + assert(pthread_mutex_lock(&cvthing.lock) == 0); + + assert(cvthing.lock != PTHREAD_MUTEX_INITIALIZER); + + /* get current system time */ + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 5; + + assert(pthread_cond_timedwait(&cvthing.notbusy, &cvthing.lock, &abstime) == ETIMEDOUT); + + assert(cvthing.notbusy != PTHREAD_COND_INITIALIZER); + + assert(pthread_create(&t[1], NULL, mythread, (void *) 1) == 0); + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 5; + + while (! (cvthing.shared > 0)) + assert(pthread_cond_timedwait(&cvthing.notbusy, &cvthing.lock, &abstime) == 0); + + assert(cvthing.shared > 0); + + assert(pthread_mutex_unlock(&cvthing.lock) == 0); + + assert(pthread_join(t[1], NULL) == 0); + + assert(pthread_mutex_destroy(&cvthing.lock) == 0); + + assert(cvthing.lock == NULL); + + assert(pthread_cond_destroy(&cvthing.notbusy) == 0); + + assert(cvthing.notbusy == NULL); + + return 0; +} diff --git a/w32-pthreads/tests/condvar5.c b/w32-pthreads/tests/condvar5.c new file mode 100644 index 000000000..73083a55e --- /dev/null +++ b/w32-pthreads/tests/condvar5.c @@ -0,0 +1,168 @@ +/* + * File: condvar5.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test pthread_cond_broadcast. + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - Test broadcast with one waiting CV. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - pthread_cond_timedwait returns 0. + * - Process returns zero exit status. + * + * Fail Criteria: + * - pthread_cond_timedwait returns ETIMEDOUT. + * - Process returns non-zero exit status. + */ + +#include "test.h" +#include + +typedef struct cvthing_t_ cvthing_t; + +struct cvthing_t_ { + pthread_cond_t notbusy; + pthread_mutex_t lock; + int shared; +}; + +static cvthing_t cvthing = { + PTHREAD_COND_INITIALIZER, + PTHREAD_MUTEX_INITIALIZER, + 0 +}; + +enum { + NUMTHREADS = 2 +}; + +void * +mythread(void * arg) +{ + assert(pthread_mutex_lock(&cvthing.lock) == 0); + cvthing.shared++; + assert(pthread_mutex_unlock(&cvthing.lock) == 0); + + assert(pthread_cond_broadcast(&cvthing.notbusy) == 0); + + return (void *) 0; +} + +int +main() +{ + pthread_t t[NUMTHREADS]; + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + cvthing.shared = 0; + + assert((t[0] = pthread_self()).p != NULL); + + assert(cvthing.notbusy == PTHREAD_COND_INITIALIZER); + + assert(cvthing.lock == PTHREAD_MUTEX_INITIALIZER); + + assert(pthread_mutex_lock(&cvthing.lock) == 0); + + assert(cvthing.lock != PTHREAD_MUTEX_INITIALIZER); + + /* get current system time */ + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 5; + + assert(pthread_cond_timedwait(&cvthing.notbusy, &cvthing.lock, &abstime) == ETIMEDOUT); + + assert(cvthing.notbusy != PTHREAD_COND_INITIALIZER); + + assert(pthread_create(&t[1], NULL, mythread, (void *) 1) == 0); + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 5; + + while (! (cvthing.shared > 0)) + assert(pthread_cond_timedwait(&cvthing.notbusy, &cvthing.lock, &abstime) == 0); + + assert(cvthing.shared > 0); + + assert(pthread_mutex_unlock(&cvthing.lock) == 0); + + assert(pthread_join(t[1], NULL) == 0); + + assert(pthread_mutex_destroy(&cvthing.lock) == 0); + + assert(cvthing.lock == NULL); + + assert(pthread_cond_destroy(&cvthing.notbusy) == 0); + + assert(cvthing.notbusy == NULL); + + return 0; +} diff --git a/w32-pthreads/tests/condvar6.c b/w32-pthreads/tests/condvar6.c new file mode 100644 index 000000000..9d0b75d81 --- /dev/null +++ b/w32-pthreads/tests/condvar6.c @@ -0,0 +1,242 @@ +/* + * File: condvar6.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test pthread_cond_broadcast. + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - Test broadcast with NUMTHREADS (=5) waiting CVs. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" +#include + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 5 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +typedef struct cvthing_t_ cvthing_t; + +struct cvthing_t_ { + pthread_cond_t notbusy; + pthread_mutex_t lock; + int shared; +}; + +static cvthing_t cvthing = { + PTHREAD_COND_INITIALIZER, + PTHREAD_MUTEX_INITIALIZER, + 0 +}; + +static pthread_mutex_t start_flag = PTHREAD_MUTEX_INITIALIZER; + +static struct timespec abstime = { 0, 0 }; + +static int awoken; + +void * +mythread(void * arg) +{ + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + /* Wait for the start gun */ + assert(pthread_mutex_lock(&start_flag) == 0); + assert(pthread_mutex_unlock(&start_flag) == 0); + + assert(pthread_mutex_lock(&cvthing.lock) == 0); + + while (! (cvthing.shared > 0)) + assert(pthread_cond_timedwait(&cvthing.notbusy, &cvthing.lock, &abstime) == 0); + + assert(cvthing.shared > 0); + + awoken++; + + assert(pthread_mutex_unlock(&cvthing.lock) == 0); + + return (void *) 0; +} + +int +main() +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + cvthing.shared = 0; + + assert((t[0] = pthread_self()).p != NULL); + + assert(cvthing.notbusy == PTHREAD_COND_INITIALIZER); + + assert(cvthing.lock == PTHREAD_MUTEX_INITIALIZER); + + assert(pthread_mutex_lock(&start_flag) == 0); + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 5; + + assert((t[0] = pthread_self()).p != NULL); + + awoken = 0; + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + + assert(pthread_mutex_unlock(&start_flag) == 0); + + /* + * Give threads time to start. + */ + Sleep(1000); + + assert(pthread_mutex_lock(&cvthing.lock) == 0); + cvthing.shared++; + assert(pthread_mutex_unlock(&cvthing.lock) == 0); + + assert(pthread_cond_broadcast(&cvthing.notbusy) == 0); + + /* + * Give threads time to complete. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + assert(pthread_join(t[i], NULL) == 0); + } + + /* + * Cleanup the CV. + */ + + assert(pthread_mutex_destroy(&cvthing.lock) == 0); + + assert(cvthing.lock == NULL); + + assert(pthread_cond_destroy(&cvthing.notbusy) == 0); + + assert(cvthing.notbusy == NULL); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + failed = !threadbag[i].started; + + if (failed) + { + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. + */ + + assert(awoken == NUMTHREADS); + + /* + * Success. + */ + return 0; +} + + diff --git a/w32-pthreads/tests/condvar7.c b/w32-pthreads/tests/condvar7.c new file mode 100644 index 000000000..0647e7d91 --- /dev/null +++ b/w32-pthreads/tests/condvar7.c @@ -0,0 +1,257 @@ +/* + * File: condvar7.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test pthread_cond_broadcast with thread cancelation. + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - Test broadcast with NUMTHREADS (=5) waiting CVs, one is canceled while waiting. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" +#include + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 5 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +typedef struct cvthing_t_ cvthing_t; + +struct cvthing_t_ { + pthread_cond_t notbusy; + pthread_mutex_t lock; + int shared; +}; + +static cvthing_t cvthing = { + PTHREAD_COND_INITIALIZER, + PTHREAD_MUTEX_INITIALIZER, + 0 +}; + +static pthread_mutex_t start_flag = PTHREAD_MUTEX_INITIALIZER; + +static struct timespec abstime = { 0, 0 }; + +static int awoken; + +void * +mythread(void * arg) +{ + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + /* Wait for the start gun */ + assert(pthread_mutex_lock(&start_flag) == 0); + assert(pthread_mutex_unlock(&start_flag) == 0); + + assert(pthread_mutex_lock(&cvthing.lock) == 0); + +#ifdef _MSC_VER +#pragma inline_depth(0) +#endif + pthread_cleanup_push(pthread_mutex_unlock, (void *) &cvthing.lock); + + while (! (cvthing.shared > 0)) + assert(pthread_cond_timedwait(&cvthing.notbusy, &cvthing.lock, &abstime) == 0); + + pthread_cleanup_pop(0); +#ifdef _MSC_VER +#pragma inline_depth() +#endif + + assert(cvthing.shared > 0); + + awoken++; + + assert(pthread_mutex_unlock(&cvthing.lock) == 0); + + return (void *) 0; +} + +int +main() +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + cvthing.shared = 0; + + assert((t[0] = pthread_self()).p != NULL); + + assert(cvthing.notbusy == PTHREAD_COND_INITIALIZER); + + assert(cvthing.lock == PTHREAD_MUTEX_INITIALIZER); + + assert(pthread_mutex_lock(&start_flag) == 0); + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (time_t)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 10; + + assert((t[0] = pthread_self()).p != NULL); + + awoken = 0; + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + + assert(pthread_mutex_unlock(&start_flag) == 0); + + /* + * Give threads time to start. + */ + Sleep(1000); + + /* + * Cancel one of the threads. + */ + assert(pthread_cancel(t[1]) == 0); + assert(pthread_join(t[1], NULL) == 0); + + assert(pthread_mutex_lock(&cvthing.lock) == 0); + cvthing.shared++; + assert(pthread_mutex_unlock(&cvthing.lock) == 0); + + /* + * Signal all remaining waiting threads. + */ + assert(pthread_cond_broadcast(&cvthing.notbusy) == 0); + + /* + * Wait for all threads to complete. + */ + for (i = 2; i <= NUMTHREADS; i++) + assert(pthread_join(t[i], NULL) == 0); + + /* + * Cleanup the CV. + */ + + assert(pthread_mutex_destroy(&cvthing.lock) == 0); + + assert(cvthing.lock == NULL); + + assert(pthread_cond_destroy(&cvthing.notbusy) == 0); + + assert(cvthing.notbusy == NULL); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + failed = !threadbag[i].started; + + if (failed) + { + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. + */ + + assert(awoken == (NUMTHREADS - 1)); + + /* + * Success. + */ + return 0; +} diff --git a/w32-pthreads/tests/condvar8.c b/w32-pthreads/tests/condvar8.c new file mode 100644 index 000000000..7c2579d98 --- /dev/null +++ b/w32-pthreads/tests/condvar8.c @@ -0,0 +1,258 @@ +/* + * File: condvar8.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test multiple pthread_cond_broadcasts. + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - Make NUMTHREADS threads wait on CV, broadcast signal them, and then repeat. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" +#include + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 5 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +typedef struct cvthing_t_ cvthing_t; + +struct cvthing_t_ { + pthread_cond_t notbusy; + pthread_mutex_t lock; + int shared; +}; + +static cvthing_t cvthing = { + PTHREAD_COND_INITIALIZER, + PTHREAD_MUTEX_INITIALIZER, + 0 +}; + +static pthread_mutex_t start_flag = PTHREAD_MUTEX_INITIALIZER; + +static struct timespec abstime = { 0, 0 }; + +static int awoken; + +static void * +mythread(void * arg) +{ + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + /* Wait for the start gun */ + assert(pthread_mutex_lock(&start_flag) == 0); + assert(pthread_mutex_unlock(&start_flag) == 0); + + assert(pthread_mutex_lock(&cvthing.lock) == 0); + +#ifdef _MSC_VER +#pragma inline_depth(0) +#endif + pthread_cleanup_push(pthread_mutex_unlock, (void *) &cvthing.lock); + + while (! (cvthing.shared > 0)) + assert(pthread_cond_timedwait(&cvthing.notbusy, &cvthing.lock, &abstime) == 0); + + pthread_cleanup_pop(0); +#ifdef _MSC_VER +#pragma inline_depth() +#endif + + assert(cvthing.shared > 0); + + awoken++; + + assert(pthread_mutex_unlock(&cvthing.lock) == 0); + + return (void *) 0; +} + +int +main() +{ + int failed = 0; + int i; + int first, last; + pthread_t t[NUMTHREADS + 1]; + + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + assert((t[0] = pthread_self()).p != NULL); + + assert(cvthing.notbusy == PTHREAD_COND_INITIALIZER); + + assert(cvthing.lock == PTHREAD_MUTEX_INITIALIZER); + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 10; + + assert((t[0] = pthread_self()).p != NULL); + + awoken = 0; + + for (first = 1, last = NUMTHREADS / 2; + first < NUMTHREADS; + first = last + 1, last = NUMTHREADS) + { + assert(pthread_mutex_lock(&start_flag) == 0); + + for (i = first; i <= last; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + cvthing.shared = 0; + + assert(pthread_mutex_unlock(&start_flag) == 0); + + /* + * Give threads time to start. + */ + Sleep(100); + + assert(pthread_mutex_lock(&cvthing.lock) == 0); + cvthing.shared++; + assert(pthread_mutex_unlock(&cvthing.lock) == 0); + + assert(pthread_cond_broadcast(&cvthing.notbusy) == 0); + + /* + * Give threads time to complete. + */ + for (i = first; i <= last; i++) + { + assert(pthread_join(t[i], NULL) == 0); + } + + assert(awoken == (i - 1)); + } + + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + failed = !threadbag[i].started; + + if (failed) + { + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + /* + * Cleanup the CV. + */ + + assert(pthread_mutex_destroy(&cvthing.lock) == 0); + + assert(cvthing.lock == NULL); + + assert(pthread_cond_destroy(&cvthing.notbusy) == 0); + + assert(cvthing.notbusy == NULL); + + assert(!failed); + + /* + * Check any results here. + */ + + assert(awoken == NUMTHREADS); + + /* + * Success. + */ + return 0; +} diff --git a/w32-pthreads/tests/condvar9.c b/w32-pthreads/tests/condvar9.c new file mode 100644 index 000000000..62d044bf8 --- /dev/null +++ b/w32-pthreads/tests/condvar9.c @@ -0,0 +1,267 @@ +/* + * File: condvar9.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test multiple pthread_cond_broadcasts with thread cancelation. + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - Make NUMTHREADS threads wait on CV, cancel one, broadcast signal them, + * and then repeat. + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" +#include + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 9 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + int finished; + /* Add more per-thread state variables here */ +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +typedef struct cvthing_t_ cvthing_t; + +struct cvthing_t_ { + pthread_cond_t notbusy; + pthread_mutex_t lock; + int shared; +}; + +static cvthing_t cvthing = { + PTHREAD_COND_INITIALIZER, + PTHREAD_MUTEX_INITIALIZER, + 0 +}; + +static pthread_mutex_t start_flag = PTHREAD_MUTEX_INITIALIZER; + +static struct timespec abstime = { 0, 0 }; + +static int awoken; + +static void * +mythread(void * arg) +{ + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + /* Wait for the start gun */ + assert(pthread_mutex_lock(&start_flag) == 0); + assert(pthread_mutex_unlock(&start_flag) == 0); + + assert(pthread_mutex_lock(&cvthing.lock) == 0); + + /* + * pthread_cond_timedwait is a cancelation point and we're + * going to cancel some threads deliberately. + */ +#ifdef _MSC_VER +#pragma inline_depth(0) +#endif + pthread_cleanup_push(pthread_mutex_unlock, (void *) &cvthing.lock); + + while (! (cvthing.shared > 0)) + assert(pthread_cond_timedwait(&cvthing.notbusy, &cvthing.lock, &abstime) == 0); + + pthread_cleanup_pop(0); +#ifdef _MSC_VER +#pragma inline_depth() +#endif + + assert(cvthing.shared > 0); + + awoken++; + bag->finished = 1; + + assert(pthread_mutex_unlock(&cvthing.lock) == 0); + + return (void *) 0; +} + +int +main() +{ + int failed = 0; + int i; + int first, last; + int canceledThreads = 0; + pthread_t t[NUMTHREADS + 1]; + + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + assert((t[0] = pthread_self()).p != NULL); + + assert(cvthing.notbusy == PTHREAD_COND_INITIALIZER); + + assert(cvthing.lock == PTHREAD_MUTEX_INITIALIZER); + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 5; + + assert((t[0] = pthread_self()).p != NULL); + + awoken = 0; + + for (first = 1, last = NUMTHREADS / 2; + first < NUMTHREADS; + first = last + 1, last = NUMTHREADS) + { + int ct; + + assert(pthread_mutex_lock(&start_flag) == 0); + + for (i = first; i <= last; i++) + { + threadbag[i].started = threadbag[i].finished = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + cvthing.shared = 0; + + assert(pthread_mutex_unlock(&start_flag) == 0); + + /* + * Give threads time to start. + */ + Sleep(1000); + + ct = (first + last) / 2; + assert(pthread_cancel(t[ct]) == 0); + canceledThreads++; + assert(pthread_join(t[ct], NULL) == 0); + + assert(pthread_mutex_lock(&cvthing.lock) == 0); + cvthing.shared++; + assert(pthread_mutex_unlock(&cvthing.lock) == 0); + + assert(pthread_cond_broadcast(&cvthing.notbusy) == 0); + + /* + * Standard check that all threads started - and wait for them to finish. + */ + for (i = first; i <= last; i++) + { + failed = !threadbag[i].started; + + if (failed) + { + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + else + { + assert(pthread_join(t[i], NULL) == 0 || threadbag[i].finished == 0); +// fprintf(stderr, "Thread %d: finished %d\n", i, threadbag[i].finished); + } + } + } + + /* + * Cleanup the CV. + */ + + assert(pthread_mutex_destroy(&cvthing.lock) == 0); + + assert(cvthing.lock == NULL); + + assert_e(pthread_cond_destroy(&cvthing.notbusy), ==, 0); + + assert(cvthing.notbusy == NULL); + + assert(!failed); + + /* + * Check any results here. + */ + + assert(awoken == NUMTHREADS - canceledThreads); + + /* + * Success. + */ + return 0; +} diff --git a/w32-pthreads/tests/context1.c b/w32-pthreads/tests/context1.c new file mode 100644 index 000000000..e63dbec10 --- /dev/null +++ b/w32-pthreads/tests/context1.c @@ -0,0 +1,142 @@ +/* + * File: context1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test context switching method. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - pthread_create + * pthread_exit + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#define _WIN32_WINNT 0x400 + +#include "test.h" +#include "../implement.h" +#include "../context.h" + +static int washere = 0; + +static void * func(void * arg) +{ + washere = 1; + + Sleep(1000); + + return 0; +} + +static void +anotherEnding () +{ + /* + * Switched context + */ + washere++; + + pthread_exit(0); +} + +int +main() +{ + pthread_t t; + HANDLE hThread; + + assert(pthread_create(&t, NULL, func, NULL) == 0); + + hThread = ((ptw32_thread_t *)t.p)->threadH; + + Sleep(500); + + SuspendThread(hThread); + + if (WaitForSingleObject(hThread, 0) == WAIT_TIMEOUT) + { + /* + * Ok, thread did not exit before we got to it. + */ + CONTEXT context; + + context.ContextFlags = CONTEXT_CONTROL; + + GetThreadContext(hThread, &context); + PTW32_PROGCTR (context) = (DWORD_PTR) anotherEnding; + SetThreadContext(hThread, &context); + ResumeThread(hThread); + } + else + { + printf("Exited early\n"); + fflush(stdout); + } + + Sleep(1000); + + assert(washere == 2); + + return 0; +} + diff --git a/w32-pthreads/tests/count1.c b/w32-pthreads/tests/count1.c new file mode 100644 index 000000000..c2386b0e9 --- /dev/null +++ b/w32-pthreads/tests/count1.c @@ -0,0 +1,90 @@ +/* + * count1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Description: + * Test some basic assertions about the number of threads at runtime. + */ + +#include "test.h" + +#define NUMTHREADS (30) + +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_t threads[NUMTHREADS]; +static unsigned numThreads = 0; + +void * +myfunc(void *arg) +{ + pthread_mutex_lock(&lock); + numThreads++; + pthread_mutex_unlock(&lock); + + Sleep(1000); + return 0; +} +int +main() +{ + int i; + int maxThreads = sizeof(threads) / sizeof(pthread_t); + + /* + * Spawn NUMTHREADS threads. Each thread should increment the + * numThreads variable, sleep for one second. + */ + for (i = 0; i < maxThreads; i++) + { + assert(pthread_create(&threads[i], NULL, myfunc, 0) == 0); + } + + /* + * Wait for all the threads to exit. + */ + for (i = 0; i < maxThreads; i++) + { + assert(pthread_join(threads[i], NULL) == 0); + } + + /* + * Check the number of threads created. + */ + assert((int) numThreads == maxThreads); + + /* + * Success. + */ + return 0; +} diff --git a/w32-pthreads/tests/create1.c b/w32-pthreads/tests/create1.c new file mode 100644 index 000000000..8c630cb93 --- /dev/null +++ b/w32-pthreads/tests/create1.c @@ -0,0 +1,66 @@ +/* + * create1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Description: + * Create a thread and check that it ran. + * + * Depends on API functions: None. + */ + +#include "test.h" + +static int washere = 0; + +void * func(void * arg) +{ + washere = 1; + return 0; +} + +int +main() +{ + pthread_t t; + + assert(pthread_create(&t, NULL, func, NULL) == 0); + + /* A dirty hack, but we cannot rely on pthread_join in this + primitive test. */ + Sleep(2000); + + assert(washere == 1); + + return 0; +} diff --git a/w32-pthreads/tests/create2.c b/w32-pthreads/tests/create2.c new file mode 100644 index 000000000..9b4e86480 --- /dev/null +++ b/w32-pthreads/tests/create2.c @@ -0,0 +1,109 @@ +/* + * File: create2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test that threads have a Win32 handle when started. + * + * Test Method (Validation or Falsification): + * - Statistical, not absolute (depends on sample size). + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +enum { + NUMTHREADS = 10000 +}; + +static int washere = 0; + +void * func(void * arg) +{ + washere = 1; + return (void *) 0; +} + +int +main() +{ + pthread_t t; + pthread_attr_t attr; + void * result = NULL; + int i; + + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); + + for (i = 0; i < NUMTHREADS; i++) + { + washere = 0; + assert(pthread_create(&t, &attr, func, NULL) == 0); + assert(pthread_join(t, &result) == 0); + assert((int)(size_t)result == 0); + assert(washere == 1); + } + + return 0; +} diff --git a/w32-pthreads/tests/create3.c b/w32-pthreads/tests/create3.c new file mode 100644 index 000000000..0d59d8475 --- /dev/null +++ b/w32-pthreads/tests/create3.c @@ -0,0 +1,109 @@ +/* + * File: create3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test passing arg to thread function. + * + * Test Method (Validation or Falsification): + * - Statistical, not absolute (depends on sample size). + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +enum { + NUMTHREADS = 10000 +}; + +static int washere = 0; + +void * func(void * arg) +{ + washere = (int)(size_t)arg; + return (void *) 0; +} + +int +main() +{ + pthread_t t; + pthread_attr_t attr; + void * result = NULL; + int i; + + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); + + for (i = 0; i < NUMTHREADS; i++) + { + washere = 0; + assert(pthread_create(&t, &attr, func, (void *)(size_t)1) == 0); + assert(pthread_join(t, &result) == 0); + assert((int)(size_t)result == 0); + assert(washere == 1); + } + + return 0; +} diff --git a/w32-pthreads/tests/delay1.c b/w32-pthreads/tests/delay1.c new file mode 100644 index 000000000..83becd890 --- /dev/null +++ b/w32-pthreads/tests/delay1.c @@ -0,0 +1,51 @@ +/* + * delay1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Depends on API functions: + * pthread_delay_np + */ + +#include "test.h" + +int +main(int argc, char * argv[]) +{ + struct timespec interval = {1L, 500000000L}; + + assert(pthread_delay_np(&interval) == 0); + + return 0; +} + diff --git a/w32-pthreads/tests/delay2.c b/w32-pthreads/tests/delay2.c new file mode 100644 index 000000000..071b837f1 --- /dev/null +++ b/w32-pthreads/tests/delay2.c @@ -0,0 +1,82 @@ +/* + * delay1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Depends on API functions: + * pthread_delay_np + */ + +#include "test.h" + +pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER; + +void * +func(void * arg) +{ + struct timespec interval = {5, 500000000L}; + + assert(pthread_mutex_lock(&mx) == 0); + +#ifdef _MSC_VER +#pragma inline_depth(0) +#endif + pthread_cleanup_push(pthread_mutex_unlock, &mx); + assert(pthread_delay_np(&interval) == 0); + pthread_cleanup_pop(1); +#ifdef _MSC_VER +#pragma inline_depth() +#endif + + return (void *)(size_t)1; +} + +int +main(int argc, char * argv[]) +{ + pthread_t t; + void* result = (void*)0; + + assert(pthread_mutex_lock(&mx) == 0); + + assert(pthread_create(&t, NULL, func, NULL) == 0); + assert(pthread_cancel(t) == 0); + + assert(pthread_mutex_unlock(&mx) == 0); + + assert(pthread_join(t, &result) == 0); + assert(result == (void*)PTHREAD_CANCELED); + + return 0; +} + diff --git a/w32-pthreads/tests/detach1.c b/w32-pthreads/tests/detach1.c new file mode 100644 index 000000000..89756c7ad --- /dev/null +++ b/w32-pthreads/tests/detach1.c @@ -0,0 +1,93 @@ +/* + * Test for pthread_detach(). + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Depends on API functions: pthread_create(), pthread_detach(), pthread_exit(). + */ + +#include "test.h" + + +enum { + NUMTHREADS = 100 +}; + +void * +func(void * arg) +{ + int i = (int)(size_t)arg; + + Sleep(i * 10); + + pthread_exit(arg); + + /* Never reached. */ + exit(1); +} + +int +main(int argc, char * argv[]) +{ + pthread_t id[NUMTHREADS]; + int i; + + /* Create a few threads and then exit. */ + for (i = 0; i < NUMTHREADS; i++) + { + assert(pthread_create(&id[i], NULL, func, (void *)(size_t)i) == 0); + } + + /* Some threads will finish before they are detached, some after. */ + Sleep(NUMTHREADS/2 * 10 + 50); + + for (i = 0; i < NUMTHREADS; i++) + { + assert(pthread_detach(id[i]) == 0); + } + + Sleep(NUMTHREADS * 10 + 100); + + /* + * Check that all threads are now invalid. + * This relies on unique thread IDs - e.g. works with + * pthreads-w32 or Solaris, but may not work for Linux, BSD etc. + */ + for (i = 0; i < NUMTHREADS; i++) + { + assert(pthread_kill(id[i], 0) == ESRCH); + } + + /* Success. */ + return 0; +} diff --git a/w32-pthreads/tests/equal1.c b/w32-pthreads/tests/equal1.c new file mode 100644 index 000000000..8932bb2aa --- /dev/null +++ b/w32-pthreads/tests/equal1.c @@ -0,0 +1,66 @@ +/* + * Test for pthread_equal. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Depends on functions: pthread_create(). + */ + +#include "test.h" + +void * func(void * arg) +{ + Sleep(2000); + return 0; +} + +int +main() +{ + pthread_t t1, t2; + + assert(pthread_create(&t1, NULL, func, (void *) 1) == 0); + + assert(pthread_create(&t2, NULL, func, (void *) 2) == 0); + + assert(pthread_equal(t1, t2) == 0); + + assert(pthread_equal(t1,t1) != 0); + + /* This is a hack. We don't want to rely on pthread_join + yet if we can help it. */ + Sleep(4000); + + /* Success. */ + return 0; +} diff --git a/w32-pthreads/tests/errno1.c b/w32-pthreads/tests/errno1.c new file mode 100644 index 000000000..70ce92802 --- /dev/null +++ b/w32-pthreads/tests/errno1.c @@ -0,0 +1,177 @@ +/* + * File: errno1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test thread-safety of errno + * - + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 3 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +pthread_mutex_t stop_here = PTHREAD_MUTEX_INITIALIZER; + +void * +mythread(void * arg) +{ + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + errno = bag->threadnum; + + Sleep(1000); + + pthread_mutex_lock(&stop_here); + + assert(errno == bag->threadnum); + + pthread_mutex_unlock(&stop_here); + + Sleep(1000); + + return 0; +} + +int +main() +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + pthread_mutex_lock(&stop_here); + errno = 0; + + assert((t[0] = pthread_self()).p != NULL); + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(2000); + pthread_mutex_unlock(&stop_here); + + /* + * Give threads time to run. + */ + Sleep(NUMTHREADS * 1000); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + failed = !threadbag[i].started; + + if (failed) + { + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print ouput on failure. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + /* ... */ + } + + assert(!failed); + + /* + * Success. + */ + return 0; +} diff --git a/w32-pthreads/tests/exception1.c b/w32-pthreads/tests/exception1.c new file mode 100644 index 000000000..62a5a63cb --- /dev/null +++ b/w32-pthreads/tests/exception1.c @@ -0,0 +1,263 @@ +/* + * File: exception1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test passing of exceptions back to the application. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel, pthread_join + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#if defined(_MSC_VER) || defined(__cplusplus) + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 4 +}; + +void * +exceptionedThread(void * arg) +{ + int dummy = 0; + void* result = (void*)((int)(size_t)PTHREAD_CANCELED + 1); + /* Set to async cancelable */ + + assert(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) == 0); + + assert(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL) == 0); + + Sleep(100); + +#if defined(_MSC_VER) && !defined(__cplusplus) + __try + { + int zero = (int) (size_t)arg; /* Passed in from arg to avoid compiler error */ + int one = 1; + /* + * The deliberate exception condition (zero divide) is + * in an "if" to avoid being optimised out. + */ + if (dummy == one/zero) + Sleep(0); + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + /* Should get into here. */ + result = (void*)((int)(size_t)PTHREAD_CANCELED + 2); + } +#elif defined(__cplusplus) + try + { + /* + * I had a zero divide exception here but it + * wasn't being caught by the catch(...) + * below under Mingw32. That could be a problem. + */ + throw dummy; + } +#if defined(PtW32CatchAll) + PtW32CatchAll +#else + catch (...) +#endif + { + /* Should get into here. */ + result = (void*)((int)(size_t)PTHREAD_CANCELED + 2); + } +#endif + + return (void *) (size_t)result; +} + +void * +canceledThread(void * arg) +{ + void* result = (void*)((int)(size_t)PTHREAD_CANCELED + 1); + int count; + + /* Set to async cancelable */ + + assert(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) == 0); + + assert(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL) == 0); + +#if defined(_MSC_VER) && !defined(__cplusplus) + __try + { + /* + * We wait up to 10 seconds, waking every 0.1 seconds, + * for a cancelation to be applied to us. + */ + for (count = 0; count < 100; count++) + Sleep(100); + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + /* Should NOT get into here. */ + result = (void*)((int)(size_t)PTHREAD_CANCELED + 2); + } +#elif defined(__cplusplus) + try + { + /* + * We wait up to 10 seconds, waking every 0.1 seconds, + * for a cancelation to be applied to us. + */ + for (count = 0; count < 100; count++) + Sleep(100); + } +#if defined(PtW32CatchAll) + PtW32CatchAll +#else + catch (...) +#endif + { + /* Should NOT get into here. */ + result = (void*)((int)(size_t)PTHREAD_CANCELED + 2); + } +#endif + + return (void *) (size_t)result; +} + +int +main() +{ + int failed = 0; + int i; + pthread_t mt; + pthread_t et[NUMTHREADS]; + pthread_t ct[NUMTHREADS]; + + assert((mt = pthread_self()).p != NULL); + + for (i = 0; i < NUMTHREADS; i++) + { + assert(pthread_create(&et[i], NULL, exceptionedThread, (void *) 0) == 0); + assert(pthread_create(&ct[i], NULL, canceledThread, NULL) == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(1000); + + for (i = 0; i < NUMTHREADS; i++) + { + assert(pthread_cancel(ct[i]) == 0); + } + + /* + * Give threads time to run. + */ + Sleep(NUMTHREADS * 1000); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 0; i < NUMTHREADS; i++) + { + int fail = 0; + void* result = (void*)0; + + /* Canceled thread */ + assert(pthread_join(ct[i], &result) == 0); + assert(!(fail = (result != PTHREAD_CANCELED))); + + failed = (failed || fail); + + /* Exceptioned thread */ + assert(pthread_join(et[i], &result) == 0); + assert(!(fail = (result != (void*)((int)(size_t)PTHREAD_CANCELED + 2)))); + + failed = (failed || fail); + } + + assert(!failed); + + /* + * Success. + */ + return 0; +} + +#else /* defined(_MSC_VER) || defined(__cplusplus) */ + +#include + +int +main() +{ + fprintf(stderr, "Test N/A for this compiler environment.\n"); + return 0; +} + +#endif /* defined(_MSC_VER) || defined(__cplusplus) */ diff --git a/w32-pthreads/tests/exception2.c b/w32-pthreads/tests/exception2.c new file mode 100644 index 000000000..faf677d9b --- /dev/null +++ b/w32-pthreads/tests/exception2.c @@ -0,0 +1,158 @@ +/* + * File: exception2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test passing of exceptions out of thread scope. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + + +#if defined(_MSC_VER) || defined(__cplusplus) + +#if defined(_MSC_VER) && defined(__cplusplus) +#include +#elif defined(__cplusplus) +#include +#endif + +#ifdef __GNUC__ +#include +#endif + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 1 +}; + + +void * +exceptionedThread(void * arg) +{ + int dummy = 0x1; + +#if defined(_MSC_VER) && !defined(__cplusplus) + + RaiseException(dummy, 0, 0, NULL); + +#elif defined(__cplusplus) + + throw dummy; + +#endif + + return (void *) 100; +} + +int +main(int argc, char* argv[]) +{ + int i; + pthread_t mt; + pthread_t et[NUMTHREADS]; + + if (argc <= 1) + { + int result; + + printf("You should see an \"abnormal termination\" message\n"); + fflush(stdout); + result = system("exception2.exe die"); + exit(0); + } + + assert((mt = pthread_self()).p != NULL); + + for (i = 0; i < NUMTHREADS; i++) + { + assert(pthread_create(&et[i], NULL, exceptionedThread, NULL) == 0); + } + + Sleep(1000); + + /* + * Success. + */ + return 0; +} + +#else /* defined(_MSC_VER) || defined(__cplusplus) */ + +#include + +int +main() +{ + fprintf(stderr, "Test N/A for this compiler environment.\n"); + return 0; +} + +#endif /* defined(_MSC_VER) || defined(__cplusplus) */ diff --git a/w32-pthreads/tests/exception3.c b/w32-pthreads/tests/exception3.c new file mode 100644 index 000000000..65bcdbef3 --- /dev/null +++ b/w32-pthreads/tests/exception3.c @@ -0,0 +1,183 @@ +/* + * File: exception3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test running of user supplied terminate() function. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +#if defined(__cplusplus) + +#if defined(_MSC_VER) +# include +#else +# if defined(__GNUC__) && __GNUC__ < 3 +# include +# else +# include + using std::set_terminate; +# endif +#endif + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 1 +}; + +int caught = 0; +pthread_mutex_t caughtLock; + +void +terminateFunction () +{ + assert(pthread_mutex_lock(&caughtLock) == 0); + caught++; +#if 0 + { + FILE * fp = fopen("pthread.log", "a"); + fprintf(fp, "Caught = %d\n", caught); + fclose(fp); + } +#endif + assert(pthread_mutex_unlock(&caughtLock) == 0); + + /* + * Notes from the MSVC++ manual: + * 1) A term_func() should call exit(), otherwise + * abort() will be called on return to the caller. + * abort() raises SIGABRT. The default signal handler + * for all signals terminates the calling program with + * exit code 3. + * 2) A term_func() must not throw an exception. Dev: Therefore + * term_func() should not call pthread_exit() if an + * exception-using version of pthreads-win32 library + * is being used (i.e. either pthreadVCE or pthreadVSE). + */ + exit(0); +} + +void * +exceptionedThread(void * arg) +{ + int dummy = 0x1; + + (void) set_terminate(&terminateFunction); + + throw dummy; + + return (void *) 0; +} + +int +main() +{ + int i; + pthread_t mt; + pthread_t et[NUMTHREADS]; + pthread_mutexattr_t ma; + + assert((mt = pthread_self()).p != NULL); + + printf("See the notes inside of exception3.c re term_funcs.\n"); + + assert(pthread_mutexattr_init(&ma) == 0); + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_ERRORCHECK) == 0); + assert(pthread_mutex_init(&caughtLock, &ma) == 0); + assert(pthread_mutexattr_destroy(&ma) == 0); + + for (i = 0; i < NUMTHREADS; i++) + { + assert(pthread_create(&et[i], NULL, exceptionedThread, NULL) == 0); + } + + Sleep(NUMTHREADS * 100); + + assert(caught == NUMTHREADS); + + /* + * Success. + */ + return 0; +} + +#else /* defined(__cplusplus) */ + +#include + +int +main() +{ + fprintf(stderr, "Test N/A for this compiler environment.\n"); + return 0; +} + +#endif /* defined(__cplusplus) */ diff --git a/w32-pthreads/tests/exit1.c b/w32-pthreads/tests/exit1.c new file mode 100644 index 000000000..38f218211 --- /dev/null +++ b/w32-pthreads/tests/exit1.c @@ -0,0 +1,50 @@ +/* + * Test for pthread_exit(). + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Depends on API functions: None. + */ + +#include "test.h" + +int +main(int argc, char * argv[]) +{ + /* A simple test first. */ + pthread_exit((void *) 0); + + /* Not reached */ + assert(0); + return 0; +} diff --git a/w32-pthreads/tests/exit2.c b/w32-pthreads/tests/exit2.c new file mode 100644 index 000000000..b9f785edf --- /dev/null +++ b/w32-pthreads/tests/exit2.c @@ -0,0 +1,64 @@ +/* + * Test for pthread_exit(). + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Depends on API functions: + * pthread_create() + * pthread_exit() + */ + +#include "test.h" + +void * +func(void * arg) +{ + pthread_exit(arg); + + /* Never reached. */ + assert(0); + + return NULL; +} + +int +main(int argc, char * argv[]) +{ + pthread_t t; + + assert(pthread_create(&t, NULL, func, (void *) NULL) == 0); + + Sleep(100); + + return 0; +} diff --git a/w32-pthreads/tests/exit3.c b/w32-pthreads/tests/exit3.c new file mode 100644 index 000000000..18859e4ee --- /dev/null +++ b/w32-pthreads/tests/exit3.c @@ -0,0 +1,68 @@ +/* + * Test for pthread_exit(). + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Depends on API functions: pthread_create(). + */ + +#include "test.h" + +void * +func(void * arg) +{ + pthread_exit(arg); + + /* Never reached. */ + assert(0); + + return NULL; +} + +int +main(int argc, char * argv[]) +{ + pthread_t id[4]; + int i; + + /* Create a few threads and then exit. */ + for (i = 0; i < 4; i++) + { + assert(pthread_create(&id[i], NULL, func, (void *)(size_t)i) == 0); + } + + Sleep(400); + + /* Success. */ + return 0; +} diff --git a/w32-pthreads/tests/exit4.c b/w32-pthreads/tests/exit4.c new file mode 100644 index 000000000..06dd8b1ee --- /dev/null +++ b/w32-pthreads/tests/exit4.c @@ -0,0 +1,199 @@ +/* + * File: exit4.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test calling pthread_exit from a Win32 thread + * without having created an implicit POSIX handle for it. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" +#ifndef _UWIN +#include +#endif + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 4 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +#if ! defined (__MINGW32__) || defined (__MSVCRT__) +unsigned __stdcall +#else +void +#endif +Win32thread(void * arg) +{ + int result = 1; + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + /* + * Doesn't return and doesn't create an implicit POSIX handle. + */ + pthread_exit((void *)(size_t)result); + + return 0; +} + +int +main() +{ + int failed = 0; + int i; + HANDLE h[NUMTHREADS + 1]; + unsigned thrAddr; /* Dummy variable to pass a valid location to _beginthreadex (Win98). */ + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; +#if ! defined (__MINGW32__) || defined (__MSVCRT__) + h[i] = (HANDLE) _beginthreadex(NULL, 0, Win32thread, (void *) &threadbag[i], 0, &thrAddr); +#else + h[i] = (HANDLE) _beginthread(Win32thread, 0, (void *) &threadbag[i]); +#endif + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(500); + + /* + * Give threads time to run. + */ + Sleep(NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + int result = 0; + +#if ! defined (__MINGW32__) || defined (__MSVCRT__) + assert(GetExitCodeThread(h[i], (LPDWORD) &result) == TRUE); +#else + /* + * Can't get a result code. + */ + result = 1; +#endif + + fail = (result != 1); + + if (fail) + { + fprintf(stderr, "Thread %d: started %d: count %d\n", + i, + threadbag[i].started, + threadbag[i].count); + } + failed = (failed || fail); + } + + assert(!failed); + + /* + * Success. + */ + return 0; +} + diff --git a/w32-pthreads/tests/exit5.c b/w32-pthreads/tests/exit5.c new file mode 100644 index 000000000..ac98f996c --- /dev/null +++ b/w32-pthreads/tests/exit5.c @@ -0,0 +1,205 @@ +/* + * File: exit5.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test calling pthread_exit from a Win32 thread + * having created an implicit POSIX handle for it. + * + * Test Method (Validation or Falsification): + * - Validate return value and that POSIX handle is created and destroyed. + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" +#ifndef _UWIN +#include +#endif + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum { + NUMTHREADS = 4 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ { + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; + pthread_t self; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +#if ! defined (__MINGW32__) || defined (__MSVCRT__) +unsigned __stdcall +#else +void +#endif +Win32thread(void * arg) +{ + int result = 1; + bag_t * bag = (bag_t *) arg; + + assert(bag == &threadbag[bag->threadnum]); + assert(bag->started == 0); + bag->started = 1; + + assert((bag->self = pthread_self()).p != NULL); + assert(pthread_kill(bag->self, 0) == 0); + + /* + * Doesn't return. + */ + pthread_exit((void *)(size_t)result); + + return 0; +} + +int +main() +{ + int failed = 0; + int i; + HANDLE h[NUMTHREADS + 1]; + unsigned thrAddr; /* Dummy variable to pass a valid location to _beginthreadex (Win98). */ + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; +#if ! defined (__MINGW32__) || defined (__MSVCRT__) + h[i] = (HANDLE) _beginthreadex(NULL, 0, Win32thread, (void *) &threadbag[i], 0, &thrAddr); +#else + h[i] = (HANDLE) _beginthread(Win32thread, 0, (void *) &threadbag[i]); +#endif + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep(500); + + /* + * Give threads time to run. + */ + Sleep(NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started); + } + } + + assert(!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + int result = 0; + +#if ! defined (__MINGW32__) || defined (__MSVCRT__) + assert(GetExitCodeThread(h[i], (LPDWORD) &result) == TRUE); +#else + /* + * Can't get a result code. + */ + result = 1; +#endif + + assert(threadbag[i].self.p != NULL && pthread_kill(threadbag[i].self, 0) == ESRCH); + + fail = (result != 1); + + if (fail) + { + fprintf(stderr, "Thread %d: started %d: count %d\n", + i, + threadbag[i].started, + threadbag[i].count); + } + failed = (failed || fail); + } + + assert(!failed); + + /* + * Success. + */ + return 0; +} + diff --git a/w32-pthreads/tests/eyal1.c b/w32-pthreads/tests/eyal1.c new file mode 100644 index 000000000..72b5697e9 --- /dev/null +++ b/w32-pthreads/tests/eyal1.c @@ -0,0 +1,367 @@ +/* Simple POSIX threads program. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Author: Eyal Lebedinsky eyal@eyal.emu.id.au + * Written: Sep 1998. + * Version Date: 12 Sep 1998 + * + * Do we need to lock stdout or is it thread safe? + * + * Used: + * pthread_t + * pthread_attr_t + * pthread_create() + * pthread_join() + * pthread_mutex_t + * PTHREAD_MUTEX_INITIALIZER + * pthread_mutex_init() [not used now] + * pthread_mutex_destroy() + * pthread_mutex_lock() + * pthread_mutex_trylock() + * pthread_mutex_unlock() + * + * What this program does is establish a work queue (implemented using + * four mutexes for each thread). It then schedules work (by storing + * a number in 'todo') and releases the threads. When the work is done + * the threads will block. The program then repeats the same thing once + * more (just to test the logic) and when the work is done it destroyes + * the threads. + * + * The 'work' we do is simply burning CPU cycles in a loop. + * The 'todo' work queue is trivial - each threads pops one element + * off it by incrementing it, the poped number is the 'work' to do. + * When 'todo' reaches the limit (nwork) the queue is considered + * empty. + * + * The number displayed at the end is the amount of work each thread + * did, so we can see if the load was properly distributed. + * + * The program was written to test a threading setup (not seen here) + * rather than to demonstrate correct usage of the pthread facilities. + * + * Note how each thread is given access to a thread control structure + * (TC) which is used for communicating to/from the main program (e.g. + * the threads knows its 'id' and also filles in the 'work' done). +*/ + +#include "test.h" + +#include +#include + +struct thread_control { + int id; + pthread_t thread; /* thread id */ + pthread_mutex_t mutex_start; + pthread_mutex_t mutex_started; + pthread_mutex_t mutex_end; + pthread_mutex_t mutex_ended; + long work; /* work done */ + int stat; /* pthread_init status */ +}; + +typedef struct thread_control TC; + +static TC *tcs = NULL; +static int nthreads = 10; +static int nwork = 100; +static int quiet = 0; + +static int todo = -1; + +static pthread_mutex_t mutex_todo = PTHREAD_MUTEX_INITIALIZER; +static pthread_mutex_t mutex_stdout = PTHREAD_MUTEX_INITIALIZER; + + +static void +die (int ret) +{ + if (NULL != tcs) + { + free (tcs); + tcs = NULL; + } + + if (ret) + exit (ret); +} + + +static double +waste_time (int n) +{ + int i; + double f, g, h, s; + + s = 0.0; + + /* + * Useless work. + */ + for (i = n*100; i > 0; --i) + { + f = rand (); + g = rand (); + h = rand (); + s += 2.0 * f * g / (h != 0.0 ? (h * h) : 1.0); + } + return s; +} + +static int +do_work_unit (int who, int n) +{ + int i; + static int nchars = 0; + double f = 0.0; + + if (quiet) + i = 0; + else { + /* + * get lock on stdout + */ + assert(pthread_mutex_lock (&mutex_stdout) == 0); + + /* + * do our job + */ + i = printf ("%c", "0123456789abcdefghijklmnopqrstuvwxyz"[who]); + + if (!(++nchars % 50)) + printf ("\n"); + + fflush (stdout); + + /* + * release lock on stdout + */ + assert(pthread_mutex_unlock (&mutex_stdout) == 0); + } + + n = rand () % 10000; /* ignore incoming 'n' */ + f = waste_time (n); + + /* This prevents the statement above from being optimised out */ + if (f > 0.0) + return(n); + + return (n); +} + +static int +print_server (void *ptr) +{ + int mywork; + int n; + TC *tc = (TC *)ptr; + + assert(pthread_mutex_lock (&tc->mutex_started) == 0); + + for (;;) + { + assert(pthread_mutex_lock (&tc->mutex_start) == 0); + assert(pthread_mutex_unlock (&tc->mutex_start) == 0); + assert(pthread_mutex_lock (&tc->mutex_ended) == 0); + assert(pthread_mutex_unlock (&tc->mutex_started) == 0); + + for (;;) + { + + /* + * get lock on todo list + */ + assert(pthread_mutex_lock (&mutex_todo) == 0); + + mywork = todo; + if (todo >= 0) + { + ++todo; + if (todo >= nwork) + todo = -1; + } + assert(pthread_mutex_unlock (&mutex_todo) == 0); + + if (mywork < 0) + break; + + assert((n = do_work_unit (tc->id, mywork)) >= 0); + tc->work += n; + } + + assert(pthread_mutex_lock (&tc->mutex_end) == 0); + assert(pthread_mutex_unlock (&tc->mutex_end) == 0); + assert(pthread_mutex_lock (&tc->mutex_started) == 0); + assert(pthread_mutex_unlock (&tc->mutex_ended) == 0); + + if (-2 == mywork) + break; + } + + assert(pthread_mutex_unlock (&tc->mutex_started) == 0); + + return (0); +} + +static void +dosync (void) +{ + int i; + + for (i = 0; i < nthreads; ++i) + { + assert(pthread_mutex_lock (&tcs[i].mutex_end) == 0); + assert(pthread_mutex_unlock (&tcs[i].mutex_start) == 0); + assert(pthread_mutex_lock (&tcs[i].mutex_started) == 0); + assert(pthread_mutex_unlock (&tcs[i].mutex_started) == 0); + } + + /* + * Now threads do their work + */ + for (i = 0; i < nthreads; ++i) + { + assert(pthread_mutex_lock (&tcs[i].mutex_start) == 0); + assert(pthread_mutex_unlock (&tcs[i].mutex_end) == 0); + assert(pthread_mutex_lock (&tcs[i].mutex_ended) == 0); + assert(pthread_mutex_unlock (&tcs[i].mutex_ended) == 0); + } +} + +static void +dowork (void) +{ + todo = 0; + dosync(); + + todo = 0; + dosync(); +} + +int +main (int argc, char *argv[]) +{ + int i; + + assert(NULL != (tcs = (TC *) calloc (nthreads, sizeof (*tcs)))); + + /* + * Launch threads + */ + for (i = 0; i < nthreads; ++i) + { + tcs[i].id = i; + + assert(pthread_mutex_init (&tcs[i].mutex_start, NULL) == 0); + assert(pthread_mutex_init (&tcs[i].mutex_started, NULL) == 0); + assert(pthread_mutex_init (&tcs[i].mutex_end, NULL) == 0); + assert(pthread_mutex_init (&tcs[i].mutex_ended, NULL) == 0); + + tcs[i].work = 0; + + assert(pthread_mutex_lock (&tcs[i].mutex_start) == 0); + assert((tcs[i].stat = + pthread_create (&tcs[i].thread, + NULL, + (void *(*)(void *))print_server, + (void *) &tcs[i]) + ) == 0); + + /* + * Wait for thread initialisation + */ + { + int trylock = 0; + + while (trylock == 0) + { + trylock = pthread_mutex_trylock(&tcs[i].mutex_started); + assert(trylock == 0 || trylock == EBUSY); + + if (trylock == 0) + { + assert(pthread_mutex_unlock (&tcs[i].mutex_started) == 0); + } + } + } + } + + dowork (); + + /* + * Terminate threads + */ + todo = -2; /* please terminate */ + dosync(); + + for (i = 0; i < nthreads; ++i) + { + if (0 == tcs[i].stat) + assert(pthread_join (tcs[i].thread, NULL) == 0); + } + + /* + * destroy locks + */ + assert(pthread_mutex_destroy (&mutex_stdout) == 0); + assert(pthread_mutex_destroy (&mutex_todo) == 0); + + /* + * Cleanup + */ + printf ("\n"); + + /* + * Show results + */ + for (i = 0; i < nthreads; ++i) + { + printf ("%2d ", i); + if (0 == tcs[i].stat) + printf ("%10ld\n", tcs[i].work); + else + printf ("failed %d\n", tcs[i].stat); + + assert(pthread_mutex_unlock(&tcs[i].mutex_start) == 0); + + assert(pthread_mutex_destroy (&tcs[i].mutex_start) == 0); + assert(pthread_mutex_destroy (&tcs[i].mutex_started) == 0); + assert(pthread_mutex_destroy (&tcs[i].mutex_end) == 0); + assert(pthread_mutex_destroy (&tcs[i].mutex_ended) == 0); + } + + die (0); + + return (0); +} diff --git a/w32-pthreads/tests/inherit1.c b/w32-pthreads/tests/inherit1.c new file mode 100644 index 000000000..24ceec557 --- /dev/null +++ b/w32-pthreads/tests/inherit1.c @@ -0,0 +1,177 @@ +/* + * File: inherit1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test thread priority inheritance. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +enum { + PTW32TEST_THREAD_INIT_PRIO = 0, + PTW32TEST_MAXPRIORITIES = 512 +}; + +int minPrio; +int maxPrio; +int validPriorities[PTW32TEST_MAXPRIORITIES]; + + +void * func(void * arg) +{ + int policy; + struct sched_param param; + + assert(pthread_getschedparam(pthread_self(), &policy, ¶m) == 0); + return (void *) (size_t)param.sched_priority; +} + + +void * +getValidPriorities(void * arg) +{ + int prioSet; + pthread_t thread = pthread_self(); + HANDLE threadH = pthread_getw32threadhandle_np(thread); + struct sched_param param; + + for (prioSet = minPrio; + prioSet <= maxPrio; + prioSet++) + { + /* + * If prioSet is invalid then the threads priority is unchanged + * from the previous value. Make the previous value a known + * one so that we can check later. + */ + param.sched_priority = prioSet; + assert(pthread_setschedparam(thread, SCHED_OTHER, ¶m) == 0); + validPriorities[prioSet+(PTW32TEST_MAXPRIORITIES/2)] = GetThreadPriority(threadH); + } + + return (void *) 0; +} + + +int +main() +{ + pthread_t t; + pthread_t mainThread = pthread_self(); + pthread_attr_t attr; + void * result = NULL; + struct sched_param param; + struct sched_param mainParam; + int prio; + int policy; + int inheritsched = -1; + pthread_t threadID = pthread_self(); + HANDLE threadH = pthread_getw32threadhandle_np(threadID); + + assert((maxPrio = sched_get_priority_max(SCHED_OTHER)) != -1); + assert((minPrio = sched_get_priority_min(SCHED_OTHER)) != -1); + + assert(pthread_create(&t, NULL, getValidPriorities, NULL) == 0); + assert(pthread_join(t, &result) == 0); + + assert(pthread_attr_init(&attr) == 0); + assert(pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED) == 0); + assert(pthread_attr_getinheritsched(&attr, &inheritsched) == 0); + assert(inheritsched == PTHREAD_INHERIT_SCHED); + + for (prio = minPrio; prio <= maxPrio; prio++) + { + mainParam.sched_priority = prio; + + /* Set the thread's priority to a known initial value. */ + SetThreadPriority(threadH, PTW32TEST_THREAD_INIT_PRIO); + + /* Change the main thread priority */ + assert(pthread_setschedparam(mainThread, SCHED_OTHER, &mainParam) == 0); + assert(pthread_getschedparam(mainThread, &policy, &mainParam) == 0); + assert(policy == SCHED_OTHER); + /* Priority returned below should be the level set by pthread_setschedparam(). */ + assert(mainParam.sched_priority == prio); + assert(GetThreadPriority(threadH) == + validPriorities[prio+(PTW32TEST_MAXPRIORITIES/2)]); + + for (param.sched_priority = prio; + param.sched_priority <= maxPrio; + param.sched_priority++) + { + /* The new thread create should ignore this new priority */ + assert(pthread_attr_setschedparam(&attr, ¶m) == 0); + assert(pthread_create(&t, &attr, func, NULL) == 0); + pthread_join(t, &result); + assert((int)(size_t) result == mainParam.sched_priority); + } + } + + return 0; +} diff --git a/w32-pthreads/tests/join0.c b/w32-pthreads/tests/join0.c new file mode 100644 index 000000000..d888e9d6b --- /dev/null +++ b/w32-pthreads/tests/join0.c @@ -0,0 +1,67 @@ +/* + * Test for pthread_join(). + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Depends on API functions: pthread_create(), pthread_exit(). + */ + +#include "test.h" + +void * +func(void * arg) +{ + Sleep(2000); + + pthread_exit(arg); + + /* Never reached. */ + exit(1); +} + +int +main(int argc, char * argv[]) +{ + pthread_t id; + void* result = (void*)0; + + /* Create a single thread and wait for it to exit. */ + assert(pthread_create(&id, NULL, func, (void *) 123) == 0); + + assert(pthread_join(id, &result) == 0); + + assert((int)(size_t)result == 123); + + /* Success. */ + return 0; +} diff --git a/w32-pthreads/tests/join1.c b/w32-pthreads/tests/join1.c new file mode 100644 index 000000000..337af832d --- /dev/null +++ b/w32-pthreads/tests/join1.c @@ -0,0 +1,78 @@ +/* + * Test for pthread_join(). + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Depends on API functions: pthread_create(), pthread_join(), pthread_exit(). + */ + +#include "test.h" + +void * +func(void * arg) +{ + int i = (int)(size_t)arg; + + Sleep(i * 100); + + pthread_exit(arg); + + /* Never reached. */ + exit(1); +} + +int +main(int argc, char * argv[]) +{ + pthread_t id[4]; + int i; + void* result = (void*)-1; + + /* Create a few threads and then exit. */ + for (i = 0; i < 4; i++) + { + assert(pthread_create(&id[i], NULL, func, (void *)(size_t)i) == 0); + } + + /* Some threads will finish before they are joined, some after. */ + Sleep(2 * 100 + 50); + + for (i = 0; i < 4; i++) + { + assert(pthread_join(id[i], &result) == 0); + assert((int)(size_t)result == i); + } + + /* Success. */ + return 0; +} diff --git a/w32-pthreads/tests/join2.c b/w32-pthreads/tests/join2.c new file mode 100644 index 000000000..b3b85ee81 --- /dev/null +++ b/w32-pthreads/tests/join2.c @@ -0,0 +1,69 @@ +/* + * Test for pthread_join() returning return value from threads. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Depends on API functions: pthread_create(). + */ + +#include "test.h" + +void * +func(void * arg) +{ + Sleep(1000); + return arg; +} + +int +main(int argc, char * argv[]) +{ + pthread_t id[4]; + int i; + void* result = (void*)-1; + + /* Create a few threads and then exit. */ + for (i = 0; i < 4; i++) + { + assert(pthread_create(&id[i], NULL, func, (void *)(size_t)i) == 0); + } + + for (i = 0; i < 4; i++) + { + assert(pthread_join(id[i], &result) == 0); + assert((int)(size_t)result == i); + } + + /* Success. */ + return 0; +} diff --git a/w32-pthreads/tests/join3.c b/w32-pthreads/tests/join3.c new file mode 100644 index 000000000..44380ace3 --- /dev/null +++ b/w32-pthreads/tests/join3.c @@ -0,0 +1,75 @@ +/* + * Test for pthread_join() returning return value from threads. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Depends on API functions: pthread_create(). + */ + +#include "test.h" + +void * +func(void * arg) +{ + sched_yield(); + return arg; +} + +int +main(int argc, char * argv[]) +{ + pthread_t id[4]; + int i; + void* result = (void*)-1; + + /* Create a few threads and then exit. */ + for (i = 0; i < 4; i++) + { + assert(pthread_create(&id[i], NULL, func, (void *)(size_t)i) == 0); + } + + /* + * Let threads exit before we join them. + * We should still retrieve the exit code for the threads. + */ + Sleep(1000); + + for (i = 0; i < 4; i++) + { + assert(pthread_join(id[i], &result) == 0); + assert((int)(size_t)result == i); + } + + /* Success. */ + return 0; +} diff --git a/w32-pthreads/tests/kill1.c b/w32-pthreads/tests/kill1.c new file mode 100644 index 000000000..fd1eaee2b --- /dev/null +++ b/w32-pthreads/tests/kill1.c @@ -0,0 +1,83 @@ +/* + * File: kill1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - pthread_kill() does not support non zero signals.. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + + +int +main() +{ + assert(pthread_kill(pthread_self(), 1) == EINVAL); + + return 0; +} diff --git a/w32-pthreads/tests/loadfree.c b/w32-pthreads/tests/loadfree.c new file mode 100644 index 000000000..65bb15c7b --- /dev/null +++ b/w32-pthreads/tests/loadfree.c @@ -0,0 +1,70 @@ +/* + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * From: Todd Owen + * To: pthreads-win32@sourceware.cygnus.com + * Subject: invalid page fault when using LoadLibrary/FreeLibrary + * + * hi, + * for me, pthread.dll consistently causes an "invalid page fault in + * kernel32.dll" when I load it "explicitly"...to be precise, loading (with + * LoadLibrary) isn't a problem, it gives the error when I call FreeLibrary. + * I guess that the dll's cleanup must be causing the error. + * + * Implicit linkage of the dll has never given me this problem. Here's a + * program (console application) that gives me the error. + * + * I compile with: mingw32 (gcc-2.95 release), with the MSVCRT add-on (not + * that the compiler should make much difference in this case). + * PTHREAD.DLL: is the precompiled 1999-11-02 one (I tried an older one as + * well, with the same result). + * + * Fascinatingly, if you have your own dll (mycode.dll) which implicitly + * loads pthread.dll, and then do LoadLibrary/FreeLibrary on _this_ dll, the + * same thing happens. + * + */ + +#include "test.h" + +int main() { + HINSTANCE hinst; + + assert((hinst = LoadLibrary("pthread")) != (HINSTANCE) 0); + + Sleep(100); + + FreeLibrary(hinst); + return 0; +} + diff --git a/w32-pthreads/tests/mutex1.c b/w32-pthreads/tests/mutex1.c new file mode 100644 index 000000000..918c90330 --- /dev/null +++ b/w32-pthreads/tests/mutex1.c @@ -0,0 +1,68 @@ +/* + * mutex1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Create a simple mutex object, lock it, and then unlock it again. + * This is the simplest test of the pthread mutex family that we can do. + * + * Depends on API functions: + * pthread_mutex_init() + * pthread_mutex_lock() + * pthread_mutex_unlock() + * pthread_mutex_destroy() + */ + +#include "test.h" + +pthread_mutex_t mutex = NULL; + +int +main() +{ + assert(mutex == NULL); + + assert(pthread_mutex_init(&mutex, NULL) == 0); + + assert(mutex != NULL); + + assert(pthread_mutex_lock(&mutex) == 0); + + assert(pthread_mutex_unlock(&mutex) == 0); + + assert(pthread_mutex_destroy(&mutex) == 0); + + assert(mutex == NULL); + + return 0; +} diff --git a/w32-pthreads/tests/mutex1e.c b/w32-pthreads/tests/mutex1e.c new file mode 100644 index 000000000..d32adb3a1 --- /dev/null +++ b/w32-pthreads/tests/mutex1e.c @@ -0,0 +1,78 @@ +/* + * mutex1e.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * As for mutex1.c but with type set to PTHREAD_MUTEX_ERRORCHECK. + * + * Create a simple mutex object, lock it, unlock it, then destroy it. + * This is the simplest test of the pthread mutex family that we can do. + * + * Depends on API functions: + * pthread_mutexattr_settype() + * pthread_mutex_init() + * pthread_mutex_destroy() + */ + +#include "test.h" + +pthread_mutex_t mutex = NULL; +pthread_mutexattr_t mxAttr; + +int +main() +{ + assert(pthread_mutexattr_init(&mxAttr) == 0); + + BEGIN_MUTEX_STALLED_ROBUST(mxAttr) + + assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_ERRORCHECK) == 0); + + assert(mutex == NULL); + + assert(pthread_mutex_init(&mutex, &mxAttr) == 0); + + assert(mutex != NULL); + + assert(pthread_mutex_lock(&mutex) == 0); + + assert(pthread_mutex_unlock(&mutex) == 0); + + assert(pthread_mutex_destroy(&mutex) == 0); + + assert(mutex == NULL); + + END_MUTEX_STALLED_ROBUST(mxAttr) + + return 0; +} diff --git a/w32-pthreads/tests/mutex1n.c b/w32-pthreads/tests/mutex1n.c new file mode 100644 index 000000000..fcfc1347c --- /dev/null +++ b/w32-pthreads/tests/mutex1n.c @@ -0,0 +1,78 @@ +/* + * mutex1n.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * As for mutex1.c but with type set to PTHREAD_MUTEX_NORMAL. + * + * Create a simple mutex object, lock it, unlock it, then destroy it. + * This is the simplest test of the pthread mutex family that we can do. + * + * Depends on API functions: + * pthread_mutexattr_settype() + * pthread_mutex_init() + * pthread_mutex_destroy() + */ + +#include "test.h" + +pthread_mutex_t mutex = NULL; +pthread_mutexattr_t mxAttr; + +int +main() +{ + assert(pthread_mutexattr_init(&mxAttr) == 0); + + BEGIN_MUTEX_STALLED_ROBUST(mxAttr) + + assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_NORMAL) == 0); + + assert(mutex == NULL); + + assert(pthread_mutex_init(&mutex, &mxAttr) == 0); + + assert(mutex != NULL); + + assert(pthread_mutex_lock(&mutex) == 0); + + assert(pthread_mutex_unlock(&mutex) == 0); + + assert(pthread_mutex_destroy(&mutex) == 0); + + assert(mutex == NULL); + + END_MUTEX_STALLED_ROBUST(mxAttr) + + return 0; +} diff --git a/w32-pthreads/tests/mutex1r.c b/w32-pthreads/tests/mutex1r.c new file mode 100644 index 000000000..15083f27a --- /dev/null +++ b/w32-pthreads/tests/mutex1r.c @@ -0,0 +1,78 @@ +/* + * mutex1r.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * As for mutex1.c but with type set to PTHREAD_MUTEX_RECURSIVE. + * + * Create a simple mutex object, lock it, unlock it, then destroy it. + * This is the simplest test of the pthread mutex family that we can do. + * + * Depends on API functions: + * pthread_mutexattr_settype() + * pthread_mutex_init() + * pthread_mutex_destroy() + */ + +#include "test.h" + +pthread_mutex_t mutex = NULL; +pthread_mutexattr_t mxAttr; + +int +main() +{ + assert(pthread_mutexattr_init(&mxAttr) == 0); + + BEGIN_MUTEX_STALLED_ROBUST(mxAttr) + + assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_RECURSIVE) == 0); + + assert(mutex == NULL); + + assert(pthread_mutex_init(&mutex, &mxAttr) == 0); + + assert(mutex != NULL); + + assert(pthread_mutex_lock(&mutex) == 0); + + assert(pthread_mutex_unlock(&mutex) == 0); + + assert(pthread_mutex_destroy(&mutex) == 0); + + assert(mutex == NULL); + + END_MUTEX_STALLED_ROBUST(mxAttr) + + return 0; +} diff --git a/w32-pthreads/tests/mutex2.c b/w32-pthreads/tests/mutex2.c new file mode 100644 index 000000000..377468e90 --- /dev/null +++ b/w32-pthreads/tests/mutex2.c @@ -0,0 +1,66 @@ +/* + * mutex2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static mutex object, lock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_mutex_lock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; + +int +main() +{ + assert(mutex == PTHREAD_MUTEX_INITIALIZER); + + assert(pthread_mutex_lock(&mutex) == 0); + + assert(mutex != PTHREAD_MUTEX_INITIALIZER); + + assert(mutex != NULL); + + assert(pthread_mutex_unlock(&mutex) == 0); + + assert(pthread_mutex_destroy(&mutex) == 0); + + assert(mutex == NULL); + + return 0; +} diff --git a/w32-pthreads/tests/mutex2e.c b/w32-pthreads/tests/mutex2e.c new file mode 100644 index 000000000..7df6073d2 --- /dev/null +++ b/w32-pthreads/tests/mutex2e.c @@ -0,0 +1,66 @@ +/* + * mutex2e.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static mutex object, lock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_mutex_lock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +pthread_mutex_t mutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER; + +int +main() +{ + assert(mutex == PTHREAD_ERRORCHECK_MUTEX_INITIALIZER); + + assert(pthread_mutex_lock(&mutex) == 0); + + assert(mutex != PTHREAD_ERRORCHECK_MUTEX_INITIALIZER); + + assert(mutex != NULL); + + assert(pthread_mutex_unlock(&mutex) == 0); + + assert(pthread_mutex_destroy(&mutex) == 0); + + assert(mutex == NULL); + + return 0; +} diff --git a/w32-pthreads/tests/mutex2r.c b/w32-pthreads/tests/mutex2r.c new file mode 100644 index 000000000..c96e366f1 --- /dev/null +++ b/w32-pthreads/tests/mutex2r.c @@ -0,0 +1,66 @@ +/* + * mutex2r.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static mutex object, lock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_mutex_lock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +pthread_mutex_t mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER; + +int +main() +{ + assert(mutex == PTHREAD_RECURSIVE_MUTEX_INITIALIZER); + + assert(pthread_mutex_lock(&mutex) == 0); + + assert(mutex != PTHREAD_RECURSIVE_MUTEX_INITIALIZER); + + assert(mutex != NULL); + + assert(pthread_mutex_unlock(&mutex) == 0); + + assert(pthread_mutex_destroy(&mutex) == 0); + + assert(mutex == NULL); + + return 0; +} diff --git a/w32-pthreads/tests/mutex3.c b/w32-pthreads/tests/mutex3.c new file mode 100644 index 000000000..bc1429e0b --- /dev/null +++ b/w32-pthreads/tests/mutex3.c @@ -0,0 +1,75 @@ +/* + * mutex3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static mutex object, lock it, trylock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_mutex_lock() + * pthread_mutex_trylock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; + +static int washere = 0; + +void * func(void * arg) +{ + assert(pthread_mutex_trylock(&mutex1) == EBUSY); + + washere = 1; + + return 0; +} + +int +main() +{ + pthread_t t; + + assert(pthread_mutex_lock(&mutex1) == 0); + + assert(pthread_create(&t, NULL, func, NULL) == 0); + assert(pthread_join(t, NULL) == 0); + + assert(pthread_mutex_unlock(&mutex1) == 0); + + assert(washere == 1); + + return 0; +} diff --git a/w32-pthreads/tests/mutex3e.c b/w32-pthreads/tests/mutex3e.c new file mode 100644 index 000000000..66cfcb71c --- /dev/null +++ b/w32-pthreads/tests/mutex3e.c @@ -0,0 +1,75 @@ +/* + * mutex3e.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static mutex object, lock it, trylock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_mutex_lock() + * pthread_mutex_trylock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +pthread_mutex_t mutex1 = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER; + +static int washere = 0; + +void * func(void * arg) +{ + assert(pthread_mutex_trylock(&mutex1) == EBUSY); + + washere = 1; + + return 0; +} + +int +main() +{ + pthread_t t; + + assert(pthread_mutex_lock(&mutex1) == 0); + + assert(pthread_create(&t, NULL, func, NULL) == 0); + assert(pthread_join(t, NULL) == 0); + + assert(pthread_mutex_unlock(&mutex1) == 0); + + assert(washere == 1); + + return 0; +} diff --git a/w32-pthreads/tests/mutex3r.c b/w32-pthreads/tests/mutex3r.c new file mode 100644 index 000000000..8fa7f2547 --- /dev/null +++ b/w32-pthreads/tests/mutex3r.c @@ -0,0 +1,75 @@ +/* + * mutex3r.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static mutex object, lock it, trylock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_mutex_lock() + * pthread_mutex_trylock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +pthread_mutex_t mutex1 = PTHREAD_RECURSIVE_MUTEX_INITIALIZER; + +static int washere = 0; + +void * func(void * arg) +{ + assert(pthread_mutex_trylock(&mutex1) == EBUSY); + + washere = 1; + + return 0; +} + +int +main() +{ + pthread_t t; + + assert(pthread_mutex_lock(&mutex1) == 0); + + assert(pthread_create(&t, NULL, func, NULL) == 0); + assert(pthread_join(t, NULL) == 0); + + assert(pthread_mutex_unlock(&mutex1) == 0); + + assert(washere == 1); + + return 0; +} diff --git a/w32-pthreads/tests/mutex4.c b/w32-pthreads/tests/mutex4.c new file mode 100644 index 000000000..6d36e0aa1 --- /dev/null +++ b/w32-pthreads/tests/mutex4.c @@ -0,0 +1,109 @@ +/* + * mutex4.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Thread A locks mutex - thread B tries to unlock. + * + * Depends on API functions: + * pthread_mutex_lock() + * pthread_mutex_trylock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +static int wasHere = 0; + +static pthread_mutex_t mutex1; + +void * unlocker(void * arg) +{ + int expectedResult = (int)(size_t)arg; + + wasHere++; + assert(pthread_mutex_unlock(&mutex1) == expectedResult); + wasHere++; + return NULL; +} + +int +main() +{ + pthread_t t; + pthread_mutexattr_t ma; + + assert(pthread_mutexattr_init(&ma) == 0); + + BEGIN_MUTEX_STALLED_ROBUST(ma) + + wasHere = 0; + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_DEFAULT) == 0); + assert(pthread_mutex_init(&mutex1, &ma) == 0); + assert(pthread_mutex_lock(&mutex1) == 0); + assert(pthread_create(&t, NULL, unlocker, (void *)(size_t)(IS_ROBUST?EPERM:0)) == 0); + assert(pthread_join(t, NULL) == 0); + assert(pthread_mutex_unlock(&mutex1) == 0); + assert(wasHere == 2); + + wasHere = 0; + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_NORMAL) == 0); + assert(pthread_mutex_init(&mutex1, &ma) == 0); + assert(pthread_mutex_lock(&mutex1) == 0); + assert(pthread_create(&t, NULL, unlocker, (void *)(size_t)(IS_ROBUST?EPERM:0)) == 0); + assert(pthread_join(t, NULL) == 0); + assert(pthread_mutex_unlock(&mutex1) == 0); + assert(wasHere == 2); + + wasHere = 0; + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_ERRORCHECK) == 0); + assert(pthread_mutex_init(&mutex1, &ma) == 0); + assert(pthread_mutex_lock(&mutex1) == 0); + assert(pthread_create(&t, NULL, unlocker, (void *)(size_t) EPERM) == 0); + assert(pthread_join(t, NULL) == 0); + assert(pthread_mutex_unlock(&mutex1) == 0); + assert(wasHere == 2); + + wasHere = 0; + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE) == 0); + assert(pthread_mutex_init(&mutex1, &ma) == 0); + assert(pthread_mutex_lock(&mutex1) == 0); + assert(pthread_create(&t, NULL, unlocker, (void *)(size_t) EPERM) == 0); + assert(pthread_join(t, NULL) == 0); + assert(pthread_mutex_unlock(&mutex1) == 0); + assert(wasHere == 2); + + END_MUTEX_STALLED_ROBUST(ma) + + return 0; +} diff --git a/w32-pthreads/tests/mutex5.c b/w32-pthreads/tests/mutex5.c new file mode 100644 index 000000000..a71f9d893 --- /dev/null +++ b/w32-pthreads/tests/mutex5.c @@ -0,0 +1,67 @@ +/* + * mutex5.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Confirm the equality/inequality of the various mutex types, + * and the default not-set value. + */ + +#include "test.h" + +static pthread_mutexattr_t mxAttr; + +/* Prevent optimiser from removing dead or obvious asserts. */ +int _optimiseFoil; +#define FOIL(x) (_optimiseFoil = x) + +int +main() +{ + int mxType = -1; + + assert(FOIL(PTHREAD_MUTEX_DEFAULT) == PTHREAD_MUTEX_NORMAL); + assert(FOIL(PTHREAD_MUTEX_DEFAULT) != PTHREAD_MUTEX_ERRORCHECK); + assert(FOIL(PTHREAD_MUTEX_DEFAULT) != PTHREAD_MUTEX_RECURSIVE); + assert(FOIL(PTHREAD_MUTEX_RECURSIVE) != PTHREAD_MUTEX_ERRORCHECK); + + assert(FOIL(PTHREAD_MUTEX_NORMAL) == PTHREAD_MUTEX_FAST_NP); + assert(FOIL(PTHREAD_MUTEX_RECURSIVE) == PTHREAD_MUTEX_RECURSIVE_NP); + assert(FOIL(PTHREAD_MUTEX_ERRORCHECK) == PTHREAD_MUTEX_ERRORCHECK_NP); + + assert(pthread_mutexattr_init(&mxAttr) == 0); + assert(pthread_mutexattr_gettype(&mxAttr, &mxType) == 0); + assert(mxType == PTHREAD_MUTEX_NORMAL); + + return 0; +} diff --git a/w32-pthreads/tests/mutex6.c b/w32-pthreads/tests/mutex6.c new file mode 100644 index 000000000..15649fc8d --- /dev/null +++ b/w32-pthreads/tests/mutex6.c @@ -0,0 +1,93 @@ +/* + * mutex6.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test the default (type not set) mutex type. + * Should be the same as PTHREAD_MUTEX_NORMAL. + * Thread locks mutex twice (recursive lock). + * Locking thread should deadlock on second attempt. + * + * Depends on API functions: + * pthread_mutex_lock() + * pthread_mutex_trylock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +static int lockCount = 0; + +static pthread_mutex_t mutex; + +void * locker(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + + /* Should wait here (deadlocked) */ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + assert(pthread_mutex_unlock(&mutex) == 0); + + return 0; +} + +int +main() +{ + pthread_t t; + + assert(pthread_mutex_init(&mutex, NULL) == 0); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + Sleep(1000); + + assert(lockCount == 1); + + /* + * Should succeed even though we don't own the lock + * because FAST mutexes don't check ownership. + */ + assert(pthread_mutex_unlock(&mutex) == 0); + + Sleep (1000); + + assert(lockCount == 2); + + exit(0); + + /* Never reached */ + return 0; +} diff --git a/w32-pthreads/tests/mutex6e.c b/w32-pthreads/tests/mutex6e.c new file mode 100644 index 000000000..908a51ba1 --- /dev/null +++ b/w32-pthreads/tests/mutex6e.c @@ -0,0 +1,109 @@ +/* + * mutex6e.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Tests PTHREAD_MUTEX_ERRORCHECK mutex type. + * Thread locks mutex twice (recursive lock). + * This should fail with an EDEADLK error. + * The second unlock attempt should fail with an EPERM error. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_mutexattr_init() + * pthread_mutexattr_destroy() + * pthread_mutexattr_settype() + * pthread_mutexattr_gettype() + * pthread_mutex_init() + * pthread_mutex_destroy() + * pthread_mutex_lock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +static int lockCount; + +static pthread_mutex_t mutex; +static pthread_mutexattr_t mxAttr; + +void * locker(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + assert(pthread_mutex_lock(&mutex) == EDEADLK); + lockCount++; + assert(pthread_mutex_unlock(&mutex) == 0); + assert(pthread_mutex_unlock(&mutex) == EPERM); + + return (void *) 555; +} + +int +main() +{ + pthread_t t; + void* result = (void*)0; + int mxType = -1; + + assert(pthread_mutexattr_init(&mxAttr) == 0); + + BEGIN_MUTEX_STALLED_ROBUST(mxAttr) + + lockCount = 0; + assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_ERRORCHECK) == 0); + assert(pthread_mutexattr_gettype(&mxAttr, &mxType) == 0); + assert(mxType == PTHREAD_MUTEX_ERRORCHECK); + + assert(pthread_mutex_init(&mutex, &mxAttr) == 0); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + assert(pthread_join(t, &result) == 0); + assert((int)(size_t)result == 555); + + assert(lockCount == 2); + + assert(pthread_mutex_destroy(&mutex) == 0); + + END_MUTEX_STALLED_ROBUST(mxAttr) + + assert(pthread_mutexattr_destroy(&mxAttr) == 0); + + exit(0); + + /* Never reached */ + return 0; +} + diff --git a/w32-pthreads/tests/mutex6es.c b/w32-pthreads/tests/mutex6es.c new file mode 100644 index 000000000..d4b624959 --- /dev/null +++ b/w32-pthreads/tests/mutex6es.c @@ -0,0 +1,94 @@ +/* + * mutex6es.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Tests PTHREAD_MUTEX_ERRORCHECK static mutex type. + * Thread locks mutex twice (recursive lock). + * This should fail with an EDEADLK error. + * The second unlock attempt should fail with an EPERM error. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_mutexattr_init() + * pthread_mutexattr_destroy() + * pthread_mutexattr_settype() + * pthread_mutexattr_gettype() + * pthread_mutex_init() + * pthread_mutex_destroy() + * pthread_mutex_lock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +static int lockCount = 0; + +static pthread_mutex_t mutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER; + +void * locker(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + assert(pthread_mutex_lock(&mutex) == EDEADLK); + lockCount++; + assert(pthread_mutex_unlock(&mutex) == 0); + assert(pthread_mutex_unlock(&mutex) == EPERM); + + return (void *) 555; +} + +int +main() +{ + pthread_t t; + void* result = (void*)0; + + assert(mutex == PTHREAD_ERRORCHECK_MUTEX_INITIALIZER); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + assert(pthread_join(t, &result) == 0); + assert((int)(size_t)result == 555); + + assert(lockCount == 2); + + assert(pthread_mutex_destroy(&mutex) == 0); + + exit(0); + + /* Never reached */ + return 0; +} + diff --git a/w32-pthreads/tests/mutex6n.c b/w32-pthreads/tests/mutex6n.c new file mode 100644 index 000000000..9cb309c2c --- /dev/null +++ b/w32-pthreads/tests/mutex6n.c @@ -0,0 +1,107 @@ +/* + * mutex6n.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Tests PTHREAD_MUTEX_NORMAL mutex type. + * Thread locks mutex twice (recursive lock). + * The thread should deadlock. + * + * Depends on API functions: + * pthread_create() + * pthread_mutexattr_init() + * pthread_mutexattr_settype() + * pthread_mutexattr_gettype() + * pthread_mutex_init() + * pthread_mutex_lock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +static int lockCount; + +static pthread_mutex_t mutex; +static pthread_mutexattr_t mxAttr; + +void * locker(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + + /* Should wait here (deadlocked) */ + assert(pthread_mutex_lock(&mutex) == 0); + + lockCount++; + assert(pthread_mutex_unlock(&mutex) == 0); + + return (void *) 555; +} + +int +main() +{ + pthread_t t; + int mxType = -1; + + assert(pthread_mutexattr_init(&mxAttr) == 0); + + BEGIN_MUTEX_STALLED_ROBUST(mxAttr) + + lockCount = 0; + assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_NORMAL) == 0); + assert(pthread_mutexattr_gettype(&mxAttr, &mxType) == 0); + assert(mxType == PTHREAD_MUTEX_NORMAL); + + assert(pthread_mutex_init(&mutex, &mxAttr) == 0); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + Sleep(100); + + assert(lockCount == 1); + + assert(pthread_mutex_unlock(&mutex) == IS_ROBUST?EPERM:0); + + Sleep (100); + + assert(lockCount == IS_ROBUST?1:2); + + END_MUTEX_STALLED_ROBUST(mxAttr) + + exit(0); + + /* Never reached */ + return 0; +} + diff --git a/w32-pthreads/tests/mutex6r.c b/w32-pthreads/tests/mutex6r.c new file mode 100644 index 000000000..9d81ad849 --- /dev/null +++ b/w32-pthreads/tests/mutex6r.c @@ -0,0 +1,107 @@ +/* + * mutex6r.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Tests PTHREAD_MUTEX_RECURSIVE mutex type. + * Thread locks mutex twice (recursive lock). + * Both locks and unlocks should succeed. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_mutexattr_init() + * pthread_mutexattr_destroy() + * pthread_mutexattr_settype() + * pthread_mutexattr_gettype() + * pthread_mutex_init() + * pthread_mutex_destroy() + * pthread_mutex_lock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +static int lockCount; + +static pthread_mutex_t mutex; +static pthread_mutexattr_t mxAttr; + +void * locker(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + assert(pthread_mutex_unlock(&mutex) == 0); + assert(pthread_mutex_unlock(&mutex) == 0); + + return (void *) 555; +} + +int +main() +{ + pthread_t t; + void* result = (void*)0; + int mxType = -1; + + assert(pthread_mutexattr_init(&mxAttr) == 0); + + BEGIN_MUTEX_STALLED_ROBUST(mxAttr) + + lockCount = 0; + assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_RECURSIVE) == 0); + assert(pthread_mutexattr_gettype(&mxAttr, &mxType) == 0); + assert(mxType == PTHREAD_MUTEX_RECURSIVE); + + assert(pthread_mutex_init(&mutex, &mxAttr) == 0); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + assert(pthread_join(t, &result) == 0); + assert((int)(size_t)result == 555); + + assert(lockCount == 2); + + assert(pthread_mutex_destroy(&mutex) == 0); + + END_MUTEX_STALLED_ROBUST(mxAttr) + + assert(pthread_mutexattr_destroy(&mxAttr) == 0); + + exit(0); + + /* Never reached */ + return 0; +} diff --git a/w32-pthreads/tests/mutex6rs.c b/w32-pthreads/tests/mutex6rs.c new file mode 100644 index 000000000..4242fd627 --- /dev/null +++ b/w32-pthreads/tests/mutex6rs.c @@ -0,0 +1,92 @@ +/* + * mutex6rs.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Tests PTHREAD_MUTEX_RECURSIVE static mutex type. + * Thread locks mutex twice (recursive lock). + * Both locks and unlocks should succeed. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_mutexattr_init() + * pthread_mutexattr_destroy() + * pthread_mutexattr_settype() + * pthread_mutexattr_gettype() + * pthread_mutex_init() + * pthread_mutex_destroy() + * pthread_mutex_lock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +static int lockCount = 0; + +static pthread_mutex_t mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER; + +void * locker(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + assert(pthread_mutex_unlock(&mutex) == 0); + assert(pthread_mutex_unlock(&mutex) == 0); + + return (void *) 555; +} + +int +main() +{ + pthread_t t; + void* result = (void*)0; + + assert(mutex == PTHREAD_RECURSIVE_MUTEX_INITIALIZER); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + assert(pthread_join(t, &result) == 0); + assert((int)(size_t)result == 555); + + assert(lockCount == 2); + + assert(pthread_mutex_destroy(&mutex) == 0); + + exit(0); + + /* Never reached */ + return 0; +} diff --git a/w32-pthreads/tests/mutex6s.c b/w32-pthreads/tests/mutex6s.c new file mode 100644 index 000000000..8b82dc3fa --- /dev/null +++ b/w32-pthreads/tests/mutex6s.c @@ -0,0 +1,93 @@ +/* + * mutex6s.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test the default (type not set) static mutex type. + * Should be the same as PTHREAD_MUTEX_NORMAL. + * Thread locks mutex twice (recursive lock). + * Locking thread should deadlock on second attempt. + * + * Depends on API functions: + * pthread_mutex_lock() + * pthread_mutex_trylock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +static int lockCount = 0; + +static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; + +void * locker(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + + /* Should wait here (deadlocked) */ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + assert(pthread_mutex_unlock(&mutex) == 0); + + return 0; +} + +int +main() +{ + pthread_t t; + + assert(mutex == PTHREAD_MUTEX_INITIALIZER); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + Sleep(1000); + + assert(lockCount == 1); + + /* + * Should succeed even though we don't own the lock + * because FAST mutexes don't check ownership. + */ + assert(pthread_mutex_unlock(&mutex) == 0); + + Sleep (1000); + + assert(lockCount == 2); + + exit(0); + + /* Never reached */ + return 0; +} diff --git a/w32-pthreads/tests/mutex7.c b/w32-pthreads/tests/mutex7.c new file mode 100644 index 000000000..4137c351d --- /dev/null +++ b/w32-pthreads/tests/mutex7.c @@ -0,0 +1,82 @@ +/* + * mutex7.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test the default (type not set) mutex type. + * Should be the same as PTHREAD_MUTEX_NORMAL. + * Thread locks then trylocks mutex (attempted recursive lock). + * The thread should lock first time and EBUSY second time. + * + * Depends on API functions: + * pthread_mutex_lock() + * pthread_mutex_trylock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +static int lockCount = 0; + +static pthread_mutex_t mutex; + +void * locker(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + assert(pthread_mutex_trylock(&mutex) == EBUSY); + lockCount++; + assert(pthread_mutex_unlock(&mutex) == 0); + assert(pthread_mutex_unlock(&mutex) == 0); + + return 0; +} + +int +main() +{ + pthread_t t; + + assert(pthread_mutex_init(&mutex, NULL) == 0); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + Sleep(1000); + + assert(lockCount == 2); + + exit(0); + + /* Never reached */ + return 0; +} diff --git a/w32-pthreads/tests/mutex7e.c b/w32-pthreads/tests/mutex7e.c new file mode 100644 index 000000000..80981b3e1 --- /dev/null +++ b/w32-pthreads/tests/mutex7e.c @@ -0,0 +1,108 @@ +/* + * mutex7e.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Tests PTHREAD_MUTEX_ERRORCHECK mutex type. + * Thread locks and then trylocks mutex (attempted recursive lock). + * Trylock should fail with an EBUSY error. + * The second unlock attempt should fail with an EPERM error. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_mutexattr_init() + * pthread_mutexattr_destroy() + * pthread_mutexattr_settype() + * pthread_mutexattr_gettype() + * pthread_mutex_init() + * pthread_mutex_destroy() + * pthread_mutex_lock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +static int lockCount; + +static pthread_mutex_t mutex; +static pthread_mutexattr_t mxAttr; + +void * locker(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + assert(pthread_mutex_trylock(&mutex) == EBUSY); + lockCount++; + assert(pthread_mutex_unlock(&mutex) == 0); + + return (void *) 555; +} + +int +main() +{ + pthread_t t; + void* result = (void*)0; + int mxType = -1; + + assert(pthread_mutexattr_init(&mxAttr) == 0); + + BEGIN_MUTEX_STALLED_ROBUST(mxAttr) + + lockCount = 0; + assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_ERRORCHECK) == 0); + assert(pthread_mutexattr_gettype(&mxAttr, &mxType) == 0); + assert(mxType == PTHREAD_MUTEX_ERRORCHECK); + + assert(pthread_mutex_init(&mutex, &mxAttr) == 0); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + assert(pthread_join(t, &result) == 0); + assert((int)(size_t)result == 555); + + assert(lockCount == 2); + + assert(pthread_mutex_destroy(&mutex) == 0); + + END_MUTEX_STALLED_ROBUST(mxAttr) + + assert(pthread_mutexattr_destroy(&mxAttr) == 0); + + exit(0); + + /* Never reached */ + return 0; +} + diff --git a/w32-pthreads/tests/mutex7n.c b/w32-pthreads/tests/mutex7n.c new file mode 100644 index 000000000..87ba10a57 --- /dev/null +++ b/w32-pthreads/tests/mutex7n.c @@ -0,0 +1,100 @@ +/* + * mutex7n.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Tests PTHREAD_MUTEX_NORMAL mutex type. + * Thread locks then trylocks mutex (attempted recursive lock). + * The thread should lock first time and EBUSY second time. + * + * Depends on API functions: + * pthread_create() + * pthread_mutexattr_init() + * pthread_mutexattr_settype() + * pthread_mutexattr_gettype() + * pthread_mutex_init() + * pthread_mutex_lock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +static int lockCount; + +static pthread_mutex_t mutex; +static pthread_mutexattr_t mxAttr; + +void * locker(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + assert(pthread_mutex_trylock(&mutex) == EBUSY); + lockCount++; + assert(pthread_mutex_unlock(&mutex) == 0); + + return (void *) 555; +} + +int +main() +{ + pthread_t t; + int mxType = -1; + + assert(pthread_mutexattr_init(&mxAttr) == 0); + + BEGIN_MUTEX_STALLED_ROBUST(mxAttr) + + lockCount = 0; + assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_NORMAL) == 0); + assert(pthread_mutexattr_gettype(&mxAttr, &mxType) == 0); + assert(mxType == PTHREAD_MUTEX_NORMAL); + + assert(pthread_mutex_init(&mutex, &mxAttr) == 0); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + Sleep(100); + + assert(lockCount == 2); + + END_MUTEX_STALLED_ROBUST(mxAttr) + + assert(pthread_mutexattr_destroy(&mxAttr) == 0); + + exit(0); + + /* Never reached */ + return 0; +} + diff --git a/w32-pthreads/tests/mutex7r.c b/w32-pthreads/tests/mutex7r.c new file mode 100644 index 000000000..4e4ae8a9a --- /dev/null +++ b/w32-pthreads/tests/mutex7r.c @@ -0,0 +1,107 @@ +/* + * mutex7r.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Tests PTHREAD_MUTEX_RECURSIVE mutex type. + * Thread locks mutex then trylocks mutex (recursive lock twice). + * Both locks and unlocks should succeed. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_mutexattr_init() + * pthread_mutexattr_destroy() + * pthread_mutexattr_settype() + * pthread_mutexattr_gettype() + * pthread_mutex_init() + * pthread_mutex_destroy() + * pthread_mutex_lock() + * pthread_mutex_unlock() + */ + +#include "test.h" + +static int lockCount; + +static pthread_mutex_t mutex; +static pthread_mutexattr_t mxAttr; + +void * locker(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + assert(pthread_mutex_trylock(&mutex) == 0); + lockCount++; + assert(pthread_mutex_unlock(&mutex) == 0); + assert(pthread_mutex_unlock(&mutex) == 0); + + return (void *) 555; +} + +int +main() +{ + pthread_t t; + void* result = (void*)0; + int mxType = -1; + + assert(pthread_mutexattr_init(&mxAttr) == 0); + + BEGIN_MUTEX_STALLED_ROBUST(mxAttr) + + lockCount = 0; + assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_RECURSIVE) == 0); + assert(pthread_mutexattr_gettype(&mxAttr, &mxType) == 0); + assert(mxType == PTHREAD_MUTEX_RECURSIVE); + + assert(pthread_mutex_init(&mutex, &mxAttr) == 0); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + assert(pthread_join(t, &result) == 0); + assert((int)(size_t)result == 555); + + assert(lockCount == 2); + + assert(pthread_mutex_destroy(&mutex) == 0); + + END_MUTEX_STALLED_ROBUST(mxAttr) + + assert(pthread_mutexattr_destroy(&mxAttr) == 0); + + exit(0); + + /* Never reached */ + return 0; +} diff --git a/w32-pthreads/tests/mutex8.c b/w32-pthreads/tests/mutex8.c new file mode 100644 index 000000000..f2636786c --- /dev/null +++ b/w32-pthreads/tests/mutex8.c @@ -0,0 +1,82 @@ +/* + * mutex8.c + * + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright (C) 1998 Ben Elliston and Ross Johnson + * Copyright (C) 1999,2000,2001 Ross Johnson + * + * Contact Email: rpj@ise.canberra.edu.au + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * -------------------------------------------------------------------------- + * + * Test the default (type not set) mutex type exercising timedlock. + * Thread locks mutex, another thread timedlocks the mutex. + * Timed thread should timeout. + * + * Depends on API functions: + * pthread_mutex_lock() + * pthread_mutex_timedlock() + * pthread_mutex_unlock() + */ + +#include "test.h" +#include + +static int lockCount = 0; + +static pthread_mutex_t mutex; + +void * locker(void * arg) +{ + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 1; + + assert(pthread_mutex_timedlock(&mutex, &abstime) == ETIMEDOUT); + + lockCount++; + + return 0; +} + +int +main() +{ + pthread_t t; + + assert(pthread_mutex_init(&mutex, NULL) == 0); + + assert(pthread_mutex_lock(&mutex) == 0); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + Sleep(2000); + + assert(lockCount == 1); + + assert(pthread_mutex_unlock(&mutex) == 0); + + return 0; +} diff --git a/w32-pthreads/tests/mutex8e.c b/w32-pthreads/tests/mutex8e.c new file mode 100644 index 000000000..a36056673 --- /dev/null +++ b/w32-pthreads/tests/mutex8e.c @@ -0,0 +1,103 @@ +/* + * mutex8e.c + * + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright (C) 1998 Ben Elliston and Ross Johnson + * Copyright (C) 1999,2000,2001 Ross Johnson + * + * Contact Email: rpj@ise.canberra.edu.au + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * -------------------------------------------------------------------------- + * + * Tests PTHREAD_MUTEX_ERRORCHECK mutex type exercising timedlock. + * Thread locks mutex, another thread timedlocks the mutex. + * Timed thread should timeout. + * + * Depends on API functions: + * pthread_create() + * pthread_mutexattr_init() + * pthread_mutexattr_destroy() + * pthread_mutexattr_settype() + * pthread_mutexattr_gettype() + * pthread_mutex_init() + * pthread_mutex_destroy() + * pthread_mutex_lock() + * pthread_mutex_timedlock() + * pthread_mutex_unlock() + */ + +#include "test.h" +#include + +static int lockCount; + +static pthread_mutex_t mutex; +static pthread_mutexattr_t mxAttr; + +void * locker(void * arg) +{ + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 1; + + assert(pthread_mutex_timedlock(&mutex, &abstime) == ETIMEDOUT); + + lockCount++; + + return 0; +} + +int +main() +{ + pthread_t t; + int mxType = -1; + + assert(pthread_mutexattr_init(&mxAttr) == 0); + + BEGIN_MUTEX_STALLED_ROBUST(mxAttr) + + lockCount = 0; + assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_ERRORCHECK) == 0); + assert(pthread_mutexattr_gettype(&mxAttr, &mxType) == 0); + assert(mxType == PTHREAD_MUTEX_ERRORCHECK); + + assert(pthread_mutex_init(&mutex, &mxAttr) == 0); + + assert(pthread_mutex_lock(&mutex) == 0); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + Sleep(2000); + + assert(lockCount == 1); + + assert(pthread_mutex_unlock(&mutex) == 0); + + END_MUTEX_STALLED_ROBUST(mxAttr) + + return 0; +} + diff --git a/w32-pthreads/tests/mutex8n.c b/w32-pthreads/tests/mutex8n.c new file mode 100644 index 000000000..0c6d97d7f --- /dev/null +++ b/w32-pthreads/tests/mutex8n.c @@ -0,0 +1,103 @@ +/* + * mutex8n.c + * + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright (C) 1998 Ben Elliston and Ross Johnson + * Copyright (C) 1999,2000,2001 Ross Johnson + * + * Contact Email: rpj@ise.canberra.edu.au + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * -------------------------------------------------------------------------- + * + * Tests PTHREAD_MUTEX_NORMAL mutex type exercising timedlock. + * Thread locks mutex, another thread timedlocks the mutex. + * Timed thread should timeout. + * + * Depends on API functions: + * pthread_create() + * pthread_mutexattr_init() + * pthread_mutexattr_destroy() + * pthread_mutexattr_settype() + * pthread_mutexattr_gettype() + * pthread_mutex_init() + * pthread_mutex_destroy() + * pthread_mutex_lock() + * pthread_mutex_timedlock() + * pthread_mutex_unlock() + */ + +#include "test.h" +#include + +static int lockCount; + +static pthread_mutex_t mutex; +static pthread_mutexattr_t mxAttr; + +void * locker(void * arg) +{ + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 1; + + assert(pthread_mutex_timedlock(&mutex, &abstime) == ETIMEDOUT); + + lockCount++; + + return 0; +} + +int +main() +{ + pthread_t t; + int mxType = -1; + + assert(pthread_mutexattr_init(&mxAttr) == 0); + + BEGIN_MUTEX_STALLED_ROBUST(mxAttr) + + lockCount = 0; + assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_NORMAL) == 0); + assert(pthread_mutexattr_gettype(&mxAttr, &mxType) == 0); + assert(mxType == PTHREAD_MUTEX_NORMAL); + + assert(pthread_mutex_init(&mutex, &mxAttr) == 0); + + assert(pthread_mutex_lock(&mutex) == 0); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + Sleep(2000); + + assert(lockCount == 1); + + assert(pthread_mutex_unlock(&mutex) == 0); + + END_MUTEX_STALLED_ROBUST(mxAttr) + + return 0; +} + diff --git a/w32-pthreads/tests/mutex8r.c b/w32-pthreads/tests/mutex8r.c new file mode 100644 index 000000000..434b9af8e --- /dev/null +++ b/w32-pthreads/tests/mutex8r.c @@ -0,0 +1,103 @@ +/* + * mutex8r.c + * + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright (C) 1998 Ben Elliston and Ross Johnson + * Copyright (C) 1999,2000,2001 Ross Johnson + * + * Contact Email: rpj@ise.canberra.edu.au + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * -------------------------------------------------------------------------- + * + * Tests PTHREAD_MUTEX_RECURSIVE mutex type exercising timedlock. + * Thread locks mutex, another thread timedlocks the mutex. + * Timed thread should timeout. + * + * Depends on API functions: + * pthread_create() + * pthread_mutexattr_init() + * pthread_mutexattr_destroy() + * pthread_mutexattr_settype() + * pthread_mutexattr_gettype() + * pthread_mutex_init() + * pthread_mutex_destroy() + * pthread_mutex_lock() + * pthread_mutex_timedlock() + * pthread_mutex_unlock() + */ + +#include "test.h" +#include + +static int lockCount; + +static pthread_mutex_t mutex; +static pthread_mutexattr_t mxAttr; + +void * locker(void * arg) +{ + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 1; + + assert(pthread_mutex_timedlock(&mutex, &abstime) == ETIMEDOUT); + + lockCount++; + + return 0; +} + +int +main() +{ + pthread_t t; + int mxType = -1; + + assert(pthread_mutexattr_init(&mxAttr) == 0); + + BEGIN_MUTEX_STALLED_ROBUST(mxAttr) + + lockCount = 0; + assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_RECURSIVE) == 0); + assert(pthread_mutexattr_gettype(&mxAttr, &mxType) == 0); + assert(mxType == PTHREAD_MUTEX_RECURSIVE); + + assert(pthread_mutex_init(&mutex, &mxAttr) == 0); + + assert(pthread_mutex_lock(&mutex) == 0); + + assert(pthread_create(&t, NULL, locker, NULL) == 0); + + Sleep(2000); + + assert(lockCount == 1); + + assert(pthread_mutex_unlock(&mutex) == 0); + + END_MUTEX_STALLED_ROBUST(mxAttr) + + return 0; +} + diff --git a/w32-pthreads/tests/once1.c b/w32-pthreads/tests/once1.c new file mode 100644 index 000000000..daec112d7 --- /dev/null +++ b/w32-pthreads/tests/once1.c @@ -0,0 +1,77 @@ +/* + * once1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Create a static pthread_once and test that it calls myfunc once. + * + * Depends on API functions: + * pthread_once() + * pthread_create() + */ + +#include "test.h" + +pthread_once_t once = PTHREAD_ONCE_INIT; + +static int washere = 0; + +void +myfunc(void) +{ + washere++; +} + +void * +mythread(void * arg) +{ + assert(pthread_once(&once, myfunc) == 0); + + return 0; +} + +int +main() +{ + pthread_t t1, t2; + + assert(pthread_create(&t1, NULL, mythread, NULL) == 0); + + assert(pthread_create(&t2, NULL, mythread, NULL) == 0); + + Sleep(2000); + + assert(washere == 1); + + return 0; +} diff --git a/w32-pthreads/tests/once2.c b/w32-pthreads/tests/once2.c new file mode 100644 index 000000000..25aff6242 --- /dev/null +++ b/w32-pthreads/tests/once2.c @@ -0,0 +1,113 @@ +/* + * once2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Create several static pthread_once objects and channel several threads + * through each. + * + * Depends on API functions: + * pthread_once() + * pthread_create() + */ + +#include "test.h" + +#define NUM_THREADS 100 /* Targeting each once control */ +#define NUM_ONCE 10 + +pthread_once_t o = PTHREAD_ONCE_INIT; +pthread_once_t once[NUM_ONCE]; + +typedef struct { + int i; + CRITICAL_SECTION cs; +} sharedInt_t; + +static sharedInt_t numOnce = {0, {0}}; +static sharedInt_t numThreads = {0, {0}}; + +void +myfunc(void) +{ + EnterCriticalSection(&numOnce.cs); + numOnce.i++; + LeaveCriticalSection(&numOnce.cs); + /* Simulate slow once routine so that following threads pile up behind it */ + Sleep(100); +} + +void * +mythread(void * arg) +{ + assert(pthread_once(&once[(int)(size_t)arg], myfunc) == 0); + EnterCriticalSection(&numThreads.cs); + numThreads.i++; + LeaveCriticalSection(&numThreads.cs); + return (void*)(size_t)0; +} + +int +main() +{ + pthread_t t[NUM_THREADS][NUM_ONCE]; + int i, j; + + InitializeCriticalSection(&numThreads.cs); + InitializeCriticalSection(&numOnce.cs); + + for (j = 0; j < NUM_ONCE; j++) + { + once[j] = o; + + for (i = 0; i < NUM_THREADS; i++) + { + /* GCC build: create was failing with EAGAIN after 790 threads */ + while (0 != pthread_create(&t[i][j], NULL, mythread, (void *)(size_t)j)) + sched_yield(); + } + } + + for (j = 0; j < NUM_ONCE; j++) + for (i = 0; i < NUM_THREADS; i++) + if (pthread_join(t[i][j], NULL) != 0) + printf("Join failed for [thread,once] = [%d,%d]\n", i, j); + + assert(numOnce.i == NUM_ONCE); + assert(numThreads.i == NUM_THREADS * NUM_ONCE); + + DeleteCriticalSection(&numOnce.cs); + DeleteCriticalSection(&numThreads.cs); + + return 0; +} diff --git a/w32-pthreads/tests/once3.c b/w32-pthreads/tests/once3.c new file mode 100644 index 000000000..5211ffef5 --- /dev/null +++ b/w32-pthreads/tests/once3.c @@ -0,0 +1,134 @@ +/* + * once3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Create several pthread_once objects and channel several threads + * through each. Make the init_routine cancelable and cancel them with + * waiters waiting. + * + * Depends on API functions: + * pthread_once() + * pthread_create() + * pthread_testcancel() + * pthread_cancel() + * pthread_once() + */ + +/* #define ASSERT_TRACE */ + +#include "test.h" + +#define NUM_THREADS 100 /* Targeting each once control */ +#define NUM_ONCE 10 + +static pthread_once_t o = PTHREAD_ONCE_INIT; +static pthread_once_t once[NUM_ONCE]; + +typedef struct { + int i; + CRITICAL_SECTION cs; +} sharedInt_t; + +static sharedInt_t numOnce = {0, {0}}; +static sharedInt_t numThreads = {0, {0}}; + +void +myfunc(void) +{ + EnterCriticalSection(&numOnce.cs); + numOnce.i++; + assert(numOnce.i > 0); + LeaveCriticalSection(&numOnce.cs); + /* Simulate slow once routine so that following threads pile up behind it */ + Sleep(10); + /* test for cancelation late so we're sure to have waiters. */ + pthread_testcancel(); +} + +void * +mythread(void * arg) +{ + /* + * Cancel every thread. These threads are deferred cancelable only, so + * only the thread performing the once routine (my_func) will see it (there are + * no other cancelation points here). The result will be that every thread + * eventually cancels only when it becomes the new 'once' thread. + */ + assert(pthread_cancel(pthread_self()) == 0); + assert(pthread_once(&once[(int)(size_t)arg], myfunc) == 0); + EnterCriticalSection(&numThreads.cs); + numThreads.i++; + LeaveCriticalSection(&numThreads.cs); + return (void*)(size_t)0; +} + +int +main() +{ + pthread_t t[NUM_THREADS][NUM_ONCE]; + int i, j; + + InitializeCriticalSection(&numThreads.cs); + InitializeCriticalSection(&numOnce.cs); + + for (j = 0; j < NUM_ONCE; j++) + { + once[j] = o; + + for (i = 0; i < NUM_THREADS; i++) + { + /* GCC build: create was failing with EAGAIN after 790 threads */ + while (0 != pthread_create(&t[i][j], NULL, mythread, (void *)(size_t)j)) + sched_yield(); + } + } + + for (j = 0; j < NUM_ONCE; j++) + for (i = 0; i < NUM_THREADS; i++) + if (pthread_join(t[i][j], NULL) != 0) + printf("Join failed for [thread,once] = [%d,%d]\n", i, j); + + /* + * All threads will cancel, none will return normally from + * pthread_once and so numThreads should never be incremented. However, + * numOnce should be incremented by every thread (NUM_THREADS*NUM_ONCE). + */ + assert(numOnce.i == NUM_ONCE * NUM_THREADS); + assert(numThreads.i == 0); + + DeleteCriticalSection(&numOnce.cs); + DeleteCriticalSection(&numThreads.cs); + + return 0; +} diff --git a/w32-pthreads/tests/once4.c b/w32-pthreads/tests/once4.c new file mode 100644 index 000000000..c8f861b79 --- /dev/null +++ b/w32-pthreads/tests/once4.c @@ -0,0 +1,193 @@ +/* + * once4.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Create several pthread_once objects and channel several threads + * through each. Make the init_routine cancelable and cancel them + * waiters waiting. Vary the priorities. + * + * Depends on API functions: + * pthread_once() + * pthread_create() + * pthread_testcancel() + * pthread_cancel() + * pthread_once() + */ + +#include "test.h" + +#define NUM_THREADS 100 /* Targeting each once control */ +#define NUM_ONCE 10 + +pthread_once_t o = PTHREAD_ONCE_INIT; +pthread_once_t once[NUM_ONCE]; + +typedef struct { + int i; + CRITICAL_SECTION cs; +} sharedInt_t; + +static sharedInt_t numOnce = {0, {0}}; +static sharedInt_t numThreads = {0, {0}}; + +typedef struct { + int threadnum; + int oncenum; + int myPrio; + HANDLE w32Thread; +} bag_t; + +static bag_t threadbag[NUM_THREADS][NUM_ONCE]; + +CRITICAL_SECTION print_lock; + +void +mycleanupfunc(void * arg) +{ + bag_t * bag = (bag_t *) arg; + EnterCriticalSection(&print_lock); + /* once thrd prio error */ + printf("%4d %4d %4d %4d\n", + bag->oncenum, + bag->threadnum, + bag->myPrio, + bag->myPrio - GetThreadPriority(bag->w32Thread)); + LeaveCriticalSection(&print_lock); +} + +void +myinitfunc(void) +{ + EnterCriticalSection(&numOnce.cs); + numOnce.i++; + LeaveCriticalSection(&numOnce.cs); + /* Simulate slow once routine so that following threads pile up behind it */ + Sleep(10); + /* test for cancelation late so we're sure to have waiters. */ + pthread_testcancel(); +} + +void * +mythread(void * arg) +{ + bag_t * bag = (bag_t *) arg; + struct sched_param param; + + /* + * Cancel every thread. These threads are deferred cancelable only, so + * only the thread performing the init_routine will see it (there are + * no other cancelation points here). The result will be that every thread + * eventually cancels only when it becomes the new initter. + */ + pthread_t self = pthread_self(); + bag->w32Thread = pthread_getw32threadhandle_np(self); + /* + * Set priority between -2 and 2 inclusive. + */ + bag->myPrio = (bag->threadnum % 5) - 2; + param.sched_priority = bag->myPrio; + pthread_setschedparam(self, SCHED_OTHER, ¶m); + + /* Trigger a cancellation at the next cancellation point in this thread */ + pthread_cancel(self); +#if 0 + pthread_cleanup_push(mycleanupfunc, arg); + assert(pthread_once(&once[bag->oncenum], myinitfunc) == 0); + pthread_cleanup_pop(1); +#else + assert(pthread_once(&once[bag->oncenum], myinitfunc) == 0); +#endif + EnterCriticalSection(&numThreads.cs); + numThreads.i++; + LeaveCriticalSection(&numThreads.cs); + return 0; +} + +int +main() +{ + pthread_t t[NUM_THREADS][NUM_ONCE]; + int i, j; + + InitializeCriticalSection(&print_lock); + InitializeCriticalSection(&numThreads.cs); + InitializeCriticalSection(&numOnce.cs); + +#if 0 + /* once thrd prio change */ + printf("once thrd prio error\n"); +#endif + + /* + * Set the priority class to realtime - otherwise normal + * Windows random priority boosting will obscure any problems. + */ + SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS); + /* Set main thread to lower prio than threads */ + SetThreadPriority(GetCurrentThread(), -2); + + for (j = 0; j < NUM_ONCE; j++) + { + once[j] = o; + + for (i = 0; i < NUM_THREADS; i++) + { + bag_t * bag = &threadbag[i][j]; + bag->threadnum = i; + bag->oncenum = j; + /* GCC build: create was failing with EAGAIN after 790 threads */ + while (0 != pthread_create(&t[i][j], NULL, mythread, (void *)bag)) + sched_yield(); + } + } + + for (j = 0; j < NUM_ONCE; j++) + for (i = 0; i < NUM_THREADS; i++) + if (pthread_join(t[i][j], NULL) != 0) + printf("Join failed for [thread,once] = [%d,%d]\n", i, j); + + /* + * All threads will cancel, none will return normally from + * pthread_once and so numThreads should never be incremented. However, + * numOnce should be incremented by every thread (NUM_THREADS*NUM_ONCE). + */ + assert(numOnce.i == NUM_ONCE * NUM_THREADS); + assert(numThreads.i == 0); + + DeleteCriticalSection(&numOnce.cs); + DeleteCriticalSection(&numThreads.cs); + DeleteCriticalSection(&print_lock); + + return 0; +} diff --git a/w32-pthreads/tests/openmp1.c b/w32-pthreads/tests/openmp1.c new file mode 100644 index 000000000..ee36e75c8 --- /dev/null +++ b/w32-pthreads/tests/openmp1.c @@ -0,0 +1,140 @@ +#include +#include +#ifdef _OPENMP +# include +#endif +#include + +enum { + Size = 10000 +}; + +const int ShouldSum = (Size-1)*Size/2; + +short Verbose = 1; + +short ThreadOK[3] = {0,0,0}; // Main, Thread1, Thread2 + +// Thread +void *_thread(void* Id) { + int i; + int x[Size]; + +#ifdef _OPENMP +# pragma omp parallel for +#endif + for ( i = 0; i < Size; i++ ) { +#ifdef _OPENMP + if (Verbose && i%1000==0) { + int tid = omp_get_thread_num(); +# pragma omp critical + printf("thread %d : tid %d handles %d\n",(int)Id,tid,i); + } +#endif + + x[i] = i; + } + + int Sum=0; + for ( i = 0; i < Size; i++ ) { + Sum += x[i]; + } + if (Verbose) { +#ifdef _OPENMP +# pragma omp critical +#endif + printf("Id %d : %s : %d(should be %d)\n",(int)Id, __FUNCTION__, Sum,ShouldSum); + } + if (Sum == ShouldSum) ThreadOK[(int)Id] = 1; + return NULL; +} + +// MainThread +void MainThread() { + int i; + +#ifdef _OPENMP +# pragma omp parallel for +#endif + for ( i = 0; i < 4; i++ ) { +#ifdef _OPENMP + int tid = omp_get_thread_num(); +# pragma omp critical + printf("Main : tid %d\n",tid); + _thread((void *)tid); +#endif + } + return; +} + +// Comment in/out for checking the effect of multiple threads. +#define SPAWN_THREADS + +// main +int main(int argc, char *argv[]) { + + if (argc>1) Verbose = 1; + +#ifdef _OPENMP + omp_set_nested(-1); + printf("%s%s%s\n", "Nested parallel blocks are ", omp_get_nested()?" ":"NOT ", "supported."); +#endif + + MainThread(); + +#ifdef SPAWN_THREADS + { + pthread_t a_thr; + pthread_t b_thr; + int status; + + printf("%s:%d - %s - a_thr:%p - b_thr:%p\n", + __FILE__,__LINE__,__FUNCTION__,a_thr.p,b_thr.p); + + status = pthread_create(&a_thr, NULL, _thread, (void*) 1 ); + if ( status != 0 ) { + printf("Failed to create thread 1\n"); + return (-1); + } + + status = pthread_create(&b_thr, NULL, _thread, (void*) 2 ); + if ( status != 0 ) { + printf("Failed to create thread 2\n"); + return (-1); + } + + status = pthread_join(a_thr, NULL); + if ( status != 0 ) { + printf("Failed to join thread 1\n"); + return (-1); + } + printf("Joined thread1\n"); + + status = pthread_join(b_thr, NULL); + if ( status != 0 ) { + printf("Failed to join thread 2\n"); + return (-1); + } + printf("Joined thread2\n"); + } +#endif // SPAWN_THREADS + + short OK = 0; + // Check that we have OpenMP before declaring things OK formally. +#ifdef _OPENMP + OK = 1; + { + short i; + for (i=0;i<3;i++) OK &= ThreadOK[i]; + } + if (OK) printf("OMP : All looks good\n"); + else printf("OMP : Error\n"); +#else + printf("OpenMP seems not enabled ...\n"); +#endif + + return OK?0:1; +} + +//g++ -fopenmp omp_test.c -o omp_test -lpthread + diff --git a/w32-pthreads/tests/priority1.c b/w32-pthreads/tests/priority1.c new file mode 100644 index 000000000..40316cc64 --- /dev/null +++ b/w32-pthreads/tests/priority1.c @@ -0,0 +1,172 @@ +/* + * File: priority1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test thread priority explicit setting using thread attribute. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +enum { + PTW32TEST_THREAD_INIT_PRIO = 0, + PTW32TEST_MAXPRIORITIES = 512 +}; + +int minPrio; +int maxPrio; +int validPriorities[PTW32TEST_MAXPRIORITIES]; + +void * +func(void * arg) +{ + int policy; + struct sched_param param; + pthread_t threadID = pthread_self(); + + assert(pthread_getschedparam(threadID, &policy, ¶m) == 0); + assert(policy == SCHED_OTHER); + return (void *) (size_t)(param.sched_priority); +} + +void * +getValidPriorities(void * arg) +{ + int prioSet; + pthread_t threadID = pthread_self(); + HANDLE threadH = pthread_getw32threadhandle_np(threadID); + + printf("Using GetThreadPriority\n"); + printf("%10s %10s\n", "Set value", "Get value"); + + for (prioSet = minPrio; + prioSet <= maxPrio; + prioSet++) + { + /* + * If prioSet is invalid then the threads priority is unchanged + * from the previous value. Make the previous value a known + * one so that we can check later. + */ + if (prioSet < 0) + SetThreadPriority(threadH, THREAD_PRIORITY_LOWEST); + else + SetThreadPriority(threadH, THREAD_PRIORITY_HIGHEST); + SetThreadPriority(threadH, prioSet); + validPriorities[prioSet+(PTW32TEST_MAXPRIORITIES/2)] = GetThreadPriority(threadH); + printf("%10d %10d\n", prioSet, validPriorities[prioSet+(PTW32TEST_MAXPRIORITIES/2)]); + } + + return (void *) 0; +} + + +int +main() +{ + pthread_t t; + pthread_attr_t attr; + void * result = NULL; + struct sched_param param; + + assert((maxPrio = sched_get_priority_max(SCHED_OTHER)) != -1); + assert((minPrio = sched_get_priority_min(SCHED_OTHER)) != -1); + + assert(pthread_create(&t, NULL, getValidPriorities, NULL) == 0); + assert(pthread_join(t, &result) == 0); + + assert(pthread_attr_init(&attr) == 0); + assert(pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED) == 0); + + /* Set the thread's priority to a known initial value. */ + SetThreadPriority(pthread_getw32threadhandle_np(pthread_self()), + PTW32TEST_THREAD_INIT_PRIO); + + printf("Using pthread_getschedparam\n"); + printf("%10s %10s %10s\n", "Set value", "Get value", "Win priority"); + + for (param.sched_priority = minPrio; + param.sched_priority <= maxPrio; + param.sched_priority++) + { + int prio; + + assert(pthread_attr_setschedparam(&attr, ¶m) == 0); + assert(pthread_create(&t, &attr, func, (void *) &attr) == 0); + + assert((prio = GetThreadPriority(pthread_getw32threadhandle_np(t))) + == validPriorities[param.sched_priority+(PTW32TEST_MAXPRIORITIES/2)]); + + assert(pthread_join(t, &result) == 0); + + assert(param.sched_priority == (int)(size_t) result); + printf("%10d %10d %10d\n", param.sched_priority, (int)(size_t) result, prio); + } + + return 0; +} diff --git a/w32-pthreads/tests/priority2.c b/w32-pthreads/tests/priority2.c new file mode 100644 index 000000000..7d4648f90 --- /dev/null +++ b/w32-pthreads/tests/priority2.c @@ -0,0 +1,169 @@ +/* + * File: priority2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test thread priority setting after creation. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +enum { + PTW32TEST_THREAD_INIT_PRIO = 0, + PTW32TEST_MAXPRIORITIES = 512 +}; + +int minPrio; +int maxPrio; +int validPriorities[PTW32TEST_MAXPRIORITIES]; +pthread_barrier_t startBarrier, endBarrier; + +void * func(void * arg) +{ + int policy; + int result; + struct sched_param param; + + result = pthread_barrier_wait(&startBarrier); + assert(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD); + assert(pthread_getschedparam(pthread_self(), &policy, ¶m) == 0); + assert(policy == SCHED_OTHER); + result = pthread_barrier_wait(&endBarrier); + assert(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD); + return (void *) (size_t)param.sched_priority; +} + + +void * +getValidPriorities(void * arg) +{ + int prioSet; + pthread_t thread = pthread_self(); + HANDLE threadH = pthread_getw32threadhandle_np(thread); + struct sched_param param; + + for (prioSet = minPrio; + prioSet <= maxPrio; + prioSet++) + { + /* + * If prioSet is invalid then the threads priority is unchanged + * from the previous value. Make the previous value a known + * one so that we can check later. + */ + param.sched_priority = prioSet; + assert(pthread_setschedparam(thread, SCHED_OTHER, ¶m) == 0); + validPriorities[prioSet+(PTW32TEST_MAXPRIORITIES/2)] = GetThreadPriority(threadH); + } + + return (void *) 0; +} + + +int +main() +{ + pthread_t t; + void * result = NULL; + int result2; + struct sched_param param; + + assert((maxPrio = sched_get_priority_max(SCHED_OTHER)) != -1); + assert((minPrio = sched_get_priority_min(SCHED_OTHER)) != -1); + + assert(pthread_create(&t, NULL, getValidPriorities, NULL) == 0); + assert(pthread_join(t, &result) == 0); + + assert(pthread_barrier_init(&startBarrier, NULL, 2) == 0); + assert(pthread_barrier_init(&endBarrier, NULL, 2) == 0); + + /* Set the thread's priority to a known initial value. + * If the new priority is invalid then the threads priority + * is unchanged from the previous value. + */ + SetThreadPriority(pthread_getw32threadhandle_np(pthread_self()), + PTW32TEST_THREAD_INIT_PRIO); + + for (param.sched_priority = minPrio; + param.sched_priority <= maxPrio; + param.sched_priority++) + { + assert(pthread_create(&t, NULL, func, NULL) == 0); + assert(pthread_setschedparam(t, SCHED_OTHER, ¶m) == 0); + result2 = pthread_barrier_wait(&startBarrier); + assert(result2 == 0 || result2 == PTHREAD_BARRIER_SERIAL_THREAD); + result2 = pthread_barrier_wait(&endBarrier); + assert(result2 == 0 || result2 == PTHREAD_BARRIER_SERIAL_THREAD); + assert(GetThreadPriority(pthread_getw32threadhandle_np(t)) == + validPriorities[param.sched_priority+(PTW32TEST_MAXPRIORITIES/2)]); + pthread_join(t, &result); + assert(param.sched_priority == (int)(size_t)result); + } + + return 0; +} diff --git a/w32-pthreads/tests/reuse1.c b/w32-pthreads/tests/reuse1.c new file mode 100644 index 000000000..1a7dff0e0 --- /dev/null +++ b/w32-pthreads/tests/reuse1.c @@ -0,0 +1,124 @@ +/* + * File: reuse1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Confirm that thread reuse works for joined threads. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +enum { + NUMTHREADS = 100 +}; + +static int washere = 0; + +void * func(void * arg) +{ + washere = 1; + return arg; +} + +int +main() +{ + pthread_t t, + last_t; + pthread_attr_t attr; + void * result = NULL; + int i; + + assert(pthread_attr_init(&attr) == 0);; + assert(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) == 0); + + washere = 0; + assert(pthread_create(&t, &attr, func, NULL) == 0); + assert(pthread_join(t, &result) == 0);; + assert((int)(size_t)result == 0); + assert(washere == 1); + last_t = t; + + for (i = 1; i < NUMTHREADS; i++) + { + washere = 0; + assert(pthread_create(&t, &attr, func, (void *)(size_t)i) == 0); + pthread_join(t, &result); + assert((int)(size_t) result == i); + assert(washere == 1); + /* thread IDs should be unique */ + assert(!pthread_equal(t, last_t)); + /* thread struct pointers should be the same */ + assert(t.p == last_t.p); + /* thread handle reuse counter should be different by one */ + assert(t.x == last_t.x+1); + last_t = t; + } + + return 0; +} diff --git a/w32-pthreads/tests/reuse2.c b/w32-pthreads/tests/reuse2.c new file mode 100644 index 000000000..362e547d9 --- /dev/null +++ b/w32-pthreads/tests/reuse2.c @@ -0,0 +1,168 @@ +/* + * File: reuse2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test that thread reuse works for detached threads. + * - Analyse thread struct reuse. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - This test is implementation specific + * because it uses knowledge of internals that should be + * opaque to an application. + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +/* + */ + +enum { + NUMTHREADS = 10000 +}; + + +static long done = 0; + +void * func(void * arg) +{ + sched_yield(); + + InterlockedIncrement(&done); + + return (void *) 0; +} + +int +main() +{ + pthread_t t[NUMTHREADS]; + pthread_attr_t attr; + int i; + unsigned int notUnique = 0, + totalHandles = 0, + reuseMax = 0, + reuseMin = NUMTHREADS; + + assert(pthread_attr_init(&attr) == 0); + assert(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) == 0); + + for (i = 0; i < NUMTHREADS; i++) + { + while(pthread_create(&t[i], &attr, func, NULL) != 0) + Sleep(1); + } + + while (NUMTHREADS > InterlockedExchangeAdd((LPLONG)&done, 0L)) + Sleep(100); + + Sleep(100); + + /* + * Analyse reuse by computing min and max number of times pthread_create() + * returned the same pthread_t value. + */ + for (i = 0; i < NUMTHREADS; i++) + { + if (t[i].p != NULL) + { + unsigned int j, thisMax; + + thisMax = t[i].x; + + for (j = i+1; j < NUMTHREADS; j++) + if (t[i].p == t[j].p) + { + if (t[i].x == t[j].x) + notUnique++; + if (thisMax < t[j].x) + thisMax = t[j].x; + t[j].p = NULL; + } + + if (reuseMin > thisMax) + reuseMin = thisMax; + + if (reuseMax < thisMax) + reuseMax = thisMax; + } + } + + for (i = 0; i < NUMTHREADS; i++) + if (t[i].p != NULL) + totalHandles++; + + /* + * pthread_t reuse counts start at 0, so we need to add 1 + * to the max and min values derived above. + */ + printf("For %d total threads:\n", NUMTHREADS); + printf("Non-unique IDs = %d\n", notUnique); + printf("Reuse maximum = %d\n", reuseMax + 1); + printf("Reuse minimum = %d\n", reuseMin + 1); + printf("Total handles = %d\n", totalHandles); + + return 0; +} diff --git a/w32-pthreads/tests/robust1.c b/w32-pthreads/tests/robust1.c new file mode 100644 index 000000000..100a8545b --- /dev/null +++ b/w32-pthreads/tests/robust1.c @@ -0,0 +1,141 @@ +/* + * robust1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * For all robust mutex types. + * Thread A locks mutex + * Thread A terminates with no threads waiting on robust mutex + * Thread B acquires (inherits) mutex and unlocks + * Main attempts to lock mutex with unrecovered state. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_mutex_init() + * pthread_mutex_lock() + * pthread_mutex_unlock() + * pthread_mutex_destroy() + * pthread_mutexattr_init() + * pthread_mutexattr_setrobust() + * pthread_mutexattr_settype() + * pthread_mutexattr_destroy() + */ + +#include "test.h" + +static int lockCount; + +static pthread_mutex_t mutex; + +void * owner(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + + return 0; +} + +void * inheritor(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == EOWNERDEAD); + lockCount++; + assert(pthread_mutex_unlock(&mutex) == 0); + + return 0; +} + +int +main() +{ + pthread_t to, ti; + pthread_mutexattr_t ma; + + assert(pthread_mutexattr_init(&ma) == 0); + assert(pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST) == 0); + + /* Default (NORMAL) type */ + lockCount = 0; + assert(pthread_mutex_init(&mutex, &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_create(&ti, NULL, inheritor, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 2); + assert(pthread_mutex_lock(&mutex) == ENOTRECOVERABLE); + assert(pthread_mutex_unlock(&mutex) == EPERM); + assert(pthread_mutex_destroy(&mutex) == 0); + + /* NORMAL type */ + lockCount = 0; + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_NORMAL) == 0); + assert(pthread_mutex_init(&mutex, &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_create(&ti, NULL, inheritor, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 2); + assert(pthread_mutex_lock(&mutex) == ENOTRECOVERABLE); + assert(pthread_mutex_unlock(&mutex) == EPERM); + assert(pthread_mutex_destroy(&mutex) == 0); + + /* ERRORCHECK type */ + lockCount = 0; + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_ERRORCHECK) == 0); + assert(pthread_mutex_init(&mutex, &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_create(&ti, NULL, inheritor, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 2); + assert(pthread_mutex_lock(&mutex) == ENOTRECOVERABLE); + assert(pthread_mutex_unlock(&mutex) == EPERM); + assert(pthread_mutex_destroy(&mutex) == 0); + + /* RECURSIVE type */ + lockCount = 0; + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE) == 0); + assert(pthread_mutex_init(&mutex, &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_create(&ti, NULL, inheritor, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 2); + assert(pthread_mutex_lock(&mutex) == ENOTRECOVERABLE); + assert(pthread_mutex_unlock(&mutex) == EPERM); + assert(pthread_mutex_destroy(&mutex) == 0); + + assert(pthread_mutexattr_destroy(&ma) == 0); + + return 0; +} diff --git a/w32-pthreads/tests/robust2.c b/w32-pthreads/tests/robust2.c new file mode 100644 index 000000000..2b3917a6e --- /dev/null +++ b/w32-pthreads/tests/robust2.c @@ -0,0 +1,143 @@ +/* + * robust2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * For all robust mutex types. + * Thread A locks mutex + * Thread B blocks on mutex + * Thread A terminates with threads waiting on robust mutex + * Thread B awakes and inherits mutex and unlocks + * Main attempts to lock mutex with unrecovered state. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_mutex_init() + * pthread_mutex_lock() + * pthread_mutex_unlock() + * pthread_mutex_destroy() + * pthread_mutexattr_init() + * pthread_mutexattr_setrobust() + * pthread_mutexattr_settype() + * pthread_mutexattr_destroy() + */ + +#include "test.h" + +static int lockCount; + +static pthread_mutex_t mutex; + +void * owner(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + Sleep(200); + + return 0; +} + +void * inheritor(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == EOWNERDEAD); + lockCount++; + assert(pthread_mutex_unlock(&mutex) == 0); + + return 0; +} + +int +main() +{ + pthread_t to, ti; + pthread_mutexattr_t ma; + + assert(pthread_mutexattr_init(&ma) == 0); + assert(pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST) == 0); + + /* Default (NORMAL) type */ + lockCount = 0; + assert(pthread_mutex_init(&mutex, &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + Sleep(100); + assert(pthread_create(&ti, NULL, inheritor, NULL) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 2); + assert(pthread_mutex_lock(&mutex) == ENOTRECOVERABLE); + assert(pthread_mutex_destroy(&mutex) == 0); + + /* NORMAL type */ + lockCount = 0; + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_NORMAL) == 0); + assert(pthread_mutex_init(&mutex, &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + Sleep(100); + assert(pthread_create(&ti, NULL, inheritor, NULL) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 2); + assert(pthread_mutex_lock(&mutex) == ENOTRECOVERABLE); + assert(pthread_mutex_destroy(&mutex) == 0); + + /* ERRORCHECK type */ + lockCount = 0; + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_ERRORCHECK) == 0); + assert(pthread_mutex_init(&mutex, &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + Sleep(100); + assert(pthread_create(&ti, NULL, inheritor, NULL) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 2); + assert(pthread_mutex_lock(&mutex) == ENOTRECOVERABLE); + assert(pthread_mutex_destroy(&mutex) == 0); + + /* RECURSIVE type */ + lockCount = 0; + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE) == 0); + assert(pthread_mutex_init(&mutex, &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + Sleep(100); + assert(pthread_create(&ti, NULL, inheritor, NULL) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 2); + assert(pthread_mutex_lock(&mutex) == ENOTRECOVERABLE); + assert(pthread_mutex_destroy(&mutex) == 0); + + assert(pthread_mutexattr_destroy(&ma) == 0); + + return 0; +} diff --git a/w32-pthreads/tests/robust3.c b/w32-pthreads/tests/robust3.c new file mode 100644 index 000000000..cbf99df73 --- /dev/null +++ b/w32-pthreads/tests/robust3.c @@ -0,0 +1,149 @@ +/* + * robust3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * For all robust mutex types. + * Thread A locks mutex + * Thread B blocks on mutex + * Thread A terminates with threads waiting on robust mutex + * Thread B awakes and inherits mutex, sets consistent and unlocks + * Main acquires mutex with recovered state. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_mutex_init() + * pthread_mutex_lock() + * pthread_mutex_unlock() + * pthread_mutex_consistent() + * pthread_mutex_destroy() + * pthread_mutexattr_init() + * pthread_mutexattr_setrobust() + * pthread_mutexattr_settype() + * pthread_mutexattr_destroy() + */ + +#include "test.h" + +static int lockCount; + +static pthread_mutex_t mutex; + +void * owner(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == 0); + lockCount++; + Sleep(200); + + return 0; +} + +void * inheritor(void * arg) +{ + assert(pthread_mutex_lock(&mutex) == EOWNERDEAD); + lockCount++; + assert(pthread_mutex_consistent(&mutex) == 0); + assert(pthread_mutex_unlock(&mutex) == 0); + + return 0; +} + +int +main() +{ + pthread_t to, ti; + pthread_mutexattr_t ma; + + assert(pthread_mutexattr_init(&ma) == 0); + assert(pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST) == 0); + + /* Default (NORMAL) type */ + lockCount = 0; + assert(pthread_mutex_init(&mutex, &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + Sleep(100); + assert(pthread_create(&ti, NULL, inheritor, NULL) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 2); + assert(pthread_mutex_lock(&mutex) == 0); + assert(pthread_mutex_unlock(&mutex) == 0); + assert(pthread_mutex_destroy(&mutex) == 0); + + /* NORMAL type */ + lockCount = 0; + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_NORMAL) == 0); + assert(pthread_mutex_init(&mutex, &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + Sleep(100); + assert(pthread_create(&ti, NULL, inheritor, NULL) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 2); + assert(pthread_mutex_lock(&mutex) == 0); + assert(pthread_mutex_unlock(&mutex) == 0); + assert(pthread_mutex_destroy(&mutex) == 0); + + /* ERRORCHECK type */ + lockCount = 0; + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_ERRORCHECK) == 0); + assert(pthread_mutex_init(&mutex, &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + Sleep(100); + assert(pthread_create(&ti, NULL, inheritor, NULL) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 2); + assert(pthread_mutex_lock(&mutex) == 0); + assert(pthread_mutex_unlock(&mutex) == 0); + assert(pthread_mutex_destroy(&mutex) == 0); + + /* RECURSIVE type */ + lockCount = 0; + assert(pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE) == 0); + assert(pthread_mutex_init(&mutex, &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + Sleep(100); + assert(pthread_create(&ti, NULL, inheritor, NULL) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 2); + assert(pthread_mutex_lock(&mutex) == 0); + assert(pthread_mutex_unlock(&mutex) == 0); + assert(pthread_mutex_destroy(&mutex) == 0); + + assert(pthread_mutexattr_destroy(&ma) == 0); + + return 0; +} diff --git a/w32-pthreads/tests/robust4.c b/w32-pthreads/tests/robust4.c new file mode 100644 index 000000000..136a183bd --- /dev/null +++ b/w32-pthreads/tests/robust4.c @@ -0,0 +1,199 @@ +/* + * robust4.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Thread A locks multiple robust mutexes + * Thread B blocks on same mutexes in different orderings + * Thread A terminates with thread waiting on mutexes + * Thread B awakes and inherits each mutex in turn, sets consistent and unlocks + * Main acquires mutexes with recovered state. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_mutex_init() + * pthread_mutex_lock() + * pthread_mutex_unlock() + * pthread_mutex_destroy() + * pthread_mutexattr_init() + * pthread_mutexattr_setrobust() + * pthread_mutexattr_settype() + * pthread_mutexattr_destroy() + */ + +#include "test.h" + +static int lockCount; + +static pthread_mutex_t mutex[3]; + +void * owner(void * arg) +{ + assert(pthread_mutex_lock(&mutex[0]) == 0); + lockCount++; + assert(pthread_mutex_lock(&mutex[1]) == 0); + lockCount++; + assert(pthread_mutex_lock(&mutex[2]) == 0); + lockCount++; + Sleep(200); + + return 0; +} + +void * inheritor(void * arg) +{ + int* o = (int*)arg; + + assert(pthread_mutex_lock(&mutex[o[0]]) == EOWNERDEAD); + lockCount++; + assert(pthread_mutex_lock(&mutex[o[1]]) == EOWNERDEAD); + lockCount++; + assert(pthread_mutex_lock(&mutex[o[2]]) == EOWNERDEAD); + lockCount++; + assert(pthread_mutex_consistent(&mutex[o[2]]) == 0); + assert(pthread_mutex_consistent(&mutex[o[1]]) == 0); + assert(pthread_mutex_consistent(&mutex[o[0]]) == 0); + assert(pthread_mutex_unlock(&mutex[o[2]]) == 0); + assert(pthread_mutex_unlock(&mutex[o[1]]) == 0); + assert(pthread_mutex_unlock(&mutex[o[0]]) == 0); + + return 0; +} + +int +main() +{ + pthread_t to, ti; + pthread_mutexattr_t ma; + int order[3]; + + assert(pthread_mutexattr_init(&ma) == 0); + assert(pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST) == 0); + + order[0]=0; + order[1]=1; + order[2]=2; + lockCount = 0; + assert(pthread_mutex_init(&mutex[0], &ma) == 0); + assert(pthread_mutex_init(&mutex[1], &ma) == 0); + assert(pthread_mutex_init(&mutex[2], &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + Sleep(100); + assert(pthread_create(&ti, NULL, inheritor, (void *)order) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 6); + assert(pthread_mutex_lock(&mutex[0]) == 0); + assert(pthread_mutex_unlock(&mutex[0]) == 0); + assert(pthread_mutex_destroy(&mutex[0]) == 0); + assert(pthread_mutex_lock(&mutex[1]) == 0); + assert(pthread_mutex_unlock(&mutex[1]) == 0); + assert(pthread_mutex_destroy(&mutex[1]) == 0); + assert(pthread_mutex_lock(&mutex[2]) == 0); + assert(pthread_mutex_unlock(&mutex[2]) == 0); + assert(pthread_mutex_destroy(&mutex[2]) == 0); + + order[0]=1; + order[1]=0; + order[2]=2; + lockCount = 0; + assert(pthread_mutex_init(&mutex[0], &ma) == 0); + assert(pthread_mutex_init(&mutex[1], &ma) == 0); + assert(pthread_mutex_init(&mutex[2], &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + Sleep(100); + assert(pthread_create(&ti, NULL, inheritor, (void *)order) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 6); + assert(pthread_mutex_lock(&mutex[0]) == 0); + assert(pthread_mutex_unlock(&mutex[0]) == 0); + assert(pthread_mutex_destroy(&mutex[0]) == 0); + assert(pthread_mutex_lock(&mutex[1]) == 0); + assert(pthread_mutex_unlock(&mutex[1]) == 0); + assert(pthread_mutex_destroy(&mutex[1]) == 0); + assert(pthread_mutex_lock(&mutex[2]) == 0); + assert(pthread_mutex_unlock(&mutex[2]) == 0); + assert(pthread_mutex_destroy(&mutex[2]) == 0); + + order[0]=0; + order[1]=2; + order[2]=1; + lockCount = 0; + assert(pthread_mutex_init(&mutex[0], &ma) == 0); + assert(pthread_mutex_init(&mutex[1], &ma) == 0); + assert(pthread_mutex_init(&mutex[2], &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + Sleep(100); + assert(pthread_create(&ti, NULL, inheritor, (void *)order) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 6); + assert(pthread_mutex_lock(&mutex[0]) == 0); + assert(pthread_mutex_unlock(&mutex[0]) == 0); + assert(pthread_mutex_destroy(&mutex[0]) == 0); + assert(pthread_mutex_lock(&mutex[1]) == 0); + assert(pthread_mutex_unlock(&mutex[1]) == 0); + assert(pthread_mutex_destroy(&mutex[1]) == 0); + assert(pthread_mutex_lock(&mutex[2]) == 0); + assert(pthread_mutex_unlock(&mutex[2]) == 0); + assert(pthread_mutex_destroy(&mutex[2]) == 0); + + order[0]=2; + order[1]=1; + order[2]=0; + lockCount = 0; + assert(pthread_mutex_init(&mutex[0], &ma) == 0); + assert(pthread_mutex_init(&mutex[1], &ma) == 0); + assert(pthread_mutex_init(&mutex[2], &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + Sleep(100); + assert(pthread_create(&ti, NULL, inheritor, (void *)order) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 6); + assert(pthread_mutex_lock(&mutex[0]) == 0); + assert(pthread_mutex_unlock(&mutex[0]) == 0); + assert(pthread_mutex_destroy(&mutex[0]) == 0); + assert(pthread_mutex_lock(&mutex[1]) == 0); + assert(pthread_mutex_unlock(&mutex[1]) == 0); + assert(pthread_mutex_destroy(&mutex[1]) == 0); + assert(pthread_mutex_lock(&mutex[2]) == 0); + assert(pthread_mutex_unlock(&mutex[2]) == 0); + assert(pthread_mutex_destroy(&mutex[2]) == 0); + + assert(pthread_mutexattr_destroy(&ma) == 0); + + return 0; +} diff --git a/w32-pthreads/tests/robust5.c b/w32-pthreads/tests/robust5.c new file mode 100644 index 000000000..c67d12482 --- /dev/null +++ b/w32-pthreads/tests/robust5.c @@ -0,0 +1,120 @@ +/* + * robust5.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Thread A locks multiple robust mutexes + * Thread B blocks on same mutexes + * Thread A terminates with thread waiting on mutexes + * Thread B awakes and inherits each mutex in turn + * Thread B terminates leaving orphaned mutexes + * Main inherits mutexes, sets consistent and unlocks. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_mutex_init() + * pthread_mutex_lock() + * pthread_mutex_unlock() + * pthread_mutex_destroy() + * pthread_mutexattr_init() + * pthread_mutexattr_setrobust() + * pthread_mutexattr_settype() + * pthread_mutexattr_destroy() + */ + +#include "test.h" + +static int lockCount; + +static pthread_mutex_t mutex[3]; + +void * owner(void * arg) +{ + assert(pthread_mutex_lock(&mutex[0]) == 0); + lockCount++; + assert(pthread_mutex_lock(&mutex[1]) == 0); + lockCount++; + assert(pthread_mutex_lock(&mutex[2]) == 0); + lockCount++; + + return 0; +} + +void * inheritor(void * arg) +{ + assert(pthread_mutex_lock(&mutex[0]) == EOWNERDEAD); + lockCount++; + assert(pthread_mutex_lock(&mutex[1]) == EOWNERDEAD); + lockCount++; + assert(pthread_mutex_lock(&mutex[2]) == EOWNERDEAD); + lockCount++; + + return 0; +} + +int +main() +{ + pthread_t to, ti; + pthread_mutexattr_t ma; + + assert(pthread_mutexattr_init(&ma) == 0); + assert(pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST) == 0); + + lockCount = 0; + assert(pthread_mutex_init(&mutex[0], &ma) == 0); + assert(pthread_mutex_init(&mutex[1], &ma) == 0); + assert(pthread_mutex_init(&mutex[2], &ma) == 0); + assert(pthread_create(&to, NULL, owner, NULL) == 0); + assert(pthread_join(to, NULL) == 0); + assert(pthread_create(&ti, NULL, inheritor, NULL) == 0); + assert(pthread_join(ti, NULL) == 0); + assert(lockCount == 6); + assert(pthread_mutex_lock(&mutex[0]) == EOWNERDEAD); + assert(pthread_mutex_consistent(&mutex[0]) == 0); + assert(pthread_mutex_unlock(&mutex[0]) == 0); + assert(pthread_mutex_destroy(&mutex[0]) == 0); + assert(pthread_mutex_lock(&mutex[1]) == EOWNERDEAD); + assert(pthread_mutex_consistent(&mutex[1]) == 0); + assert(pthread_mutex_unlock(&mutex[1]) == 0); + assert(pthread_mutex_destroy(&mutex[1]) == 0); + assert(pthread_mutex_lock(&mutex[2]) == EOWNERDEAD); + assert(pthread_mutex_consistent(&mutex[2]) == 0); + assert(pthread_mutex_unlock(&mutex[2]) == 0); + assert(pthread_mutex_destroy(&mutex[2]) == 0); + + assert(pthread_mutexattr_destroy(&ma) == 0); + + return 0; +} diff --git a/w32-pthreads/tests/rwlock1.c b/w32-pthreads/tests/rwlock1.c new file mode 100644 index 000000000..3d08ac993 --- /dev/null +++ b/w32-pthreads/tests/rwlock1.c @@ -0,0 +1,61 @@ +/* + * rwlock1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Create a simple rwlock object and then destroy it. + * + * Depends on API functions: + * pthread_rwlock_init() + * pthread_rwlock_destroy() + */ + +#include "test.h" + +pthread_rwlock_t rwlock = NULL; + +int +main() +{ + assert(rwlock == NULL); + + assert(pthread_rwlock_init(&rwlock, NULL) == 0); + + assert(rwlock != NULL); + + assert(pthread_rwlock_destroy(&rwlock) == 0); + + assert(rwlock == NULL); + + return 0; +} diff --git a/w32-pthreads/tests/rwlock2.c b/w32-pthreads/tests/rwlock2.c new file mode 100644 index 000000000..07518ebde --- /dev/null +++ b/w32-pthreads/tests/rwlock2.c @@ -0,0 +1,66 @@ +/* + * rwlock2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static rwlock object, lock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_rwlock_rdlock() + * pthread_rwlock_unlock() + */ + +#include "test.h" + +pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; + +int +main() +{ + assert(rwlock == PTHREAD_RWLOCK_INITIALIZER); + + assert(pthread_rwlock_rdlock(&rwlock) == 0); + + assert(rwlock != PTHREAD_RWLOCK_INITIALIZER); + + assert(rwlock != NULL); + + assert(pthread_rwlock_unlock(&rwlock) == 0); + + assert(pthread_rwlock_destroy(&rwlock) == 0); + + assert(rwlock == NULL); + + return 0; +} diff --git a/w32-pthreads/tests/rwlock2_t.c b/w32-pthreads/tests/rwlock2_t.c new file mode 100644 index 000000000..4267ddbc8 --- /dev/null +++ b/w32-pthreads/tests/rwlock2_t.c @@ -0,0 +1,78 @@ +/* + * rwlock2_t.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static rwlock object, timed-lock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_rwlock_timedrdlock() + * pthread_rwlock_unlock() + */ + +#include "test.h" +#include + +pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; + +int +main() +{ + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 1; + + assert(rwlock == PTHREAD_RWLOCK_INITIALIZER); + + assert(pthread_rwlock_timedrdlock(&rwlock, &abstime) == 0); + + assert(rwlock != PTHREAD_RWLOCK_INITIALIZER); + + assert(rwlock != NULL); + + assert(pthread_rwlock_unlock(&rwlock) == 0); + + assert(pthread_rwlock_destroy(&rwlock) == 0); + + assert(rwlock == NULL); + + return 0; +} diff --git a/w32-pthreads/tests/rwlock3.c b/w32-pthreads/tests/rwlock3.c new file mode 100644 index 000000000..d30f04088 --- /dev/null +++ b/w32-pthreads/tests/rwlock3.c @@ -0,0 +1,78 @@ +/* + * rwlock3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static rwlock object, wrlock it, trywrlock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_rwlock_wrlock() + * pthread_rwlock_trywrlock() + * pthread_rwlock_unlock() + */ + +#include "test.h" + +pthread_rwlock_t rwlock1 = PTHREAD_RWLOCK_INITIALIZER; + +static int washere = 0; + +void * func(void * arg) +{ + assert(pthread_rwlock_trywrlock(&rwlock1) == EBUSY); + + washere = 1; + + return 0; +} + +int +main() +{ + pthread_t t; + + assert(pthread_rwlock_wrlock(&rwlock1) == 0); + + assert(pthread_create(&t, NULL, func, NULL) == 0); + + assert(pthread_join(t, NULL) == 0); + + assert(pthread_rwlock_unlock(&rwlock1) == 0); + + assert(washere == 1); + + return 0; +} diff --git a/w32-pthreads/tests/rwlock3_t.c b/w32-pthreads/tests/rwlock3_t.c new file mode 100644 index 000000000..6419de13e --- /dev/null +++ b/w32-pthreads/tests/rwlock3_t.c @@ -0,0 +1,87 @@ +/* + * rwlock3_t.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static rwlock object, timed-wrlock it, trywrlock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_rwlock_timedwrlock() + * pthread_rwlock_trywrlock() + * pthread_rwlock_unlock() + */ + +#include "test.h" +#include + +pthread_rwlock_t rwlock1 = PTHREAD_RWLOCK_INITIALIZER; + +static int washere = 0; + +void * func(void * arg) +{ + assert(pthread_rwlock_trywrlock(&rwlock1) == EBUSY); + + washere = 1; + + return 0; +} + +int +main() +{ + pthread_t t; + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 1; + + assert(pthread_rwlock_timedwrlock(&rwlock1, &abstime) == 0); + + assert(pthread_create(&t, NULL, func, NULL) == 0); + + Sleep(2000); + + assert(pthread_rwlock_unlock(&rwlock1) == 0); + + assert(washere == 1); + + return 0; +} diff --git a/w32-pthreads/tests/rwlock4.c b/w32-pthreads/tests/rwlock4.c new file mode 100644 index 000000000..a19a00132 --- /dev/null +++ b/w32-pthreads/tests/rwlock4.c @@ -0,0 +1,78 @@ +/* + * rwlock4.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static rwlock object, rdlock it, trywrlock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_rwlock_rdlock() + * pthread_rwlock_trywrlock() + * pthread_rwlock_unlock() + */ + +#include "test.h" + +pthread_rwlock_t rwlock1 = PTHREAD_RWLOCK_INITIALIZER; + +static int washere = 0; + +void * func(void * arg) +{ + assert(pthread_rwlock_trywrlock(&rwlock1) == EBUSY); + + washere = 1; + + return 0; +} + +int +main() +{ + pthread_t t; + + assert(pthread_rwlock_rdlock(&rwlock1) == 0); + + assert(pthread_create(&t, NULL, func, NULL) == 0); + + assert(pthread_join(t, NULL) == 0); + + assert(pthread_rwlock_unlock(&rwlock1) == 0); + + assert(washere == 1); + + return 0; +} diff --git a/w32-pthreads/tests/rwlock4_t.c b/w32-pthreads/tests/rwlock4_t.c new file mode 100644 index 000000000..58b3602fb --- /dev/null +++ b/w32-pthreads/tests/rwlock4_t.c @@ -0,0 +1,87 @@ +/* + * rwlock4_t.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static rwlock object, timed-rdlock it, trywrlock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_rwlock_timedrdlock() + * pthread_rwlock_trywrlock() + * pthread_rwlock_unlock() + */ + +#include "test.h" +#include + +pthread_rwlock_t rwlock1 = PTHREAD_RWLOCK_INITIALIZER; + +static int washere = 0; + +void * func(void * arg) +{ + assert(pthread_rwlock_trywrlock(&rwlock1) == EBUSY); + + washere = 1; + + return 0; +} + +int +main() +{ + pthread_t t; + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 1; + + assert(pthread_rwlock_timedrdlock(&rwlock1, &abstime) == 0); + + assert(pthread_create(&t, NULL, func, NULL) == 0); + + Sleep(2000); + + assert(pthread_rwlock_unlock(&rwlock1) == 0); + + assert(washere == 1); + + return 0; +} diff --git a/w32-pthreads/tests/rwlock5.c b/w32-pthreads/tests/rwlock5.c new file mode 100644 index 000000000..3b4054756 --- /dev/null +++ b/w32-pthreads/tests/rwlock5.c @@ -0,0 +1,80 @@ +/* + * rwlock5.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static rwlock object, rdlock it, tryrdlock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_create() + * pthread_join() + * pthread_rwlock_rdlock() + * pthread_rwlock_tryrdlock() + * pthread_rwlock_unlock() + */ + +#include "test.h" + +pthread_rwlock_t rwlock1 = PTHREAD_RWLOCK_INITIALIZER; + +static int washere = 0; + +void * func(void * arg) +{ + assert(pthread_rwlock_tryrdlock(&rwlock1) == 0); + + assert(pthread_rwlock_unlock(&rwlock1) == 0); + + washere = 1; + + return 0; +} + +int +main() +{ + pthread_t t; + + assert(pthread_rwlock_rdlock(&rwlock1) == 0); + + assert(pthread_create(&t, NULL, func, NULL) == 0); + + assert(pthread_join(t, NULL) == 0); + + assert(pthread_rwlock_unlock(&rwlock1) == 0); + + assert(washere == 1); + + return 0; +} diff --git a/w32-pthreads/tests/rwlock5_t.c b/w32-pthreads/tests/rwlock5_t.c new file mode 100644 index 000000000..4a94658fb --- /dev/null +++ b/w32-pthreads/tests/rwlock5_t.c @@ -0,0 +1,89 @@ +/* + * rwlock5_t.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static rwlock object, timed-rdlock it, tryrdlock it, + * and then unlock it again. + * + * Depends on API functions: + * pthread_rwlock_timedrdlock() + * pthread_rwlock_tryrdlock() + * pthread_rwlock_unlock() + */ + +#include "test.h" +#include + +pthread_rwlock_t rwlock1 = PTHREAD_RWLOCK_INITIALIZER; + +static int washere = 0; + +void * func(void * arg) +{ + assert(pthread_rwlock_tryrdlock(&rwlock1) == 0); + + assert(pthread_rwlock_unlock(&rwlock1) == 0); + + washere = 1; + + return 0; +} + +int +main() +{ + pthread_t t; + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 1; + + assert(pthread_rwlock_timedrdlock(&rwlock1, &abstime) == 0); + + assert(pthread_create(&t, NULL, func, NULL) == 0); + + Sleep(2000); + + assert(pthread_rwlock_unlock(&rwlock1) == 0); + + assert(washere == 1); + + return 0; +} diff --git a/w32-pthreads/tests/rwlock6.c b/w32-pthreads/tests/rwlock6.c new file mode 100644 index 000000000..f667ce5ce --- /dev/null +++ b/w32-pthreads/tests/rwlock6.c @@ -0,0 +1,101 @@ +/* + * rwlock6.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Check writer and reader locking + * + * Depends on API functions: + * pthread_rwlock_rdlock() + * pthread_rwlock_wrlock() + * pthread_rwlock_unlock() + */ + +#include "test.h" + +static pthread_rwlock_t rwlock1 = PTHREAD_RWLOCK_INITIALIZER; + +static int bankAccount = 0; + +void * wrfunc(void * arg) +{ + int ba; + + assert(pthread_rwlock_wrlock(&rwlock1) == 0); + Sleep(200); + bankAccount += 10; + ba = bankAccount; + assert(pthread_rwlock_unlock(&rwlock1) == 0); + + return ((void *)(size_t)ba); +} + +void * rdfunc(void * arg) +{ + int ba; + + assert(pthread_rwlock_rdlock(&rwlock1) == 0); + ba = bankAccount; + assert(pthread_rwlock_unlock(&rwlock1) == 0); + + return ((void *)(size_t)ba); +} + +int +main() +{ + pthread_t wrt1; + pthread_t wrt2; + pthread_t rdt; + void* wr1Result = (void*)0; + void* wr2Result = (void*)0; + void* rdResult = (void*)0; + + bankAccount = 0; + + assert(pthread_create(&wrt1, NULL, wrfunc, NULL) == 0); + Sleep(50); + assert(pthread_create(&rdt, NULL, rdfunc, NULL) == 0); + Sleep(50); + assert(pthread_create(&wrt2, NULL, wrfunc, NULL) == 0); + + assert(pthread_join(wrt1, &wr1Result) == 0); + assert(pthread_join(rdt, &rdResult) == 0); + assert(pthread_join(wrt2, &wr2Result) == 0); + + assert((int)(size_t)wr1Result == 10); + assert((int)(size_t)rdResult == 10); + assert((int)(size_t)wr2Result == 20); + + return 0; +} diff --git a/w32-pthreads/tests/rwlock6_t.c b/w32-pthreads/tests/rwlock6_t.c new file mode 100644 index 000000000..71cbe220a --- /dev/null +++ b/w32-pthreads/tests/rwlock6_t.c @@ -0,0 +1,126 @@ +/* + * rwlock6_t.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Check writer and reader locking with reader timeouts + * + * Depends on API functions: + * pthread_rwlock_timedrdlock() + * pthread_rwlock_wrlock() + * pthread_rwlock_unlock() + */ + +#include "test.h" +#include + +static pthread_rwlock_t rwlock1 = PTHREAD_RWLOCK_INITIALIZER; + +static int bankAccount = 0; + +void * wrfunc(void * arg) +{ + assert(pthread_rwlock_wrlock(&rwlock1) == 0); + Sleep(2000); + bankAccount += 10; + assert(pthread_rwlock_unlock(&rwlock1) == 0); + + return ((void *)(size_t)bankAccount); +} + +void * rdfunc(void * arg) +{ + int ba = -1; + struct timespec abstime = { 0, 0 }; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + + if ((int) (size_t)arg == 1) + { + abstime.tv_sec += 1; + assert(pthread_rwlock_timedrdlock(&rwlock1, &abstime) == ETIMEDOUT); + ba = 0; + } + else if ((int) (size_t)arg == 2) + { + abstime.tv_sec += 3; + assert(pthread_rwlock_timedrdlock(&rwlock1, &abstime) == 0); + ba = bankAccount; + assert(pthread_rwlock_unlock(&rwlock1) == 0); + } + + return ((void *)(size_t)ba); +} + +int +main() +{ + pthread_t wrt1; + pthread_t wrt2; + pthread_t rdt1; + pthread_t rdt2; + void* wr1Result = (void*)0; + void* wr2Result = (void*)0; + void* rd1Result = (void*)0; + void* rd2Result = (void*)0; + + bankAccount = 0; + + assert(pthread_create(&wrt1, NULL, wrfunc, NULL) == 0); + Sleep(500); + assert(pthread_create(&rdt1, NULL, rdfunc, (void *)(size_t)1) == 0); + Sleep(500); + assert(pthread_create(&wrt2, NULL, wrfunc, NULL) == 0); + Sleep(500); + assert(pthread_create(&rdt2, NULL, rdfunc, (void *)(size_t)2) == 0); + + assert(pthread_join(wrt1, &wr1Result) == 0); + assert(pthread_join(rdt1, &rd1Result) == 0); + assert(pthread_join(wrt2, &wr2Result) == 0); + assert(pthread_join(rdt2, &rd2Result) == 0); + + assert((int)(size_t)wr1Result == 10); + assert((int)(size_t)rd1Result == 0); + assert((int)(size_t)wr2Result == 20); + assert((int)(size_t)rd2Result == 20); + + return 0; +} + + diff --git a/w32-pthreads/tests/rwlock6_t2.c b/w32-pthreads/tests/rwlock6_t2.c new file mode 100644 index 000000000..b8b0df9f2 --- /dev/null +++ b/w32-pthreads/tests/rwlock6_t2.c @@ -0,0 +1,119 @@ +/* + * rwlock6_t2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Check writer and reader timeouts. + * + * Depends on API functions: + * pthread_rwlock_timedrdlock() + * pthread_rwlock_timedwrlock() + * pthread_rwlock_unlock() + */ + +#include "test.h" +#include + +static pthread_rwlock_t rwlock1 = PTHREAD_RWLOCK_INITIALIZER; + +static int bankAccount = 0; +struct timespec abstime = { 0, 0 }; + +void * wrfunc(void * arg) +{ + int result; + + result = pthread_rwlock_timedwrlock(&rwlock1, &abstime); + if ((int) (size_t)arg == 1) + { + assert(result == 0); + Sleep(2000); + bankAccount += 10; + assert(pthread_rwlock_unlock(&rwlock1) == 0); + return ((void *)(size_t)bankAccount); + } + else if ((int) (size_t)arg == 2) + { + assert(result == ETIMEDOUT); + return ((void *) 100); + } + + return ((void *)(size_t)-1); +} + +void * rdfunc(void * arg) +{ + int ba = 0; + + assert(pthread_rwlock_timedrdlock(&rwlock1, &abstime) == ETIMEDOUT); + + return ((void *)(size_t)ba); +} + +int +main() +{ + pthread_t wrt1; + pthread_t wrt2; + pthread_t rdt; + void* wr1Result = (void*)0; + void* wr2Result = (void*)0; + void* rdResult = (void*)0; + PTW32_STRUCT_TIMEB currSysTime; + const DWORD NANOSEC_PER_MILLISEC = 1000000; + + PTW32_FTIME(&currSysTime); + + abstime.tv_sec = (long)currSysTime.time; + abstime.tv_nsec = NANOSEC_PER_MILLISEC * currSysTime.millitm; + + abstime.tv_sec += 1; + + bankAccount = 0; + + assert(pthread_create(&wrt1, NULL, wrfunc, (void *)(size_t)1) == 0); + Sleep(100); + assert(pthread_create(&rdt, NULL, rdfunc, NULL) == 0); + Sleep(100); + assert(pthread_create(&wrt2, NULL, wrfunc, (void *)(size_t)2) == 0); + + assert(pthread_join(wrt1, &wr1Result) == 0); + assert(pthread_join(rdt, &rdResult) == 0); + assert(pthread_join(wrt2, &wr2Result) == 0); + + assert((int)(size_t)wr1Result == 10); + assert((int)(size_t)rdResult == 0); + assert((int)(size_t)wr2Result == 100); + + return 0; +} diff --git a/w32-pthreads/tests/rwlock7.c b/w32-pthreads/tests/rwlock7.c new file mode 100644 index 000000000..69d1a73fd --- /dev/null +++ b/w32-pthreads/tests/rwlock7.c @@ -0,0 +1,199 @@ +/* + * rwlock7.c + * + * Hammer on a bunch of rwlocks to test robustness and fairness. + * Printed stats should be roughly even for each thread. + */ + +#include "test.h" +#include + +#ifdef __GNUC__ +#include +#endif + +#define THREADS 5 +#define DATASIZE 7 +#define ITERATIONS 1000000 + +/* + * Keep statistics for each thread. + */ +typedef struct thread_tag { + int thread_num; + pthread_t thread_id; + int updates; + int reads; + int changed; + int seed; +} thread_t; + +/* + * Read-write lock and shared data + */ +typedef struct data_tag { + pthread_rwlock_t lock; + int data; + int updates; +} data_t; + +static thread_t threads[THREADS]; +static data_t data[DATASIZE]; + +/* + * Thread start routine that uses read-write locks + */ +void *thread_routine (void *arg) +{ + thread_t *self = (thread_t*)arg; + int iteration; + int element = 0; + int seed = self->seed; + int interval = 1 + rand_r (&seed) % 71; + + self->changed = 0; + + for (iteration = 0; iteration < ITERATIONS; iteration++) + { + if (iteration % (ITERATIONS / 10) == 0) + { + putchar('.'); + fflush(stdout); + } + /* + * Each "self->interval" iterations, perform an + * update operation (write lock instead of read + * lock). + */ + if ((iteration % interval) == 0) + { + assert(pthread_rwlock_wrlock (&data[element].lock) == 0); + data[element].data = self->thread_num; + data[element].updates++; + self->updates++; + interval = 1 + rand_r (&seed) % 71; + assert(pthread_rwlock_unlock (&data[element].lock) == 0); + } else { + /* + * Look at the current data element to see whether + * the current thread last updated it. Count the + * times, to report later. + */ + assert(pthread_rwlock_rdlock (&data[element].lock) == 0); + + self->reads++; + + if (data[element].data != self->thread_num) + { + self->changed++; + interval = 1 + self->changed % 71; + } + + assert(pthread_rwlock_unlock (&data[element].lock) == 0); + } + + element = (element + 1) % DATASIZE; + + } + + return NULL; +} + +int +main (int argc, char *argv[]) +{ + int count; + int data_count; + int thread_updates = 0; + int data_updates = 0; + int seed = 1; + + PTW32_STRUCT_TIMEB currSysTime1; + PTW32_STRUCT_TIMEB currSysTime2; + + /* + * Initialize the shared data. + */ + for (data_count = 0; data_count < DATASIZE; data_count++) + { + data[data_count].data = 0; + data[data_count].updates = 0; + + assert(pthread_rwlock_init (&data[data_count].lock, NULL) == 0); + } + + PTW32_FTIME(&currSysTime1); + + /* + * Create THREADS threads to access shared data. + */ + for (count = 0; count < THREADS; count++) + { + threads[count].thread_num = count; + threads[count].updates = 0; + threads[count].reads = 0; + threads[count].seed = 1 + rand_r (&seed) % 71; + + assert(pthread_create (&threads[count].thread_id, + NULL, thread_routine, (void*)(size_t)&threads[count]) == 0); + } + + /* + * Wait for all threads to complete, and collect + * statistics. + */ + for (count = 0; count < THREADS; count++) + { + assert(pthread_join (threads[count].thread_id, NULL) == 0); + } + + putchar('\n'); + fflush(stdout); + + for (count = 0; count < THREADS; count++) + { + if (threads[count].changed > 0) + { + printf ("Thread %d found changed elements %d times\n", + count, threads[count].changed); + } + } + + putchar('\n'); + fflush(stdout); + + for (count = 0; count < THREADS; count++) + { + thread_updates += threads[count].updates; + printf ("%02d: seed %d, updates %d, reads %d\n", + count, threads[count].seed, + threads[count].updates, threads[count].reads); + } + + putchar('\n'); + fflush(stdout); + + /* + * Collect statistics for the data. + */ + for (data_count = 0; data_count < DATASIZE; data_count++) + { + data_updates += data[data_count].updates; + printf ("data %02d: value %d, %d updates\n", + data_count, data[data_count].data, data[data_count].updates); + assert(pthread_rwlock_destroy (&data[data_count].lock) == 0); + } + + printf ("%d thread updates, %d data updates\n", + thread_updates, data_updates); + + PTW32_FTIME(&currSysTime2); + + printf( "\nstart: %ld/%d, stop: %ld/%d, duration:%ld\n", + (long)currSysTime1.time,currSysTime1.millitm, + (long)currSysTime2.time,currSysTime2.millitm, + ((long)((currSysTime2.time*1000+currSysTime2.millitm) - + (currSysTime1.time*1000+currSysTime1.millitm)))); + + return 0; +} diff --git a/w32-pthreads/tests/rwlock8.c b/w32-pthreads/tests/rwlock8.c new file mode 100644 index 000000000..99c357aab --- /dev/null +++ b/w32-pthreads/tests/rwlock8.c @@ -0,0 +1,205 @@ +/* + * rwlock8.c + * + * Hammer on a bunch of rwlocks to test robustness and fairness. + * Printed stats should be roughly even for each thread. + * + * Yield during each access to exercise lock contention code paths + * more than rwlock7.c does (particularly on uni-processor systems). + */ + +#include "test.h" +#include + +#ifdef __GNUC__ +#include +#endif + +#define THREADS 5 +#define DATASIZE 7 +#define ITERATIONS 100000 + +/* + * Keep statistics for each thread. + */ +typedef struct thread_tag { + int thread_num; + pthread_t thread_id; + int updates; + int reads; + int changed; + int seed; +} thread_t; + +/* + * Read-write lock and shared data + */ +typedef struct data_tag { + pthread_rwlock_t lock; + int data; + int updates; +} data_t; + +static thread_t threads[THREADS]; +static data_t data[DATASIZE]; + +/* + * Thread start routine that uses read-write locks + */ +void *thread_routine (void *arg) +{ + thread_t *self = (thread_t*)arg; + int iteration; + int element = 0; + int seed = self->seed; + int interval = 1 + rand_r (&seed) % 71; + + self->changed = 0; + + for (iteration = 0; iteration < ITERATIONS; iteration++) + { + if (iteration % (ITERATIONS / 10) == 0) + { + putchar('.'); + fflush(stdout); + } + /* + * Each "self->interval" iterations, perform an + * update operation (write lock instead of read + * lock). + */ + if ((iteration % interval) == 0) + { + assert(pthread_rwlock_wrlock (&data[element].lock) == 0); + data[element].data = self->thread_num; + data[element].updates++; + self->updates++; + interval = 1 + rand_r (&seed) % 71; + sched_yield(); + assert(pthread_rwlock_unlock (&data[element].lock) == 0); + } else { + /* + * Look at the current data element to see whether + * the current thread last updated it. Count the + * times, to report later. + */ + assert(pthread_rwlock_rdlock (&data[element].lock) == 0); + + self->reads++; + + if (data[element].data != self->thread_num) + { + self->changed++; + interval = 1 + self->changed % 71; + } + + sched_yield(); + + assert(pthread_rwlock_unlock (&data[element].lock) == 0); + } + + element = (element + 1) % DATASIZE; + + } + + return NULL; +} + +int +main (int argc, char *argv[]) +{ + int count; + int data_count; + int thread_updates = 0; + int data_updates = 0; + int seed = 1; + + PTW32_STRUCT_TIMEB currSysTime1; + PTW32_STRUCT_TIMEB currSysTime2; + + /* + * Initialize the shared data. + */ + for (data_count = 0; data_count < DATASIZE; data_count++) + { + data[data_count].data = 0; + data[data_count].updates = 0; + + assert(pthread_rwlock_init (&data[data_count].lock, NULL) == 0); + } + + PTW32_FTIME(&currSysTime1); + + /* + * Create THREADS threads to access shared data. + */ + for (count = 0; count < THREADS; count++) + { + threads[count].thread_num = count; + threads[count].updates = 0; + threads[count].reads = 0; + threads[count].seed = 1 + rand_r (&seed) % 71; + + assert(pthread_create (&threads[count].thread_id, + NULL, thread_routine, (void*)(size_t)&threads[count]) == 0); + } + + /* + * Wait for all threads to complete, and collect + * statistics. + */ + for (count = 0; count < THREADS; count++) + { + assert(pthread_join (threads[count].thread_id, NULL) == 0); + } + + putchar('\n'); + fflush(stdout); + + for (count = 0; count < THREADS; count++) + { + if (threads[count].changed > 0) + { + printf ("Thread %d found changed elements %d times\n", + count, threads[count].changed); + } + } + + putchar('\n'); + fflush(stdout); + + for (count = 0; count < THREADS; count++) + { + thread_updates += threads[count].updates; + printf ("%02d: seed %d, updates %d, reads %d\n", + count, threads[count].seed, + threads[count].updates, threads[count].reads); + } + + putchar('\n'); + fflush(stdout); + + /* + * Collect statistics for the data. + */ + for (data_count = 0; data_count < DATASIZE; data_count++) + { + data_updates += data[data_count].updates; + printf ("data %02d: value %d, %d updates\n", + data_count, data[data_count].data, data[data_count].updates); + assert(pthread_rwlock_destroy (&data[data_count].lock) == 0); + } + + printf ("%d thread updates, %d data updates\n", + thread_updates, data_updates); + + PTW32_FTIME(&currSysTime2); + + printf( "\nstart: %ld/%d, stop: %ld/%d, duration:%ld\n", + (long)currSysTime1.time,currSysTime1.millitm, + (long)currSysTime2.time,currSysTime2.millitm, + ((long)((currSysTime2.time*1000+currSysTime2.millitm) - + (currSysTime1.time*1000+currSysTime1.millitm)))); + + return 0; +} diff --git a/w32-pthreads/tests/self1.c b/w32-pthreads/tests/self1.c new file mode 100644 index 000000000..aa08328f9 --- /dev/null +++ b/w32-pthreads/tests/self1.c @@ -0,0 +1,69 @@ +/* + * self1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test for pthread_self(). + * + * Depends on API functions: + * pthread_self() + * + * Implicitly depends on: + * pthread_getspecific() + * pthread_setspecific() + */ + +#include "test.h" + +int +main(int argc, char * argv[]) +{ + /* + * This should always succeed unless the system has no + * resources (memory) left. + */ + pthread_t self; + +#if defined(PTW32_STATIC_LIB) && !(defined(_MSC_VER) || defined(__MINGW32__)) + pthread_win32_process_attach_np(); +#endif + + self = pthread_self(); + + assert(self.p != NULL); + +#if defined(PTW32_STATIC_LIB) && !(defined(_MSC_VER) || defined(__MINGW32__)) + pthread_win32_process_detach_np(); +#endif + return 0; +} diff --git a/w32-pthreads/tests/self2.c b/w32-pthreads/tests/self2.c new file mode 100644 index 000000000..28e57252e --- /dev/null +++ b/w32-pthreads/tests/self2.c @@ -0,0 +1,73 @@ +/* + * self2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test for pthread_self(). + * + * Depends on API functions: + * pthread_create() + * pthread_self() + * + * Implicitly depends on: + * pthread_getspecific() + * pthread_setspecific() + */ + +#include "test.h" +#include + +static pthread_t me; + +void * +entry(void * arg) +{ + me = pthread_self(); + + return arg; +} + +int +main() +{ + pthread_t t; + + assert(pthread_create(&t, NULL, entry, NULL) == 0); + + Sleep(100); + + assert(pthread_equal(t, me) != 0); + + /* Success. */ + return 0; +} diff --git a/w32-pthreads/tests/semaphore1.c b/w32-pthreads/tests/semaphore1.c new file mode 100644 index 000000000..8fc91ee02 --- /dev/null +++ b/w32-pthreads/tests/semaphore1.c @@ -0,0 +1,150 @@ +/* + * File: semaphore1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Verify trywait() returns -1 and sets EAGAIN. + * - + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +void * +thr(void * arg) +{ + sem_t s; + int result; + + assert(sem_init(&s, PTHREAD_PROCESS_PRIVATE, 0) == 0); + + assert((result = sem_trywait(&s)) == -1); + + if ( result == -1 ) + { + int err = errno; + if (err != EAGAIN) + { + printf("thread: sem_trywait 1: expecting error %s: got %s\n", + error_string[EAGAIN], error_string[err]); fflush(stdout); + } + assert(err == EAGAIN); + } + else + { + printf("thread: ok 1\n"); + } + + assert((result = sem_post(&s)) == 0); + + assert((result = sem_trywait(&s)) == 0); + + assert(sem_post(&s) == 0); + + return NULL; +} + + +int +main() +{ + pthread_t t; + sem_t s; + void* result1 = (void*)-1; + int result2; + + assert(pthread_create(&t, NULL, thr, NULL) == 0); + assert(pthread_join(t, &result1) == 0); + assert((int)(size_t)result1 == 0); + + assert(sem_init(&s, PTHREAD_PROCESS_PRIVATE, 0) == 0); + + assert((result2 = sem_trywait(&s)) == -1); + + if (result2 == -1) + { + int err = errno; + if (err != EAGAIN) + { + printf("main: sem_trywait 1: expecting error %s: got %s\n", + error_string[EAGAIN], error_string[err]); fflush(stdout); + } + assert(err == EAGAIN); + } + else + { + printf("main: ok 1\n"); + } + + assert((result2 = sem_post(&s)) == 0); + + assert((result2 = sem_trywait(&s)) == 0); + + assert(sem_post(&s) == 0); + + return 0; +} + diff --git a/w32-pthreads/tests/semaphore2.c b/w32-pthreads/tests/semaphore2.c new file mode 100644 index 000000000..af4d0ea70 --- /dev/null +++ b/w32-pthreads/tests/semaphore2.c @@ -0,0 +1,108 @@ +/* + * File: semaphore2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Verify sem_getvalue returns the correct value. + * - + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +#define MAX_COUNT 100 + +int +main() +{ + sem_t s; + int value = 0; + int i; + + assert(sem_init(&s, PTHREAD_PROCESS_PRIVATE, MAX_COUNT) == 0); + assert(sem_getvalue(&s, &value) == 0); + assert(value == MAX_COUNT); +// printf("Value = %ld\n", value); + + for (i = MAX_COUNT - 1; i >= 0; i--) + { + assert(sem_wait(&s) == 0); + assert(sem_getvalue(&s, &value) == 0); +// printf("Value = %ld\n", value); + assert(value == i); + } + + for (i = 1; i <= MAX_COUNT; i++) + { + assert(sem_post(&s) == 0); + assert(sem_getvalue(&s, &value) == 0); +// printf("Value = %ld\n", value); + assert(value == i); + } + + return 0; +} + diff --git a/w32-pthreads/tests/semaphore3.c b/w32-pthreads/tests/semaphore3.c new file mode 100644 index 000000000..a0dfcb6f6 --- /dev/null +++ b/w32-pthreads/tests/semaphore3.c @@ -0,0 +1,121 @@ +/* + * File: semaphore3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Verify sem_getvalue returns the correct number of waiters. + * - + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +#define MAX_COUNT 100 + +sem_t s; + +void * +thr (void * arg) +{ + assert(sem_wait(&s) == 0); + assert(pthread_detach(pthread_self()) == 0); + return NULL; +} + +int +main() +{ + int value = 0; + int i; + pthread_t t[MAX_COUNT+1]; + + assert(sem_init(&s, PTHREAD_PROCESS_PRIVATE, 0) == 0); + assert(sem_getvalue(&s, &value) == 0); +// printf("Value = %d\n", value); fflush(stdout); + assert(value == 0); + + for (i = 1; i <= MAX_COUNT; i++) + { + assert(pthread_create(&t[i], NULL, thr, NULL) == 0); + do { + sched_yield(); + assert(sem_getvalue(&s, &value) == 0); + } while (value != -i); +// printf("Value = %d\n", value); fflush(stdout); + assert(-value == i); + } + + for (i = MAX_COUNT - 1; i >= 0; i--) + { + assert(sem_post(&s) == 0); + assert(sem_getvalue(&s, &value) == 0); +// printf("Value = %d\n", value); fflush(stdout); + assert(-value == i); + } + + return 0; +} + diff --git a/w32-pthreads/tests/semaphore4.c b/w32-pthreads/tests/semaphore4.c new file mode 100644 index 000000000..3a28c7b50 --- /dev/null +++ b/w32-pthreads/tests/semaphore4.c @@ -0,0 +1,132 @@ +/* + * File: semaphore4.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Verify sem_getvalue returns the correct number of waiters + * after threads are cancelled. + * - + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +#define MAX_COUNT 100 + +sem_t s; + +void * +thr (void * arg) +{ + assert(sem_wait(&s) == 0); + return NULL; +} + +int +main() +{ + int value = 0; + int i; + pthread_t t[MAX_COUNT+1]; + + assert(sem_init(&s, PTHREAD_PROCESS_PRIVATE, 0) == 0); + assert(sem_getvalue(&s, &value) == 0); + assert(value == 0); + + for (i = 1; i <= MAX_COUNT; i++) + { + assert(pthread_create(&t[i], NULL, thr, NULL) == 0); + do { + sched_yield(); + assert(sem_getvalue(&s, &value) == 0); + } while (value != -i); + assert(-value == i); + } + + assert(sem_getvalue(&s, &value) == 0); + assert(-value == MAX_COUNT); + assert(pthread_cancel(t[50]) == 0); + { + void* result; + assert(pthread_join(t[50], &result) == 0); + } + assert(sem_getvalue(&s, &value) == 0); + assert(-value == (MAX_COUNT - 1)); + + for (i = MAX_COUNT - 2; i >= 0; i--) + { + assert(sem_post(&s) == 0); + assert(sem_getvalue(&s, &value) == 0); + assert(-value == i); + } + + for (i = 1; i <= MAX_COUNT; i++) + if (i != 50) + assert(pthread_join(t[i], NULL) == 0); + + return 0; +} + diff --git a/w32-pthreads/tests/semaphore4t.c b/w32-pthreads/tests/semaphore4t.c new file mode 100644 index 000000000..97bc7f88a --- /dev/null +++ b/w32-pthreads/tests/semaphore4t.c @@ -0,0 +1,129 @@ +/* + * File: semaphore4t.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Verify sem_getvalue returns the correct number of waiters + * after threads are cancelled. + * - + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - sem_timedwait cancellation. + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +#define MAX_COUNT 100 + +sem_t s; + +void * +thr (void * arg) +{ + assert(sem_timedwait(&s, NULL) == 0); + return NULL; +} + +int +main() +{ + int value = 0; + int i; + pthread_t t[MAX_COUNT+1]; + + assert(sem_init(&s, PTHREAD_PROCESS_PRIVATE, 0) == 0); + assert(sem_getvalue(&s, &value) == 0); + assert(value == 0); + + for (i = 1; i <= MAX_COUNT; i++) + { + assert(pthread_create(&t[i], NULL, thr, NULL) == 0); + do { + sched_yield(); + assert(sem_getvalue(&s, &value) == 0); + } while (value != -i); + assert(-value == i); + } + + assert(sem_getvalue(&s, &value) == 0); + assert(-value == MAX_COUNT); + assert(pthread_cancel(t[50]) == 0); + assert(pthread_join(t[50], NULL) == 0); + assert(sem_getvalue(&s, &value) == 0); + assert(-value == MAX_COUNT - 1); + + for (i = MAX_COUNT - 2; i >= 0; i--) + { + assert(sem_post(&s) == 0); + assert(sem_getvalue(&s, &value) == 0); + assert(-value == i); + } + + for (i = 1; i <= MAX_COUNT; i++) + if (i != 50) + assert(pthread_join(t[i], NULL) == 0); + + return 0; +} + diff --git a/w32-pthreads/tests/semaphore5.c b/w32-pthreads/tests/semaphore5.c new file mode 100644 index 000000000..5f7e6925d --- /dev/null +++ b/w32-pthreads/tests/semaphore5.c @@ -0,0 +1,103 @@ +/* + * File: semaphore5.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Verify sem_destroy EBUSY race avoidance + * - + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +// #define ASSERT_TRACE + +#include "test.h" + +void * +thr(void * arg) +{ + assert(sem_post((sem_t *)arg) == 0); + + return 0; +} + + +int +main() +{ + pthread_t t; + sem_t s; + + assert(sem_init(&s, PTHREAD_PROCESS_PRIVATE, 0) == 0); + assert(pthread_create(&t, NULL, thr, (void *)&s) == 0); + + assert(sem_wait(&s) == 0); + assert(sem_destroy(&s) == 0); + + assert(pthread_join(t, NULL) == 0); + + return 0; +} + diff --git a/w32-pthreads/tests/sequence1.c b/w32-pthreads/tests/sequence1.c new file mode 100644 index 000000000..46388eebd --- /dev/null +++ b/w32-pthreads/tests/sequence1.c @@ -0,0 +1,142 @@ +/* + * File: sequence1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - that unique thread sequence numbers are generated. + * - Analyse thread struct reuse. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - This test is implementation specific + * because it uses knowledge of internals that should be + * opaque to an application. + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - analysis output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - unique sequence numbers are generated for every new thread. + * + * Fail Criteria: + * - + */ + +#include "test.h" + +/* + */ + +enum { + NUMTHREADS = 10000 +}; + + +static long done = 0; +/* + * seqmap should have 1 in every element except [0] + * Thread sequence numbers start at 1 and we will also + * include this main thread so we need NUMTHREADS+2 + * elements. + */ +static UINT64 seqmap[NUMTHREADS+2]; + +void * func(void * arg) +{ + sched_yield(); + seqmap[(int)pthread_getunique_np(pthread_self())] = 1; + InterlockedIncrement(&done); + + return (void *) 0; +} + +int +main() +{ + pthread_t t[NUMTHREADS]; + pthread_attr_t attr; + int i; + + assert(pthread_attr_init(&attr) == 0); + assert(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) == 0); + + for (i = 0; i < NUMTHREADS+2; i++) + { + seqmap[i] = 0; + } + + for (i = 0; i < NUMTHREADS; i++) + { + if (NUMTHREADS/2 == i) + { + /* Include this main thread, which will be an implicit pthread_t */ + seqmap[(int)pthread_getunique_np(pthread_self())] = 1; + } + assert(pthread_create(&t[i], &attr, func, NULL) == 0); + } + + while (NUMTHREADS > InterlockedExchangeAdd((LPLONG)&done, 0L)) + Sleep(100); + + Sleep(100); + + assert(seqmap[0] == 0); + for (i = 1; i < NUMTHREADS+2; i++) + { + assert(seqmap[i] == 1); + } + + return 0; +} diff --git a/w32-pthreads/tests/sizes.c b/w32-pthreads/tests/sizes.c new file mode 100644 index 000000000..554d0e843 --- /dev/null +++ b/w32-pthreads/tests/sizes.c @@ -0,0 +1,32 @@ +#define _WIN32_WINNT 0x400 + +#include "test.h" +#include "../implement.h" + +int +main() +{ + printf("Sizes of pthreads-win32 structs\n"); + printf("-------------------------------\n"); + printf("%30s %4d\n", "pthread_t", (int)sizeof(pthread_t)); + printf("%30s %4d\n", "ptw32_thread_t", (int)sizeof(ptw32_thread_t)); + printf("%30s %4d\n", "pthread_attr_t_", (int)sizeof(struct pthread_attr_t_)); + printf("%30s %4d\n", "sem_t_", (int)sizeof(struct sem_t_)); + printf("%30s %4d\n", "pthread_mutex_t_", (int)sizeof(struct pthread_mutex_t_)); + printf("%30s %4d\n", "pthread_mutexattr_t_", (int)sizeof(struct pthread_mutexattr_t_)); + printf("%30s %4d\n", "pthread_spinlock_t_", (int)sizeof(struct pthread_spinlock_t_)); + printf("%30s %4d\n", "pthread_barrier_t_", (int)sizeof(struct pthread_barrier_t_)); + printf("%30s %4d\n", "pthread_barrierattr_t_", (int)sizeof(struct pthread_barrierattr_t_)); + printf("%30s %4d\n", "pthread_key_t_", (int)sizeof(struct pthread_key_t_)); + printf("%30s %4d\n", "pthread_cond_t_", (int)sizeof(struct pthread_cond_t_)); + printf("%30s %4d\n", "pthread_condattr_t_", (int)sizeof(struct pthread_condattr_t_)); + printf("%30s %4d\n", "pthread_rwlock_t_", (int)sizeof(struct pthread_rwlock_t_)); + printf("%30s %4d\n", "pthread_rwlockattr_t_", (int)sizeof(struct pthread_rwlockattr_t_)); + printf("%30s %4d\n", "pthread_once_t_", (int)sizeof(struct pthread_once_t_)); + printf("%30s %4d\n", "ptw32_cleanup_t", (int)sizeof(struct ptw32_cleanup_t)); + printf("%30s %4d\n", "ptw32_mcs_node_t_", (int)sizeof(struct ptw32_mcs_node_t_)); + printf("%30s %4d\n", "sched_param", (int)sizeof(struct sched_param)); + printf("-------------------------------\n"); + + return 0; +} diff --git a/w32-pthreads/tests/spin1.c b/w32-pthreads/tests/spin1.c new file mode 100644 index 000000000..00ecd11b1 --- /dev/null +++ b/w32-pthreads/tests/spin1.c @@ -0,0 +1,59 @@ +/* + * spin1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Create a simple spinlock object, lock it, and then unlock it again. + * This is the simplest test of the pthread mutex family that we can do. + * + */ + +#include "test.h" + +pthread_spinlock_t lock; + +int +main() +{ + assert(pthread_spin_init(&lock, PTHREAD_PROCESS_PRIVATE) == 0); + + assert(pthread_spin_lock(&lock) == 0); + + assert(pthread_spin_unlock(&lock) == 0); + + assert(pthread_spin_destroy(&lock) == 0); + + assert(pthread_spin_lock(&lock) == EINVAL); + + return 0; +} diff --git a/w32-pthreads/tests/spin2.c b/w32-pthreads/tests/spin2.c new file mode 100644 index 000000000..b13c29c4e --- /dev/null +++ b/w32-pthreads/tests/spin2.c @@ -0,0 +1,75 @@ +/* + * spin2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a spinlock object, lock it, trylock it, + * and then unlock it again. + * + */ + +#include "test.h" + +pthread_spinlock_t lock = NULL; + +static int washere = 0; + +void * func(void * arg) +{ + assert(pthread_spin_trylock(&lock) == EBUSY); + + washere = 1; + + return 0; +} + +int +main() +{ + pthread_t t; + + assert(pthread_spin_init(&lock, PTHREAD_PROCESS_PRIVATE) == 0); + + assert(pthread_spin_lock(&lock) == 0); + + assert(pthread_create(&t, NULL, func, NULL) == 0); + assert(pthread_join(t, NULL) == 0); + + assert(pthread_spin_unlock(&lock) == 0); + + assert(pthread_spin_destroy(&lock) == 0); + + assert(washere == 1); + + return 0; +} diff --git a/w32-pthreads/tests/spin3.c b/w32-pthreads/tests/spin3.c new file mode 100644 index 000000000..bbf8bfb22 --- /dev/null +++ b/w32-pthreads/tests/spin3.c @@ -0,0 +1,76 @@ +/* + * spin3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Thread A locks spin - thread B tries to unlock. + * This should succeed, but it's undefined behaviour. + * + */ + +#include "test.h" + +static int wasHere = 0; + +static pthread_spinlock_t spin; + +void * unlocker(void * arg) +{ + int expectedResult = (int)(size_t)arg; + + wasHere++; + assert(pthread_spin_unlock(&spin) == expectedResult); + wasHere++; + return NULL; +} + +int +main() +{ + pthread_t t; + + wasHere = 0; + assert(pthread_spin_init(&spin, PTHREAD_PROCESS_PRIVATE) == 0); + assert(pthread_spin_lock(&spin) == 0); + assert(pthread_create(&t, NULL, unlocker, (void*)0) == 0); + assert(pthread_join(t, NULL) == 0); + /* + * Our spinlocks don't record the owner thread so any thread can unlock the spinlock, + * but nor is it an error for any thread to unlock a spinlock that is not locked. + */ + assert(pthread_spin_unlock(&spin) == 0); + assert(pthread_spin_destroy(&spin) == 0); + assert(wasHere == 2); + + return 0; +} diff --git a/w32-pthreads/tests/spin4.c b/w32-pthreads/tests/spin4.c new file mode 100644 index 000000000..3a4fd6f24 --- /dev/null +++ b/w32-pthreads/tests/spin4.c @@ -0,0 +1,103 @@ +/* + * spin4.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Declare a static spinlock object, lock it, spin on it, + * and then unlock it again. + */ + +#include "test.h" +#include + +pthread_spinlock_t lock = PTHREAD_SPINLOCK_INITIALIZER; +PTW32_STRUCT_TIMEB currSysTimeStart; +PTW32_STRUCT_TIMEB currSysTimeStop; + +#define GetDurationMilliSecs(_TStart, _TStop) ((_TStop.time*1000+_TStop.millitm) \ + - (_TStart.time*1000+_TStart.millitm)) + +static int washere = 0; + +void * func(void * arg) +{ + PTW32_FTIME(&currSysTimeStart); + washere = 1; + assert(pthread_spin_lock(&lock) == 0); + assert(pthread_spin_unlock(&lock) == 0); + PTW32_FTIME(&currSysTimeStop); + + return (void *)(size_t)GetDurationMilliSecs(currSysTimeStart, currSysTimeStop); +} + +int +main() +{ + void* result = (void*)0; + pthread_t t; + int CPUs; + PTW32_STRUCT_TIMEB sysTime; + + if ((CPUs = pthread_num_processors_np()) == 1) + { + printf("Test not run - it requires multiple CPUs.\n"); + exit(0); + } + + assert(pthread_spin_lock(&lock) == 0); + + assert(pthread_create(&t, NULL, func, NULL) == 0); + + while (washere == 0) + { + sched_yield(); + } + + do + { + sched_yield(); + PTW32_FTIME(&sysTime); + } + while (GetDurationMilliSecs(currSysTimeStart, sysTime) <= 1000); + + assert(pthread_spin_unlock(&lock) == 0); + + assert(pthread_join(t, &result) == 0); + assert((int)(size_t)result > 1000); + + assert(pthread_spin_destroy(&lock) == 0); + + assert(washere == 1); + + return 0; +} diff --git a/w32-pthreads/tests/stress1.c b/w32-pthreads/tests/stress1.c new file mode 100644 index 000000000..7c787dcfb --- /dev/null +++ b/w32-pthreads/tests/stress1.c @@ -0,0 +1,278 @@ +/* + * stress1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Stress test condition variables, mutexes, semaphores. + * + * Test Method (Validation or Falsification): + * - Validation + * + * Requirements Tested: + * - Correct accounting of semaphore and condition variable waiters. + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * Attempting to expose race conditions in cond vars, semaphores etc. + * - Master attempts to signal slave close to when timeout is due. + * - Master and slave do battle continuously until main tells them to stop. + * - Afterwards, the CV must be successfully destroyed (will return an + * error if there are waiters (including any internal semaphore waiters, + * which, if there are, cannot be real waiters). + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - CV is successfully destroyed. + * + * Fail Criteria: + * - CV destroy fails. + */ + +#include "test.h" +#include +#include + + +const unsigned int ITERATIONS = 1000; + +static pthread_t master, slave; +typedef struct { + int value; + pthread_cond_t cv; + pthread_mutex_t mx; +} mysig_t; + +static int allExit; +static mysig_t control = {0, PTHREAD_COND_INITIALIZER, PTHREAD_MUTEX_INITIALIZER}; +static pthread_barrier_t startBarrier, readyBarrier, holdBarrier; +static int timeoutCount = 0; +static int signalsTakenCount = 0; +static int signalsSent = 0; +static int bias = 0; +static int timeout = 10; // Must be > 0 + +enum { + CTL_STOP = -1 +}; + +/* + * Returns abstime 'milliseconds' from 'now'. + * + * Works for: -INT_MAX <= millisecs <= INT_MAX + */ +struct timespec * +millisecondsFromNow (struct timespec * time, int millisecs) +{ + PTW32_STRUCT_TIMEB currSysTime; + int64_t nanosecs, secs; + const int64_t NANOSEC_PER_MILLISEC = 1000000; + const int64_t NANOSEC_PER_SEC = 1000000000; + + /* get current system time and add millisecs */ + PTW32_FTIME(&currSysTime); + + secs = (int64_t)(currSysTime.time) + (millisecs / 1000); + nanosecs = ((int64_t) (millisecs%1000 + currSysTime.millitm)) * NANOSEC_PER_MILLISEC; + if (nanosecs >= NANOSEC_PER_SEC) + { + secs++; + nanosecs -= NANOSEC_PER_SEC; + } + else if (nanosecs < 0) + { + secs--; + nanosecs += NANOSEC_PER_SEC; + } + + time->tv_nsec = (long)nanosecs; + time->tv_sec = (long)secs; + + return time; +} + +void * +masterThread (void * arg) +{ + int dither = (int)(size_t)arg; + + timeout = (int)(size_t)arg; + + pthread_barrier_wait(&startBarrier); + + do + { + int sleepTime; + + assert(pthread_mutex_lock(&control.mx) == 0); + control.value = timeout; + assert(pthread_mutex_unlock(&control.mx) == 0); + + /* + * We are attempting to send the signal close to when the slave + * is due to timeout. We feel around by adding some [non-random] dither. + * + * dither is in the range 2*timeout peak-to-peak + * sleep time is the average of timeout plus dither. + * e.g. + * if timeout = 10 then dither = 20 and + * sleep millisecs is: 5 <= ms <= 15 + * + * The bias value attempts to apply some negative feedback to keep + * the ratio of timeouts to signals taken close to 1:1. + * bias changes more slowly than dither so as to average more. + * + * Finally, if abs(bias) exceeds timeout then timeout is incremented. + */ + if (signalsSent % timeout == 0) + { + if (timeoutCount > signalsTakenCount) + { + bias++; + } + else if (timeoutCount < signalsTakenCount) + { + bias--; + } + if (bias < -timeout || bias > timeout) + { + timeout++; + } + } + dither = (dither + 1 ) % (timeout * 2); + sleepTime = (timeout - bias + dither) / 2; + Sleep(sleepTime); + assert(pthread_cond_signal(&control.cv) == 0); + signalsSent++; + + pthread_barrier_wait(&holdBarrier); + pthread_barrier_wait(&readyBarrier); + } + while (!allExit); + + return NULL; +} + +void * +slaveThread (void * arg) +{ + struct timespec time; + + pthread_barrier_wait(&startBarrier); + + do + { + assert(pthread_mutex_lock(&control.mx) == 0); + if (pthread_cond_timedwait(&control.cv, + &control.mx, + millisecondsFromNow(&time, control.value)) == ETIMEDOUT) + { + timeoutCount++; + } + else + { + signalsTakenCount++; + } + assert(pthread_mutex_unlock(&control.mx) == 0); + + pthread_barrier_wait(&holdBarrier); + pthread_barrier_wait(&readyBarrier); + } + while (!allExit); + + return NULL; +} + +int +main () +{ + unsigned int i; + + assert(pthread_barrier_init(&startBarrier, NULL, 3) == 0); + assert(pthread_barrier_init(&readyBarrier, NULL, 3) == 0); + assert(pthread_barrier_init(&holdBarrier, NULL, 3) == 0); + + assert(pthread_create(&master, NULL, masterThread, (void *)(size_t)timeout) == 0); + assert(pthread_create(&slave, NULL, slaveThread, NULL) == 0); + + allExit = FALSE; + + pthread_barrier_wait(&startBarrier); + + for (i = 1; !allExit; i++) + { + pthread_barrier_wait(&holdBarrier); + if (i >= ITERATIONS) + { + allExit = TRUE; + } + pthread_barrier_wait(&readyBarrier); + } + + assert(pthread_join(slave, NULL) == 0); + assert(pthread_join(master, NULL) == 0); + + printf("Signals sent = %d\nWait timeouts = %d\nSignals taken = %d\nBias = %d\nTimeout = %d\n", + signalsSent, + timeoutCount, + signalsTakenCount, + (int) bias, + timeout); + + /* Cleanup */ + assert(pthread_barrier_destroy(&holdBarrier) == 0); + assert(pthread_barrier_destroy(&readyBarrier) == 0); + assert(pthread_barrier_destroy(&startBarrier) == 0); + assert(pthread_cond_destroy(&control.cv) == 0); + assert(pthread_mutex_destroy(&control.mx) == 0); + + /* Success. */ + return 0; +} diff --git a/w32-pthreads/tests/test.h b/w32-pthreads/tests/test.h new file mode 100644 index 000000000..042e87b68 --- /dev/null +++ b/w32-pthreads/tests/test.h @@ -0,0 +1,182 @@ +/* + * test.h + * + * Useful definitions and declarations for tests. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + */ + +#ifndef _PTHREAD_TEST_H_ +#define _PTHREAD_TEST_H_ + +#include "pthread.h" +#include "sched.h" +#include "semaphore.h" + +#include +#include + +#define PTW32_THREAD_NULL_ID {NULL,0} + +/* + * Some non-thread POSIX API substitutes + */ +#define rand_r( _seed ) \ + ( _seed == _seed? rand() : rand() ) + +#if defined(__MINGW32__) +#include +#elif defined(__BORLANDC__) +#define int64_t ULONGLONG +#else +#define int64_t _int64 +#endif + +#if defined(_MSC_VER) && _MSC_VER >= 1400 +# define PTW32_FTIME(x) _ftime64_s(x) +# define PTW32_STRUCT_TIMEB struct __timeb64 +#elif ( defined(_MSC_VER) && _MSC_VER >= 1300 ) || \ + ( defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x0601 ) +# define PTW32_FTIME(x) _ftime64(x) +# define PTW32_STRUCT_TIMEB struct __timeb64 +#else +# define PTW32_FTIME(x) _ftime(x) +# define PTW32_STRUCT_TIMEB struct _timeb +#endif + + +const char * error_string[] = { + "ZERO_or_EOK", + "EPERM", + "ENOFILE_or_ENOENT", + "ESRCH", + "EINTR", + "EIO", + "ENXIO", + "E2BIG", + "ENOEXEC", + "EBADF", + "ECHILD", + "EAGAIN", + "ENOMEM", + "EACCES", + "EFAULT", + "UNKNOWN_15", + "EBUSY", + "EEXIST", + "EXDEV", + "ENODEV", + "ENOTDIR", + "EISDIR", + "EINVAL", + "ENFILE", + "EMFILE", + "ENOTTY", + "UNKNOWN_26", + "EFBIG", + "ENOSPC", + "ESPIPE", + "EROFS", + "EMLINK", + "EPIPE", + "EDOM", + "ERANGE", + "UNKNOWN_35", + "EDEADLOCK_or_EDEADLK", + "UNKNOWN_37", + "ENAMETOOLONG", + "ENOLCK", + "ENOSYS", + "ENOTEMPTY", + "EILSEQ", + "EOWNERDEAD", + "ENOTRECOVERABLE" +}; + +/* + * The Mingw32 assert macro calls the CRTDLL _assert function + * which pops up a dialog. We want to run in batch mode so + * we define our own assert macro. + */ +#ifdef assert +# undef assert +#endif + +#ifndef ASSERT_TRACE +# define ASSERT_TRACE 0 +#else +# undef ASSERT_TRACE +# define ASSERT_TRACE 1 +#endif + +# define assert(e) \ + ((e) ? ((ASSERT_TRACE) ? fprintf(stderr, \ + "Assertion succeeded: (%s), file %s, line %d\n", \ + #e, __FILE__, (int) __LINE__), \ + fflush(stderr) : \ + 0) : \ + (fprintf(stderr, "Assertion failed: (%s), file %s, line %d\n", \ + #e, __FILE__, (int) __LINE__), exit(1), 0)) + +int assertE; +# define assert_e(e, o, r) \ + (((assertE = e) o (r)) ? ((ASSERT_TRACE) ? fprintf(stderr, \ + "Assertion succeeded: (%s), file %s, line %d\n", \ + #e, __FILE__, (int) __LINE__), \ + fflush(stderr) : \ + 0) : \ + (fprintf(stderr, "Assertion failed: (%s %s %s), file %s, line %d, error %s\n", \ + #e,#o,#r, __FILE__, (int) __LINE__, error_string[assertE]), exit(1), 0)) + +#endif + +# define BEGIN_MUTEX_STALLED_ROBUST(mxAttr) \ + for(;;) \ + { \ + static int _i=0; \ + static int _robust; \ + pthread_mutexattr_getrobust(&(mxAttr), &_robust); + +# define END_MUTEX_STALLED_ROBUST(mxAttr) \ + printf("Pass %s\n", _robust==PTHREAD_MUTEX_ROBUST?"Robust":"Non-robust"); \ + if (++_i > 1) \ + break; \ + else \ + { \ + pthread_mutexattr_t *pma, *pmaEnd; \ + for(pma = &(mxAttr), pmaEnd = pma + sizeof(mxAttr)/sizeof(pthread_mutexattr_t); \ + pma < pmaEnd; \ + pthread_mutexattr_setrobust(pma++, PTHREAD_MUTEX_ROBUST)); \ + } \ + } + +# define IS_ROBUST (_robust==PTHREAD_MUTEX_ROBUST) diff --git a/w32-pthreads/tests/tryentercs.c b/w32-pthreads/tests/tryentercs.c new file mode 100644 index 000000000..13a6e096d --- /dev/null +++ b/w32-pthreads/tests/tryentercs.c @@ -0,0 +1,103 @@ +/* + * tryentercs.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * See if we have the TryEnterCriticalSection function. + * Does not use any part of pthreads. + */ + +#include +#include +#include + +/* + * Function pointer to TryEnterCriticalSection if it exists + * - otherwise NULL + */ +BOOL (WINAPI *_try_enter_critical_section)(LPCRITICAL_SECTION) = +NULL; + +/* + * Handle to kernel32.dll + */ +static HINSTANCE _h_kernel32; + + +int +main() +{ + CRITICAL_SECTION cs; + + SetLastError(0); + + printf("Last Error [main enter] %ld\n", (long) GetLastError()); + + /* + * Load KERNEL32 and try to get address of TryEnterCriticalSection + */ + _h_kernel32 = LoadLibrary(TEXT("KERNEL32.DLL")); + _try_enter_critical_section = + (BOOL (PT_STDCALL *)(LPCRITICAL_SECTION)) + GetProcAddress(_h_kernel32, + (LPCSTR) "TryEnterCriticalSection"); + + if (_try_enter_critical_section != NULL) + { + InitializeCriticalSection(&cs); + + SetLastError(0); + + if ((*_try_enter_critical_section)(&cs) != 0) + { + LeaveCriticalSection(&cs); + } + else + { + printf("Last Error [try enter] %ld\n", (long) GetLastError()); + + _try_enter_critical_section = NULL; + } + DeleteCriticalSection(&cs); + } + + (void) FreeLibrary(_h_kernel32); + + printf("This system %s TryEnterCriticalSection.\n", + (_try_enter_critical_section == NULL) ? "DOES NOT SUPPORT" : "SUPPORTS"); + printf("POSIX Mutexes will be based on Win32 %s.\n", + (_try_enter_critical_section == NULL) ? "Mutexes" : "Critical Sections"); + + return(0); +} + diff --git a/w32-pthreads/tests/tryentercs2.c b/w32-pthreads/tests/tryentercs2.c new file mode 100644 index 000000000..a1c4d97f3 --- /dev/null +++ b/w32-pthreads/tests/tryentercs2.c @@ -0,0 +1,92 @@ +/* + * tryentercs.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * See if we have the TryEnterCriticalSection function. + * Does not use any part of pthreads. + */ + +#include +#include +#include + +/* + * Function pointer to TryEnterCriticalSection if it exists + * - otherwise NULL + */ +BOOL (WINAPI *_try_enter_critical_section)(LPCRITICAL_SECTION) = NULL; + +/* + * Handle to kernel32.dll + */ +static HINSTANCE _h_kernel32; + + +int +main() +{ + LPCRITICAL_SECTION lpcs = NULL; + + SetLastError(0); + + printf("Last Error [main enter] %ld\n", (long) GetLastError()); + + /* + * Load KERNEL32 and try to get address of TryEnterCriticalSection + */ + _h_kernel32 = LoadLibrary(TEXT("KERNEL32.DLL")); + _try_enter_critical_section = + (BOOL (PT_STDCALL *)(LPCRITICAL_SECTION)) + GetProcAddress(_h_kernel32, + (LPCSTR) "TryEnterCriticalSection"); + + if (_try_enter_critical_section != NULL) + { + SetLastError(0); + + (*_try_enter_critical_section)(lpcs); + + printf("Last Error [try enter] %ld\n", (long) GetLastError()); + } + + (void) FreeLibrary(_h_kernel32); + + printf("This system %s TryEnterCriticalSection.\n", + (_try_enter_critical_section == NULL) ? "DOES NOT SUPPORT" : "SUPPORTS"); + printf("POSIX Mutexes will be based on Win32 %s.\n", + (_try_enter_critical_section == NULL) ? "Mutexes" : "Critical Sections"); + + return(0); +} + diff --git a/w32-pthreads/tests/tsd1.c b/w32-pthreads/tests/tsd1.c new file mode 100644 index 000000000..84d78886c --- /dev/null +++ b/w32-pthreads/tests/tsd1.c @@ -0,0 +1,209 @@ +/* + * tsd1.c + * + * Test Thread Specific Data (TSD) key creation and destruction. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * + * -------------------------------------------------------------------------- + * + * Description: + * - + * + * Test Method (validation or falsification): + * - validation + * + * Requirements Tested: + * - keys are created for each existing thread including the main thread + * - keys are created for newly created threads + * - keys are thread specific + * - destroy routine is called on each thread exit including the main thread + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Environment: + * - + * + * Input: + * - none + * + * Output: + * - text to stdout + * + * Assumptions: + * - already validated: pthread_create() + * pthread_once() + * - main thread also has a POSIX thread identity + * + * Pass Criteria: + * - stdout matches file reference/tsd1.out + * + * Fail Criteria: + * - fails to match file reference/tsd1.out + * - output identifies failed component + */ + +#include +#include "test.h" + +enum { + NUM_THREADS = 100 +}; + +static pthread_key_t key = NULL; +static int accesscount[NUM_THREADS]; +static int thread_set[NUM_THREADS]; +static int thread_destroyed[NUM_THREADS]; +static pthread_barrier_t startBarrier; + +static void +destroy_key(void * arg) +{ + int * j = (int *) arg; + + (*j)++; + + assert(*j == 2); + + thread_destroyed[j - accesscount] = 1; +} + +static void +setkey(void * arg) +{ + int * j = (int *) arg; + + thread_set[j - accesscount] = 1; + + assert(*j == 0); + + assert(pthread_getspecific(key) == NULL); + + assert(pthread_setspecific(key, arg) == 0); + assert(pthread_setspecific(key, arg) == 0); + assert(pthread_setspecific(key, arg) == 0); + + assert(pthread_getspecific(key) == arg); + + (*j)++; + + assert(*j == 1); +} + +static void * +mythread(void * arg) +{ + (void) pthread_barrier_wait(&startBarrier); + + setkey(arg); + + return 0; + + /* Exiting the thread will call the key destructor. */ +} + +int +main() +{ + int i; + int fail = 0; + pthread_t thread[NUM_THREADS]; + + assert(pthread_barrier_init(&startBarrier, NULL, NUM_THREADS/2) == 0); + + for (i = 1; i < NUM_THREADS/2; i++) + { + accesscount[i] = thread_set[i] = thread_destroyed[i] = 0; + assert(pthread_create(&thread[i], NULL, mythread, (void *)&accesscount[i]) == 0); + } + + /* + * Here we test that existing threads will get a key created + * for them. + */ + assert(pthread_key_create(&key, destroy_key) == 0); + + (void) pthread_barrier_wait(&startBarrier); + + /* + * Test main thread key. + */ + accesscount[0] = 0; + setkey((void *) &accesscount[0]); + + /* + * Here we test that new threads will get a key created + * for them. + */ + for (i = NUM_THREADS/2; i < NUM_THREADS; i++) + { + accesscount[i] = thread_set[i] = thread_destroyed[i] = 0; + assert(pthread_create(&thread[i], NULL, mythread, (void *)&accesscount[i]) == 0); + } + + /* + * Wait for all threads to complete. + */ + for (i = 1; i < NUM_THREADS; i++) + { + assert(pthread_join(thread[i], NULL) == 0); + } + + assert(pthread_key_delete(key) == 0); + + assert(pthread_barrier_destroy(&startBarrier) == 0); + + for (i = 1; i < NUM_THREADS; i++) + { + /* + * The counter is incremented once when the key is set to + * a value, and again when the key is destroyed. If the key + * doesn't get set for some reason then it will still be + * NULL and the destroy function will not be called, and + * hence accesscount will not equal 2. + */ + if (accesscount[i] != 2) + { + fail++; + fprintf(stderr, "Thread %d key, set = %d, destroyed = %d\n", + i, thread_set[i], thread_destroyed[i]); + } + } + + fflush(stderr); + + return (fail); +} diff --git a/w32-pthreads/tests/tsd2.c b/w32-pthreads/tests/tsd2.c new file mode 100644 index 000000000..16e69948c --- /dev/null +++ b/w32-pthreads/tests/tsd2.c @@ -0,0 +1,213 @@ +/* + * tsd2.c + * + * Test Thread Specific Data (TSD) key creation and destruction. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * + * -------------------------------------------------------------------------- + * + * Description: + * - + * + * Test Method (validation or falsification): + * - validation + * + * Requirements Tested: + * - keys are created for each existing thread including the main thread + * - keys are created for newly created threads + * - keys are thread specific + * - destroy routine is called on each thread exit including the main thread + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Environment: + * - + * + * Input: + * - none + * + * Output: + * - text to stdout + * + * Assumptions: + * - already validated: pthread_create() + * pthread_once() + * - main thread also has a POSIX thread identity + * + * Pass Criteria: + * - stdout matches file reference/tsd1.out + * + * Fail Criteria: + * - fails to match file reference/tsd1.out + * - output identifies failed component + */ + +#include +#include "test.h" + +enum { + NUM_THREADS = 100 +}; + +static pthread_key_t key = NULL; +static int accesscount[NUM_THREADS]; +static int thread_set[NUM_THREADS]; +static int thread_destroyed[NUM_THREADS]; +static pthread_barrier_t startBarrier; + +static void +destroy_key(void * arg) +{ + int * j = (int *) arg; + + (*j)++; + + /* Set TSD key from the destructor to test destructor iteration */ + if (*j == 2) + assert(pthread_setspecific(key, arg) == 0); + else + assert(*j == 3); + + thread_destroyed[j - accesscount] = 1; +} + +static void +setkey(void * arg) +{ + int * j = (int *) arg; + + thread_set[j - accesscount] = 1; + + assert(*j == 0); + + assert(pthread_getspecific(key) == NULL); + + assert(pthread_setspecific(key, arg) == 0); + assert(pthread_setspecific(key, arg) == 0); + assert(pthread_setspecific(key, arg) == 0); + + assert(pthread_getspecific(key) == arg); + + (*j)++; + + assert(*j == 1); +} + +static void * +mythread(void * arg) +{ + (void) pthread_barrier_wait(&startBarrier); + + setkey(arg); + + return 0; + + /* Exiting the thread will call the key destructor. */ +} + +int +main() +{ + int i; + int fail = 0; + pthread_t thread[NUM_THREADS]; + + assert(pthread_barrier_init(&startBarrier, NULL, NUM_THREADS/2) == 0); + + for (i = 1; i < NUM_THREADS/2; i++) + { + accesscount[i] = thread_set[i] = thread_destroyed[i] = 0; + assert(pthread_create(&thread[i], NULL, mythread, (void *)&accesscount[i]) == 0); + } + + /* + * Here we test that existing threads will get a key created + * for them. + */ + assert(pthread_key_create(&key, destroy_key) == 0); + + (void) pthread_barrier_wait(&startBarrier); + + /* + * Test main thread key. + */ + accesscount[0] = 0; + setkey((void *) &accesscount[0]); + + /* + * Here we test that new threads will get a key created + * for them. + */ + for (i = NUM_THREADS/2; i < NUM_THREADS; i++) + { + accesscount[i] = thread_set[i] = thread_destroyed[i] = 0; + assert(pthread_create(&thread[i], NULL, mythread, (void *)&accesscount[i]) == 0); + } + + /* + * Wait for all threads to complete. + */ + for (i = 1; i < NUM_THREADS; i++) + { + assert(pthread_join(thread[i], NULL) == 0); + } + + assert(pthread_key_delete(key) == 0); + + assert(pthread_barrier_destroy(&startBarrier) == 0); + + for (i = 1; i < NUM_THREADS; i++) + { + /* + * The counter is incremented once when the key is set to + * a value, and again when the key is destroyed. If the key + * doesn't get set for some reason then it will still be + * NULL and the destroy function will not be called, and + * hence accesscount will not equal 2. + */ + if (accesscount[i] != 3) + { + fail++; + fprintf(stderr, "Thread %d key, set = %d, destroyed = %d\n", + i, thread_set[i], thread_destroyed[i]); + } + } + + fflush(stderr); + + return (fail); +} diff --git a/w32-pthreads/tests/valid1.c b/w32-pthreads/tests/valid1.c new file mode 100644 index 000000000..a3913fd04 --- /dev/null +++ b/w32-pthreads/tests/valid1.c @@ -0,0 +1,103 @@ +/* + * File: valid1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test that thread validation works. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +enum { + NUMTHREADS = 1 +}; + +static int washere = 0; + +void * func(void * arg) +{ + washere = 1; + return (void *) 0; +} + +int +main() +{ + pthread_t t; + void * result = NULL; + + washere = 0; + assert(pthread_create(&t, NULL, func, NULL) == 0); + assert(pthread_join(t, &result) == 0); + assert((int)(size_t)result == 0); + assert(washere == 1); + sched_yield(); + assert(pthread_kill(t, 0) == ESRCH); + + return 0; +} diff --git a/w32-pthreads/tests/valid2.c b/w32-pthreads/tests/valid2.c new file mode 100644 index 000000000..b9671798b --- /dev/null +++ b/w32-pthreads/tests/valid2.c @@ -0,0 +1,84 @@ +/* + * File: valid2.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Confirm that thread validation fails for garbage thread ID. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +int +main() +{ + pthread_t NullThread = PTW32_THREAD_NULL_ID; + + assert(pthread_kill(NullThread, 0) == ESRCH); + + return 0; +} diff --git a/w32-pthreads/tsd.c b/w32-pthreads/tsd.c new file mode 100644 index 000000000..ed44fe6cb --- /dev/null +++ b/w32-pthreads/tsd.c @@ -0,0 +1,44 @@ +/* + * tsd.c + * + * Description: + * POSIX thread functions which implement thread-specific data (TSD). + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +#include "pthread_key_create.c" +#include "pthread_key_delete.c" +#include "pthread_setspecific.c" +#include "pthread_getspecific.c" diff --git a/w32-pthreads/version.rc b/w32-pthreads/version.rc new file mode 100644 index 000000000..02ade072f --- /dev/null +++ b/w32-pthreads/version.rc @@ -0,0 +1,394 @@ +/* This is an implementation of the threads API of POSIX 1003.1-2001. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include +#include "pthread.h" + +/* + * Note: the correct __CLEANUP_* macro must be defined corresponding to + * the definition used for the object file builds. This is done in the + * relevent makefiles for the command line builds, but users should ensure + * that their resource compiler knows what it is too. + * If using the default (no __CLEANUP_* defined), pthread.h will define it + * as __CLEANUP_C. + */ + +#if defined(__MINGW64__) +# define PTW32_ARCH "x64 (mingw64)" +#elif defined (__MINGW32__) +# define PTW32_ARCH "x86 (mingw32)" +#endif +#if defined(PTW32_ARCHx64) +# define PTW32_ARCH "x64" +#elif defined(PTW32_ARCHx86) +# define PTW32_ARCH "x86" +#endif + +#if defined(PTW32_RC_MSC) +# if defined(__CLEANUP_C) +# define PTW32_VERSIONINFO_NAME "pthreadVC2.DLL\0" +# define PTW32_VERSIONINFO_DESCRIPTION "MS C " PTW32_ARCH "\0" +# elif defined(__CLEANUP_CXX) +# define PTW32_VERSIONINFO_NAME "pthreadVCE2.DLL\0" +# define PTW32_VERSIONINFO_DESCRIPTION "MS C++ " PTW32_ARCH "\0" +# elif defined(__CLEANUP_SEH) +# define PTW32_VERSIONINFO_NAME "pthreadVSE2.DLL\0" +# define PTW32_VERSIONINFO_DESCRIPTION "MS C SEH " PTW32_ARCH "\0" +# else +# error Resource compiler doesn't know which cleanup style you're using - see version.rc +# endif +#elif defined(__GNUC__) +# if defined(__CLEANUP_C) +# define PTW32_VERSIONINFO_NAME "pthreadGC2.DLL\0" +# define PTW32_VERSIONINFO_DESCRIPTION "GNU C " PTW32_ARCH "\0" +# elif defined(__CLEANUP_CXX) +# define PTW32_VERSIONINFO_NAME "pthreadGCE2.DLL\0" +# define PTW32_VERSIONINFO_DESCRIPTION "GNU C++ " PTW32_ARCH "\0" +# else +# error Resource compiler doesn't know which cleanup style you're using - see version.rc +# endif +#elif defined(__BORLANDC__) +# if defined(__CLEANUP_C) +# define PTW32_VERSIONINFO_NAME "pthreadBC2.DLL\0" +# define PTW32_VERSIONINFO_DESCRIPTION "BORLAND C " PTW32_ARCH "\0" +# elif defined(__CLEANUP_CXX) +# define PTW32_VERSIONINFO_NAME "pthreadBCE2.DLL\0" +# define PTW32_VERSIONINFO_DESCRIPTION "BORLAND C++ " PTW32_ARCH "\0" +# else +# error Resource compiler doesn't know which cleanup style you're using - see version.rc +# endif +#elif defined(__WATCOMC__) +# if defined(__CLEANUP_C) +# define PTW32_VERSIONINFO_NAME "pthreadWC2.DLL\0" +# define PTW32_VERSIONINFO_DESCRIPTION "WATCOM C " PTW32_ARCH "\0" +# elif defined(__CLEANUP_CXX) +# define PTW32_VERSIONINFO_NAME "pthreadWCE2.DLL\0" +# define PTW32_VERSIONINFO_DESCRIPTION "WATCOM C++ " PTW32_ARCH "\0" +# else +# error Resource compiler doesn't know which cleanup style you're using - see version.rc +# endif +#else +# error Resource compiler doesn't know which compiler you're using - see version.rc +#endif + + +VS_VERSION_INFO VERSIONINFO + FILEVERSION PTW32_VERSION + PRODUCTVERSION PTW32_VERSION + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK + FILEFLAGS 0 + FILEOS VOS__WINDOWS32 + FILETYPE VFT_DLL +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "ProductName", "POSIX Threads for Windows LPGL\0" + VALUE "ProductVersion", PTW32_VERSION_STRING + VALUE "FileVersion", PTW32_VERSION_STRING + VALUE "FileDescription", PTW32_VERSIONINFO_DESCRIPTION + VALUE "InternalName", PTW32_VERSIONINFO_NAME + VALUE "OriginalFilename", PTW32_VERSIONINFO_NAME + VALUE "CompanyName", "Open Source Software community LGPL\0" + VALUE "LegalCopyright", "Copyright (C) Project contributors 2012\0" + VALUE "Comments", "http://sourceware.org/pthreads-win32/\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +/* +VERSIONINFO Resource + +The VERSIONINFO resource-definition statement creates a version-information +resource. The resource contains such information about the file as its +version number, its intended operating system, and its original filename. +The resource is intended to be used with the Version Information functions. + +versionID VERSIONINFO fixed-info { block-statement...} + +versionID + Version-information resource identifier. This value must be 1. + +fixed-info + Version information, such as the file version and the intended operating + system. This parameter consists of the following statements. + + + Statement Description + -------------------------------------------------------------------------- + FILEVERSION + version Binary version number for the file. The version + consists of two 32-bit integers, defined by four + 16-bit integers. For example, "FILEVERSION 3,10,0,61" + is translated into two doublewords: 0x0003000a and + 0x0000003d, in that order. Therefore, if version is + defined by the DWORD values dw1 and dw2, they need + to appear in the FILEVERSION statement as follows: + HIWORD(dw1), LOWORD(dw1), HIWORD(dw2), LOWORD(dw2). + PRODUCTVERSION + version Binary version number for the product with which the + file is distributed. The version parameter is two + 32-bit integers, defined by four 16-bit integers. + For more information about version, see the + FILEVERSION description. + FILEFLAGSMASK + fileflagsmask Bits in the FILEFLAGS statement are valid. If a bit + is set, the corresponding bit in FILEFLAGS is valid. + FILEFLAGSfileflags Attributes of the file. The fileflags parameter must + be the combination of all the file flags that are + valid at compile time. For 16-bit Windows, this + value is 0x3f. + FILEOSfileos Operating system for which this file was designed. + The fileos parameter can be one of the operating + system values given in the Remarks section. + FILETYPEfiletype General type of file. The filetype parameter can be + one of the file type values listed in the Remarks + section. + FILESUBTYPE + subtype Function of the file. The subtype parameter is zero + unless the type parameter in the FILETYPE statement + is VFT_DRV, VFT_FONT, or VFT_VXD. For a list of file + subtype values, see the Remarks section. + +block-statement + Specifies one or more version-information blocks. A block can contain + string information or variable information. For more information, see + StringFileInfo Block or VarFileInfo Block. + +Remarks + +To use the constants specified with the VERSIONINFO statement, you must +include the Winver.h or Windows.h header file in the resource-definition file. + +The following list describes the parameters used in the VERSIONINFO statement: + +fileflags + A combination of the following values. + + Value Description + + VS_FF_DEBUG File contains debugging information or is compiled + with debugging features enabled. + VS_FF_PATCHED File has been modified and is not identical to the + original shipping file of the same version number. + VS_FF_PRERELEASE File is a development version, not a commercially + released product. + VS_FF_PRIVATEBUILD File was not built using standard release procedures. + If this value is given, the StringFileInfo block must + contain a PrivateBuild string. + VS_FF_SPECIALBUILD File was built by the original company using standard + release procedures but is a variation of the standard + file of the same version number. If this value is + given, the StringFileInfo block must contain a + SpecialBuild string. + +fileos + One of the following values. + + Value Description + + VOS_UNKNOWN The operating system for which the file was designed + is unknown. + VOS_DOS File was designed for MS-DOS. + VOS_NT File was designed for Windows Server 2003 family, + Windows XP, Windows 2000, or Windows NT. + VOS__WINDOWS16 File was designed for 16-bit Windows. + VOS__WINDOWS32 File was designed for 32-bit Windows. + VOS_DOS_WINDOWS16 File was designed for 16-bit Windows running with + MS-DOS. + VOS_DOS_WINDOWS32 File was designed for 32-bit Windows running with + MS-DOS. + VOS_NT_WINDOWS32 File was designed for Windows Server 2003 family, + Windows XP, Windows 2000, or Windows NT. + + The values 0x00002L, 0x00003L, 0x20000L and 0x30000L are reserved. + +filetype + One of the following values. + + Value Description + + VFT_UNKNOWN File type is unknown. + VFT_APP File contains an application. + VFT_DLL File contains a dynamic-link library (DLL). + VFT_DRV File contains a device driver. If filetype is + VFT_DRV, subtype contains a more specific + description of the driver. + VFT_FONT File contains a font. If filetype is VFT_FONT, + subtype contains a more specific description of the + font. + VFT_VXD File contains a virtual device. + VFT_STATIC_LIB File contains a static-link library. + + All other values are reserved for use by Microsoft. + +subtype + Additional information about the file type. + + If filetype specifies VFT_DRV, this parameter can be one of the + following values. + + Value Description + + VFT2_UNKNOWN Driver type is unknown. + VFT2_DRV_COMM File contains a communications driver. + VFT2_DRV_PRINTER File contains a printer driver. + VFT2_DRV_KEYBOARD File contains a keyboard driver. + VFT2_DRV_LANGUAGE File contains a language driver. + VFT2_DRV_DISPLAY File contains a display driver. + VFT2_DRV_MOUSE File contains a mouse driver. + VFT2_DRV_NETWORK File contains a network driver. + VFT2_DRV_SYSTEM File contains a system driver. + VFT2_DRV_INSTALLABLE File contains an installable driver. + VFT2_DRV_SOUND File contains a sound driver. + VFT2_DRV_VERSIONED_PRINTER File contains a versioned printer driver. + + If filetype specifies VFT_FONT, this parameter can be one of the + following values. + + Value Description + + VFT2_UNKNOWN Font type is unknown. + VFT2_FONT_RASTER File contains a raster font. + VFT2_FONT_VECTOR File contains a vector font. + VFT2_FONT_TRUETYPE File contains a TrueType font. + + If filetype specifies VFT_VXD, this parameter must be the virtual-device + identifier included in the virtual-device control block. + + All subtype values not listed here are reserved for use by Microsoft. + +langID + One of the following language codes. + + Code Language Code Language + + 0x0401 Arabic 0x0415 Polish + 0x0402 Bulgarian 0x0416 Portuguese (Brazil) + 0x0403 Catalan 0x0417 Rhaeto-Romanic + 0x0404 Traditional Chinese 0x0418 Romanian + 0x0405 Czech 0x0419 Russian + 0x0406 Danish 0x041A Croato-Serbian (Latin) + 0x0407 German 0x041B Slovak + 0x0408 Greek 0x041C Albanian + 0x0409 U.S. English 0x041D Swedish + 0x040A Castilian Spanish 0x041E Thai + 0x040B Finnish 0x041F Turkish + 0x040C French 0x0420 Urdu + 0x040D Hebrew 0x0421 Bahasa + 0x040E Hungarian 0x0804 Simplified Chinese + 0x040F Icelandic 0x0807 Swiss German + 0x0410 Italian 0x0809 U.K. English + 0x0411 Japanese 0x080A Mexican Spanish + 0x0412 Korean 0x080C Belgian French + 0x0413 Dutch 0x0C0C Canadian French + 0x0414 Norwegian ā€“ Bokmal 0x100C Swiss French + 0x0810 Swiss Italian 0x0816 Portuguese (Portugal) + 0x0813 Belgian Dutch 0x081A Serbo-Croatian (Cyrillic) + 0x0814 Norwegian ā€“ Nynorsk + +charsetID + One of the following character-set identifiers. + + Identifier Character Set + + 0 7-bit ASCII + 932 Japan (Shift %Gā€“%@ JIS X-0208) + 949 Korea (Shift %Gā€“%@ KSC 5601) + 950 Taiwan (Big5) + 1200 Unicode + 1250 Latin-2 (Eastern European) + 1251 Cyrillic + 1252 Multilingual + 1253 Greek + 1254 Turkish + 1255 Hebrew + 1256 Arabic + +string-name + One of the following predefined names. + + Name Description + + Comments Additional information that should be displayed for + diagnostic purposes. + CompanyName Company that produced the file%Gā€”%@for example, + "Microsoft Corporation" or "Standard Microsystems + Corporation, Inc." This string is required. + FileDescription File description to be presented to users. This + string may be displayed in a list box when the user + is choosing files to install%Gā€”%@for example, + "Keyboard Driver for AT-Style Keyboards". This + string is required. + FileVersion Version number of the file%Gā€”%@for example, + "3.10" or "5.00.RC2". This string is required. + InternalName Internal name of the file, if one exists ā€” for + example, a module name if the file is a dynamic-link + library. If the file has no internal name, this + string should be the original filename, without + extension. This string is required. + LegalCopyright Copyright notices that apply to the file. This + should include the full text of all notices, legal + symbols, copyright dates, and so on ā€” for example, + "Copyright (C) Microsoft Corporation 1990ā€“1999". + This string is optional. + LegalTrademarks Trademarks and registered trademarks that apply to + the file. This should include the full text of all + notices, legal symbols, trademark numbers, and so on. + This string is optional. + OriginalFilename Original name of the file, not including a path. + This information enables an application to determine + whether a file has been renamed by a user. The + format of the name depends on the file system for + which the file was created. This string is required. + PrivateBuild Information about a private version of the file ā€” for + example, "Built by TESTER1 on \TESTBED". This string + should be present only if VS_FF_PRIVATEBUILD is + specified in the fileflags parameter of the root + block. + ProductName Name of the product with which the file is + distributed. This string is required. + ProductVersion Version of the product with which the file is + distributed ā€” for example, "3.10" or "5.00.RC2". + This string is required. + SpecialBuild Text that indicates how this version of the file + differs from the standard version ā€” for example, + "Private build for TESTER1 solving mouse problems + on M250 and M250E computers". This string should be + present only if VS_FF_SPECIALBUILD is specified in + the fileflags parameter of the root block. + */ diff --git a/w32-pthreads/w32_CancelableWait.c b/w32-pthreads/w32_CancelableWait.c new file mode 100644 index 000000000..070633e0f --- /dev/null +++ b/w32-pthreads/w32_CancelableWait.c @@ -0,0 +1,161 @@ +/* + * w32_CancelableWait.c + * + * Description: + * This translation unit implements miscellaneous thread functions. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include "pthread.h" +#include "implement.h" + + +static INLINE int +ptw32_cancelable_wait (HANDLE waitHandle, DWORD timeout) + /* + * ------------------------------------------------------------------- + * This provides an extra hook into the pthread_cancel + * mechanism that will allow you to wait on a Windows handle and make it a + * cancellation point. This function blocks until the given WIN32 handle is + * signaled or pthread_cancel has been called. It is implemented using + * WaitForMultipleObjects on 'waitHandle' and a manually reset WIN32 + * event used to implement pthread_cancel. + * + * Given this hook it would be possible to implement more of the cancellation + * points. + * ------------------------------------------------------------------- + */ +{ + int result; + pthread_t self; + ptw32_thread_t * sp; + HANDLE handles[2]; + DWORD nHandles = 1; + DWORD status; + + handles[0] = waitHandle; + + self = pthread_self(); + sp = (ptw32_thread_t *) self.p; + + if (sp != NULL) + { + /* + * Get cancelEvent handle + */ + if (sp->cancelState == PTHREAD_CANCEL_ENABLE) + { + + if ((handles[1] = sp->cancelEvent) != NULL) + { + nHandles++; + } + } + } + else + { + handles[1] = NULL; + } + + status = WaitForMultipleObjects (nHandles, handles, PTW32_FALSE, timeout); + + switch (status - WAIT_OBJECT_0) + { + case 0: + /* + * Got the handle. + * In the event that both handles are signalled, the smallest index + * value (us) is returned. As it has been arranged, this ensures that + * we don't drop a signal that we should act on (i.e. semaphore, + * mutex, or condition variable etc). + */ + result = 0; + break; + + case 1: + /* + * Got cancel request. + * In the event that both handles are signaled, the cancel will + * be ignored (see case 0 comment). + */ + ResetEvent (handles[1]); + + if (sp != NULL) + { + ptw32_mcs_local_node_t stateLock; + /* + * Should handle POSIX and implicit POSIX threads.. + * Make sure we haven't been async-canceled in the meantime. + */ + ptw32_mcs_lock_acquire (&sp->stateLock, &stateLock); + if (sp->state < PThreadStateCanceling) + { + sp->state = PThreadStateCanceling; + sp->cancelState = PTHREAD_CANCEL_DISABLE; + ptw32_mcs_lock_release (&stateLock); + ptw32_throw (PTW32_EPS_CANCEL); + + /* Never reached */ + } + ptw32_mcs_lock_release (&stateLock); + } + + /* Should never get to here. */ + result = EINVAL; + break; + + default: + if (status == WAIT_TIMEOUT) + { + result = ETIMEDOUT; + } + else + { + result = EINVAL; + } + break; + } + + return (result); + +} /* CancelableWait */ + +int +pthreadCancelableWait (HANDLE waitHandle) +{ + return (ptw32_cancelable_wait (waitHandle, INFINITE)); +} + +int +pthreadCancelableTimedWait (HANDLE waitHandle, DWORD timeout) +{ + return (ptw32_cancelable_wait (waitHandle, timeout)); +}