diff --git a/AUTHORS b/AUTHORS index 27b5f4e..52c16b9 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1,54 +1,51 @@ Package: npth -Download: ftp://ftp.gnupg.org/gcrypt/npth/ +Download: https://gnupg.org/ftp/gcrypt/npth/ Repository: git://git.gnupg.org/npth.git Maintainer: Werner Koch Bug reports: gnupg-devel@gnupg.org Security related bug reports: security@gnupg.org -License (software): LGPLv3+/GPLv2+ +License: LGPLv2+ + + +nPth is free software. See the file COPYING.LIB for copying +conditions. License copyright years may be listed using range +notation, e.g., 2000-2013, indicating that every year in the range, +inclusive, is a copyrightable year that would otherwise be listed +individually. + * Authors g10 Code GmbH - Design and implementation. * Copyright - nPth is Copyright (C) 2011, 2012, 2014, 2015 g10 Code GmbH - - nPth is free software; you can redistribute it and/or modify it - under the terms of either - - - the GNU Lesser General Public License as published by the Free - Software Foundation; either version 3 of the License, or (at - your option) any later version. - - or - - - the GNU General Public License as published by the Free - Software Foundation; either version 2 of the License, or (at - your option) any later version. + nPth is Copyright (C) 2011, 2012, 2014, 2015, 2017 g10 Code GmbH - or both in parallel, as here. + nPth is free software; you can redistribute it 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. - nPth is distributed in the hope that 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. + nPth is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See + the GNU Lesser General Public License for more details. - You should have received a copies of the GNU General Public License - and the GNU Lesser General Public License along with this program; - if not, see . + You should have received a copy of the GNU Lesser General Public + License along with this program; if not, see . # This file is Copyright 2011, 2012 g10 Code GmbH # # This file is free software; as a special exception the author gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # # This file is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. diff --git a/COPYING b/COPYING deleted file mode 100644 index d511905..0000000 --- a/COPYING +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) 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 -this service 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 make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. 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. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -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 Program or any portion -of it, thus forming a work based on the Program, 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) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -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 Program, 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 Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) 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; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, 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 executable. However, as a -special exception, the source code 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. - -If distribution of executable or 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 counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program 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. - - 5. 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 Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program 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 to -this License. - - 7. 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 Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program 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 Program. - -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. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program 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. - - 9. The Free Software Foundation may publish revised and/or new versions -of the 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 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 Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, 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 - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. - - 12. 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 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. - - 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 -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 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 2 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, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision 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, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This 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. diff --git a/COPYING.LESSER b/COPYING.LESSER deleted file mode 100644 index fc8a5de..0000000 --- a/COPYING.LESSER +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER 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. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - 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 that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU 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 as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/COPYING.LIB b/COPYING.LIB new file mode 100644 index 0000000..5522aa5 --- /dev/null +++ b/COPYING.LIB @@ -0,0 +1,508 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 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/HACKING b/HACKING index 0a779b3..915879b 100644 --- a/HACKING +++ b/HACKING @@ -1,23 +1,23 @@ # HACKING -*- org -*- -#+TITLE: Hacking notes for NPTH +#+TITLE: Hacking notes for nPth #+STARTUP: showall * No ChangeLog files Do not write ChangeLog files for NPTH. We put change information only in the GIT commit log, and generate a top-level ChangeLog file from logs at "make dist" time. As such, there are strict requirements on the form of the commit log messages. * Commit log requirements Your commit log should always start with a one-line summary, the second line should be blank, and the remaining lines are usually ChangeLog-style entries for all affected files. However, it's fine -- even recommended -- to write a few lines of prose describing the change, when the summary and ChangeLog entries don't give enough of the big picture. Omit the leading TABs that you're used to seeing in a "real" ChangeLog file, but keep the maximum line length at 72 or smaller, so that the generated ChangeLog lines, each with its leading TAB, will not exceed 80 columns. diff --git a/Makefile.am b/Makefile.am index 2e1d3bd..7451af2 100644 --- a/Makefile.am +++ b/Makefile.am @@ -1,63 +1,63 @@ # Makefile.am - Top level Makefile for npth. # Copyright (C) 2011 g10 Code GmbH # -# This file is part of NPTH. +# This file is part of nPth. # -# NPTH is free software; you can redistribute it and/or modify it +# nPth is free software; you can redistribute it 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. # -# NPTH is distributed in the hope that it will be useful, but WITHOUT +# nPth is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General # Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, see . ## Process this file with automake to produce Makefile.in ACLOCAL_AMFLAGS = -I m4 EXTRA_DIST = npth-config.in npth.m4 npth.spec.in autogen.sh autogen.rc HACKING bin_SCRIPTS = npth-config m4datadir = $(datadir)/aclocal m4data_DATA = npth.m4 if RUN_TESTS tests = tests else tests = endif if HAVE_W32_SYSTEM npthdir = w32 else npthdir = src endif SUBDIRS = ${npthdir} ${tests} # Fix the version of the spec file and create a file named VERSION # to be used for patch's Prereq: feature. dist-hook: gen-ChangeLog @set -e; \ sed -e 's/@pkg_version@/$(VERSION)/g' \ $(top_srcdir)/npth.spec.in > $(distdir)/npth.spec echo "$(VERSION)" > $(distdir)/VERSION gen_start_date = 2011-12-01T00:00:00 .PHONY: gen-ChangeLog gen-ChangeLog: if test -d $(top_srcdir)/.git; then \ (cd $(top_srcdir) && \ gitlog-to-changelog \ --append-dot --tear-off \ --amend=build-aux/git-log-fix \ --since=$(gen_start_date) ) > $(distdir)/cl-t; \ cat $(top_srcdir)/build-aux/git-log-footer >> $(distdir)/cl-t;\ rm -f $(distdir)/ChangeLog; \ mv $(distdir)/cl-t $(distdir)/ChangeLog; \ fi diff --git a/NEWS b/NEWS index dfbcbbe..c6a867c 100644 --- a/NEWS +++ b/NEWS @@ -1,62 +1,70 @@ Noteworthy changes in version 1.4 (unreleased) ---------------------------------------------- + * On macOS make use of an unnamed semaphore. + + * Build fixes for FreeBSD, NetBSD, and DragonFlyBSD. + + * New function npth_is_protected to help debugging. + + * Change license from LGPLv3+/GPLv2+ to LGPLv2+. + Noteworthy changes in version 1.3 (2016-11-22) ---------------------------------------------- * Bypass npth_protect/npth_unprotect iff the library has not yet been initialized. * Fix problems on macOS and AIX * Improve detection of clock_gettime Noteworthy changes in version 1.2 (2015-04-11) ---------------------------------------------- * Fix possible clobbering of ERRNO. * Improved building on Windows with newer versions of Mingw. Noteworthy changes in version 1.1 (2014-10-31) ---------------------------------------------- * Make it work on OS X and some other systems. Noteworthy changes in version 1.0 (2014-09-18) ---------------------------------------------- * Various fixes for the Windows port. Noteworthy changes in version 0.91 (2012-08-08) ----------------------------------------------- * Fixed a flaw in the initialization code. * npth_init does now return an error on failure. * Various fixes for better portability. * Provide a pselect emulation for OpenBSD et al. Noteworthy changes in version 0.90 (2012-05-03) ----------------------------------------------- * First tarball release. Copyright 2011, 2012, 2014 g10 Code GmbH This file is free software; as a special exception the author gives unlimited permission to copy and/or distribute it, with or without modifications, as long as this notice is preserved. This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, to the extent permitted by law; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. diff --git a/README b/README index 23b6ada..804eeeb 100644 --- a/README +++ b/README @@ -1,32 +1,30 @@ nPth - The New GNU Portable Threads Library * Overview This is a library to provide the GNU Pth API and thus a non-preemptive threads implementation. In contrast to GNU Pth is is based on the system's standard threads implementation. This allows the use of libraries which are not compatible to GNU Pth. Experience with a Windows Pth emulation showed that this is a solid way to provide a co-routine based framework. See the file AUTHORS for contact and copyright information. * License - nPth is currently released under a mixed LGPLv3+/GPLv2+ license. - This is to allow its use with GPLv2(only) software. If there is a - need for other licensing terms, please contact us. + nPth is released under the LGPLv2+ license. * Porting hints Documentation is currently missing. If you are using GNU Pth you should be able to understand the API. Given that GNU Pth is rarely used, we hestitate to spend work on a migration guide. If you have questions, please ask on gnupg-devel. Here are some hints: - Pth mutexes are recursive, that is they will not block if called by the same thread. In contrast, nPth mutexes are not recursive; it is best to change your code to avoid recursive use of mutexes. nPth uses non-recursive mutexes for performance reasons. diff --git a/configure.ac b/configure.ac index 1fda995..9eda97d 100644 --- a/configure.ac +++ b/configure.ac @@ -1,381 +1,372 @@ # configure.ac -*- Autoconf -*- # Copyright (C) 2011, 2012 g10 Code GmbH -# This file is part of NPTH. # -# NPTH is free software; you can redistribute it and/or modify it -# under the terms of either +# This file is part of nPth. # -# - the GNU Lesser General Public License as published by the Free -# Software Foundation; either version 3 of the License, or (at -# your option) any later version. +# nPth is free software; you can redistribute it 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. # -# or -# -# - the GNU General Public License as published by the Free -# Software Foundation; either version 2 of the License, or (at -# your option) any later version. -# -# or both in parallel, as here. -# -# NPTH is distributed in the hope that it will be useful, but WITHOUT +# nPth is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General # Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, see . # Process this file with autoconf to produce a configure script. AC_PREREQ([2.67]) min_automake_version="1.14" # To build a release you need to create a tag with the version number # (git tag -s npth-n.m) and run "./autogen.sh --force". Please bump # the version number immediately after the release and do another # commit and push so that the git magic is able to work. # See below for the LT versions. m4_define(my_version, [1.4]) # Below is m4 magic to extract and compute the git revision number, # the decimalized short revision number, a beta version string and a # flag indicating a development version (my_isgit). The latter works # by requiring the final tag in the repository. m4_define([git_revision], m4_esyscmd([git rev-parse --short HEAD | tr -d '\n\r'])) m4_define([git_revision_dec], m4_esyscmd_s([echo $((0x$(echo ]git_revision[|head -c 4)))])) m4_define([git_betastring], m4_esyscmd_s([git describe --match 'npth-[0-9].*[0-9]' --long|\ awk -F- '$3!=0{print"-beta"$3}'])) m4_define([my_isgit],m4_if(git_betastring,[],[no],[yes])) m4_define([my_full_version],[my_version[]git_betastring]) AC_INIT([npth],[my_full_version],[gnupg-devel@gnupg.org]) # LT Version numbers, remember to change them just *before* a release. # (Code changed: REVISION++) # (Interfaces added/removed/changed: CURRENT++, REVISION=0) # (Interfaces added: AGE++) # (Interfaces removed/changed: AGE=0) # LIBNPTH_LT_CURRENT=0 LIBNPTH_LT_AGE=0 LIBNPTH_LT_REVISION=6 # If the API is changed in an incompatible way: increment the next counter. NPTH_CONFIG_API_VERSION=1 ############################################## PACKAGE=$PACKAGE_NAME VERSION=$PACKAGE_VERSION AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_SRCDIR([src/npth.c]) AC_CONFIG_HEADERS([config.h]) AC_CONFIG_MACRO_DIR([m4]) AM_INIT_AUTOMAKE([serial-tests dist-bzip2 no-dist-gzip]) AM_MAINTAINER_MODE AC_CANONICAL_HOST AM_SILENT_RULES # Enable GNU extensions on systems that have them. AC_GNU_SOURCE AH_VERBATIM([_REENTRANT], [#ifndef _REENTRANT # define _REENTRANT 1 #endif]) # Checks for programs. AC_PROG_CC AC_SUBST(LIBNPTH_LT_CURRENT) AC_SUBST(LIBNPTH_LT_AGE) AC_SUBST(LIBNPTH_LT_REVISION) AC_SUBST(PACKAGE) AC_SUBST(VERSION) AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of this package]) AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version of this package]) run_tests="yes" AC_ARG_ENABLE(tests, AC_HELP_STRING([--disable-tests], [disable tests]), run_tests=$enableval) AM_CONDITIONAL(RUN_TESTS, test "$run_tests" = "yes") # Don't default to build static libs. LT_PREREQ([2.2.6]) LT_INIT([win32-dll disable-static]) LT_LANG([Windows Resource]) # For now we hardcode the use of version scripts. It would be better # to write a test for this or even implement this within libtool. have_ld_version_script=no case "${host}" in *-*-linux*) have_ld_version_script=yes ;; *-*-gnu*) have_ld_version_script=yes ;; *-apple-darwin*) AC_SEARCH_LIBS([dispatch_semaphore_create],[dispatch], [AC_DEFINE([HAVE_LIB_DISPATCH],1,[Defined if we have libdispatch])]) ;; *-*-aix*) have_fork_unsafe_semaphore=yes ;; *-*-dragonfly*|*-*-freebsd*|*-*-netbsd*) LIBS="-lpthread $LIBS" AC_SEARCH_LIBS([sem_init],[rt]) ;; esac AM_CONDITIONAL(HAVE_LD_VERSION_SCRIPT, test "$have_ld_version_script" = "yes") if test "$have_fork_unsafe_semaphore" = yes; then AC_DEFINE(HAVE_FORK_UNSAFE_SEMAPHORE, 1, [Defined if we have fork-unsafe semaphore]) fi # Set some default values config_libs="-lnpth $LIBS" have_w32_system=no have_w32ce_system=no have_w64_system=no # Define OS macros case "${host}" in x86_64-*mingw32*) have_w64_system=yes ;; *-mingw32ce*) have_w32ce_system=yes ;; esac case "${host}" in *-mingw32ce*|*-mingw32*) have_w32_system=yes ;; *) ;; esac if test "$have_w32_system" = yes; then AC_DEFINE(HAVE_W32_SYSTEM,1, [Defined if we run on any kind of W32 API based system]) fi AM_CONDITIONAL(HAVE_W32_SYSTEM, test "$have_w32_system" = yes) if test "$have_w64_system" = yes; then AC_DEFINE(HAVE_W64_SYSTEM,1, [Defined if we run on a 64 bit W32 API based system]) fi AM_CONDITIONAL(HAVE_W64_SYSTEM, test "$have_w64_system" = yes) # # Generate values for the DLL version info # if test "$have_w32_system" = yes; then BUILD_ISODATE=`date --iso-8601` changequote(,)dnl BUILD_FILEVERSION=`echo "$VERSION" | sed 's/\([0-9.]*\).*/\1./;s/\./,/g'` changequote([,])dnl BUILD_FILEVERSION="${BUILD_FILEVERSION}git_revision_dec" fi AC_SUBST(BUILD_ISODATE) AC_SUBST(BUILD_FILEVERSION) AC_ARG_ENABLE([build-timestamp], AC_HELP_STRING([--enable-build-timestamp], [set an explicit build timestamp for reproducibility. (default is the current time in ISO-8601 format)]), [if test "$enableval" = "yes"; then BUILD_TIMESTAMP=`date -u +%Y-%m-%dT%H:%M+0000 2>/dev/null || date` else BUILD_TIMESTAMP="$enableval" fi], [BUILD_TIMESTAMP=""]) AC_SUBST(BUILD_TIMESTAMP) AC_DEFINE_UNQUOTED(BUILD_TIMESTAMP, "$BUILD_TIMESTAMP", [The time this package was configured for a build]) # # Checks for header files. # # fixme: For what do we need the sys/socket test? AC_CHECK_HEADERS([sys/socket.h sys/select.h unistd.h sys/time.h time.h \ signal.h]) INSERT_SYS_SELECT_H= if test x"$ac_cv_header_sys_select_h" = xyes; then INSERT_SYS_SELECT_H="include " fi AC_SUBST(INSERT_SYS_SELECT_H) if test x"$ac_cv_header_sys_time_h" = xyes; then INSERT_SYS_TIME_H="include " fi AC_SUBST(INSERT_SYS_TIME_H) if test x"$ac_cv_header_time_h" = xyes; then INSERT_TIME_H="include " fi AC_SUBST(INSERT_TIME_H) if test x"$ac_cv_header_signal_h" = xyes; then INSERT_SIGNAL_H="include " fi AC_SUBST(INSERT_SIGNAL_H) # Some systems lack socklen_t - provide a replacement. gl_TYPE_SOCKLEN_T case "${host}" in *-*-mingw32*) # socklen_t may or may not be defined depending on what headers # are included. To be safe we use int as this is the actual type. INSERT_SOCKLEN_T="define _npth_socklen_t int" ;; *) if test ".$gl_cv_socklen_t_equiv" = "."; then INSERT_SOCKLEN_T="define _npth_socklen_t socklen_t" else INSERT_SOCKLEN_T="define _npth_socklen_t ${gl_cv_socklen_t_equiv}" fi esac AC_SUBST(INSERT_SOCKLEN_T) # # Checks for typedefs, structures, and compiler characteristics. # AC_TYPE_PID_T AC_TYPE_SIZE_T AC_TYPE_SSIZE_T # # Checks for libraries and functions. # # We test for pthread_detach because glibc 2.22 includes # pthread_create but not pthread_detach. if test "$have_w32_system" = no; then AC_SEARCH_LIBS([pthread_detach],[pthread]) case "x$ac_cv_search_pthread_detach" in xno) have_pthread=no ;; xnone\ required) have_pthread=yes ;; *) have_pthread=yes config_libs="$config_libs $ac_cv_search_pthread_detach" ;; esac if test "$have_pthread" != no; then AC_DEFINE(HAVE_PTHREAD,1,[Define if we have pthread.]) AC_CHECK_FUNCS([pthread_tryjoin_np pthread_setname_np pthread_getname_np]) AC_CHECK_FUNCS([pthread_mutex_timedlock]) AC_CHECK_FUNCS([pthread_rwlock_rdlock pthread_rwlock_wrlock]) AC_CHECK_FUNCS([pthread_rwlock_timedrdlock pthread_rwlock_timedwrlock]) AC_CHECK_FUNCS([pthread_rwlock_tryrdlock pthread_rwlock_trywrlock]) AC_CHECK_FUNCS([pthread_atfork]) fi fi AC_CHECK_FUNCS([select pselect gettimeofday]) npth_LIBSOCKET config_libs="$config_libs $LIBSOCKET" # Save and restore LIBS so e.g., -lrt, isn't added to it. Otherwise, *all* # programs in the package would end up linked with that potentially-shared # library, inducing unnecessary run-time overhead. LIB_CLOCK_GETTIME= AC_SUBST([LIB_CLOCK_GETTIME]) gl_saved_libs=$LIBS AC_SEARCH_LIBS([clock_gettime], [rt posix4], [if test "$ac_cv_search_clock_gettime" != "none required"; then LIB_CLOCK_GETTIME=$ac_cv_search_clock_gettime config_libs="$config_libs $LIB_CLOCK_GETTIME" fi AC_DEFINE([HAVE_CLOCK_GETTIME],1, [Define to 1 if you have the `clock_gettime' function.]) ]) LIBS=$gl_saved_libs # # Set NETLIBS # if test "$have_w32ce_system" = yes; then NETLIBS="-lws2 $NETLIBS" elif test "$have_w32_system" = yes; then NETLIBS="-lws2_32 $NETLIBS" fi AC_SUBST(NETLIBS) # # Substitutions to set generated files in a Emacs buffer to read-only. # AC_SUBST(emacs_local_vars_begin, [['Local][ ][Variables:']]) AC_SUBST(emacs_local_vars_read_only, ['buffer-read-only: t']) AC_SUBST(emacs_local_vars_end, ['End:']) # # Substitution used for npth-config # NPTH_CONFIG_LIBS="$config_libs" NPTH_CONFIG_CFLAGS="" NPTH_CONFIG_HOST="$host" AC_SUBST(NPTH_CONFIG_API_VERSION) AC_SUBST(NPTH_CONFIG_LIBS) AC_SUBST(NPTH_CONFIG_CFLAGS) AC_SUBST(NPTH_CONFIG_HOST) # # Last check. # die=no if test "$have_w32_system" = no; then if test "$have_pthread" = "no"; then die=yes AC_MSG_NOTICE([[ *** *** You need Pthread to build this program. *** Normally, this library comes with your system. On Windows, you can use: *** http://sourceware.org/pthreads-win32/ ***]]) fi fi if test "$die" = "yes"; then AC_MSG_ERROR([[ *** *** Required libraries not found. Please consult the above messages *** and install them before running configure again. ***]]) fi # # Write output # AC_CONFIG_FILES([Makefile src/npth.h src/Makefile w32/Makefile tests/Makefile]) AC_CONFIG_FILES(npth-config, chmod +x npth-config) AC_OUTPUT echo " $PACKAGE_NAME-$PACKAGE_VERSION prepared for make Revision: git_revision (git_revision_dec) Platform: $host " diff --git a/npth.spec.in b/npth.spec.in index 1c16aca..8ec6dbd 100644 --- a/npth.spec.in +++ b/npth.spec.in @@ -1,56 +1,56 @@ # This is a template. The dist target uses it to create the real file. Summary: NPTH - the new GNU Portable Threads Library Name: npth Version: @pkg_version@ Release: 1 URL: http://www.gnupg.org/ Source: ftp://ftp.gnupg.org/gcrypt/alpha Group: Development/Libraries -Copyright: LGPLv3+/GPLv2+ +Copyright: LGPLv2+ BuildRoot: %{_tmppath}/%{name}-%{version} BuildRequires: make Prereq: /sbin/ldconfig /sbin/install-info %description NPTH is a cooperative thread library. %prep %setup -q %build CFLAGS="$RPM_OPT_FLAGS"; export CFLAGS ./configure --prefix=/usr make %install rm -fr $RPM_BUILD_ROOT mkdir -p $RPM_BUILD_ROOT make install prefix=$RPM_BUILD_ROOT/usr %clean rm -fr $RPM_BUILD_ROOT make distclean %post /sbin/ldconfig %preun %postun /sbin/ldconfig %files %defattr(-,root,root) %doc COPYING COPYING.LESSER AUTHORS README INSTALL NEWS ChangeLog TODO THANKS %attr(0755,root,root) %{_bindir}/npth-config %attr(0755,root,root) %{_libdir}/*npth.so* %attr(0755,root,root) %{_libdir}/*npth.la %attr(0644,root,root) %{_libdir}/*npth.a %{_includedir}/npth.h %{_datadir}/aclocal/npth.m4 %changelog * Thu Oct 06 2011 Marcus Brinkmann - initial specfile release for npth. # EOF diff --git a/src/Makefile.am b/src/Makefile.am index 59792d2..123408b 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -1,88 +1,78 @@ # Makefile.am - src/ Makefile for npth. # Copyright (C) 2011 g10 Code GmbH # -# This file is part of NPTH. +# This file is part of nPth. # -# NPTH is free software; you can redistribute it and/or modify it -# under the terms of either +# nPth is free software; you can redistribute it 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. # -# - the GNU Lesser General Public License as published by the Free -# Software Foundation; either version 3 of the License, or (at -# your option) any later version. -# -# or -# -# - the GNU General Public License as published by the Free -# Software Foundation; either version 2 of the License, or (at -# your option) any later version. -# -# or both in parallel, as here. -# -# NPTH is distributed in the hope that it will be useful, but WITHOUT +# nPth is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General # Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, see . ## Process this file with automake to produce Makefile.in EXTRA_DIST = libnpth.vers # versioninfo.rc.in nodist_include_HEADERS = npth.h lib_LTLIBRARIES = libnpth.la if HAVE_LD_VERSION_SCRIPT libnpth_version_script_cmd = -Wl,--version-script=$(srcdir)/libnpth.vers else libnpth_version_script_cmd = endif libnpth_la_SOURCES = npth.h npth.c npth-sigev.c # AM_CPPFLAGS = # AM_CFLAGS = if HAVE_W32_SYSTEM RCCOMPILE = $(RC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) LTRCCOMPILE = $(LIBTOOL) --mode=compile --tag=RC $(RCCOMPILE) SUFFIXES = .rc .lo .rc.lo: $(LTRCCOMPILE) -i "$<" -o "$@" npth_res = versioninfo.lo no_undefined = -no-undefined export_symbols = -export-symbols $(srcdir)/npth.def install-def-file: $(INSTALL) $(srcdir)/npth.def $(DESTDIR)$(libdir)/npth.def uninstall-def-file: -rm $(DESTDIR)$(libdir)/npth.def gpgme_deps = $(gpgme_res) npth.def else npth_res = no_undefined = export_symbols = install-def-file: uninstall-def-file: npth_deps = endif libnpth_la_LDFLAGS = $(no_undefined) $(export_symbols) \ $(libnpth_version_script_cmd) -version-info \ @LIBNPTH_LT_CURRENT@:@LIBNPTH_LT_REVISION@:@LIBNPTH_LT_AGE@ libnpth_la_DEPENDENCIES = $(srcdir)/libnpth.vers $(npth_deps) install-data-local: install-def-file uninstall-local: uninstall-def-file diff --git a/src/libnpth.vers b/src/libnpth.vers index 6eaef0f..7d35c96 100644 --- a/src/libnpth.vers +++ b/src/libnpth.vers @@ -1,68 +1,68 @@ # libnpth.vers - List of symbols to export. # Copyright (C) 2002, 2004, 2005, 2009 g10 Code GmbH # -# This file is part of NPTH. +# This file is part of nPth. # -# NPTH is free software; you can redistribute it 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. +# nPth is free software; you can redistribute it 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. # -# NPTH is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License for more details. +# nPth is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General +# Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, see . #------------------------------------------------------- # Please remember to add new functions also to npth.def #------------------------------------------------------- NPTH_1.0 { global: npth_init; npth_create; npth_join; npth_exit; npth_mutex_lock; npth_mutex_timedlock; npth_rwlock_rdlock; npth_rwlock_timedrdlock; npth_rwlock_wrlock; npth_rwlock_timedwrlock; npth_cond_wait; npth_cond_timedwait; npth_usleep; npth_sleep; npth_waitpid; npth_system; npth_sigmask; npth_sigwait; npth_connect; npth_accept; npth_select; npth_pselect; npth_read; npth_write; npth_recvmsg; npth_sendmsg; npth_unprotect; npth_protect; npth_is_protected; npth_clock_gettime; npth_sigev_init; npth_sigev_add; npth_sigev_fini; npth_sigev_sigmask; npth_sigev_get_pending; npth_getname_np; npth_setname_np; local: *; }; diff --git a/src/npth-sigev.c b/src/npth-sigev.c index 7cd609a..f5edc65 100644 --- a/src/npth-sigev.c +++ b/src/npth-sigev.c @@ -1,179 +1,170 @@ /* npth-sigev.c - signal handling interface - Copyright (C) 2011 g10 Code GmbH - - This file is part of NPTH. - - NPTH is free software; you can redistribute it and/or modify it - under the terms of either - - - the GNU Lesser General Public License as published by the Free - Software Foundation; either version 3 of the License, or (at - your option) any later version. - - or - - - the GNU General Public License as published by the Free - Software Foundation; either version 2 of the License, or (at - your option) any later version. - - or both in parallel, as here. - - NPTH is distributed in the hope that 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 copies of the GNU General Public License - and the GNU Lesser General Public License along with this program; - if not, see . */ + * Copyright (C) 2011 g10 Code GmbH + * + * This file is part of nPth. + * + * nPth is free software; you can redistribute it 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. + * + * nPth is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See + * the GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, see . + */ /* This is a support interface to make it easier to handle signals. - - The interfaces here support one (and only one) thread (here called - "main thread") in the application to monitor several signals while - selecting on filedescriptors. - - First, the main thread should call npth_sigev_init. This - initializes some global data structures used to record interesting - and pending signals. - - Then, the main thread should call npth_sigev_add for every signal - it is interested in observing, and finally npth_sigev_fini. This - will block the signal in the main threads sigmask. Note that these - signals should also be blocked in all other threads. Since they - are blocked in the main thread after calling npth_sigev_add, it is - recommended to call npth_sigev_add in the main thread before - creating any threads. - - The function npth_sigev_sigmask is a convenient function that - returns the sigmask of the thread at time of npth_sigev_init, but - with all registered signals unblocked. It is recommended to do all - other changes to the main thread's sigmask before calling - npth_sigev_init, so that the return value of npth_sigev_sigmask can - be used in the npth_pselect invocation. - - In any case, the main thread should invoke npth_pselect with a - sigmask that has all signals that should be monitored unblocked. - - After npth_pselect returns, npth_sigev_get_pending can be called in - a loop until it returns 0 to iterate over the list of pending - signals. Each time a signal is returned by that function, its - status is reset to non-pending. */ + * + * The interfaces here support one (and only one) thread (here called + * "main thread") in the application to monitor several signals while + * selecting on filedescriptors. + * + * First, the main thread should call npth_sigev_init. This + * initializes some global data structures used to record interesting + * and pending signals. + * + * Then, the main thread should call npth_sigev_add for every signal + * it is interested in observing, and finally npth_sigev_fini. This + * will block the signal in the main threads sigmask. Note that these + * signals should also be blocked in all other threads. Since they + * are blocked in the main thread after calling npth_sigev_add, it is + * recommended to call npth_sigev_add in the main thread before + * creating any threads. + * + * The function npth_sigev_sigmask is a convenient function that + * returns the sigmask of the thread at time of npth_sigev_init, but + * with all registered signals unblocked. It is recommended to do all + * other changes to the main thread's sigmask before calling + * npth_sigev_init, so that the return value of npth_sigev_sigmask can + * be used in the npth_pselect invocation. + * + * In any case, the main thread should invoke npth_pselect with a + * sigmask that has all signals that should be monitored unblocked. + * + * After npth_pselect returns, npth_sigev_get_pending can be called in + * a loop until it returns 0 to iterate over the list of pending + * signals. Each time a signal is returned by that function, its + * status is reset to non-pending. + */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include "npth.h" /* Record events that have been noticed. */ static sigset_t sigev_pending; /* The signal mask during normal operation. */ static sigset_t sigev_block; /* The signal mask during pselect. */ static sigset_t sigev_unblock; /* Registered signal numbers. Needed to iterate over sigset_t. Bah. */ #define SIGEV_MAX 32 static int sigev_signum[SIGEV_MAX]; static int sigev_signum_cnt; /* The internal handler which just sets a global flag. */ static void _sigev_handler (int signum) { sigaddset (&sigev_pending, signum); } /* Start setting up signal event handling. */ void npth_sigev_init (void) { sigemptyset (&sigev_pending); pthread_sigmask (SIG_SETMASK, NULL, &sigev_block); pthread_sigmask (SIG_SETMASK, NULL, &sigev_unblock); } /* Add signal SIGNUM to the list of watched signals. */ void npth_sigev_add (int signum) { struct sigaction sa; sigset_t ss; sigemptyset(&ss); assert (sigev_signum_cnt < SIGEV_MAX); sigev_signum[sigev_signum_cnt++] = signum; /* Make sure we can receive it. */ sigdelset (&sigev_unblock, signum); sigaddset (&sigev_block, signum); sa.sa_handler = _sigev_handler; sa.sa_mask = ss; sa.sa_flags = 0; /* NOT setting SA_RESTART! */ sigaction (signum, &sa, NULL); } #ifdef HAVE_PTHREAD_ATFORK /* There is non-POSIX operating system where fork is not available to applications. There, we have no pthread_atfork either. In such a case, we don't call pthread_atfork. */ static void restore_sigmask_for_child_process (void) { pthread_sigmask (SIG_SETMASK, &sigev_unblock, NULL); } #endif /* Finish the list of watched signals. This starts to block them, too. */ void npth_sigev_fini (void) { /* Block the interesting signals. */ pthread_sigmask (SIG_SETMASK, &sigev_block, NULL); #ifdef HAVE_PTHREAD_ATFORK pthread_atfork (NULL, NULL, restore_sigmask_for_child_process); #endif } /* Get the sigmask as needed for pselect. */ sigset_t * npth_sigev_sigmask (void) { return &sigev_unblock; } /* Return the next signal event that occured. Returns if none are left, 1 on success. */ int npth_sigev_get_pending (int *r_signum) { int i; for (i = 0; i < sigev_signum_cnt; i++) { int signum = sigev_signum[i]; if (sigismember (&sigev_pending, signum)) { sigdelset (&sigev_pending, signum); *r_signum = signum; return 1; } } return 0; } diff --git a/src/npth.c b/src/npth.c index bf5e212..f25f1d2 100644 --- a/src/npth.c +++ b/src/npth.c @@ -1,785 +1,775 @@ /* npth.c - a lightweight implementation of pth over pthread. - Copyright (C) 2011 g10 Code GmbH - - This file is part of NPTH. - - NPTH is free software; you can redistribute it and/or modify it - under the terms of either - - - the GNU Lesser General Public License as published by the Free - Software Foundation; either version 3 of the License, or (at - your option) any later version. - - or - - - the GNU General Public License as published by the Free - Software Foundation; either version 2 of the License, or (at - your option) any later version. - - or both in parallel, as here. - - NPTH is distributed in the hope that 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 copies of the GNU General Public License - and the GNU Lesser General Public License along with this program; - if not, see . */ + * Copyright (C) 2011 g10 Code GmbH + * + * This file is part of nPth. + * + * nPth is free software; you can redistribute it 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. + * + * nPth is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See + * the GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, see . + */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include #ifdef HAVE_LIB_DISPATCH # include typedef dispatch_semaphore_t sem_t; /* This glue code is for macOS which does not have full implementation of POSIX semaphore. On macOS, using semaphore in Grand Central Dispatch library is better than using the partial implementation of POSIX semaphore where sem_init doesn't work well. */ static int sem_init (sem_t *sem, int is_shared, unsigned int value) { (void)is_shared; if ((*sem = dispatch_semaphore_create (value)) == NULL) return -1; else return 0; } static int sem_post (sem_t *sem) { dispatch_semaphore_signal (*sem); return 0; } static int sem_wait (sem_t *sem) { dispatch_semaphore_wait (*sem, DISPATCH_TIME_FOREVER); return 0; } #else # include #endif #ifdef HAVE_UNISTD_H # include #endif #ifndef HAVE_PSELECT # include #endif #include "npth.h" /* The global lock that excludes all threads but one. This is a semaphore, because these can be safely used in a library even if the application or other libraries call fork(), including from a signal handler. sem_post is async-signal-safe. (The reason a semaphore is safe and a mutex is not safe is that a mutex has an owner, while a semaphore does not.) We init sceptre to a static buffer for use by sem_init; in case sem_open is used instead SCEPTRE will changed to the value returned by sem_open. GOT_SCEPTRE is a flag used for debugging to tell wether we hold SCEPTRE. */ static sem_t sceptre_buffer; static sem_t *sceptre = &sceptre_buffer; static int got_sceptre; /* Configure defines HAVE_FORK_UNSAFE_SEMAPHORE if child process can't access non-shared unnamed semaphore which is created by its parent. We use unnamed semaphore (if available) for the global lock. The specific semaphore is only valid for those threads in a process, and it is no use by other processes. Thus, PSHARED argument for sem_init is naturally 0. However, there are daemon-like applications which use fork after npth's initialization by npth_init. In this case, a child process uses the semaphore which was created by its parent process, while parent does nothing with the semaphore. In some system (e.g. AIX), access by child process to non-shared unnamed semaphore is prohibited. For such a system, HAVE_FORK_UNSAFE_SEMAPHORE should be defined, so that unnamed semaphore will be created with the option PSHARED=1. The purpose of the setting of PSHARED=1 is only for allowing the access of the lock by child process. For NPTH, it does not mean any other interactions between processes. */ #ifdef HAVE_FORK_UNSAFE_SEMAPHORE #define NPTH_SEMAPHORE_PSHARED 1 #else #define NPTH_SEMAPHORE_PSHARED 0 #endif /* The main thread is the active thread at the time pth_init was called. As of now it is only useful for debugging. The volatile make sure the compiler does not eliminate this set but not used variable. */ static volatile pthread_t main_thread; /* This flag is set as soon as npth_init has been called or if any * thread has been created. It will never be cleared again. The only * purpose is to make npth_protect and npth_unprotect more robust in * that they can be shortcut when npth_init has not yet been called. * This is important for libraries which want to support nPth by using * those two functions but may have be initialized before pPth. */ static int initialized_or_any_threads; /* Systems that don't have pthread_mutex_timedlock get a busy wait implementation that probes the lock every BUSY_WAIT_INTERVAL milliseconds. */ #define BUSY_WAIT_INTERVAL 200 typedef int (*trylock_func_t) (void *); static int busy_wait_for (trylock_func_t trylock, void *lock, const struct timespec *abstime) { int err; /* This is not great, but better than nothing. Only works for locks which are mostly uncontested. Provides absolutely no fairness at all. Creates many wake-ups. */ while (1) { struct timespec ts; err = npth_clock_gettime (&ts); if (err < 0) { /* Just for safety make sure we return some error. */ err = errno ? errno : EINVAL; break; } if (! npth_timercmp (abstime, &ts, <)) { err = ETIMEDOUT; break; } err = (*trylock) (lock); if (err != EBUSY) break; /* Try again after waiting a bit. We could calculate the maximum wait time from ts and abstime, but we don't bother, as our granularity is pretty fine. */ usleep (BUSY_WAIT_INTERVAL * 1000); } return err; } static void enter_npth (void) { int res; got_sceptre = 0; res = sem_post (sceptre); assert (res == 0); } static void leave_npth (void) { int res; int save_errno = errno; do { res = sem_wait (sceptre); } while (res < 0 && errno == EINTR); assert (!res); got_sceptre = 1; errno = save_errno; } #define ENTER() enter_npth () #define LEAVE() leave_npth () int npth_init (void) { int res; main_thread = pthread_self(); /* Track that we have been initialized. */ initialized_or_any_threads |= 1; /* Better reset ERRNO so that we know that it has been set by sem_init. */ errno = 0; /* The semaphore is binary. */ res = sem_init (sceptre, NPTH_SEMAPHORE_PSHARED, 1); /* There are some versions of operating systems which have sem_init symbol defined but the call actually returns ENOSYS at runtime. We know this problem for older versions of AIX (<= 4.3.3) and macOS. For macOS, we use semaphore in Grand Central Dispatch library, so ENOSYS doesn't happen. We only support AIX >= 5.2, where sem_init is supported. */ if (res < 0) { /* POSIX.1-2001 defines the semaphore interface but does not specify the return value for success. Thus we better bail out on error only on a POSIX.1-2008 system. */ #if _POSIX_C_SOURCE >= 200809L return errno; #endif } LEAVE(); return 0; } int npth_getname_np (npth_t target_thread, char *buf, size_t buflen) { #ifdef HAVE_PTHREAD_GETNAME_NP return pthread_getname_np (target_thread, buf, buflen); #else (void)target_thread; (void)buf; (void)buflen; return ENOSYS; #endif } int npth_setname_np (npth_t target_thread, const char *name) { #ifdef HAVE_PTHREAD_SETNAME_NP #ifdef __NetBSD__ return pthread_setname_np (target_thread, "%s", (void*) name); #else #ifdef __APPLE__ if (target_thread == npth_self ()) return pthread_setname_np (name); else return ENOTSUP; #else return pthread_setname_np (target_thread, name); #endif #endif #else (void)target_thread; (void)name; return ENOSYS; #endif } struct startup_s { void *(*start_routine) (void *); void *arg; }; static void * thread_start (void *startup_arg) { struct startup_s *startup = startup_arg; void *(*start_routine) (void *); void *arg; void *result; start_routine = startup->start_routine; arg = startup->arg; free (startup); LEAVE(); result = (*start_routine) (arg); /* Note: instead of returning here, we might end up in npth_exit() instead. */ ENTER(); return result; } int npth_create (npth_t *thread, const npth_attr_t *attr, void *(*start_routine) (void *), void *arg) { int err; struct startup_s *startup; startup = malloc (sizeof (*startup)); if (!startup) return errno; initialized_or_any_threads |= 2; startup->start_routine = start_routine; startup->arg = arg; err = pthread_create (thread, attr, thread_start, startup); if (err) { free (startup); return err; } /* Memory is released in thread_start. */ return 0; } int npth_join (npth_t thread, void **retval) { int err; #ifdef HAVE_PTHREAD_TRYJOIN_NP /* No need to allow competing threads to enter when we can get the lock immediately. pthread_tryjoin_np is a GNU extension. */ err = pthread_tryjoin_np (thread, retval); if (err != EBUSY) return err; #endif /*HAVE_PTHREAD_TRYJOIN_NP*/ ENTER(); err = pthread_join (thread, retval); LEAVE(); return err; } void npth_exit (void *retval) { ENTER(); pthread_exit (retval); /* Never reached. But just in case pthread_exit does return... */ LEAVE(); } int npth_mutex_lock (npth_mutex_t *mutex) { int err; /* No need to allow competing threads to enter when we can get the lock immediately. */ err = pthread_mutex_trylock (mutex); if (err != EBUSY) return err; ENTER(); err = pthread_mutex_lock (mutex); LEAVE(); return err; } int npth_mutex_timedlock (npth_mutex_t *mutex, const struct timespec *abstime) { int err; /* No need to allow competing threads to enter when we can get the lock immediately. */ err = pthread_mutex_trylock (mutex); if (err != EBUSY) return err; ENTER(); #if HAVE_PTHREAD_MUTEX_TIMEDLOCK err = pthread_mutex_timedlock (mutex, abstime); #else err = busy_wait_for ((trylock_func_t) pthread_mutex_trylock, mutex, abstime); #endif LEAVE(); return err; } #ifndef _NPTH_NO_RWLOCK int npth_rwlock_rdlock (npth_rwlock_t *rwlock) { int err; #ifdef HAVE_PTHREAD_RWLOCK_TRYRDLOCK /* No need to allow competing threads to enter when we can get the lock immediately. */ err = pthread_rwlock_tryrdlock (rwlock); if (err != EBUSY) return err; #endif ENTER(); err = pthread_rwlock_rdlock (rwlock); LEAVE(); return err; } int npth_rwlock_timedrdlock (npth_rwlock_t *rwlock, const struct timespec *abstime) { int err; #ifdef HAVE_PTHREAD_RWLOCK_TRYRDLOCK /* No need to allow competing threads to enter when we can get the lock immediately. */ err = pthread_rwlock_tryrdlock (rwlock); if (err != EBUSY) return err; #endif ENTER(); #if HAVE_PTHREAD_RWLOCK_TIMEDRDLOCK err = pthread_rwlock_timedrdlock (rwlock, abstime); #else err = busy_wait_for ((trylock_func_t) pthread_rwlock_tryrdlock, rwlock, abstime); #endif LEAVE(); return err; } int npth_rwlock_wrlock (npth_rwlock_t *rwlock) { int err; #ifdef HAVE_PTHREAD_RWLOCK_TRYWRLOCK /* No need to allow competing threads to enter when we can get the lock immediately. */ err = pthread_rwlock_trywrlock (rwlock); if (err != EBUSY) return err; #endif ENTER(); err = pthread_rwlock_wrlock (rwlock); LEAVE(); return err; } int npth_rwlock_timedwrlock (npth_rwlock_t *rwlock, const struct timespec *abstime) { int err; #ifdef HAVE_PTHREAD_RWLOCK_TRYWRLOCK /* No need to allow competing threads to enter when we can get the lock immediately. */ err = pthread_rwlock_trywrlock (rwlock); if (err != EBUSY) return err; #endif ENTER(); #if HAVE_PTHREAD_RWLOCK_TIMEDWRLOCK err = pthread_rwlock_timedwrlock (rwlock, abstime); #elif HAVE_PTHREAD_RWLOCK_TRYRDLOCK err = busy_wait_for ((trylock_func_t) pthread_rwlock_trywrlock, rwlock, abstime); #else err = ENOSYS; #endif LEAVE(); return err; } #endif int npth_cond_wait (npth_cond_t *cond, npth_mutex_t *mutex) { int err; ENTER(); err = pthread_cond_wait (cond, mutex); LEAVE(); return err; } int npth_cond_timedwait (npth_cond_t *cond, npth_mutex_t *mutex, const struct timespec *abstime) { int err; ENTER(); err = pthread_cond_timedwait (cond, mutex, abstime); LEAVE(); return err; } /* Standard POSIX Replacement API */ int npth_usleep(unsigned int usec) { int res; ENTER(); res = usleep(usec); LEAVE(); return res; } unsigned int npth_sleep(unsigned int sec) { unsigned res; ENTER(); res = sleep(sec); LEAVE(); return res; } int npth_system(const char *cmd) { int res; ENTER(); res = system(cmd); LEAVE(); return res; } pid_t npth_waitpid(pid_t pid, int *status, int options) { pid_t res; ENTER(); res = waitpid(pid,status, options); LEAVE(); return res; } int npth_connect(int s, const struct sockaddr *addr, socklen_t addrlen) { int res; ENTER(); res = connect(s, addr, addrlen); LEAVE(); return res; } int npth_accept(int s, struct sockaddr *addr, socklen_t *addrlen) { int res; ENTER(); res = accept(s, addr, addrlen); LEAVE(); return res; } int npth_select(int nfd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *timeout) { int res; ENTER(); res = select(nfd, rfds, wfds, efds, timeout); LEAVE(); return res; } int npth_pselect(int nfd, fd_set *rfds, fd_set *wfds, fd_set *efds, const struct timespec *timeout, const sigset_t *sigmask) { int res; ENTER(); #ifdef HAVE_PSELECT res = pselect (nfd, rfds, wfds, efds, timeout, sigmask); #else /*!HAVE_PSELECT*/ { /* A better emulation of pselect would be to create a pipe, wait in the select for one end and have a signal handler write to the other end. However, this is non-trivial to implement and thus we only print a compile time warning. */ # ifdef __GNUC__ # warning Using a non race free pselect emulation. # endif struct timeval t, *tp; tp = NULL; if (!timeout) ; else if (timeout->tv_nsec >= 0 && timeout->tv_nsec < 1000000000) { t.tv_sec = timeout->tv_sec; t.tv_usec = (timeout->tv_nsec + 999) / 1000; tp = &t; } else { errno = EINVAL; res = -1; goto leave; } if (sigmask) { int save_errno; sigset_t savemask; pthread_sigmask (SIG_SETMASK, sigmask, &savemask); res = select (nfd, rfds, wfds, efds, tp); save_errno = errno; pthread_sigmask (SIG_SETMASK, &savemask, NULL); errno = save_errno; } else res = select (nfd, rfds, wfds, efds, tp); leave: ; } #endif /*!HAVE_PSELECT*/ LEAVE(); return res; } ssize_t npth_read(int fd, void *buf, size_t nbytes) { ssize_t res; ENTER(); res = read(fd, buf, nbytes); LEAVE(); return res; } ssize_t npth_write(int fd, const void *buf, size_t nbytes) { ssize_t res; ENTER(); res = write(fd, buf, nbytes); LEAVE(); return res; } int npth_recvmsg (int fd, struct msghdr *msg, int flags) { int res; ENTER(); res = recvmsg (fd, msg, flags); LEAVE(); return res; } int npth_sendmsg (int fd, const struct msghdr *msg, int flags) { int res; ENTER(); res = sendmsg (fd, msg, flags); LEAVE(); return res; } void npth_unprotect (void) { /* If we are not initialized we may not access the semaphore and * thus we shortcut it. Note that in this case the unprotect/protect * is not needed. For failsafe reasons if an nPth thread has ever * been created but nPth has accidentally not initialized we do not * shortcut so that a stack backtrace (due to the access of the * uninitialized semaphore) is more expressive. */ if (initialized_or_any_threads) ENTER(); } void npth_protect (void) { /* See npth_unprotect for commentary. */ if (initialized_or_any_threads) LEAVE(); } int npth_is_protected (void) { return got_sceptre; } int npth_clock_gettime (struct timespec *ts) { #if defined(CLOCK_REALTIME) && HAVE_CLOCK_GETTIME return clock_gettime (CLOCK_REALTIME, ts); #elif HAVE_GETTIMEOFDAY { struct timeval tv; if (gettimeofday (&tv, NULL)) return -1; ts->tv_sec = tv.tv_sec; ts->tv_nsec = tv.tv_usec * 1000; return 0; } #else /* FIXME: fall back on time() with seconds resolution. */ # error clock_gettime not available - please provide a fallback. #endif } diff --git a/src/npth.h.in b/src/npth.h.in index 207a06c..39dcf32 100644 --- a/src/npth.h.in +++ b/src/npth.h.in @@ -1,463 +1,452 @@ /* npth.h - a lightweight implementation of pth over pthread. * Configured for: @NPTH_CONFIG_HOST@. * Copyright (C) 2011, 2012, 2015, 2017 g10 Code GmbH * - * This file is part of NPTH. + * This file is part of nPth. * - * NPTH is free software; you can redistribute it and/or modify it - * under the terms of either + * nPth is free software; you can redistribute it 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. * - * - the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 3 of the License, or (at - * your option) any later version. + * nPth is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See + * the GNU Lesser General Public License for more details. * - * or - * - * - the GNU General Public License as published by the Free - * Software Foundation; either version 2 of the License, or (at - * your option) any later version. - * - * or both in parallel, as here. - * - * NPTH is distributed in the hope that 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 copies of the GNU General Public License - * and the GNU Lesser General Public License along with this program; - * if not, see . + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, see . */ /* Changes to GNU Pth: * * Return value and arguments follow strictly the pthread format: * * - Return the error number instead of setting errno, * * - have timedlock function instead of extra event argument, * * - have trylock function instead of extra event argument. Can't mix * timed and try. * * - No _new functions. Use _init functions instead. * * - Attributes are set by specific instead of generic getter/setter * functions. * * - Offers replacement functions for sendmsg and recvmsg. */ #ifndef _NPTH_H #define _NPTH_H #include #include #@INSERT_SYS_TIME_H@ #@INSERT_TIME_H@ #include #@INSERT_SOCKLEN_T@ #@INSERT_SYS_SELECT_H@ #@INSERT_SIGNAL_H@ #include #ifdef __ANDROID__ #include #if __ANDROID_API__ < 9 /* Android 8 and earlier are missing rwlocks. We punt to mutexes in that case. */ #define _NPTH_NO_RWLOCK 1 #endif #endif #ifdef __cplusplus extern "C" { #if 0 /* (Keep Emacsens' auto-indent happy.) */ } #endif #endif /* Global Library Management */ #define npth_t pthread_t /* Initialize the library and convert current thread to main thread. Must be first npth function called in a process. Returns error number on error and 0 on success. */ int npth_init(void); /* Not needed. */ /* pth_kill, pth_ctrl, pth_version */ /* Thread Attribute Handling */ /* Can't do that. */ /* pth_attr_of */ #define npth_attr_t pthread_attr_t #define npth_attr_init pthread_attr_init #define npth_attr_destroy pthread_attr_destroy #define NPTH_CREATE_JOINABLE PTHREAD_CREATE_JOINABLE #define NPTH_CREATE_DETACHED PTHREAD_CREATE_DETACHED #define npth_attr_getdetachstate pthread_attr_getdetachstate #define npth_attr_setdetachstate pthread_attr_setdetachstate int npth_getname_np (npth_t target_thread, char *buf, size_t buflen); int npth_setname_np (npth_t target_thread, const char *name); /* Thread Control */ int npth_create(npth_t *thread, const npth_attr_t *attr, void *(*start_routine) (void *), void *arg); /* The Pth version of pth_once supports passing an argument, the pthread version does not. We would have to reimplement the whole feature with a global table. Not needed. */ /* pth_once */ #define npth_self pthread_self /* No can do! */ /* pth_suspend, pth_resume */ /* Yield is considered harmful and should never be used in high-level applications. Use a condition instead to wait for a specific event to happen, or, as a last resort, use npth_usleep to back off a hard busy wait. */ /* pth_yield */ /* Not needed. */ /* pth_nap */ /* pth_wait, pth_cancel, pth_abort, pth_raise */ int npth_join(npth_t thread, void **retval); #define npth_detach pthread_detach void npth_exit(void *retval); /* Utilities */ /* pth_fdmode, pth_time, pth_timeout, pth_sfiodisc */ /* Cancellation Management */ /* Not needed. */ /* pth_cancel_state. npth_cancel_point */ /* Event Handling */ /* No equivalent in pthread. */ /* pth_event, pth_event_typeof, pth_event_extract, pth_event_concat, pth_event_isolate, pth_event_walk, pth_event_status, pth_event_free */ /* Key-Based Storage */ #define npth_key_t pthread_key_t #define npth_key_create pthread_key_create #define npth_key_delete pthread_key_delete #define npth_setspecific pthread_setspecific #define npth_getspecific pthread_getspecific /* Message Port Communication */ /* No equivalent in pthread. */ /* pth_msgport_create, pth_msgport_destroy, pth_msgport_find, pth_msgport_pending, pth_msgport_put, pth_msgport_get, pth_msgport_reply. */ /* Thread Cleanups */ /* Not needed. */ /* pth_cleanup_push, pth_cleanup_pop */ /* Process Forking */ /* POSIX only supports a global atfork handler. So, to implement per-thread handlers like in Pth, we would need to keep the data in thread local storage. But, neither pthread_self nor pthread_getspecific are standardized as async-signal-safe (what a joke!), and __thread is an ELF extension. Still, using pthread_self and pthread_getspecific is probably portable enough to implement the atfork handlers, if required. pth_fork is only required because fork() is not pth aware. fork() is pthread aware though, and already only creates a single thread in the child process. */ /* pth_atfork_push, pth_atfork_pop, pth_fork */ /* Synchronization */ #define npth_mutexattr_t pthread_mutexattr_t #define npth_mutexattr_init pthread_mutexattr_init #define npth_mutexattr_destroy pthread_mutexattr_destroy #define npth_mutexattr_settype pthread_mutexattr_settype #define npth_mutexattr_gettype pthread_mutexattr_gettype #define NPTH_MUTEX_NORMAL PTHREAD_MUTEX_NORMAL #define NPTH_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE #define NPTH_MUTEX_ERRORCHECK PTHREAD_MUTEX_ERRORCHECK #define NPTH_MUTEX_DEFAULT PTHREAD_MUTEX_DEFAULT #define npth_mutex_t pthread_mutex_t #define NPTH_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER #define NPTH_RECURSIVE_MUTEX_INITIALIZER_NP \ PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP #define NPTH_ERRORCHECK_MUTEX_INITIALIZER_NP \ PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP #define npth_mutex_init pthread_mutex_init #define npth_mutex_destroy pthread_mutex_destroy #define npth_mutex_trylock pthread_mutex_trylock int npth_mutex_lock(npth_mutex_t *mutex); int npth_mutex_timedlock(npth_mutex_t *mutex, const struct timespec *abstime); #define npth_mutex_unlock pthread_mutex_unlock #ifdef _NPTH_NO_RWLOCK typedef int npth_rwlockattr_t; #define npth_rwlockattr_init(attr) #define npth_rwlockattr_destroy(attr) #define npth_rwlockattr_gettype_np(attr,kind) #define npth_rwlockattr_settype_np(attr,kind) #define NPTH_RWLOCK_PREFER_READER_NP 0 #define NPTH_RWLOCK_PREFER_WRITER_NP 0 #define NPTH_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP 0 #define NPTH_RWLOCK_DEFAULT_NP 0 #define NPTH_RWLOCK_INITIALIZER NPTH_MUTEX_INITIALIZER #define NPTH_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP NPTH_MUTEX_INITIALIZER typedef npth_mutex_t npth_rwlock_t; #define npth_rwlock_init(rwlock,attr) npth_mutex_init(rwlock,0) #define npth_rwlock_destroy npth_mutex_destroy #define npth_rwlock_tryrdlock npth_mutex_trylock #define npth_rwlock_rdlock npth_mutex_lock #define npth_rwlock_trywrlock npth_mutex_trylock #define npth_rwlock_timedrdlock npth_mutex_timedlock #define npth_rwlock_wrlock npth_mutex_lock #define npth_rwlock_rdlock npth_mutex_lock #define npth_rwlock_timedwrlock npth_mutex_timedlock #define npth_rwlock_unlock npth_mutex_unlock #else /* _NPTH_NO_RWLOCK */ #define npth_rwlockattr_t pthread_rwlockattr_t #define npth_rwlockattr_init pthread_rwlockattr_init #define npth_rwlockattr_destroy pthread_rwlockattr_destroy #define npth_rwlockattr_gettype_np pthread_rwlockattr_gettype_np #define npth_rwlockattr_settype_np pthread_rwlockattr_settype_np #define NPTH_RWLOCK_PREFER_READER_NP PTHREAD_RWLOCK_PREFER_READER_NP /* Note: The prefer-writer setting is ineffective and the same as prefer-reader. This is because reader locks are specified to be recursive, but for efficiency reasons we do not keep track of which threads already hold a reader lock. For this reason, we can not prefer some reader locks over others, and thus a recursive reader lock could be stalled by a pending writer, leading to a dead lock. */ #define NPTH_RWLOCK_PREFER_WRITER_NP PTHREAD_RWLOCK_PREFER_WRITER_NP /* The non-recursive choise is a promise by the application that it does not lock the rwlock for reading recursively. In this setting, writers are preferred, but note that recursive reader locking is prone to deadlocks in that case. */ #define NPTH_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP \ PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP #define NPTH_RWLOCK_DEFAULT_NP PTHREAD_RWLOCK_DEFAULT_NP #define NPTH_RWLOCK_INITIALIZER PTHREAD_RWLOCK_INITIALIZER #define NPTH_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP \ PTHREAD_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP typedef pthread_rwlock_t npth_rwlock_t; #define npth_rwlock_init pthread_rwlock_init #define npth_rwlock_destroy pthread_rwlock_destroy #define npth_rwlock_tryrdlock pthread_rwlock_tryrdlock int npth_rwlock_rdlock (npth_rwlock_t *rwlock); int npth_rwlock_timedrdlock (npth_rwlock_t *rwlock, const struct timespec *abstime); #define npth_rwlock_trywrlock pthread_rwlock_trywrlock int npth_rwlock_wrlock (npth_rwlock_t *rwlock); int npth_rwlock_timedwrlock (npth_rwlock_t *rwlock, const struct timespec *abstime); #define npth_rwlock_unlock pthread_rwlock_unlock #endif /* !_NPTH_NO_RWLOCK */ typedef pthread_cond_t npth_cond_t; #define NPTH_COND_INITIALIZER PTHREAD_COND_INITIALIZER /* For now, we don't support any cond attributes. */ #define npth_cond_init pthread_cond_init #define npth_cond_broadcast pthread_cond_broadcast #define npth_cond_signal pthread_cond_signal #define npth_cond_destroy pthread_cond_destroy int npth_cond_wait(npth_cond_t *cond, npth_mutex_t *mutex); int npth_cond_timedwait(npth_cond_t *cond, npth_mutex_t *mutex, const struct timespec *abstime); /* Not needed. */ /* pth_barrier_t, pth_barrier_init, pth_barrier_reach */ /* User-Space Context */ /* Can not be implemented. */ /* pth_uctx_create, pth_uctx_make, pth_uctx_switch, pth_uctx_destroy */ /* Generalized POSIX Replacement API */ /* In general, we can not support these easily. */ /* pth_sigwait_ev, pth_accept_ev, pth_connect_ev, pth_select_ev, pth_poll_ev, pth_read_ev, pth_readv_ev, pth_write_ev, pth_writev_ev, pth_recv_ev, pth_recvfrom_ev, pth_send_ev, pth_sendto_ev */ /* Standard POSIX Replacement API */ /* We will provide a more specific way to handle signals. */ /* pth_sigmask, pth_sigwait */ /* Not needed. */ /* pth_nanosleep, pth_system, pth_readv, pth_writev, pth_poll, pth_recv, pth_send, pth_recvfrom, pth_sendto */ int npth_usleep(unsigned int usec); unsigned int npth_sleep(unsigned int sec); pid_t npth_waitpid(pid_t pid, int *status, int options); int npth_system(const char *cmd); #define npth_sigmask pthread_sigmask int npth_sigwait(const sigset_t *set, int *sig); int npth_connect(int s, const struct sockaddr *addr, _npth_socklen_t addrlen); int npth_accept(int s, struct sockaddr *addr, _npth_socklen_t *addrlen); int npth_select(int nfd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *timeout); int npth_pselect(int nfd, fd_set *rfds, fd_set *wfds, fd_set *efds, const struct timespec *timeout, const sigset_t *sigmask); ssize_t npth_read(int fd, void *buf, size_t nbytes); ssize_t npth_write(int fd, const void *buf, size_t nbytes); int npth_recvmsg (int fd, struct msghdr *msg, int flags); int npth_sendmsg (int fd, const struct msghdr *msg, int flags); /* For anything not covered here, you can enter/leave manually at your own risk. */ void npth_unprotect (void); void npth_protect (void); /* If you run into problems with the above calls, this function can be * used to examine in which state nPth is. */ int npth_is_protected (void); /* Because the timed functions work on timespec, we provide a clock interface for convenience and portability. */ int npth_clock_gettime (struct timespec *tp); /* CMP may be ==, < or >. Do not use <= or >=. */ #define npth_timercmp(t1, t2, cmp) \ (((t1)->tv_sec == (t2)->tv_sec) ? \ ((t1)->tv_nsec cmp (t2)->tv_nsec) : \ ((t1)->tv_sec cmp (t2)->tv_sec)) #define npth_timeradd(t1, t2, result) \ do { \ (result)->tv_sec = (t1)->tv_sec + (t2)->tv_sec; \ (result)->tv_nsec = (t1)->tv_nsec + (t2)->tv_nsec; \ if ((result)->tv_nsec >= 1000000000) \ { \ ++(result)->tv_sec; \ (result)->tv_nsec -= 1000000000; \ } \ } while (0) #define npth_timersub(t1, t2, result) \ do { \ (result)->tv_sec = (t1)->tv_sec - (t2)->tv_sec; \ (result)->tv_nsec = (t1)->tv_nsec - (t2)->tv_nsec; \ if ((result)->tv_nsec < 0) { \ --(result)->tv_sec; \ (result)->tv_nsec += 1000000000; \ } \ } while (0) /* This is a support interface to make it easier to handle signals. * * The interfaces here support one (and only one) thread (here called * "main thread") in the application to monitor several signals while * selecting on filedescriptors. * * First, the main thread should call npth_sigev_init. This * initializes some global data structures used to record interesting * and pending signals. * * Then, the main thread should call npth_sigev_add for every signal * it is interested in observing, and finally npth_sigev_fini. This * will block the signal in the main threads sigmask. Note that these * signals should also be blocked in all other threads. Since they * are blocked in the main thread after calling npth_sigev_add, it is * recommended to call npth_sigev_add in the main thread before * creating any threads. * * The function npth_sigev_sigmask is a convenient function that * returns the sigmask of the thread at time of npth_sigev_init, but * with all registered signals unblocked. It is recommended to do all * other changes to the main thread's sigmask before calling * npth_sigev_init, so that the return value of npth_sigev_sigmask can * be used in the npth_pselect invocation. * * In any case, the main thread should invoke npth_pselect with a * sigmask that has all signals that should be monitored unblocked. * * After npth_pselect returns, npth_sigev_get_pending can be called in * a loop until it returns 0 to iterate over the list of pending * signals. Each time a signal is returned by that function, its * status is reset to non-pending. */ /* Start setting up signal event handling. */ void npth_sigev_init (void); /* Add signal SIGNUM to the list of watched signals. */ void npth_sigev_add (int signum); /* Finish the list of watched signals. This starts to block them, too. */ void npth_sigev_fini (void); /* Get the sigmask as needed for pselect. */ sigset_t *npth_sigev_sigmask (void); /* Return the next signal event that occured. Returns if none are left, 1 on success. */ int npth_sigev_get_pending (int *r_signum); #if 0 /* (Keep Emacsens' auto-indent happy.) */ { #endif #ifdef __cplusplus } #endif #endif /*_NPTH_H*/ /* @emacs_local_vars_begin@ @emacs_local_vars_read_only@ @emacs_local_vars_end@ */ diff --git a/tests/Makefile.am b/tests/Makefile.am index 2a0542b..8092a3c 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -1,48 +1,38 @@ # Makefile.am - Makefile for NPTH tests. # Copyright (C) 2011 g10 Code GmbH # -# This file is part of NPTH. +# This file is part of nPth. # -# NPTH is free software; you can redistribute it and/or modify it -# under the terms of either +# nPth is free software; you can redistribute it 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. # -# - the GNU Lesser General Public License as published by the Free -# Software Foundation; either version 3 of the License, or (at -# your option) any later version. -# -# or -# -# - the GNU General Public License as published by the Free -# Software Foundation; either version 2 of the License, or (at -# your option) any later version. -# -# or both in parallel, as here. -# -# NPTH is distributed in the hope that it will be useful, but WITHOUT +# nPth is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General # Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, see . ## Process this file with automake to produce Makefile.in TESTS = t-mutex t-thread # We explicitly require POSIX.1-2001 so that pthread_rwlock_t is # available when build with c99. if HAVE_W32_SYSTEM AM_CPPFLAGS = -I$(top_srcdir)/w32 AM_LDFLAGS = LDADD = ../w32/libnpth.la $(LIB_CLOCK_GETTIME) else AM_CPPFLAGS = -I../src -D_POSIX_C_SOURCE=200112L AM_LDFLAGS = LDADD = ../src/libnpth.la $(LIBSOCKET) $(LIB_CLOCK_GETTIME) TESTS += t-fork endif noinst_HEADERS = t-support.h noinst_PROGRAMS = $(TESTS) diff --git a/w32/Makefile.am b/w32/Makefile.am index eb41a63..ca2acb4 100644 --- a/w32/Makefile.am +++ b/w32/Makefile.am @@ -1,73 +1,63 @@ -# Makefile.am - src/ Makefile for npth. +# Makefile.am - w32 Makefile for nPth. # Copyright (C) 2011 g10 Code GmbH # -# This file is part of NPTH. +# This file is part of nPth. # -# NPTH is free software; you can redistribute it and/or modify it -# under the terms of either +# nPth is free software; you can redistribute it 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. # -# - the GNU Lesser General Public License as published by the Free -# Software Foundation; either version 3 of the License, or (at -# your option) any later version. -# -# or -# -# - the GNU General Public License as published by the Free -# Software Foundation; either version 2 of the License, or (at -# your option) any later version. -# -# or both in parallel, as here. -# -# NPTH is distributed in the hope that it will be useful, but WITHOUT +# nPth is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General # Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, see . ## Process this file with automake to produce Makefile.in # Note: This directory is only used for W32 EXTRA_DIST = npth.def nodist_include_HEADERS = npth.h lib_LTLIBRARIES = libnpth.la libnpth_la_SOURCES = npth.h npth.c # AM_CPPFLAGS = # AM_CFLAGS = RCCOMPILE = $(RC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) LTRCCOMPILE = $(LIBTOOL) --mode=compile --tag=RC $(RCCOMPILE) SUFFIXES = .rc .lo .rc.lo: $(LTRCCOMPILE) -i "$<" -o "$@" npth_res = versioninfo.lo no_undefined = -no-undefined export_symbols = -export-symbols $(srcdir)/npth.def extra_ltoptions = -XCClinker -static-libgcc install-def-file: $(INSTALL) $(srcdir)/npth.def $(DESTDIR)$(libdir)/npth.def uninstall-def-file: -rm $(DESTDIR)$(libdir)/npth.def gpgme_deps = $(gpgme_res) npth.def libnpth_la_LDFLAGS = $(no_undefined) $(export_symbols) $(extra_ltoptions) \ -version-info \ @LIBNPTH_LT_CURRENT@:@LIBNPTH_LT_REVISION@:@LIBNPTH_LT_AGE@ libnpth_la_DEPENDENCIES = $(npth_deps) libnpth_la_LIBADD = @NETLIBS@ install-data-local: install-def-file uninstall-local: uninstall-def-file diff --git a/w32/npth.c b/w32/npth.c index 3b760e9..1dad63e 100644 --- a/w32/npth.c +++ b/w32/npth.c @@ -1,2045 +1,2035 @@ -/* npth.c - a lightweight implementation of pth over pthread. - Copyright (C) 2011, 2014 g10 Code GmbH - - This file is part of NPTH. - - NPTH is free software; you can redistribute it and/or modify it - under the terms of either - - - the GNU Lesser General Public License as published by the Free - Software Foundation; either version 3 of the License, or (at - your option) any later version. - - or - - - the GNU General Public License as published by the Free - Software Foundation; either version 2 of the License, or (at - your option) any later version. - - or both in parallel, as here. - - NPTH is distributed in the hope that 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 copies of the GNU General Public License - and the GNU Lesser General Public License along with this program; - if not, see . */ +/* npth.c - a lightweight implementation of pth over native threads + * Copyright (C) 2011, 2014 g10 Code GmbH + * + * This file is part of nPth. + * + * nPth is free software; you can redistribute it 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. + * + * nPth is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See + * the GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, see . + */ /* We implement the join mechanism ourself. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include "npth.h" #include #define DEBUG_CALLS 1 #define _npth_debug(x, ...) fprintf(stderr, __VA_ARGS__) #ifndef TEST #undef DEBUG_CALLS #define DEBUG_CALLS 0 #undef _npth_debug #define _npth_debug(x, ...) #endif /* This seems to be a common standard. */ #define THREAD_NAME_MAX 15 /* The global lock that excludes all threads but one. Note that this implements the single-user-thread policy, but also protects all our global data such as the thread_table. GOT_SCEPTRE is a flag used for debugging to tell wether we hold SCEPTRE. */ static CRITICAL_SECTION sceptre; static int got_sceptre; /* This flag is set as soon as npth_init has been called or if any * thread has been created. It will never be cleared again. The only * purpose is to make npth_protect and npth_unprotect more robust in * that they can be shortcut when npth_init has not yet been called. * This is important for libraries which want to support nPth by using * those two functions but may have been initialized before nPth. */ static int initialized_or_any_threads; typedef struct npth_impl_s *npth_impl_t; #define MAX_THREADS 1024 #define INVALID_THREAD_ID 0 /* Thread ID to thread context table. We never allocate ID 0. */ static npth_impl_t thread_table[MAX_THREADS]; /* The TLS index to store thread ID of the current thread. Used to make faster lookups of the thread data. */ DWORD tls_index; /* Map a windows error value (GetLastError) to a POSIX error value. */ static int map_error (int winerr) { /* FIXME */ return EIO; } static int wait_for_single_object (HANDLE obj, DWORD msecs) { DWORD res; res = WaitForSingleObject(obj, msecs); if (res == WAIT_ABANDONED) return EDEADLK; else if (res == WAIT_TIMEOUT) return ETIMEDOUT; else if (res == WAIT_FAILED) return map_error (GetLastError()); else if (res != WAIT_OBJECT_0) return EINTR; else return 0; } int npth_clock_gettime(struct timespec *tp) { FILETIME ftime; ULARGE_INTEGER systime; unsigned long long usecs; GetSystemTimeAsFileTime (&ftime); systime.LowPart = ftime.dwLowDateTime; systime.HighPart = ftime.dwHighDateTime; /* systime.QuadPart has the 100-nanosecond intervals since Jan 1, 1601. */ tp->tv_sec = systime.QuadPart / 10000000ULL; tp->tv_nsec = (systime.QuadPart * 100ULL) % 1000000000ULL; return 0; } static int calculate_timeout (const struct timespec *abstime, DWORD *msecs_r) { struct timespec tp; struct timespec tp_delta; DWORD msecs; npth_clock_gettime (&tp); /* Make sure there is a positive time delta. */ if (!(npth_timercmp (&tp, abstime, <))) return ETIMEDOUT; npth_timersub (abstime, &tp, &tp_delta); /* Make sure to round up to at least one millisecond. Note that within reasonable timeouts and the above macros, we should always end up with a positive wait time here. */ msecs = (tp_delta.tv_sec * 1000) + (tp_delta.tv_nsec + 999999) / 1000000; if (msecs < 1) { /* Log a critical error here. */ return ETIMEDOUT; } *msecs_r = msecs; return 0; } static void enter_npth (const char *function) { int res; if (DEBUG_CALLS) _npth_debug (DEBUG_CALLS, "tid %lu: enter_npth (%s)\n", npth_self (), function ? function : "unknown"); got_sceptre = 0; LeaveCriticalSection (&sceptre); } static void leave_npth (const char *function) { EnterCriticalSection (&sceptre); got_sceptre = 1; if (DEBUG_CALLS) _npth_debug (DEBUG_CALLS, "tid %lu: leave_npth (%s)\n", npth_self (), function ? function : ""); } #define ENTER() enter_npth(__FUNCTION__) #define LEAVE() leave_npth(__FUNCTION__) struct npth_impl_s { /* Usually there is one ref owned by the thread as long as it is running, and one ref for everybody else as long as the thread is joinable. */ int refs; HANDLE handle; /* True if thread is detached. */ int detached; /* The start routine and arg. */ void *(*start_routine) (void *); void *start_arg; char name[THREAD_NAME_MAX + 1]; /* Doubly-linked list for the waiter queue in condition variables. */ npth_impl_t next; npth_impl_t *prev_ptr; /* The event on which this thread waits when it is queued. */ HANDLE event; void *result; }; static void dequeue_thread (npth_impl_t thread) { /* Unlink the thread from any condition waiter queue. */ if (thread->next) { thread->next->prev_ptr = thread->prev_ptr; thread->next = NULL; } if (thread->prev_ptr) { *(thread->prev_ptr) = thread->next; thread->prev_ptr = NULL; } } /* Enqueue THREAD to come after the thread whose next pointer is prev_ptr. */ static void enqueue_thread (npth_impl_t thread, npth_impl_t *prev_ptr) { if (*prev_ptr) (*prev_ptr)->prev_ptr = &thread->next; thread->prev_ptr = prev_ptr; thread->next = *prev_ptr; *prev_ptr = thread; } static int find_thread (npth_t thread_id, npth_impl_t *thread) { if (thread_id < 1 || thread_id >= MAX_THREADS) return ESRCH; if (! thread_table[thread_id]) return ESRCH; *thread = thread_table[thread_id]; return 0; } static int new_thread (npth_t *thread_id) { npth_impl_t thread; int id; /* ID 0 is never allocated. */ for (id = 1; id < MAX_THREADS; id++) if (! thread_table[id]) break; if (id == MAX_THREADS) return EAGAIN; thread = malloc (sizeof (*thread)); if (! thread) return errno; thread->refs = 1; thread->handle = INVALID_HANDLE_VALUE; thread->detached = 0; thread->start_routine = NULL; thread->start_arg = NULL; thread->next = NULL; thread->prev_ptr = NULL; /* We create the event when it is first needed (not all threads wait on conditions). */ thread->event = INVALID_HANDLE_VALUE; memset (thread->name, '\0', sizeof (thread->name)); thread_table[id] = thread; *thread_id = id; return 0; } static void free_thread (npth_t thread_id) { npth_impl_t thread = thread_table[thread_id]; if (thread->handle) CloseHandle (thread->handle); /* Unlink the thread from any condition waiter queue. */ dequeue_thread (thread); free (thread); thread_table[thread_id] = NULL; } static void deref_thread (npth_t thread_id) { npth_impl_t thread = thread_table[thread_id]; thread->refs -= 1; if (thread->refs == 0) free_thread (thread_id); } int npth_init (void) { int err; npth_t thread_id; BOOL res; HANDLE handle; npth_impl_t thread; InitializeCriticalSection (&sceptre); /* Track that we have been initialized. */ initialized_or_any_threads = 1; /* Fake a thread table item for the main thread. */ tls_index = TlsAlloc(); if (tls_index == TLS_OUT_OF_INDEXES) return map_error (GetLastError()); err = new_thread(&thread_id); if (err) return err; /* GetCurrentThread() is not usable by other threads, so it needs to be duplicated. */ res = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &handle, 0, FALSE, DUPLICATE_SAME_ACCESS); if (!res) { free_thread (thread_id); return map_error(GetLastError()); } thread = thread_table[thread_id]; thread->handle = handle; if (! TlsSetValue(tls_index, (LPVOID) thread_id)) return map_error (GetLastError()); LEAVE(); return 0; } struct npth_attr_s { int detachstate; }; int npth_attr_init (npth_attr_t *attr_r) { npth_attr_t attr; attr = malloc (sizeof *attr); if (!attr) return errno; attr->detachstate = NPTH_CREATE_JOINABLE; *attr_r = attr; return 0; } int npth_attr_destroy (npth_attr_t *attr) { free (*attr); return 0; } int npth_attr_getdetachstate (npth_attr_t *attr, int *detachstate) { *detachstate = (*attr)->detachstate; return 0; } int npth_attr_setdetachstate (npth_attr_t *attr, int detachstate) { if (detachstate != NPTH_CREATE_JOINABLE && detachstate != NPTH_CREATE_DETACHED) return EINVAL; (*attr)->detachstate = detachstate; return 0; } int npth_getname_np (npth_t target_thread, char *buf, size_t buflen) { npth_impl_t thread; int err; if (buflen < THREAD_NAME_MAX + 1) return ERANGE; err = find_thread (target_thread, &thread); if (err) return err; strcpy (buf, thread->name); return 0; } int npth_setname_np (npth_t target_thread, const char *name) { npth_impl_t thread; int err; if (strlen(name) > THREAD_NAME_MAX) return ERANGE; err = find_thread (target_thread, &thread); if (err) return err; strcpy (thread->name, name); return 0; } static DWORD thread_start (void *arg) { npth_t thread_id = (npth_t) arg; npth_impl_t thread; void *result; if (! TlsSetValue(tls_index, (LPVOID) thread_id)) /* FIXME: There is not much we can do here. */ ; LEAVE(); /* We must be protected here, because we access the global thread_table. */ thread = thread_table[thread_id]; result = thread->start_routine (thread->start_arg); /* We might not return here if the thread calls npth_exit(). */ thread->result = result; /* Any joiner will be signaled once we terminate. */ deref_thread (thread_id); ENTER(); /* We can not return result, as that is a void*, not a DWORD. */ return 0; } int npth_create (npth_t *newthread, const npth_attr_t *user_attr, void *(*start_routine) (void *), void *start_arg) { int err = 0; npth_t thread_id = INVALID_THREAD_ID; npth_attr_t attr; int attr_allocated; npth_impl_t thread; HANDLE handle; /* We must stay protected here, because we access the global thread_table. Also, creating a new thread is not a blocking operation. */ if (user_attr) { attr = *user_attr; attr_allocated = 0; } else { err = npth_attr_init (&attr); if (err) return err; attr_allocated = 1; } err = new_thread (&thread_id); if (err) goto err_out; thread = thread_table[thread_id]; if (attr->detachstate == NPTH_CREATE_DETACHED) thread->detached = 1; else thread->refs += 1; thread->start_routine = start_routine; thread->start_arg = start_arg; handle = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)thread_start, (void *) thread_id, CREATE_SUSPENDED, NULL); if (handle == NULL) { err = map_error (GetLastError()); goto err_out; } thread->handle = handle; *newthread = thread_id; ResumeThread (thread->handle); return 0; err_out: if (thread_id) free_thread (thread_id); if (attr_allocated) npth_attr_destroy (&attr); return err; } npth_t npth_self (void) { LPVOID thread_id; thread_id = TlsGetValue (tls_index); if (thread_id == 0 && GetLastError() != ERROR_SUCCESS) /* FIXME: Log the error. */ ; return (npth_t) thread_id; } /* Not part of the public interface at the moment, thus static. */ static int npth_tryjoin_np (npth_t thread_id, void **thread_return) { int err; npth_impl_t thread; int res; err = find_thread (thread_id, &thread); if (err) return err; if (thread->detached) return EINVAL; /* No need to allow competing threads to enter when we can get the lock immediately. */ err = wait_for_single_object (thread->handle, 0); if (err == ETIMEDOUT) err = EBUSY; if (err) return err; if (thread_return) *thread_return = thread->result; deref_thread (thread_id); return 0; } int npth_join (npth_t thread_id, void **thread_return) { int err; npth_impl_t thread; int res; /* No need to allow competing threads to enter when we can get the lock immediately. */ err = npth_tryjoin_np (thread_id, thread_return); if (err != EBUSY) return err; err = find_thread (thread_id, &thread); if (err) return err; if (thread->detached) return EINVAL; ENTER(); err = wait_for_single_object (thread->handle, INFINITE); LEAVE(); if (err) return err; if (thread_return) *thread_return = thread->result; deref_thread (thread_id); return 0; } int npth_detach (npth_t thread_id) { int err; npth_impl_t thread; err = find_thread (thread_id, &thread); if (err) return err; if (thread->detached) return EINVAL; /* The detached flag indicates to other thread that the outside reference in the global thread table has been consumed. */ thread->detached = 1; deref_thread (thread_id); return 0; } void npth_exit (void *retval) { int err; npth_t thread_id; npth_impl_t thread; thread_id = npth_self(); err = find_thread (thread_id, &thread); if (err) /* FIXME: log this? */ return; thread->result = retval; /* Any joiner will be signaled once we terminate. */ deref_thread (thread_id); ENTER(); /* We can not use retval here, as that is a void*, not a DWORD. */ ExitThread(0); /* Never reached. But just in case ExitThread does return... */ LEAVE(); } int npth_key_create (npth_key_t *key, void (*destr_function) (void *)) { DWORD idx; if (destr_function) return EOPNOTSUPP; idx = TlsAlloc (); if (idx == TLS_OUT_OF_INDEXES) return map_error (GetLastError()); *key = idx; return 0; } int npth_key_delete (npth_key_t key) { BOOL res; res = TlsFree (key); if (res == 0) return map_error (GetLastError()); return 0; } void * npth_getspecific (npth_key_t key) { /* Pthread doesn't support error reporting beyond returning NULL for an invalid key, which is also what TlsGetValue returns in that case. */ return TlsGetValue (key); } int npth_setspecific (npth_key_t key, const void *pointer) { BOOL res; res = TlsSetValue (key, (void *) pointer); if (res == 0) return map_error (GetLastError()); return 0; } struct npth_mutexattr_s { int kind; }; int npth_mutexattr_init (npth_mutexattr_t *attr_r) { npth_mutexattr_t attr; attr = malloc (sizeof *attr); if (!attr) return errno; attr->kind = NPTH_MUTEX_DEFAULT; *attr_r = attr; return 0; } int npth_mutexattr_destroy (npth_mutexattr_t *attr) { free (*attr); *attr = NULL; return 0; } int npth_mutexattr_gettype (const npth_mutexattr_t *attr, int *kind) { *kind = (*attr)->kind; return 0; } int npth_mutexattr_settype (npth_mutexattr_t *attr, int kind) { if (kind != NPTH_MUTEX_NORMAL && kind != NPTH_MUTEX_RECURSIVE && kind != NPTH_MUTEX_ERRORCHECK) return EINVAL; (*attr)->kind = kind; return 0; } struct npth_mutex_s { /* We have to use a mutex, not a CRITICAL_SECTION, because the latter can not be used with timed waits. */ HANDLE mutex; }; int npth_mutex_init (npth_mutex_t *mutex_r, const npth_mutexattr_t *mutex_attr) { npth_mutex_t mutex; /* We can not check *mutex_r here, as it may contain random data. */ mutex = malloc (sizeof (*mutex)); if (!mutex) return errno; /* We ignore MUTEX_ATTR. */ mutex->mutex = CreateMutex (NULL, FALSE, NULL); if (!mutex->mutex) { int err = map_error (GetLastError()); free (mutex); return err; } *mutex_r = mutex; return 0; } int npth_mutex_destroy (npth_mutex_t *mutex) { BOOL res; if (*mutex == 0 || *mutex == NPTH_MUTEX_INITIALIZER || *mutex == NPTH_RECURSIVE_MUTEX_INITIALIZER_NP) return EINVAL; res = CloseHandle ((*mutex)->mutex); if (res == 0) return map_error (GetLastError()); free (*mutex); *mutex = NULL; return 0; } /* Must be called with global lock held. */ static int mutex_init_check (npth_mutex_t *mutex) { int err; npth_mutexattr_t attr; int kind; if (*mutex == 0) return EINVAL; if ((*mutex) == NPTH_MUTEX_INITIALIZER) kind = NPTH_MUTEX_NORMAL; else if ((*mutex) == NPTH_RECURSIVE_MUTEX_INITIALIZER_NP) kind = NPTH_MUTEX_RECURSIVE; else if ((*mutex) == NPTH_ERRORCHECK_MUTEX_INITIALIZER_NP) kind = NPTH_MUTEX_ERRORCHECK; else /* Already initialized. */ return 0; /* Make sure we don't try again in case of error. */ *mutex = 0; err = npth_mutexattr_init (&attr); if (err) return err; err = npth_mutexattr_settype (&attr, kind); if (err) { npth_mutexattr_destroy (&attr); return err; } err = npth_mutex_init (mutex, &attr); npth_mutexattr_destroy (&attr); return err; } int npth_mutex_lock (npth_mutex_t *mutex) { int err; /* While we are protected, let's check for a static initializer. */ err = mutex_init_check (mutex); if (err) return err; /* No need to allow competing threads to enter when we can get the lock immediately. */ err = npth_mutex_trylock (mutex); if (err != EBUSY) return err; ENTER(); err = wait_for_single_object ((*mutex)->mutex, INFINITE); LEAVE(); if (err) return err; return 0; } int npth_mutex_trylock (npth_mutex_t *mutex) { int err; DWORD res; /* While we are protected, let's check for a static initializer. */ err = mutex_init_check (mutex); if (err) return err; /* We do not leave the global lock for a quick try. */ err = wait_for_single_object ((*mutex)->mutex, 0); if (err == ETIMEDOUT) err = EBUSY; if (err) return err; return 0; } int npth_mutex_timedlock (npth_mutex_t *mutex, const struct timespec *abstime) { int err; DWORD msecs; /* While we are protected, let's check for a static initializer. */ err = mutex_init_check (mutex); if (err) return err; /* No need to allow competing threads to enter when we can get the lock immediately. */ err = npth_mutex_trylock (mutex); if (err != EBUSY) return err; err = calculate_timeout (abstime, &msecs); if (err) return err; ENTER(); err = wait_for_single_object ((*mutex)->mutex, msecs); LEAVE(); if (err) return err; return 0; } int npth_mutex_unlock (npth_mutex_t *mutex) { BOOL res; if (*mutex == 0 || *mutex == NPTH_MUTEX_INITIALIZER || *mutex == NPTH_RECURSIVE_MUTEX_INITIALIZER_NP) return EINVAL; res = ReleaseMutex ((*mutex)->mutex); if (res == 0) return map_error (GetLastError()); return 0; } struct npth_cond_s { /* All conditions are protected by the global lock, so this is simple. */ /* The waiter queue. */ npth_impl_t waiter; }; int npth_cond_init (npth_cond_t *cond_r, const npth_condattr_t *cond_attr) { npth_cond_t cond; if (cond_attr != NULL) return EINVAL; /* We can not check *cond_r here, as it may contain random data. */ cond = malloc (sizeof (*cond)); if (!cond) return errno; cond->waiter = NULL; *cond_r = cond; return 0; } int npth_cond_destroy (npth_cond_t *cond) { if (*cond == 0) return EINVAL; if ((*cond)->waiter) return EBUSY; free (*cond); *cond = NULL; return 0; } /* Must be called with global lock held. */ static int cond_init_check (npth_cond_t *cond) { int err; if (*cond == 0 || *cond == NPTH_COND_INITIALIZER) return EINVAL; if (*cond != NPTH_COND_INITIALIZER) /* Already initialized. */ return 0; /* Make sure we don't try again in case of error. */ *cond = 0; err = npth_cond_init (cond, NULL); return err; } int npth_cond_signal (npth_cond_t *cond) { int err; npth_impl_t thread; DWORD res; /* While we are protected, let's check for a static initializer. */ err = cond_init_check (cond); if (err) return err; if ((*cond)->waiter == INVALID_THREAD_ID) return 0; /* Dequeue the first thread and wake it up. */ thread = (*cond)->waiter; dequeue_thread (thread); res = SetEvent (thread->event); if (res == 0) /* FIXME: An error here implies a mistake in the npth code. Log it. */ ; /* Force the woken up thread into the mutex lock function (for the mutex associated with the condition, which is why we have to release the global lock here). This helps to ensure fairness, because otherwise our own thread might release and reacquire the lock first (followed by removing the condition that lead to the wakeup) and starve the woken up thread. */ ENTER (); Sleep (0); LEAVE (); return 0; } int npth_cond_broadcast (npth_cond_t *cond) { int err; npth_impl_t thread; DWORD res; int any; /* While we are protected, let's check for a static initializer. */ err = cond_init_check (cond); if (err) return err; if ((*cond)->waiter == INVALID_THREAD_ID) return 0; while ((*cond)->waiter) { /* Dequeue the first thread and wake it up. */ thread = (*cond)->waiter; dequeue_thread (thread); res = SetEvent (thread->event); if (res == 0) /* FIXME: An error here implies a mistake in the npth code. Log it. */ ; } /* Force the woken up threads into the mutex lock function (for the mutex associated with the condition, which is why we have to release the global lock here). This helps to ensure fairness, because otherwise our own thread might release and reacquire the lock first (followed by removing the condition that lead to the wakeup) and starve the woken up threads. */ ENTER (); Sleep (0); LEAVE (); return 0; } /* As a special exception in W32 NPTH, mutex can be NULL, in which case the global lock doubles as the mutex protecting the condition. This is used internally in the RW implementation as an optimization. Note that this is safe as long as the caller does not yield to other threads (directly or indirectly) between checking the condition and waiting on it. */ int npth_cond_wait (npth_cond_t *cond, npth_mutex_t *mutex) { int err; int err2; BOOL bres; npth_impl_t thread; npth_impl_t *prev_ptr; /* While we are protected, let's check for a static initializer. */ err = cond_init_check (cond); if (err) return err; err = find_thread (npth_self(), &thread); if (err) return err; /* Ensure there is an event. */ if (thread->event == INVALID_HANDLE_VALUE) { thread->event = CreateEvent (NULL, TRUE, FALSE, NULL); if (thread->event == INVALID_HANDLE_VALUE) return map_error (GetLastError()); } /* Find end of queue and enqueue the thread. */ prev_ptr = &(*cond)->waiter; while (*prev_ptr) prev_ptr = &(*prev_ptr)->next; enqueue_thread (thread, prev_ptr); /* Make sure the event is not signaled before releasing the mutex. */ bres = ResetEvent (thread->event); if (bres == 0) /* Log an error. */ ; if (mutex) { err = npth_mutex_unlock (mutex); if (err) { dequeue_thread (thread); return err; } } ENTER(); err = wait_for_single_object (thread->event, INFINITE); LEAVE(); /* Make sure the thread is dequeued (in case of error). */ dequeue_thread (thread); if (mutex) { err2 = npth_mutex_lock (mutex); if (err2) /* FIXME: Log this at least. */ ; } if (err) return err; return 0; } int npth_cond_timedwait (npth_cond_t *cond, npth_mutex_t *mutex, const struct timespec *abstime) { int err; int err2; BOOL bres; npth_impl_t thread; npth_impl_t *prev_ptr; DWORD msecs; err = calculate_timeout (abstime, &msecs); if (err) { if (err != ETIMEDOUT) return err; /* We have to give up the lock anyway to give others a chance to signal or broadcast. */ err = npth_mutex_unlock (mutex); if (err) return err; ENTER(); Sleep (0); LEAVE(); err = npth_mutex_lock (mutex); if (err) return (err); return ETIMEDOUT; } /* While we are protected, let's check for a static initializer. */ err = cond_init_check (cond); if (err) return err; err = find_thread (npth_self(), &thread); if (err) return err; /* Ensure there is an event. */ if (thread->event == INVALID_HANDLE_VALUE) { thread->event = CreateEvent (NULL, TRUE, FALSE, NULL); if (thread->event == INVALID_HANDLE_VALUE) return map_error (GetLastError()); } /* Make sure the event is not signaled. */ bres = ResetEvent (thread->event); if (bres == 0) /* Log an error. */ ; /* Find end of queue and enqueue the thread. */ prev_ptr = &(*cond)->waiter; while (*prev_ptr) prev_ptr = &(*prev_ptr)->next; enqueue_thread (thread, prev_ptr); err = npth_mutex_unlock (mutex); if (err) { dequeue_thread (thread); return err; } ENTER(); err = wait_for_single_object (thread->event, msecs); LEAVE(); err2 = npth_mutex_lock (mutex); if (err2) /* FIXME: Log this at least. */ ; if (err) return err; return 0; } struct npth_rwlockattr_s { int kind; }; int npth_rwlockattr_init (npth_rwlockattr_t *attr_r) { npth_rwlockattr_t attr; attr = malloc (sizeof *attr); if (!attr) return errno; attr->kind = NPTH_RWLOCK_DEFAULT_NP; *attr_r = attr; return 0; } int npth_rwlockattr_destroy (npth_rwlockattr_t *attr) { free (*attr); *attr = NULL; return 0; } int npth_rwlockattr_gettype_np (const npth_rwlockattr_t *attr, int *kind) { *kind = (*attr)->kind; return 0; } int npth_rwlockattr_settype_np (npth_rwlockattr_t *attr, int kind) { if (kind != NPTH_RWLOCK_PREFER_READER_NP && kind != NPTH_RWLOCK_PREFER_WRITER_NP && kind != NPTH_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) return EINVAL; (*attr)->kind = kind; return 0; } struct npth_rwlock_s { /* Objects are protected by the global lock, so no lock here necessary. This is even true for the condition (by specifying NULL as the mutex in npth_cond_wait and npth_cond_timedwait). */ /* True if we prefer writers over readers. */ int prefer_writer; /* Readers who want the lock wait on this condition, which is broadcast when the last writer goes away. */ npth_cond_t reader_wait; /* The number of readers waiting on the condition. */ int nr_readers_queued; /* The number of current readers. */ int nr_readers; /* Writers who want the lock wait on this condition, which is signaled when the current writer or last reader goes away. */ npth_cond_t writer_wait; /* The number of queued writers. */ int nr_writers_queued; /* The number of current writers. This is either 1 (then nr_readers is 0) or it is 0. At unlock time this value tells us if the current lock holder is a writer or a reader. */ int nr_writers; }; int npth_rwlock_init (npth_rwlock_t *rwlock_r, const npth_rwlockattr_t *user_attr) { int err; npth_rwlock_t rwlock; npth_rwlockattr_t attr; int attr_allocated; if (user_attr != NULL) { attr = *user_attr; attr_allocated = 0; } else { err = npth_rwlockattr_init (&attr); if (err) return err; } /* We can not check *rwlock_r here, as it may contain random data. */ rwlock = malloc (sizeof (*rwlock)); if (!rwlock) { err = errno; goto err_out; } rwlock->prefer_writer = (attr->kind == NPTH_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); err = npth_cond_init (&rwlock->reader_wait, NULL); if (err) { free (rwlock); goto err_out; } err = npth_cond_init (&rwlock->writer_wait, NULL); if (err) { npth_cond_destroy (&rwlock->reader_wait); free (rwlock); goto err_out; } rwlock->nr_readers = 0; rwlock->nr_readers_queued = 0; rwlock->nr_writers = 0; rwlock->nr_writers_queued = 0; *rwlock_r = rwlock; err_out: if (attr_allocated) npth_rwlockattr_destroy (&attr); return err; } /* Must be called with global lock held. */ static int rwlock_init_check (npth_rwlock_t *rwlock) { int err; npth_rwlockattr_t attr; int kind; if (*rwlock == 0) return EINVAL; if ((*rwlock) == NPTH_RWLOCK_INITIALIZER) kind = NPTH_RWLOCK_PREFER_READER_NP; if ((*rwlock) == NPTH_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP) kind = NPTH_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP; else /* Already initialized. */ return 0; /* Make sure we don't try again in case of error. */ *rwlock = 0; err = npth_rwlockattr_init (&attr); if (err) return err; err = npth_rwlockattr_settype_np (&attr, kind); if (err) { npth_rwlockattr_destroy (&attr); return err; } err = npth_rwlock_init (rwlock, &attr); npth_rwlockattr_destroy (&attr); return err; } int npth_rwlock_destroy (npth_rwlock_t *rwlock) { int err; if (*rwlock == 0 || *rwlock == NPTH_RWLOCK_INITIALIZER) return EINVAL; if ((*rwlock)->nr_writers || (*rwlock)->nr_readers || (*rwlock)->nr_writers_queued || (*rwlock)->nr_readers_queued) return EBUSY; err = npth_cond_destroy (&(*rwlock)->reader_wait); if (err) /* FIXME: Log this. */ ; err = npth_cond_destroy (&(*rwlock)->writer_wait); if (err) /* FIXME: Log this. */ ; free (rwlock); *rwlock = NULL; return 0; } int npth_rwlock_tryrdlock (npth_rwlock_t *rwlock) { if ((*rwlock)->nr_writers) return EBUSY; if ((*rwlock)->nr_writers_queued && (*rwlock)->prefer_writer) return EBUSY; (*rwlock)->nr_readers++; return 0; } int npth_rwlock_rdlock (npth_rwlock_t *rwlock) { int err; while (1) { /* Quick check. */ err = npth_rwlock_tryrdlock (rwlock); if (err != EBUSY) return err; (*rwlock)->nr_readers_queued++; err = npth_cond_wait (&(*rwlock)->reader_wait, NULL); (*rwlock)->nr_readers_queued--; if (err) return err; } } int npth_rwlock_timedrdlock (npth_rwlock_t *rwlock, const struct timespec *abstime) { int err; while (1) { /* Quick check. */ err = npth_rwlock_tryrdlock (rwlock); if (err != EBUSY) return err; (*rwlock)->nr_readers_queued++; err = npth_cond_timedwait (&(*rwlock)->reader_wait, NULL, abstime); (*rwlock)->nr_readers_queued--; if (err) return err; } } int npth_rwlock_trywrlock (npth_rwlock_t *rwlock) { if ((*rwlock)->nr_writers) return EBUSY; if ((*rwlock)->nr_readers) return EBUSY; (*rwlock)->nr_writers = 1; return 0; } int npth_rwlock_wrlock (npth_rwlock_t *rwlock) { int err; while (1) { /* Quick check. */ err = npth_rwlock_trywrlock (rwlock); if (err != EBUSY) return err; (*rwlock)->nr_writers_queued++; err = npth_cond_wait (&(*rwlock)->writer_wait, NULL); (*rwlock)->nr_writers_queued--; if (err) return err; } } int npth_rwlock_timedwrlock (npth_rwlock_t *rwlock, const struct timespec *abstime) { int err; while (1) { /* Quick check. */ err = npth_rwlock_trywrlock (rwlock); if (err != EBUSY) return err; (*rwlock)->nr_writers_queued++; err = npth_cond_timedwait (&(*rwlock)->writer_wait, NULL, abstime); (*rwlock)->nr_writers_queued--; if (err) return err; } } int npth_rwlock_unlock (npth_rwlock_t *rwlock) { int err; if ((*rwlock)->nr_writers) /* We are the writer. */ (*rwlock)->nr_writers = 0; else /* We are the reader. */ (*rwlock)->nr_readers--; if ((*rwlock)->nr_readers == 0) { if ((*rwlock)->nr_writers_queued) { err = npth_cond_signal (&(*rwlock)->writer_wait); if (err) return err; } else if ((*rwlock)->nr_readers_queued) { err = npth_cond_broadcast (&(*rwlock)->reader_wait); return err; } } return 0; } /* Standard POSIX Replacement API */ int npth_usleep(unsigned int usec) { ENTER(); Sleep((usec + 999) / 1000); LEAVE(); return 0; } unsigned int npth_sleep(unsigned int sec) { ENTER(); Sleep (sec * 1000); LEAVE(); return 0; } int npth_system(const char *cmd) { int res; ENTER(); res = system(cmd); LEAVE(); return res; } pid_t npth_waitpid(pid_t pid, int *status, int options) { return EOPNOTSUPP; } int npth_connect(int s, const struct sockaddr *addr, socklen_t addrlen) { int res; ENTER(); res = connect(s, addr, addrlen); LEAVE(); return res; } int npth_accept(int s, struct sockaddr *addr, socklen_t *addrlen) { int res; ENTER(); res = accept(s, addr, addrlen); LEAVE(); return res; } int npth_select(int nfd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *timeout) { int res; ENTER(); res = select(nfd, rfds, wfds, efds, timeout); LEAVE(); return res; } ssize_t npth_read(int fd, void *buf, size_t nbytes) { ssize_t res; ENTER(); res = read(fd, buf, nbytes); LEAVE(); return res; } ssize_t npth_write(int fd, const void *buf, size_t nbytes) { ssize_t res; ENTER(); res = write(fd, buf, nbytes); LEAVE(); return res; } int npth_recvmsg (int fd, struct msghdr *msg, int flags) { return EOPNOTSUPP; } int npth_sendmsg (int fd, const struct msghdr *msg, int flags) { return EOPNOTSUPP; } void npth_unprotect (void) { /* If we are not initialized we may not access the semaphore and * thus we shortcut it. Note that in this case the unprotect/protect * is not needed. For failsafe reasons if an nPth thread has ever * been created but nPth has accidentally not initialized we do not * shortcut so that a stack backtrace (due to the access of the * uninitialized semaphore) is more expressive. */ if (initialized_or_any_threads) ENTER(); } void npth_protect (void) { /* See npth_unprotect for commentary. */ if (initialized_or_any_threads) LEAVE(); } int npth_is_protected (void) { return got_sceptre; } /* Maximum number of extra handles. We can only support 31 as that is the number of bits we can return. This is smaller than the maximum number of allowed wait objects for WFMO (which is 64). */ #define MAX_EVENTS 31 /* Although the WSAEventSelect machinery seems to have no limit on the number of selectable fds, we impose the same limit as used by traditional select. This allows us to work with a static data structure instead of an dynamically allocated array. */ #define MAX_FDOBJS FD_SETSIZE /* Using WFMO even for sockets makes Windows objects more composable, which helps faking signals and other constructs, so we support that. You can still use npth_select for the plain select function. */ int npth_eselect(int nfd, fd_set *rfds, fd_set *wfds, fd_set *efds, const struct timespec *timeout, HANDLE *events, unsigned int *events_set) { int err = 0; DWORD msecs; int i; u_int idx; /* One more for the handle associated with socket events. */ HANDLE obj[MAX_EVENTS + 1]; int nr_obj = 0; /* Number of extra events. */ int nr_events = 0; HANDLE sock_event = INVALID_HANDLE_VALUE; /* This will be (nr_obj - 1) == nr_events. */ int sock_event_idx = -1; int res; DWORD ret; SOCKET fd; long flags; int cnt; struct { SOCKET fd; long flags; } fdobj[MAX_FDOBJS]; int nr_fdobj = 0; (void)nfd; /* No need for it under Windows. */ if (events) { if (!events_set) { errno = EINVAL; return -1; } /* We always ensure that the events_set is valid, even after an error. */ *events_set = 0; } if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0)) { errno = EINVAL; return -1; } if (timeout == NULL) msecs = INFINITE; else if (timeout->tv_sec == 0 && timeout->tv_nsec == 0) msecs = 0; else { msecs = (timeout->tv_sec * 1000) + (timeout->tv_nsec + 999999) / 1000000; if (msecs < 1) msecs = 1; } if (events) { /* Copy the extra handles. */ for (i = 0; i < MAX_EVENTS; i++) { if (events[i] == INVALID_HANDLE_VALUE) break; obj[nr_obj] = events[i]; nr_obj++; nr_events++; } /* We can only return the status of up to MAX_EVENTS handles in EVENTS_SET. */ if (events[i] != INVALID_HANDLE_VALUE) { errno = EINVAL; return -1; } } /* From here on, we clean up at err_out, and you can set ERR to return an error. */ sock_event = WSACreateEvent (); if (sock_event == INVALID_HANDLE_VALUE) { err = EINVAL; return -1; } sock_event_idx = nr_obj; obj[nr_obj] = sock_event; nr_obj++; /* Combine FDs from all lists. */ #define SET_FDOBJ(x,v) do { \ for (idx=0; idx < (x)->fd_count; idx++) \ { \ for (i=0; i < nr_fdobj; i++) \ if (fdobj[i].fd == (x)->fd_array[idx]) \ break; \ if (i < nr_fdobj) \ ; \ else if (nr_fdobj < MAX_FDOBJS) \ { \ i = nr_fdobj++; \ fdobj[i].fd = (x)->fd_array[idx]; \ fdobj[i].flags = 0; \ } \ else \ { \ err = EINVAL; \ goto err_out; \ } \ fdobj[i].flags |= (v); \ } \ } while (0) if (rfds) SET_FDOBJ (rfds, FD_READ | FD_ACCEPT); if (wfds) SET_FDOBJ (wfds, FD_WRITE); if (efds) SET_FDOBJ (efds, FD_OOB | FD_CLOSE); #undef SET_FDOBJ /* Set the select flags. */ for (i = 0; i < nr_fdobj; i++) { res = WSAEventSelect (fdobj[i].fd, sock_event, fdobj[i].flags); if (res == SOCKET_ERROR) { err = map_error (WSAGetLastError()); goto err_out; } } /* Let's wait. */ ENTER(); ret = WaitForMultipleObjects (nr_obj, obj, FALSE, msecs); LEAVE(); if (ret == WAIT_TIMEOUT) { err = ETIMEDOUT; goto err_out; } else if (ret == WAIT_FAILED) { err = map_error (GetLastError()); goto err_out; } /* All other return values: We look at the objects. We must not fail from here, because then we could lose events. */ /* Keep track of result count. */ cnt = 0; for (i = 0; i < nr_events; i++) { ret = WaitForSingleObject (obj[i], 0); if (ret != WAIT_OBJECT_0) /* We ignore errors here. */ continue; *events_set = (*events_set) | (1 << i); /* We consume the event here. This may be undesirable, but unless we make it configurable we need a common policy, and this saves the user one step. */ ResetEvent (obj[i]); /* Increase result count. */ cnt++; } /* Now update the file descriptors sets. */ if (rfds) FD_ZERO (rfds); if (wfds) FD_ZERO (wfds); if (efds) FD_ZERO (efds); for (i = 0; i < nr_fdobj; i++) { WSANETWORKEVENTS ne; fd = fdobj[i].fd; flags = fdobj[i].flags; res = WSAEnumNetworkEvents (fd, NULL, &ne); if (res == SOCKET_ERROR) continue; /* FIXME: We ignore this error here. */ /* NB that the test on FLAGS guarantees that ?fds is not NULL. */ if ((flags & FD_READ) && (ne.lNetworkEvents & (FD_READ | FD_ACCEPT))) { FD_SET (fd, rfds); cnt++; } if ((flags & FD_WRITE) && (ne.lNetworkEvents & FD_WRITE)) { FD_SET (fd, wfds); cnt++; } if ((flags & FD_CLOSE) && (ne.lNetworkEvents & (FD_OOB | FD_CLOSE))) { FD_SET (fd, efds); cnt++; } WSAEventSelect (fd, NULL, 0); /* We ignore errors. */ } /* We ignore errors. */ WSACloseEvent (sock_event); return cnt; /* Cleanup. */ err_out: if (sock_event != INVALID_HANDLE_VALUE) { for (i = 0; i < nr_fdobj; i++) { WSAEventSelect (fdobj[i].fd, NULL, 0); /* We ignore errors. */ } WSACloseEvent (sock_event); /* We ignore errors. */ } if (err == ETIMEDOUT) return 0; errno = err; return -1; } diff --git a/w32/npth.def b/w32/npth.def index b56a46e..6b4970c 100644 --- a/w32/npth.def +++ b/w32/npth.def @@ -1,84 +1,83 @@ ; npth.def - List of symbols to export. ; Copyright (C) 2011 g10 Code GmbH ; ; This file is part of NPTH. ; ; NPTH is free software; you can redistribute it and/or modify -; it under the terms of the GNU Lesser general Public License as +; 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. ; -; NPTH is distributed in the hope that it will be useful, -; but WITHOUT ANY WARRANTY; without even the implied warranty of -; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -; GNU Lesser General Public License for more details. +; NPTH is distributed in the hope that it will be useful, but +; WITHOUT ANY WARRANTY; without even the implied warranty of +; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See +; the GNU Lesser General Public License for more details. ; ; You should have received a copy of the GNU Lesser General Public -; License along with this program; if not, write to the Free Software -; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA +; License along with this program; if not, see . EXPORTS npth_init @1 npth_attr_init @2 npth_attr_destroy @3 npth_attr_getdetachstate @4 npth_attr_setdetachstate @5 npth_getname_np @6 npth_setname_np @7 npth_create @8 npth_self @9 npth_join @10 npth_detach @11 npth_exit @12 npth_key_create @13 npth_key_delete @14 npth_getspecific @15 npth_setspecific @16 npth_mutexattr_init @17 npth_mutexattr_destroy @18 npth_mutexattr_gettype @19 npth_mutexattr_settype @20 npth_mutex_init @21 npth_mutex_destroy @22 npth_mutex_trylock @23 npth_mutex_lock @24 npth_mutex_timedlock @25 npth_mutex_unlock @26 npth_rwlockattr_init @27 npth_rwlockattr_destroy @28 npth_rwlockattr_gettype_np @29 npth_rwlockattr_settype_np @30 npth_rwlock_init @31 npth_rwlock_destroy @32 npth_rwlock_tryrdlock @33 npth_rwlock_rdlock @34 npth_rwlock_timedrdlock @35 npth_rwlock_trywrlock @36 npth_rwlock_wrlock @37 npth_rwlock_timedwrlock @38 npth_rwlock_unlock @39 npth_cond_init @40 npth_cond_broadcast @41 npth_cond_signal @42 npth_cond_destroy @43 npth_cond_wait @44 npth_cond_timedwait @45 npth_usleep @46 npth_sleep @47 npth_waitpid @48 npth_system @49 npth_connect @50 npth_accept @51 npth_select @52 npth_read @53 npth_write @54 npth_recvmsg @55 npth_sendmsg @56 npth_clock_gettime @57 npth_eselect @58 npth_unprotect @59 npth_protect @60 npth_is_protected @61 ; END diff --git a/w32/npth.h b/w32/npth.h index baa668b..008001b 100644 --- a/w32/npth.h +++ b/w32/npth.h @@ -1,248 +1,238 @@ -/* npth.h - a lightweight implementation of pth over pthread. - Copyright (C) 2011, 2015 g10 Code GmbH - - This file is part of NPTH. - - NPTH is free software; you can redistribute it and/or modify it - under the terms of either - - - the GNU Lesser General Public License as published by the Free - Software Foundation; either version 3 of the License, or (at - your option) any later version. - - or - - - the GNU General Public License as published by the Free - Software Foundation; either version 2 of the License, or (at - your option) any later version. - - or both in parallel, as here. - - NPTH is distributed in the hope that 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 copies of the GNU General Public License - and the GNU Lesser General Public License along with this program; - if not, see . */ +/* npth.h - a lightweight implementation of pth over native threads + * Copyright (C) 2011, 2015 g10 Code GmbH + * + * This file is part of nPth. + * + * nPth is free software; you can redistribute it 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. + * + * nPth is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See + * the GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, see . + */ #ifndef _NPTH_H #define _NPTH_H #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #if 0 /* (Keep Emacsens' auto-indent happy.) */ } #endif #endif struct msghdr; /* The mingw-w64 headers define timespec. For older compilers we keep our replacement. */ #ifndef __MINGW64_VERSION_MAJOR struct timespec { long tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; #endif /*__MINGW64_VERSION_MAJOR */ #ifndef ETIMEDOUT #define ETIMEDOUT 10060 /* This is WSAETIMEDOUT. */ #endif #ifndef EOPNOTSUPP #define EOPNOTSUPP 10045 /* This is WSAEOPNOTSUPP. */ #endif int npth_init (void); typedef struct npth_attr_s *npth_attr_t; typedef unsigned long int npth_t; typedef struct npth_mutexattr_s *npth_mutexattr_t; typedef struct npth_mutex_s *npth_mutex_t; typedef struct npth_rwlockattr_s *npth_rwlockattr_t; typedef struct npth_rwlock_s *npth_rwlock_t; typedef struct npth_condattr_s *npth_condattr_t; typedef struct npth_cond_s *npth_cond_t; int npth_attr_init (npth_attr_t *attr); int npth_attr_destroy (npth_attr_t *attr); #define NPTH_CREATE_JOINABLE 0 #define NPTH_CREATE_DETACHED 1 int npth_attr_getdetachstate(npth_attr_t *attr, int *detachstate); int npth_attr_setdetachstate(npth_attr_t *attr, int detachstate); int npth_getname_np (npth_t target_thread, char *buf, size_t buflen); int npth_setname_np (npth_t target_thread, const char *name); int npth_create (npth_t *newthread, const npth_attr_t *attr, void *(*start_routine) (void *), void *arg); npth_t npth_self (void); int npth_join (npth_t th, void **thread_return); int npth_detach (npth_t th); void npth_exit (void *retval); typedef DWORD npth_key_t; int npth_key_create (npth_key_t *key, void (*destr_function) (void *)); int npth_key_delete (npth_key_t key); void *npth_getspecific (npth_key_t key); int npth_setspecific (npth_key_t key, const void *pointer); int npth_mutexattr_init (npth_mutexattr_t *attr); int npth_mutexattr_destroy (npth_mutexattr_t *attr); int npth_mutexattr_gettype (const npth_mutexattr_t *attr, int *kind); int npth_mutexattr_settype (npth_mutexattr_t *attr, int kind); #define NPTH_MUTEX_NORMAL 0 #define NPTH_MUTEX_RECURSIVE 1 #define NPTH_MUTEX_ERRORCHECK 2 #define NPTH_MUTEX_DEFAULT NPTH_MUTEX_NORMAL #define NPTH_MUTEX_INITIALIZER ((npth_mutex_t) -1) #define NPTH_RECURSIVE_MUTEX_INITIALIZER_NP ((npth_mutex_t) -2) #define NPTH_ERRORCHECK_MUTEX_INITIALIZER_NP ((npth_mutex_t) -3) int npth_mutex_init (npth_mutex_t *mutex, const npth_mutexattr_t *mutexattr); int npth_mutex_destroy (npth_mutex_t *mutex); int npth_mutex_trylock(npth_mutex_t *mutex); int npth_mutex_lock(npth_mutex_t *mutex); int npth_mutex_timedlock(npth_mutex_t *mutex, const struct timespec *abstime); int npth_mutex_unlock(npth_mutex_t *mutex); int npth_rwlockattr_init (npth_rwlockattr_t *attr); int npth_rwlockattr_destroy (npth_rwlockattr_t *attr); int npth_rwlockattr_gettype_np (const npth_rwlockattr_t *attr, int *kind); int npth_rwlockattr_settype_np (npth_rwlockattr_t *attr, int kind); #define NPTH_RWLOCK_PREFER_READER_NP 0 #define NPTH_RWLOCK_PREFER_WRITER_NP 1 #define NPTH_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP 2 #define NPTH_RWLOCK_DEFAULT_NP NPTH_RWLOCK_PREFER_READER_NP #define NPTH_RWLOCK_INITIALIZER ((npth_rwlock_t) -1) #define NPTH_RWLOCK_WRITER_NONRECURSIVE_INITIALIZER_NP ((npth_rwlock_t) -2) /* For now, we don't support any rwlock attributes. */ int npth_rwlock_init (npth_rwlock_t *rwlock, const npth_rwlockattr_t *attr); int npth_rwlock_destroy (npth_rwlock_t *rwlock); int npth_rwlock_tryrdlock (npth_rwlock_t *rwlock); int npth_rwlock_rdlock (npth_rwlock_t *rwlock); int npth_rwlock_timedrdlock (npth_rwlock_t *rwlock, const struct timespec *abstime); int npth_rwlock_trywrlock (npth_rwlock_t *rwlock); int npth_rwlock_wrlock (npth_rwlock_t *rwlock); int npth_rwlock_timedwrlock (npth_rwlock_t *rwlock, const struct timespec *abstime); int npth_rwlock_unlock (npth_rwlock_t *rwlock); #define NPTH_COND_INITIALIZER ((npth_cond_t) -1) /* For now, we don't support any cond attributes. */ int npth_cond_init (npth_cond_t *cond, const npth_condattr_t *cond_attr); int npth_cond_broadcast (npth_cond_t *cond); int npth_cond_signal (npth_cond_t *cond); int npth_cond_destroy (npth_cond_t *cond); int npth_cond_wait (npth_cond_t *cond, npth_mutex_t *mutex); int npth_cond_timedwait (npth_cond_t *cond, npth_mutex_t *mutex, const struct timespec *abstime); int npth_usleep(unsigned int usec); unsigned int npth_sleep(unsigned int sec); pid_t npth_waitpid(pid_t pid, int *status, int options); int npth_system(const char *cmd); #if 0 /* We do not support this on windows. */ int npth_sigmask(int how, const sigset_t *set, sigset_t *oldset); int npth_sigwait(const sigset_t *set, int *sig); #endif int npth_connect(int s, const struct sockaddr *addr, socklen_t addrlen); int npth_accept(int s, struct sockaddr *addr, socklen_t *addrlen); /* Only good for sockets! */ int npth_select(int nfd, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *timeout); #if 0 /* We do not support this on windows. */ int npth_pselect(int nfd, fd_set *rfds, fd_set *wfds, fd_set *efds, const struct timespec *timeout, const sigset_t *sigmask); #endif /* Wait on the FDs (only good for sockets!) and the INVALID_HANDLE_VALUE terminated list of extra events. On return (even on error), the bits in EVENTS_SET will contain the extra events that occured (which means that there can only be up to 31 extra events). */ int npth_eselect(int nfd, fd_set *rfds, fd_set *wfds, fd_set *efds, const struct timespec *timeout, HANDLE *events, unsigned int *events_set); ssize_t npth_read(int fd, void *buf, size_t nbytes); ssize_t npth_write(int fd, const void *buf, size_t nbytes); int npth_recvmsg (int fd, struct msghdr *msg, int flags); int npth_sendmsg (int fd, const struct msghdr *msg, int flags); void npth_unprotect (void); void npth_protect (void); /* Return true when we hold the sceptre. This is used to debug * problems with npth_unprotect and npth_protect. */ int npth_is_protected (void); int npth_clock_gettime(struct timespec *tp); /* CMP may be ==, < or >. Do not use <= or >=. */ #define npth_timercmp(t1, t2, cmp) \ (((t1)->tv_sec == (t2)->tv_sec) ? \ ((t1)->tv_nsec cmp (t2)->tv_nsec) : \ ((t1)->tv_sec cmp (t2)->tv_sec)) #define npth_timeradd(t1, t2, result) \ do { \ (result)->tv_sec = (t1)->tv_sec + (t2)->tv_sec; \ (result)->tv_nsec = (t1)->tv_nsec + (t2)->tv_nsec; \ if ((result)->tv_nsec >= 1000000000) \ { \ ++(result)->tv_sec; \ (result)->tv_nsec -= 1000000000; \ } \ } while (0) #define npth_timersub(t1, t2, result) \ do { \ (result)->tv_sec = (t1)->tv_sec - (t2)->tv_sec; \ (result)->tv_nsec = (t1)->tv_nsec - (t2)->tv_nsec; \ if ((result)->tv_nsec < 0) { \ --(result)->tv_sec; \ (result)->tv_nsec += 1000000000; \ } \ } while (0) #if 0 /* We do not support this on windows. */ void npth_sigev_init (void); void npth_sigev_add (int signum); void npth_sigev_fini (void); sigset_t *npth_sigev_sigmask (void); int npth_sigev_get_pending (int *r_signum); #endif #if 0 /* (Keep Emacsens' auto-indent happy.) */ { #endif #ifdef __cplusplus } #endif #endif /*_NPTH_H*/