pax_global_header00006660000000000000000000000064146755352620014531gustar00rootroot0000000000000052 comment=dbedf16f80c5b4e1807ea4f80cc89d1f15d36f0a libusbgx-libusbgx-v0.3.0/000077500000000000000000000000001467553526200153535ustar00rootroot00000000000000libusbgx-libusbgx-v0.3.0/.gbs.conf000066400000000000000000000001211467553526200170450ustar00rootroot00000000000000[general] upstream_branch = upstream upstream_tag = libusbgx-v${upstreamversion} libusbgx-libusbgx-v0.3.0/.gitignore000066400000000000000000000006251467553526200173460ustar00rootroot00000000000000/examples/* !/examples/*.* /examples/.deps/ /examples/.libs/ /include/usbg/usbg_version.h /src/.deps/ /src/.libs/ /src/function/.deps/ /src/function/.dirstamp /tests/* !/tests/*.* /tests/.deps/ *.o *.lo *.la *.so *.so.* Makefile Makefile.in /configure /config.* /aclocal.m4 /autom4te.cache /compile /depcomp /libtool /ltmain.sh /ar-lib /missing /install-sh /doxygen.cfg /libusbgx.pc /LibUsbgxConfig.cmake libusbgx-libusbgx-v0.3.0/AUTHORS000066400000000000000000000001141467553526200164170ustar00rootroot00000000000000Matt Porter Krzysztof Opasiak libusbgx-libusbgx-v0.3.0/COPYING000066400000000000000000000432541467553526200164160ustar00rootroot00000000000000 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. libusbgx-libusbgx-v0.3.0/COPYING.LGPL000066400000000000000000000636421467553526200171560ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 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. [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 Street, 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! libusbgx-libusbgx-v0.3.0/ChangeLog000066400000000000000000000020021467553526200171170ustar00rootroot00000000000000Wed, 09 Sep 2024 Michael Grzeschik 0.3.0 - Add meson build support - Add support for usb9pfs - Add more controls for USB Audio Class 2 (UAC2) - Add support for USB Video Class (UVC) - Add support for Printer8664b79 - Improved support for network gadget - Many smaller fixes Fri, 02 Ma 2018 Krzysztof Opasiak 0.2.0 - Use prefix for our enums - Use string names similar to USB spec - Get rid of static buffers - Add support for HID function - Fix C++ compilation issues - Many smaller fixes Wed, 23 Dec 2015 Krzysztof Opasiak 0.1.0 - Rework most of the API to be more flexible and usable - Introduce internal API for adding function support - Add support for FunctionFS - Add support for Mass Storage - Add support for MIDI - Add support for Loopback - Add spec file for generating rpm package - Add test suit and various test cases Tue, 22 Dec 2015 Krzysztof Opasiak 0.0.1 - Initial fork from libusbg libusbgx-libusbgx-v0.3.0/DoxygenLayout.xml000066400000000000000000000133261467553526200207150ustar00rootroot00000000000000 libusbgx-libusbgx-v0.3.0/INSTALL000066400000000000000000000002361467553526200164050ustar00rootroot00000000000000Prerequisites: - autoconf - libtool - libconfig-dev Installing libusbgx: $ autoreconf -i $ ./configure $ make $ make doxygen-doc [optional] $ make install libusbgx-libusbgx-v0.3.0/LibUsbgxConfig.cmake.in000066400000000000000000000016701467553526200216330ustar00rootroot00000000000000get_filename_component(LibUsbgx_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) include(CMakeFindDependencyMacro) # Compute the installation prefix relative to this file. get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH) get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) if(_IMPORT_PREFIX STREQUAL "/") set(_IMPORT_PREFIX "") endif() set(LibUsbgx_INCLUDE_DIRS "${_IMPORT_PREFIX}/include") if(NOT TARGET LibUsbgx::LibUsbgx) add_library(LibUsbgx::LibUsbgx SHARED IMPORTED) set_property(TARGET LibUsbgx::LibUsbgx APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) set_target_properties(LibUsbgx::LibUsbgx PROPERTIES IMPORTED_LOCATION "${_IMPORT_PREFIX}/lib/libusbgx.so" INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include") endif() set(LibUsbgx_LIBRARIES LibUsbgx::LibUsbgx) libusbgx-libusbgx-v0.3.0/Makefile.am000066400000000000000000000015451467553526200174140ustar00rootroot00000000000000include $(top_srcdir)/aminclude.am SUBDIRS = src if BUILD_EXAMPLES SUBDIRS += examples endif if BUILD_TESTS SUBDIRS += tests endif ACLOCAL_AMFLAGS = -I m4 EXTRA_DIST = doxygen.cfg library_includedir=$(includedir)/usbg library_include_HEADERS = include/usbg/usbg.h include/usbg/usbg_version.h function_includedir=$(includedir)/usbg/function function_include_HEADERS = include/usbg/function/ffs.h include/usbg/function/loopback.h include/usbg/function/midi.h include/usbg/function/ms.h include/usbg/function/net.h include/usbg/function/phonet.h include/usbg/function/serial.h include/usbg/function/hid.h include/usbg/function/uac2.h include/usbg/function/uvc.h include/usbg/function/printer.h include/usbg/function/9pfs.h pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = libusbgx.pc cmakeconfigdir = $(libdir)/cmake/LibUsbgx cmakeconfig_DATA = LibUsbgxConfig.cmake libusbgx-libusbgx-v0.3.0/NEWS000066400000000000000000000000131467553526200160440ustar00rootroot00000000000000See README libusbgx-libusbgx-v0.3.0/README000066400000000000000000000025601467553526200162360ustar00rootroot00000000000000libusbg-neXt (libusbgx) ------- libusbgx is a C library encapsulating the kernel USB gadget-configfs userspace API functionality. It provides routines for creating and parsing USB gadget devices using the configfs API. Currently, all USB gadget configfs functions that can be enabled in kernel release 3.11 (Linux for Workgroups!) are supported. See the Doxygen docs and examples for complete details on the programming API and INSTALL for installation of the library and examples. The library is licensed under the GNU LGPL-2.1 (or later) and the examples are licensed under the GNU GPL-2.0 (or later). To run the examples: $ modprobe configfs $ modprobe libcomposite $ mount -t configfs none /sys/kernel/config $ gadget-acm-ecm $ show-gadgets ID 1d6b:0104 'g1' UDC 3f120000.usbotg bDeviceClass 0x00 bDeviceSubClass 0x00 bDeviceProtocol 0x00 bMaxPacketSize0 0x40 bcdDevice 0x0311 bcdUSB 0x0000 idVendor 0x1d6b idProduct 0x0104 Serial Number 0123456789 Manufacturer Foo Inc. Product Bar Gadget Function 'acm.usb0' port_num 0 Function 'acm.usb1' port_num 1 Function 'ecm.usb0' dev_addr 32:1b:dc:a4:bc:a2 host_addr 82:b7:58:62:f6:31 ifname usb0 qmult 5 Configuration 'c.1' MaxPower 2 bmAttributes 0x80 configuration CDC 2xACM+ECM acm.GS0 -> acm.usb0 acm.GS1 -> acm.usb0 ecm.usb0 -> ecm.usb0 libusbgx-libusbgx-v0.3.0/acinclude.m4000066400000000000000000000276501467553526200175560ustar00rootroot00000000000000# This file is part of Autoconf. -*- Autoconf -*- # Copyright (C) 2004 Oren Ben-Kiki # This file is distributed under the same terms as the Autoconf macro files. ########## CHANGELOG ################## # 2009-01-14 Martin Mann # * DX_ARG_ABLE : new variable 'DX_FLAG_DX_CURRENT_FEATURE' # * DX_CLEAR_DEPEND : use of explicit variable 'DX_FLAG_DX_CURRENT_FEATURE' # in AC_SUBST instead of 'DX_FLAG[]DX_CURRENT_FEATURE' which is rejected by # newer autotools # Generate automatic documentation using Doxygen. Works in concert with the # aminclude.m4 file and a compatible doxygen configuration file. Defines the # following public macros: # # DX_???_FEATURE(ON|OFF) - control the default setting fo a Doxygen feature. # Supported features are 'DOXYGEN' itself, 'DOT' for generating graphics, # 'HTML' for plain HTML, 'CHM' for compressed HTML help (for MS users), 'CHI' # for generating a seperate .chi file by the .chm file, and 'MAN', 'RTF', # 'XML', 'PDF' and 'PS' for the appropriate output formats. The environment # variable DOXYGEN_PAPER_SIZE may be specified to override the default 'a4wide' # paper size. # # By default, HTML, PDF and PS documentation is generated as this seems to be # the most popular and portable combination. MAN pages created by Doxygen are # usually problematic, though by picking an appropriate subset and doing some # massaging they might be better than nothing. CHM and RTF are specific for MS # (note that you can't generate both HTML and CHM at the same time). The XML is # rather useless unless you apply specialized post-processing to it. # # The macro mainly controls the default state of the feature. The use can # override the default by specifying --enable or --disable. The macros ensure # that contradictory flags are not given (e.g., --enable-doxygen-html and # --enable-doxygen-chm, --enable-doxygen-anything with --disable-doxygen, etc.) # Finally, each feature will be automatically disabled (with a warning) if the # required programs are missing. # # Once all the feature defaults have been specified, call DX_INIT_DOXYGEN with # the following parameters: a one-word name for the project for use as a # filename base etc., an optional configuration file name (the default is # 'Doxyfile', the same as Doxygen's default), and an optional output directory # name (the default is 'doxygen-doc'). ## ----------## ## Defaults. ## ## ----------## DX_ENV="" AC_DEFUN([DX_FEATURE_doc], ON) AC_DEFUN([DX_FEATURE_dot], ON) AC_DEFUN([DX_FEATURE_man], OFF) AC_DEFUN([DX_FEATURE_html], ON) AC_DEFUN([DX_FEATURE_chm], OFF) AC_DEFUN([DX_FEATURE_chi], OFF) AC_DEFUN([DX_FEATURE_rtf], OFF) AC_DEFUN([DX_FEATURE_xml], OFF) AC_DEFUN([DX_FEATURE_pdf], ON) AC_DEFUN([DX_FEATURE_ps], ON) ## --------------- ## ## Private macros. ## ## --------------- ## # DX_ENV_APPEND(VARIABLE, VALUE) # ------------------------------ # Append VARIABLE="VALUE" to DX_ENV for invoking doxygen. AC_DEFUN([DX_ENV_APPEND], [AC_SUBST([DX_ENV], ["$DX_ENV $1='$2'"])]) # DX_DIRNAME_EXPR # --------------- # Expand into a shell expression prints the directory part of a path. AC_DEFUN([DX_DIRNAME_EXPR], [[expr ".$1" : '\(\.\)[^/]*$' \| "x$1" : 'x\(.*\)/[^/]*$']]) # DX_IF_FEATURE(FEATURE, IF-ON, IF-OFF) # ------------------------------------- # Expands according to the M4 (static) status of the feature. AC_DEFUN([DX_IF_FEATURE], [ifelse(DX_FEATURE_$1, ON, [$2], [$3])]) # DX_REQUIRE_PROG(VARIABLE, PROGRAM) # ---------------------------------- # Require the specified program to be found for the DX_CURRENT_FEATURE to work. AC_DEFUN([DX_REQUIRE_PROG], [ AC_PATH_TOOL([$1], [$2]) if test "$DX_FLAG_DX_CURRENT_FEATURE$$1" = 1; then AC_MSG_WARN([$2 not found - will not DX_CURRENT_DESCRIPTION]) AC_SUBST([DX_FLAG_DX_CURRENT_FEATURE], 0) fi ]) # DX_TEST_FEATURE(FEATURE) # ------------------------ # Expand to a shell expression testing whether the feature is active. AC_DEFUN([DX_TEST_FEATURE], [test "$DX_FLAG_$1" = 1]) # DX_CHECK_DEPEND(REQUIRED_FEATURE, REQUIRED_STATE) # ------------------------------------------------- # Verify that a required features has the right state before trying to turn on # the DX_CURRENT_FEATURE. AC_DEFUN([DX_CHECK_DEPEND], [ test "$DX_FLAG_$1" = "$2" \ || AC_MSG_ERROR([doxygen-DX_CURRENT_FEATURE ifelse([$2], 1, requires, contradicts) doxygen-DX_CURRENT_FEATURE]) ]) # DX_CLEAR_DEPEND(FEATURE, REQUIRED_FEATURE, REQUIRED_STATE) # ---------------------------------------------------------- # Turn off the DX_CURRENT_FEATURE if the required feature is off. AC_DEFUN([DX_CLEAR_DEPEND], [ test "$DX_FLAG_$1" = "$2" || AC_SUBST([DX_FLAG_DX_CURRENT_FEATURE], 0) ]) # DX_FEATURE_ARG(FEATURE, DESCRIPTION, # CHECK_DEPEND, CLEAR_DEPEND, # REQUIRE, DO-IF-ON, DO-IF-OFF) # -------------------------------------------- # Parse the command-line option controlling a feature. CHECK_DEPEND is called # if the user explicitly turns the feature on (and invokes DX_CHECK_DEPEND), # otherwise CLEAR_DEPEND is called to turn off the default state if a required # feature is disabled (using DX_CLEAR_DEPEND). REQUIRE performs additional # requirement tests (DX_REQUIRE_PROG). Finally, an automake flag is set and # DO-IF-ON or DO-IF-OFF are called according to the final state of the feature. AC_DEFUN([DX_ARG_ABLE], [ AC_DEFUN([DX_CURRENT_FEATURE], [$1]) AC_DEFUN([DX_FLAG_DX_CURRENT_FEATURE], [DX_FLAG_$1]) AC_DEFUN([DX_CURRENT_DESCRIPTION], [$2]) AC_ARG_ENABLE(doxygen-$1, [AS_HELP_STRING(DX_IF_FEATURE([$1], [--disable-doxygen-$1], [--enable-doxygen-$1]), DX_IF_FEATURE([$1], [don't $2], [$2]))], [ case "$enableval" in #( y|Y|yes|Yes|YES) AC_SUBST([DX_FLAG_$1], 1) $3 ;; #( n|N|no|No|NO) AC_SUBST([DX_FLAG_$1], 0) ;; #( *) AC_MSG_ERROR([invalid value '$enableval' given to doxygen-$1]) ;; esac ], [ AC_SUBST([DX_FLAG_$1], [DX_IF_FEATURE([$1], 1, 0)]) $4 ]) if DX_TEST_FEATURE([$1]); then $5 : fi if DX_TEST_FEATURE([$1]); then AM_CONDITIONAL(DX_COND_$1, :) $6 : else AM_CONDITIONAL(DX_COND_$1, false) $7 : fi ]) ## -------------- ## ## Public macros. ## ## -------------- ## # DX_XXX_FEATURE(DEFAULT_STATE) # ----------------------------- AC_DEFUN([DX_DOXYGEN_FEATURE], [AC_DEFUN([DX_FEATURE_doc], [$1])]) AC_DEFUN([DX_MAN_FEATURE], [AC_DEFUN([DX_FEATURE_man], [$1])]) AC_DEFUN([DX_HTML_FEATURE], [AC_DEFUN([DX_FEATURE_html], [$1])]) AC_DEFUN([DX_CHM_FEATURE], [AC_DEFUN([DX_FEATURE_chm], [$1])]) AC_DEFUN([DX_CHI_FEATURE], [AC_DEFUN([DX_FEATURE_chi], [$1])]) AC_DEFUN([DX_RTF_FEATURE], [AC_DEFUN([DX_FEATURE_rtf], [$1])]) AC_DEFUN([DX_XML_FEATURE], [AC_DEFUN([DX_FEATURE_xml], [$1])]) AC_DEFUN([DX_XML_FEATURE], [AC_DEFUN([DX_FEATURE_xml], [$1])]) AC_DEFUN([DX_PDF_FEATURE], [AC_DEFUN([DX_FEATURE_pdf], [$1])]) AC_DEFUN([DX_PS_FEATURE], [AC_DEFUN([DX_FEATURE_ps], [$1])]) # DX_INIT_DOXYGEN(PROJECT, [CONFIG-FILE], [OUTPUT-DOC-DIR]) # --------------------------------------------------------- # PROJECT also serves as the base name for the documentation files. # The default CONFIG-FILE is "Doxyfile" and OUTPUT-DOC-DIR is "doxygen-doc". AC_DEFUN([DX_INIT_DOXYGEN], [ # Files: AC_SUBST([DX_PROJECT], [$1]) AC_SUBST([DX_CONFIG], [ifelse([$2], [], Doxyfile, [$2])]) AC_SUBST([DX_DOCDIR], [ifelse([$3], [], doxygen-doc, [$3])]) # Environment variables used inside doxygen.cfg: DX_ENV_APPEND(SRCDIR, $srcdir) DX_ENV_APPEND(PROJECT, $DX_PROJECT) DX_ENV_APPEND(DOCDIR, $DX_DOCDIR) DX_ENV_APPEND(VERSION, $PACKAGE_VERSION) # Doxygen itself: DX_ARG_ABLE(doc, [generate any doxygen documentation], [], [], [DX_REQUIRE_PROG([DX_DOXYGEN], doxygen) DX_REQUIRE_PROG([DX_PERL], perl)], [DX_ENV_APPEND(PERL_PATH, $DX_PERL)]) # Dot for graphics: DX_ARG_ABLE(dot, [generate graphics for doxygen documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [DX_REQUIRE_PROG([DX_DOT], dot)], [DX_ENV_APPEND(HAVE_DOT, YES) DX_ENV_APPEND(DOT_PATH, [`DX_DIRNAME_EXPR($DX_DOT)`])], [DX_ENV_APPEND(HAVE_DOT, NO)]) # Man pages generation: DX_ARG_ABLE(man, [generate doxygen manual pages], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [], [DX_ENV_APPEND(GENERATE_MAN, YES)], [DX_ENV_APPEND(GENERATE_MAN, NO)]) # RTF file generation: DX_ARG_ABLE(rtf, [generate doxygen RTF documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [], [DX_ENV_APPEND(GENERATE_RTF, YES)], [DX_ENV_APPEND(GENERATE_RTF, NO)]) # XML file generation: DX_ARG_ABLE(xml, [generate doxygen XML documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [], [DX_ENV_APPEND(GENERATE_XML, YES)], [DX_ENV_APPEND(GENERATE_XML, NO)]) # (Compressed) HTML help generation: DX_ARG_ABLE(chm, [generate doxygen compressed HTML help documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [DX_REQUIRE_PROG([DX_HHC], hhc)], [DX_ENV_APPEND(HHC_PATH, $DX_HHC) DX_ENV_APPEND(GENERATE_HTML, YES) DX_ENV_APPEND(GENERATE_HTMLHELP, YES)], [DX_ENV_APPEND(GENERATE_HTMLHELP, NO)]) # Seperate CHI file generation. DX_ARG_ABLE(chi, [generate doxygen seperate compressed HTML help index file], [DX_CHECK_DEPEND(chm, 1)], [DX_CLEAR_DEPEND(chm, 1)], [], [DX_ENV_APPEND(GENERATE_CHI, YES)], [DX_ENV_APPEND(GENERATE_CHI, NO)]) # Plain HTML pages generation: DX_ARG_ABLE(html, [generate doxygen plain HTML documentation], [DX_CHECK_DEPEND(doc, 1) DX_CHECK_DEPEND(chm, 0)], [DX_CLEAR_DEPEND(doc, 1) DX_CLEAR_DEPEND(chm, 0)], [], [DX_ENV_APPEND(GENERATE_HTML, YES)], [DX_TEST_FEATURE(chm) || DX_ENV_APPEND(GENERATE_HTML, NO)]) # PostScript file generation: DX_ARG_ABLE(ps, [generate doxygen PostScript documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [DX_REQUIRE_PROG([DX_LATEX], latex) DX_REQUIRE_PROG([DX_MAKEINDEX], makeindex) DX_REQUIRE_PROG([DX_DVIPS], dvips) DX_REQUIRE_PROG([DX_EGREP], egrep)]) # PDF file generation: DX_ARG_ABLE(pdf, [generate doxygen PDF documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [DX_REQUIRE_PROG([DX_PDFLATEX], pdflatex) DX_REQUIRE_PROG([DX_MAKEINDEX], makeindex) DX_REQUIRE_PROG([DX_EGREP], egrep)]) # LaTeX generation for PS and/or PDF: if DX_TEST_FEATURE(ps) || DX_TEST_FEATURE(pdf); then AM_CONDITIONAL(DX_COND_latex, :) DX_ENV_APPEND(GENERATE_LATEX, YES) else AM_CONDITIONAL(DX_COND_latex, false) DX_ENV_APPEND(GENERATE_LATEX, NO) fi # Paper size for PS and/or PDF: AC_ARG_VAR(DOXYGEN_PAPER_SIZE, [a4wide (default), a4, letter, legal or executive]) case "$DOXYGEN_PAPER_SIZE" in #( "") AC_SUBST(DOXYGEN_PAPER_SIZE, "") ;; #( a4wide|a4|letter|legal|executive) DX_ENV_APPEND(PAPER_SIZE, $DOXYGEN_PAPER_SIZE) ;; #( *) AC_MSG_ERROR([unknown DOXYGEN_PAPER_SIZE='$DOXYGEN_PAPER_SIZE']) ;; esac #For debugging: echo DX_FLAG_doc=$DX_FLAG_doc echo DX_FLAG_dot=$DX_FLAG_dot echo DX_FLAG_man=$DX_FLAG_man echo DX_FLAG_html=$DX_FLAG_html echo DX_FLAG_chm=$DX_FLAG_chm echo DX_FLAG_chi=$DX_FLAG_chi echo DX_FLAG_rtf=$DX_FLAG_rtf echo DX_FLAG_xml=$DX_FLAG_xml echo DX_FLAG_pdf=$DX_FLAG_pdf echo DX_FLAG_ps=$DX_FLAG_ps echo DX_ENV=$DX_ENV ]) libusbgx-libusbgx-v0.3.0/aminclude.am000066400000000000000000000111751467553526200176400ustar00rootroot00000000000000# Copyright (C) 2004 Oren Ben-Kiki # This file is distributed under the same terms as the Automake macro files. # Generate automatic documentation using Doxygen. Goals and variables values # are controlled by the various DX_COND_??? conditionals set by autoconf. # # The provided goals are: # doxygen-doc: Generate all doxygen documentation. # doxygen-run: Run doxygen, which will generate some of the documentation # (HTML, CHM, CHI, MAN, RTF, XML) but will not do the post # processing required for the rest of it (PS, PDF, and some MAN). # doxygen-man: Rename some doxygen generated man pages. # doxygen-ps: Generate doxygen PostScript documentation. # doxygen-pdf: Generate doxygen PDF documentation. # # Note that by default these are not integrated into the automake goals. If # doxygen is used to generate man pages, you can achieve this integration by # setting man3_MANS to the list of man pages generated and then adding the # dependency: # # $(man3_MANS): doxygen-doc # # This will cause make to run doxygen and generate all the documentation. # # The following variable is intended for use in Makefile.am: # # DX_CLEANFILES = everything to clean. # # This is usually added to MOSTLYCLEANFILES. ## --------------------------------- ## ## Format-independent Doxygen rules. ## ## --------------------------------- ## if DX_COND_doc ## ------------------------------- ## ## Rules specific for HTML output. ## ## ------------------------------- ## if DX_COND_html DX_CLEAN_HTML = @DX_DOCDIR@/html endif DX_COND_html ## ------------------------------ ## ## Rules specific for CHM output. ## ## ------------------------------ ## if DX_COND_chm DX_CLEAN_CHM = @DX_DOCDIR@/chm if DX_COND_chi DX_CLEAN_CHI = @DX_DOCDIR@/@PACKAGE@.chi endif DX_COND_chi endif DX_COND_chm ## ------------------------------ ## ## Rules specific for MAN output. ## ## ------------------------------ ## if DX_COND_man DX_CLEAN_MAN = @DX_DOCDIR@/man endif DX_COND_man ## ------------------------------ ## ## Rules specific for RTF output. ## ## ------------------------------ ## if DX_COND_rtf DX_CLEAN_RTF = @DX_DOCDIR@/rtf endif DX_COND_rtf ## ------------------------------ ## ## Rules specific for XML output. ## ## ------------------------------ ## if DX_COND_xml DX_CLEAN_XML = @DX_DOCDIR@/xml endif DX_COND_xml ## ----------------------------- ## ## Rules specific for PS output. ## ## ----------------------------- ## if DX_COND_ps DX_CLEAN_PS = @DX_DOCDIR@/@PACKAGE@.ps DX_PS_GOAL = doxygen-ps doxygen-ps: @DX_DOCDIR@/@PACKAGE@.ps @DX_DOCDIR@/@PACKAGE@.ps: @DX_DOCDIR@/@PACKAGE@.tag cd @DX_DOCDIR@/latex; \ rm -f *.aux *.toc *.idx *.ind *.ilg *.log *.out; \ $(DX_LATEX) refman.tex; \ $(MAKEINDEX_PATH) refman.idx; \ $(DX_LATEX) refman.tex; \ countdown=5; \ while $(DX_EGREP) 'Rerun (LaTeX|to get cross-references right)' \ refman.log > /dev/null 2>&1 \ && test $$countdown -gt 0; do \ $(DX_LATEX) refman.tex; \ countdown=`expr $$countdown - 1`; \ done; \ $(DX_DVIPS) -o ../@PACKAGE@.ps refman.dvi endif DX_COND_ps ## ------------------------------ ## ## Rules specific for PDF output. ## ## ------------------------------ ## if DX_COND_pdf DX_CLEAN_PDF = @DX_DOCDIR@/@PACKAGE@.pdf DX_PDF_GOAL = doxygen-pdf doxygen-pdf: @DX_DOCDIR@/@PACKAGE@.pdf @DX_DOCDIR@/@PACKAGE@.pdf: @DX_DOCDIR@/@PACKAGE@.tag cd @DX_DOCDIR@/latex; \ rm -f *.aux *.toc *.idx *.ind *.ilg *.log *.out; \ $(DX_PDFLATEX) refman.tex; \ $(DX_MAKEINDEX) refman.idx; \ $(DX_PDFLATEX) refman.tex; \ countdown=5; \ while $(DX_EGREP) 'Rerun (LaTeX|to get cross-references right)' \ refman.log > /dev/null 2>&1 \ && test $$countdown -gt 0; do \ $(DX_PDFLATEX) refman.tex; \ countdown=`expr $$countdown - 1`; \ done; \ mv refman.pdf ../@PACKAGE@.pdf endif DX_COND_pdf ## ------------------------------------------------- ## ## Rules specific for LaTeX (shared for PS and PDF). ## ## ------------------------------------------------- ## if DX_COND_latex DX_CLEAN_LATEX = @DX_DOCDIR@/latex endif DX_COND_latex .PHONY: doxygen-run doxygen-doc $(DX_PS_GOAL) $(DX_PDF_GOAL) .INTERMEDIATE: doxygen-run $(DX_PS_GOAL) $(DX_PDF_GOAL) doxygen-run: @DX_DOCDIR@/@PACKAGE@.tag doxygen-doc: doxygen-run $(DX_PS_GOAL) $(DX_PDF_GOAL) @DX_DOCDIR@/@PACKAGE@.tag: $(DX_CONFIG) $(pkginclude_HEADERS) rm -rf @DX_DOCDIR@ $(DX_ENV) $(DX_DOXYGEN) $(srcdir)/$(DX_CONFIG) DX_CLEANFILES = \ @DX_DOCDIR@/@PACKAGE@.tag \ -r \ $(DX_CLEAN_HTML) \ $(DX_CLEAN_CHM) \ $(DX_CLEAN_CHI) \ $(DX_CLEAN_MAN) \ $(DX_CLEAN_RTF) \ $(DX_CLEAN_XML) \ $(DX_CLEAN_PS) \ $(DX_CLEAN_PDF) \ $(DX_CLEAN_LATEX) endif DX_COND_doc libusbgx-libusbgx-v0.3.0/configure.ac000066400000000000000000000045731467553526200176520ustar00rootroot00000000000000AC_INIT([libusbgx], [0.3.0], [m.grzeschik@pengutronix.de]) AM_INIT_AUTOMAKE([1.12 -Wall -Werror foreign serial-tests]) AC_PROG_CC AC_PROG_CXX AM_PROG_AR AM_PROG_CC_C_O AC_CONFIG_MACRO_DIR([m4]) AC_DEFINE([_GNU_SOURCE], [], [Use GNU extensions]) USBG_VERSION_HEX=`printf '0x%02x%02x%04x' $(printf '%s' "$PACKAGE_VERSION" | sed -e 's/\./ /g')` AC_SUBST([USBG_VERSION_HEX]) AC_ARG_WITH([libconfig], AS_HELP_STRING([--without-libconfig], [build without using libconfig]), [with_libconfig=$withval], [with_libconfig=yes]) AC_ARG_ENABLE([examples], AS_HELP_STRING([--disable-examples], [build without examples]), [enable_examples=$enableval], [enable_examples=yes]) AC_ARG_ENABLE([gadget-schemes], AS_HELP_STRING([--disable-gadget-schemes], [build without gadget-schemes support]), [enable_gadget_schemes=$enableval], [enable_gadget_schemes=yes]) AC_ARG_ENABLE([tests], AS_HELP_STRING([--enable-tests], [build with tests]), [enable_tests=$enableval], [enable_tests=no]) # if both tests and schemes are disabled, we do not need libconfig AS_IF([test "x$enable_gadget_schemes" = xno && test "x$enable_tests" = xno], [with_libconfig=no]) AS_IF([test "x$with_libconfig" = xyes], [ PKG_CHECK_MODULES([LIBCONFIG], [libconfig >= 1.4], [ AC_DEFINE(HAS_LIBCONFIG, 1, [detected libconfig]) PKG_CHECK_MODULES([NEW_LIBCONFIG], [libconfig >= 1.5], AC_DEFINE(HAVE_LIBCONFIG_15, 1, [detected libconfig equal to or greater than 1.5]), AC_DEFINE(HAVE_LIBCONFIG_15, 0, [])) ]) libconfig_req="libconfig" CFLAGS="$CFLAGS $LIBCONFIG_CFLAGS" LIBS="$LIBS $LIBCONFIG_LIBS" ], [ libconfig_req="" enable_gadget_schemes=no ]) REQUIRES="$libconfig_req" AC_SUBST([REQUIRES]) AM_CONDITIONAL(BUILD_EXAMPLES, [test "x$enable_examples" = xyes]) AS_IF([test "x$enable_tests" = xyes], [ PKG_CHECK_MODULES([CMOCKA], [cmocka >= 1.0.0], AC_DEFINE(HAS_CMOCKA, 1, [detected cmocka])) ]) AM_CONDITIONAL(BUILD_TESTS, [test "x$enable_tests" = xyes]) AS_IF([test "x$enable_gadget_schemes" = xyes], [AC_DEFINE(HAS_GADGET_SCHEMES, 1, [gadget schemes are enables])]) AM_CONDITIONAL(TEST_GADGET_SCHEMES, [test "x$enable_gadget_schemes" != xno]) LT_INIT AC_CONFIG_FILES([Makefile src/Makefile tests/Makefile examples/Makefile include/usbg/usbg_version.h libusbgx.pc doxygen.cfg LibUsbgxConfig.cmake]) DX_INIT_DOXYGEN([$PACKAGE_NAME],[doxygen.cfg]) AC_OUTPUT libusbgx-libusbgx-v0.3.0/doc/000077500000000000000000000000001467553526200161205ustar00rootroot00000000000000libusbgx-libusbgx-v0.3.0/doc/gadget_schemes.txt000066400000000000000000000237771467553526200216430ustar00rootroot00000000000000 Gadget schemes Index: 1. What are gadget schemes? 2. Why gadget schemes? 3. Gadget scheme syntax 3.1 Function scheme 3.2 Configuration scheme 3.3 Gadget scheme 4. Conclusion 1. What are gadget schemes? Gadget schemes are files which contains configuration data of gadget/function/configuration. Those files can be generated using usbg_export_*() functions for whole gadget, configuration or single function. Library provides also set of usbg_import_*() functions which allows to load configuration data back to configfs. 2. Why gadget schemes? New kernel interface - ConfigFS which along with libcomposite allows to set up custom gadget. This can be achieved using simple, command line file system operation like mkdir, rmdir, ln -s, read and write. Yes, it is possible to configure usb gadget using only command line but each time after reboot user needs to recreate all gadgets once again. This means that after each reboot user needs to use about 15 commands (depends on number and types of function). This is definitely not acceptable for those who used legacy gadgets and write only modprobe g_ether. One of first idea to solve this is to create a script and run it after each reboot. This approach is feasible but has many disadvantages. First of them is security. ConfigFS is modifiable by default only by root, so scripts has to be executed with root rights. Secondly it's really hard to modify such a script because many calls has hard-coded path where for example echo should be done. There is a lot of simple, but low level operations which can cause a lot of confusion for beginner. Second approach is to create executable which will create our gadget using base libusbg API. It is also possible but let's think for a moment why configfs has been introduced. It has been announced to separate code from configuration. Code is a piece of C code in kernel module which realizes usb function and configuration is understood as composition of those functions into a gadget as a whole. If we would like to create binary file for each gadget we would waste a lot of work which kernel contributors put to remove hard-coded gadgets from linux kernel. This all leads us to solution described in this document - gadget schemes. Light weight configuration files which describes composition of functions into gadget. They can be simply loaded using usbg_import_*() and exported using usbg_export_*(). This makes them easy to use equivalent of modprobe gadget_module. 3. Gadget scheme syntax Gadget schemes implementation uses libconfig for reading and writing scheme files. This means that all limitations of libconfig are also present in gadget schemes. More over there are additional constrains for scheme files. Gadget scheme is only a password and import and export is not limited to whole gadgets. It is possible to export all 3 types of gadget entity: function, configuration and gadget. Please refer to libconfig documentation for details about syntax and rules. 3.1 Function scheme Function scheme is a file or part of file which represents single function. Example: instance = "my_func_instance" type = "ecm" attrs = { dev_addr = "ef:33:be:9a:90:36" dev_addr = "ab:63:6e:8b:10:16" qmult = 5 } For functions, type is the only attribute which is always mandatory. Instance is mandatory only if function is part of bigger scheme (gadget for example). By default usbg_export_function() does not export instance name, because usbg_import_function() takes instance as one of parameters. This convention allows for simple function movement between gadgets without names conflict. Attrs section is optional. It may not be included, present but empty or present and filled with function attributes. Attribute names are similar as those from configfs. Each type of function has own set of possible attributes. It is worth to mention that some attributes are read only and they cannot be imported from file. To make it more user-friendly read-only parameters are just ignored. This allows for direct use of previously exported function in import. If some attribute has not been provided default value provided by kernel will be used. 3.2 Configuration scheme Configuration scheme is a file or part of file which represents single configuration with its attributes, strings and bindings. Simple example: id = 1 name = "My favorite config" attrs = { bMaxPower = 0x40 bmAttributes = 0x00 } strings = ( { lang = 0x409 configuration = "My favorite string" } ) functions = ( "function_label" ) This is example of simple configuration with some attributes values, strings in US English and only one function. For configurations name is the only field which is always mandatory. Id is mandatory only if this is a part of bigger structure (gadget scheme). Attrs section is optional. It may not be included, present but empty or present and filled with function attributes. Attribute names are similar as those from configfs. Currently usb configuration has only two attributes: bMaxPower and bmAttributes. Their meaning and set of allowed values can be found in usb standard. Strings section presence policy is the same as attrs section. This section contains a list (that's the meaning of parentheses) of strings with their language codes. Each group of strings has to declare their language using lang field. Configuration string is optional. If this field is not set, empty string provided by kernel will be used for this language. Max number of languages is defined during kernel compilation using MAX_USB_STRING_LANGS define. Functions section is also optional. This allows for exporting not fully configured configurations. This section defines bindings between functions and configurations. The easiest and shortest way to define a connection between functions and configuration is to provide list of comma separated functions labels. For details about function labels please refer to gadget schemes subsection. Bindings of function to given configuration could be defined in different ways which has been presented in featured example. Featured example: id = 1 name = "My favorite config" attrs = { bMaxPower = 0x40 bmAttributes = 0x00 } strings = ( { lang = 0x409 configuration = "My favorite string" } , { lang = 0x415 configuration = "Moj ulubiony napis" } ) functions = ( "function_label" , { name = "my_binding_name" function = "other_function_label" } , { name = "my_binding_name" function = { type = "ecm" instance = "my_inline_func_definition" attrs = { dev_addr = "ef:33:be:9a:90:36" } } } ) First way to add function to configuration has been described along with simple example. Second way is to provide a group with two fields. First one is name and it should contain a string with binding name. This field is optional and can be omitted what makes this more verbose equivalent of previous method. Second field, named function is mandatory. This field should contain function label. Third way to add function to config is to define it inline. This method allows to define a brand new function instead of providing function label of existing one. 3.3 Gadget scheme Gadget scheme is a file which represents whole gadget with configurations, attributes, strings and functions. Example: attrs = { bcdUSB = 0x200 bDeviceClass = 0x0 bDeviceSubClass = 0x0 bDeviceProtocol = 0x0 bMaxPacketSize0 = 0x40 idVendor = 0x1D6B idProduct = 0x104 bcdDevice = 0x1 } strings = ( { lang = 0x409 manufacturer = "Foo Inc." product = "Bar Gadget" serialnumber = "0123456789" } ) functions = { acm_usb0 = { instance = "usb0" type = "acm" } my_awesome_label = { instance = "inst_name" @include "my_func_scheme.scheme" } } configs = ( { id = 1 name = "The only one" attrs = { bmAttributes = 0x80 bMaxPower = 0x2 } strings = ( { lang = 0x409 configuration = "Config id 1" } ) functions = ( { name = "acm.GS0" function = "acm_usb0" } ) } , { id = 2 @include "some_config.scheme" } ) All sections in gadget scheme are optional. If attrs section has not been defined defaults provided by kernel are used for each attribute. All possible gadget attributes has been listed in above example. Their names are similar to those provided by usb standard and configfs. Strings section is similar to strings section from configuration scheme. Allowed strings are listed in example. Functions section is used to define functions which are aggregated by this gadget. Definition of each function begins with unique label. Any string which fulfills libconfig naming rules can be used as label, but there is one important thing - function labels are not stored in configfs. They are transient and are lost while executing usbg_cleanup(). To allow using this label after next usbg_init() there is a naming rule: type + "_" + instance. If label follows this convention it could be regenerated each time when it is needed. Definition of each function contains a function scheme which has been described in one of previous sections. It is also possible to use include directive of libconfig and provide only instance name in gadget shceme and include previously exported function scheme from other gadget. Configfs section contains list of configurations definitions. Each configuration is defined using configuration scheme described in previous section. Each configuration can be fully defined in gadget scheme file or simply included from other file just like function. 4. Conclusion Syntax of gadget scheme is based on libconfig and if any doubts appear don't hesitate to look into documentation of this library. There are also sample applications which shows how to use usbg_import_*() and usbg_export_*() functions in examples directory. libusbgx-libusbgx-v0.3.0/doc/tests_guideline.txt000066400000000000000000000145331467553526200220560ustar00rootroot00000000000000Libusbg testing guideline ------------------------- Libusbg tests use cmocka library to simulate fake configfs filesystem, by wrapping input/output functions. ## Building and running tests # Requirements Building libusbg tests requires: -CMocka unit testing framework in version >= 0.3 -libconfig in version >= 1.4 # Building and running Before testing make sure that you have successfully built libusbg (see INSTALL for more details). Tests must be enabled in configuration, do it by adding proper flag when configuring: $ ./configure --enable-tests Then, to build and run all provided tests, run following command: $ make check This should execute testing script and produce report on standart output. It contains list of all test cases and its status - OK, FAILED and SKIPPED. At the end of report number of passed/failed tests is written and then all failed test cases are listed. This report is also avaible in tests/test-suite.log file. It's also possible to pass custom configuration file to testing environment. Currently it's used only for skipping tests. Use --generate-config and --use-config options of test.sh to generate default config and read config from file. Run ./test.sh --help for more help with testing environment. # Tests skipping When you want to skip some test cases, use configuration files for test suite. To generate default config run: $ make check GENERATE_CONFIG=[file_name] It will generate tests/[file_name] file with configuration for testing. You can remove test cases from 'tests' list to disable them. With custom configuration file run: $make check USE_CONFIG=[file_name] Where file_name is name of previously generated configuration file. Test suite will skip tests not listed in config. ## Writting tests Before starting your own tests implementation, become familiar with cmocka library (cmocka.org). test.c file contains tests implementation. Test cases are stored in UnitTest structures (from cmocka) and run by run_tests macro. In cmocka each test case can be composed of three parts: setup, test and teardown. # Setup functions In setup input data must be initialized and assigned to pointer given as argument. Libusbg requires initialized usbg_state structure for most of it's api functions. In most cases we define initial state in test_* strutures and pass it to test function, in order to run usbg_init. Each test_state can be defined quite simply by listing gadgets, its configs and functions (using gcc extenstion), e.g.: static struct test_state simple_state = { .path = "config", .gadgets = simple_gadgets, .udcs = simple_udcs }; test_state structure (or other structure, if neccessary for test case) is casted to void * in setup function. Note, that when using test_state you must sort its content and fill additional fields (i.e. pathes strings). It can be done by calling prepare_state before test. # Test functions Test functions contain libusbg functions calls, preparations for them and checking results. When calling usbg function which operates on filesystem proper preparation is needed. Usbg-test framework provides functions which tell cmocka what operations are expected from corresponding usbg function (push_* and pull_* functions). E.g., in most cases you want correctly initialized usbg_state. It can be done by preparing filesystem by push_init and running usbg_init after that: push_init(in); usbg_ret = usbg_init(in->path, out); init_with_state function does that and checks results. When tested usbg function was run, you can check results by cmocka assert macros. Usbg-test also provides set of assert functions for usbg structures. # Teardown functions When test was run, you can define teardown function, which can do the cleanup. Argument is passed same way as before, by assigning it to cmocka state pointer in test function and receiving it in teardown function. In most cases you will just want to cleanup after initializing state and running some usbg functions. To do that teardown_state can be used as teardown function. You can write custom teardown for other cases. Note that in preparation for test some memory is allocated. All allocated pointers are stored on global stack and should be freed by calling cleanup_stack after test is finished (in teardown function). Remember that teardown is called also when test failed. You should assign something correct (NULL for example) for your teardown function to test argument before running functions which may fail. # Composing test cases All test cases are defined in list of UnitTest structures. You can define test case by macros provided by cmocka or by USBG_TEST or USBG_TEST_TS macro. USBG_TEST is similar to unit_test_setup_teardown from cmocka, but always uses the same teardown (teardown_state) and names test case with custom string. It combines setup function with test function, so one test function can be run with many different states. # Documenting test cases For tests documentation few doxygen macros are created. \usbg_test indicates that current comment block contains test case documentation. \test_desc{name, description, function} describe test with its name, function which is tested and short descripttion of what this test does. # Adding tests Simplest way to add more tests is defining test states and new setup functions, combining them with existing testing functions using USBG_TEST. You can also write own test function. When you have test and setup prepared, add USBG_TEST_TS("test_name", test_function, setup_function), or USBG_TEST("test_name", test_function, setup_function, teardown_function), at the end of tests[] array. Remember to add documentation to the case (see Documenting test cases). # Removing tests In order to remove test case just delete corresponding element on tests[] list (including documentation above it). # Modyfing tests When you want to change data using in test case, change corresponding test_* structures. Note, that single test state can be used in many test cases and modyfing it can effect them as well. You can also change test logic (by modifying test function used in case), as long as you know what you're doing. ## Final notes Remember, that in test environment functions operating on files are replaced and operations on files cannot be performed. However, using standard input/output is possible. All test cases are run in single thread, so some failures on one test case (e.g. SIGSEGV) can cause crash on whole tests set. libusbgx-libusbgx-v0.3.0/doxygen.cfg.in000066400000000000000000002242511467553526200201240ustar00rootroot00000000000000# Doxyfile 1.7.6.1 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" "). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or sequence of words) that should # identify the project. Note that if you do not use Doxywizard you need # to put quotes around the project name if it contains spaces. PROJECT_NAME = $(PROJECT)-$(VERSION) # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer # a quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = # With the PROJECT_LOGO tag one can specify an logo or icon that is # included in the documentation. The maximum height of the logo should not # exceed 55 pixels and the maximum width should not exceed 200 pixels. # Doxygen will copy the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = $(DOCDIR) # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, # Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English # messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, # Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, # Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = YES # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. STRIP_FROM_PATH = $(SRCDIR) # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful if your file system # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 8 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding # "class=itcl::class" will allow you to use the command class in the # itcl::class meaning. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = YES # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given extension. # Doxygen has a built-in mapping, but you can override or extend it using this # tag. The format is ext=language, where ext is a file extension, and language # is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, # C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make # doxygen treat .inc files as Fortran files (default is PHP), and .f files as C # (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions # you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. EXTENSION_MAPPING = # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also makes the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate getter # and setter methods for a property. Setting this option to YES (the default) # will make doxygen replace the get and set methods by a property in the # documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and # unions are shown inside the group in which they are included (e.g. using # @ingroup) instead of on a separate page (for HTML and Man pages) or # section (for LaTeX and RTF). INLINE_GROUPED_CLASSES = YES # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and # unions with only public data fields will be shown inline in the documentation # of the scope in which they are defined (i.e. file, namespace, or group # documentation), provided this scope is documented. If set to NO (the default), # structs, classes, and unions are shown on a separate page (for HTML and Man # pages) or section (for LaTeX and RTF). INLINE_SIMPLE_STRUCTS = YES # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO # The SYMBOL_CACHE_SIZE determines the size of the internal cache use to # determine which symbols to keep in memory and which to flush to disk. # When the cache is full, less often used symbols will be written to disk. # For small to medium size projects (<1000 input files) the default value is # probably good enough. For larger projects a too small cache size can cause # doxygen to be busy swapping symbols to and from disk most of the time # causing a significant performance penalty. # If the system has enough physical memory increasing the cache will improve the # performance by keeping more symbols in memory. Note that the value works on # a logarithmic scale so increasing the size by one will roughly double the # memory usage. The cache size is given by this formula: # 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. SYMBOL_CACHE_SIZE = 0 # Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be # set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given # their name and scope. Since this can be an expensive process and often the # same symbol appear multiple times in the code, doxygen keeps a cache of # pre-resolved symbols. If the cache is too small doxygen will become slower. # If the cache is too large, memory is wasted. The cache size is given by this # formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = NO # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = NO # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespaces are hidden. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # will list include files with double quotes in the documentation # rather than with sharp brackets. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen # will sort the (brief and detailed) documentation of class members so that # constructors and destructors are listed first. If set to NO (the default) # the constructors will appear in the respective orders defined by # SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. # This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO # and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to # do proper type resolution of all parameters of a function it will reject a # match between the prototype and the implementation of a member function even # if there is only one candidate or it is obvious which candidate to choose # by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen # will still accept a match between prototype and implementation in such cases. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or macro consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and macros in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES # If the sources in your project are distributed over multiple directories # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy # in the documentation. The default is NO. SHOW_DIRECTORIES = NO # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. # This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. The create the layout file # that represents doxygen's defaults, run doxygen with the -l option. # You can optionally specify a file name after the option, if omitted # DoxygenLayout.xml will be used as the name of the layout file. LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files # containing the references data. This must be a list of .bib files. The # .bib extension is automatically appended if omitted. Using this command # requires the bibtex tool to be installed. See also # http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style # of the bibliography can be controlled using LATEX_BIB_STYLE. To use this # feature you need bibtex and perl available in the search path. CITE_BIB_FILES = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = NO # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # The WARN_NO_PARAMDOC option can be enabled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = YES # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = $(SRCDIR)/include/usbg/ $(SRCDIR)/src $(SRCDIR)/examples/ @BUILD_TESTS_TRUE@INPUT += $(SRCDIR)/tests/ # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh # *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py # *.f90 *.f *.for *.vhd *.vhdl FILE_PATTERNS = # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = NO # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # Note that relative paths are relative to the directory from which doxygen is # run. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = $(SRCDIR)/examples/ # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. # If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. # Doxygen will compare the file name with each pattern and apply the # filter if there is a match. # The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty or if # non of the patterns match the file name, INPUT_FILTER is applied. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) # and it is also possible to disable source filtering for a specific pattern # using *.ext= (so without naming a filter). This option only has effect when # FILTER_SOURCE_FILES is enabled. FILTER_SOURCE_PATTERNS = #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = NO # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = NO # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. # Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = YES # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. Note that when using a custom header you are responsible # for the proper inclusion of any scripts and style sheets that doxygen # needs, which is dependent on the configuration options used. # It is advised to generate a default header using "doxygen -w html # header.html footer.html stylesheet.css YourConfigFile" and then modify # that header. Note that the header is subject to change so you typically # have to redo this when upgrading to a newer version of doxygen or when # changing the value of configuration settings such as GENERATE_TREEVIEW! HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet. Note that doxygen will try to copy # the style sheet file to the HTML output directory, so don't put your own # style sheet in the HTML output directory as well, or it will be erased! HTML_STYLESHEET = # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that # the files will be copied as-is; there are no commands or markers available. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. # Doxygen will adjust the colors in the style sheet and background images # according to this color. Hue is specified as an angle on a colorwheel, # see http://en.wikipedia.org/wiki/Hue for more information. # For instance the value 0 represents red, 60 is yellow, 120 is green, # 180 is cyan, 240 is blue, 300 purple, and 360 is red again. # The allowed range is 0 to 359. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of # the colors in the HTML output. For a value of 0 the output will use # grayscales only. A value of 255 will produce the most vivid colors. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to # the luminance component of the colors in the HTML output. Values below # 100 gradually make the output lighter, whereas values above 100 make # the output darker. The value divided by 100 is the actual gamma applied, # so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, # and 100 does not change the gamma. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting # this to NO can help when comparing the output of multiple runs. HTML_TIMESTAMP = YES # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. For this to work a browser that supports # JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox # Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). HTML_DYNAMIC_SECTIONS = NO # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated # that can be used as input for Qt's qhelpgenerator to generate a # Qt Compressed Help (.qch) of the generated HTML documentation. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = doc # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to # add. For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see # # Qt Help Project / Custom Filters. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's # filter section matches. # # Qt Help Project / Filter Attributes. QHP_SECT_FILTER_ATTRS = # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files # will be generated, which together with the HTML files, form an Eclipse help # plugin. To install this plugin and make it available under the help contents # menu in Eclipse, the contents of the directory containing the HTML and XML # files needs to be copied into the plugins directory of eclipse. The name of # the directory within the plugins directory should be the same as # the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before # the help appears. GENERATE_ECLIPSEHELP = NO # A unique identifier for the eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have # this name. ECLIPSE_DOC_ID = org.doxygen.Project # The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) # at top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. Since the tabs have the same information as the # navigation tree you can set this option to NO if you already set # GENERATE_TREEVIEW to YES. DISABLE_INDEX = NO # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to YES, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). # Windows users are probably better off using the HTML help feature. # Since the tree basically has the same information as the tab index you # could consider to set DISABLE_INDEX to NO when enabling this option. GENERATE_TREEVIEW = NO # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values # (range [0,1..20]) that doxygen will group on one line in the generated HTML # documentation. Note that a value of 0 will completely suppress the enum # values from appearing in the overview section. ENUM_VALUES_PER_LINE = 4 # By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, # and Class Hierarchy pages using a tree view instead of an ordered list. USE_INLINE_TREES = NO # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 # When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open # links to external symbols imported via tag files in a separate window. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are # not supported properly for IE 6.0, but are supported on all modern browsers. # Note that when changing this option you need to delete any form_*.png files # in the HTML output before the changes have effect. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax # (see http://www.mathjax.org) which uses client side Javascript for the # rendering instead of using prerendered bitmaps. Use this if you do not # have LaTeX installed or if you want to formulas look prettier in the HTML # output. When enabled you also need to install MathJax separately and # configure the path to it using the MATHJAX_RELPATH option. USE_MATHJAX = NO # When MathJax is enabled you need to specify the location relative to the # HTML output directory using the MATHJAX_RELPATH option. The destination # directory should contain the MathJax.js script. For instance, if the mathjax # directory is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to the # mathjax.org site, so you can quickly see the result without installing # MathJax, but it is strongly recommended to install a local copy of MathJax # before deployment. MATHJAX_RELPATH = http://www.mathjax.org/mathjax # The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension # names that should be enabled during MathJax rendering. MATHJAX_EXTENSIONS = # When the SEARCHENGINE tag is enabled doxygen will generate a search box # for the HTML output. The underlying search engine uses javascript # and DHTML and should work on any modern browser. Note that when using # HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets # (GENERATE_DOCSET) there is already a search function so this one should # typically be disabled. For large projects the javascript based search engine # can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. SEARCHENGINE = YES # When the SERVER_BASED_SEARCH tag is enabled the search engine will be # implemented using a PHP enabled web server instead of at the web client # using Javascript. Doxygen will generate the search PHP script and index # file to put on the web server. The advantage of the server # based approach is that it scales better to large projects and allows # full text search. The disadvantages are that it is more difficult to setup # and does not have live searching capabilities. SERVER_BASED_SEARCH = NO #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = YES # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. # Note that when enabling USE_PDFLATEX this option is only used for # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4 # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for # the generated latex document. The footer should contain everything after # the last chapter. If it is left blank doxygen will generate a # standard footer. Notice: only use this tag if you know what you are doing! LATEX_FOOTER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = YES # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = YES # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO # If LATEX_SOURCE_CODE is set to YES then doxygen will include # source code with syntax highlighting in the LaTeX output. # Note that which sources are shown also depends on other settings # such as SOURCE_BROWSER. LATEX_SOURCE_CODE = NO # The LATEX_BIB_STYLE tag can be used to specify the style to use for the # bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See # http://en.wikipedia.org/wiki/BibTeX for more info. LATEX_BIB_STYLE = plain #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load style sheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. # This is useful # if you want to understand what is going on. # On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = NO # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # pointed to by INCLUDE_PATH will be searched when a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = DOXYGEN # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition that # overrules the definition found in the source code. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all references to function-like macros # that are alone on a line, have an all uppercase name, and do not end with a # semicolon, because these will confuse the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. # Optionally an initial location of the external documentation # can be added for each tagfile. The format of a tag file without # this location is as follows: # # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths or # URLs. If a location is present for each tag, the installdox tool # does not have to be run to correct the links. # Note that each tag file must have a unique name # (where the name does NOT include the path) # If a tag file is not located in the directory in which doxygen # is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option also works with HAVE_DOT disabled, but it is recommended to # install and use dot, since it yields more powerful graphs. CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = NO # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is # allowed to run in parallel. When set to 0 (the default) doxygen will # base this on the number of processors available in the system. You can set it # explicitly to a value larger than 0 to get control over the balance # between CPU load and processing speed. DOT_NUM_THREADS = 0 # By default doxygen will use the Helvetica font for all dot files that # doxygen generates. When you want a differently looking font you can specify # the font name using DOT_FONTNAME. You need to make sure dot is able to find # the font, which can be done by putting it in a standard location or by setting # the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the # directory containing the font. DOT_FONTNAME = Helvetica # The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. # The default size is 10pt. DOT_FONTSIZE = 10 # By default doxygen will tell dot to use the Helvetica font. # If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to # set the path where dot can find it. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = NO # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = NO # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = NO # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will generate a graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are svg, png, jpg, or gif. # If left blank png will be used. If you choose svg you need to set # HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible in IE 9+ (other browsers do not have this requirement). DOT_IMAGE_FORMAT = png # If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to # enable generation of interactive SVG images that allow zooming and panning. # Note that this requires a modern browser other than Internet Explorer. # Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you # need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible. Older versions of IE do not have SVG support. INTERACTIVE_SVG = NO # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the # \mscfile command). MSCFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = NO # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = YES # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES ALIASES += tests_start=" \n" ALIASES += usbg_test="\page usbg_tests" ALIASES += test_desc{3}=" \n" ALIASES += tests_end="
Name Description Tested function
\1 \2 \ref \3
" libusbgx-libusbgx-v0.3.0/examples/000077500000000000000000000000001467553526200171715ustar00rootroot00000000000000libusbgx-libusbgx-v0.3.0/examples/Makefile.am000066400000000000000000000013071467553526200212260ustar00rootroot00000000000000bin_PROGRAMS = show-gadgets gadget-acm-ecm gadget-vid-pid-remove gadget-uvc gadget-ffs gadget-export gadget-import show-udcs gadget-ms gadget-midi gadget-hid gadget-rndis-os-desc gadget-uac2 gadget-printer gadget_acm_ecm_SOURCES = gadget-acm-ecm.c gadget_uvc_SOURCES = gadget-uvc.c show_gadgets_SOURCES = show-gadgets.c gadget_vid_pid_remove_SOURCES = gadget-vid-pid-remove.c gadget_ffs_SOURCES = gadget-ffs.c gadget_export_SOURCE = gadget-export.c gadget_import_SOURCE = gadget-import.c gadget_rndis_os_desc_SOURCES = gadget-rndis-os-desc.c gadget_printer_SOURCE = gadget_printer.c show_udcs_SOURCE = show-udcs.c AM_CPPFLAGS=-I$(top_srcdir)/include/ -I$(top_builddir)/include/usbg AM_LDFLAGS=-L../src/ -lusbgx libusbgx-libusbgx-v0.3.0/examples/gadget-acm-ecm.c000066400000000000000000000104121467553526200220660ustar00rootroot00000000000000/* * Copyright (C) 2013 Linaro Limited * * Matt Porter * * Copyright (C) 2013 - 2015 Samsung Electronics * * Krzysztof Opasiak * * 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. */ #include #include #include #include #include /** * @file gadget-acm-ecm.c * @example gadget-acm-ecm.c * This is an example of how to create an ACM+ECM gadget device. */ #define VENDOR 0x1d6b #define PRODUCT 0x0104 int main(void) { usbg_state *s; usbg_gadget *g; usbg_config *c; usbg_function *f_acm0, *f_acm1, *f_ecm; int ret = -EINVAL; int usbg_ret; struct usbg_gadget_attrs g_attrs = { .bcdUSB = 0x0200, .bDeviceClass = USB_CLASS_PER_INTERFACE, .bDeviceSubClass = 0x00, .bDeviceProtocol = 0x00, .bMaxPacketSize0 = 64, /* Max allowed ep0 packet size */ .idVendor = VENDOR, .idProduct = PRODUCT, .bcdDevice = 0x0001, /* Verson of device */ }; struct usbg_gadget_strs g_strs = { .serial = "0123456789", /* Serial number */ .manufacturer = "Foo Inc.", /* Manufacturer */ .product = "Bar Gadget" /* Product string */ }; struct usbg_config_strs c_strs = { .configuration = "CDC 2xACM+ECM" }; usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB gadget init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out1; } usbg_ret = usbg_create_gadget(s, "g1", &g_attrs, &g_strs, &g); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on create gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_function(g, USBG_F_ACM, "usb0", NULL, &f_acm0); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating acm0 function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_function(g, USBG_F_ACM, "usb1", NULL, &f_acm1); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating acm1 function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_function(g, USBG_F_ECM, "usb0", NULL, &f_ecm); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating ecm function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } /* NULL can be passed to use kernel defaults */ usbg_ret = usbg_create_config(g, 1, "The only one", NULL, &c_strs, &c); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating config\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_add_config_function(c, "acm.GS0", f_acm0); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error adding acm.GS0\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_add_config_function(c, "acm.GS1", f_acm1); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error adding acm.GS1\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_add_config_function(c, "ecm.usb0", f_ecm); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error adding ecm.usb0\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_enable_gadget(g, DEFAULT_UDC); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error enabling gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } ret = 0; out2: usbg_cleanup(s); out1: return ret; } libusbgx-libusbgx-v0.3.0/examples/gadget-export.c000066400000000000000000000037151467553526200221150ustar00rootroot00000000000000/* * Copyright (C) 2014 Samsung Electronics * * Krzysztof Opasiak * * 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. */ /** * @file gadget-export.c * @example gadget-export.c * This is an example of how to export a gadget to file. * Common reason of doing this is to share schema of gadget * between different devices or preserve gadget between reboots. */ #include #include #include #include int main(int argc, char **argv) { usbg_state *s; usbg_gadget *g; int ret = -EINVAL; int usbg_ret; FILE *output; if (argc != 3) { fprintf(stderr, "Usage: gadget-export gadget_name file_name\n"); return ret; } /* Prepare output file */ output = fopen(argv[2], "w"); if (!output) { fprintf(stderr, "Error on fopen. Error: %s\n", strerror(errno)); goto out1; } /* Do gadget exporting */ usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB gadget init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } g = usbg_get_gadget(s, argv[1]); if (!g) { fprintf(stderr, "Error on get gadget\n"); goto out3; } usbg_ret = usbg_export_gadget(g, output); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on export gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out3; } ret = 0; out3: usbg_cleanup(s); out2: fclose(output); out1: return ret; } libusbgx-libusbgx-v0.3.0/examples/gadget-ffs.c000066400000000000000000000105331467553526200213460ustar00rootroot00000000000000/* * Copyright (C) 2014 Samsung Electronics * * Krzysztof Opasiak * * 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. */ /** * @file gadget-ffs.c * @example gadget-ffs.c * This is an example of how to create gadget with FunctionFS based functions * in two ways. After executing this program gadget will not be enabled * because ffs instances should be mounted and both descriptors and strings * should be written to ep0. * For more details about FunctionFS please refer to FunctionFS documentation * in linux kernel repository. */ #include #include #include #include #define VENDOR 0x1d6b #define PRODUCT 0x0104 int main(void) { usbg_state *s; usbg_gadget *g; usbg_config *c; usbg_function *f_ffs1, *f_ffs2; int ret = -EINVAL; int usbg_ret; struct usbg_gadget_attrs g_attrs = { .bcdUSB = 0x0200, .bDeviceClass = USB_CLASS_PER_INTERFACE, .bDeviceSubClass = 0x00, .bDeviceProtocol = 0x00, .bMaxPacketSize0 = 64, /* Max allowed ep0 packet size */ .idVendor = VENDOR, .idProduct = PRODUCT, .bcdDevice = 0x0001, /* Verson of device */ }; struct usbg_gadget_strs g_strs = { .serial = "0123456789", /* Serial number */ .manufacturer = "Foo Inc.", /* Manufacturer */ .product = "Bar Gadget" /* Product string */ }; struct usbg_config_strs c_strs = { .configuration = "2xFFS" }; usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB gadget init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out1; } usbg_ret = usbg_create_gadget(s, "g1", &g_attrs, &g_strs, &g); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on create gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_function(g, USBG_F_FFS, "my_dev_name", NULL, &f_ffs1); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating ffs1 function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_function(g, USBG_F_FFS, "my_other_dev_name", NULL, &f_ffs2); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating ffs2 function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } /* NULL can be passed to use kernel defaults */ usbg_ret = usbg_create_config(g, 1, "The only one", NULL, &c_strs, &c); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating config\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_add_config_function(c, "some_name_here", f_ffs1); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error adding ffs1\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_add_config_function(c, "some_name_here_too", f_ffs2); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error adding ffs2\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } fprintf(stdout, "2xFFS gadget has been created.\n" "Enable it after preparing your functions.\n"); /* * Here we end up with two created ffs instances but they are not * fully operational. Now we have to do step by step: * 1) Mount both instances: * $ mount my_dev_name -t functionfs /path/to/mount/dir1 * $ mount my_awesome_dev_name -t functionfs /path/to/mount/dir2 * * 2) Run ffs daemons for both instances: * $ my-ffs-daemon /path/to/mount/dir1 * $ my-ffs-daemon /path/to/mount/dir2 * * 3) Enable your gadget: * $ echo "my_udc_name" > /sys/kernel/config/usb_gadget/g1/UDC */ ret = 0; out2: usbg_cleanup(s); out1: return ret; } libusbgx-libusbgx-v0.3.0/examples/gadget-hid.c000066400000000000000000000117541467553526200213420ustar00rootroot00000000000000/* * Copyright (C) 2014 Samsung Electronics * * Krzysztof Opasiak * * 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. */ #include #include #include #include #include #define VENDOR 0x1d6b #define PRODUCT 0x0104 static char report_desc[] = { 0x05, 0x01, /* USAGE_PAGE (Generic Desktop) */ 0x09, 0x06, /* USAGE (Keyboard) */ 0xa1, 0x01, /* COLLECTION (Application) */ 0x05, 0x07, /* USAGE_PAGE (Keyboard) */ 0x19, 0xe0, /* USAGE_MINIMUM (Keyboard LeftControl) */ 0x29, 0xe7, /* USAGE_MAXIMUM (Keyboard Right GUI) */ 0x15, 0x00, /* LOGICAL_MINIMUM (0) */ 0x25, 0x01, /* LOGICAL_MAXIMUM (1) */ 0x75, 0x01, /* REPORT_SIZE (1) */ 0x95, 0x08, /* REPORT_COUNT (8) */ 0x81, 0x02, /* INPUT (Data,Var,Abs) */ 0x95, 0x01, /* REPORT_COUNT (1) */ 0x75, 0x08, /* REPORT_SIZE (8) */ 0x81, 0x03, /* INPUT (Cnst,Var,Abs) */ 0x95, 0x05, /* REPORT_COUNT (5) */ 0x75, 0x01, /* REPORT_SIZE (1) */ 0x05, 0x08, /* USAGE_PAGE (LEDs) */ 0x19, 0x01, /* USAGE_MINIMUM (Num Lock) */ 0x29, 0x05, /* USAGE_MAXIMUM (Kana) */ 0x91, 0x02, /* OUTPUT (Data,Var,Abs) */ 0x95, 0x01, /* REPORT_COUNT (1) */ 0x75, 0x03, /* REPORT_SIZE (3) */ 0x91, 0x03, /* OUTPUT (Cnst,Var,Abs) */ 0x95, 0x06, /* REPORT_COUNT (6) */ 0x75, 0x08, /* REPORT_SIZE (8) */ 0x15, 0x00, /* LOGICAL_MINIMUM (0) */ 0x25, 0x65, /* LOGICAL_MAXIMUM (101) */ 0x05, 0x07, /* USAGE_PAGE (Keyboard) */ 0x19, 0x00, /* USAGE_MINIMUM (Reserved) */ 0x29, 0x65, /* USAGE_MAXIMUM (Keyboard Application) */ 0x81, 0x00, /* INPUT (Data,Ary,Abs) */ 0xc0 /* END_COLLECTION */ }; int main() { usbg_state *s; usbg_gadget *g; usbg_config *c; usbg_function *f_hid; int ret = -EINVAL; int usbg_ret; struct usbg_gadget_attrs g_attrs = { .bcdUSB = 0x0200, .bDeviceClass = USB_CLASS_PER_INTERFACE, .bDeviceSubClass = 0x00, .bDeviceProtocol = 0x00, .bMaxPacketSize0 = 64, /* Max allowed ep0 packet size */ .idVendor = VENDOR, .idProduct = PRODUCT, .bcdDevice = 0x0001, /* Verson of device */ }; struct usbg_gadget_strs g_strs = { .serial = "0123456789", /* Serial number */ .manufacturer = "Foo Inc.", /* Manufacturer */ .product = "Bar Gadget" /* Product string */ }; struct usbg_config_strs c_strs = { .configuration = "1xHID" }; struct usbg_f_hid_attrs f_attrs = { .protocol = 1, .report_desc = { .desc = report_desc, .len = sizeof(report_desc), }, .report_length = 8, .subclass = 0, }; usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on usbg init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out1; } usbg_ret = usbg_create_gadget(s, "g1", &g_attrs, &g_strs, &g); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_function(g, USBG_F_HID, "usb0", &f_attrs, &f_hid); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_config(g, 1, "The only one", NULL, &c_strs, &c); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating config\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_add_config_function(c, "some_name", f_hid); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error adding function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_enable_gadget(g, DEFAULT_UDC); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error enabling gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } ret = 0; out2: usbg_cleanup(s); out1: return ret; } libusbgx-libusbgx-v0.3.0/examples/gadget-import.c000066400000000000000000000040421467553526200221000ustar00rootroot00000000000000/* * Copyright (C) 2014 Samsung Electronics * * Krzysztof Opasiak * * 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. */ /** * @file gadget-import.c * @example gadget-import.c * This is an example of how to import a gadget from file. * Common reason of doing this is to create gadget base on schema * from other devices or resurect gadget after reboot. */ #include #include #include #include #include int main(int argc, char **argv) { usbg_state *s; int ret = -EINVAL; int usbg_ret; FILE *input; if (argc != 3) { fprintf(stderr, "Usage: gadget-import gadget_name file_name\n"); return ret; } /* Prepare input file */ input = fopen(argv[2], "r"); if (!input) { fprintf(stderr, "Error on fopen. Error: %s\n", strerror(errno)); goto out1; } /* Do gadget exporting */ usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB gadget init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_import_gadget(s, input, argv[1], NULL); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on import gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); if (usbg_ret == USBG_ERROR_INVALID_FORMAT) fprintf(stderr, "Line: %d. Error: %s\n", usbg_get_gadget_import_error_line(s), usbg_get_gadget_import_error_text(s)); goto out3; } ret = 0; out3: usbg_cleanup(s); out2: fclose(input); out1: return ret; } libusbgx-libusbgx-v0.3.0/examples/gadget-midi.c000066400000000000000000000061561467553526200215200ustar00rootroot00000000000000/* * Copyright (C) 2014 Samsung Electronics * * Pawel Szewczyk * * 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. */ #include #include #include #include #include #define VENDOR 0x1d6b #define PRODUCT 0x0104 int main() { usbg_state *s; usbg_gadget *g; usbg_config *c; usbg_function *f_midi; int ret = -EINVAL; int usbg_ret; struct usbg_gadget_attrs g_attrs = { .bcdUSB = 0x0200, .bDeviceClass = USB_CLASS_PER_INTERFACE, .bDeviceSubClass = 0x00, .bDeviceProtocol = 0x00, .bMaxPacketSize0 = 64, /* Max allowed ep0 packet size */ .idVendor = VENDOR, .idProduct = PRODUCT, .bcdDevice = 0x0001, /* Verson of device */ }; struct usbg_gadget_strs g_strs = { .serial = "0123456789", /* Serial number */ .manufacturer = "Foo Inc.", /* Manufacturer */ .product = "Bar Gadget" /* Product string */ }; struct usbg_config_strs c_strs = { .configuration = "1xMIDI" }; struct usbg_f_midi_attrs f_attrs = { .index = 0, .id = "usb0", .buflen = 128, .qlen = 16, .in_ports = 2, .out_ports = 3, }; usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on usbg init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out1; } usbg_ret = usbg_create_gadget(s, "g1", &g_attrs, &g_strs, &g); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_function(g, USBG_F_MIDI, "usb0", &f_attrs, &f_midi); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_config(g, 1, "The only one", NULL, &c_strs, &c); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating config\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_add_config_function(c, "some_name", f_midi); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error adding function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_enable_gadget(g, DEFAULT_UDC); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error enabling gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } ret = 0; out2: usbg_cleanup(s); out1: return ret; } libusbgx-libusbgx-v0.3.0/examples/gadget-ms.c000066400000000000000000000077631467553526200212220ustar00rootroot00000000000000/* * Copyright (C) 2014 Samsung Electronics * * Krzysztof Opasiak * * 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. */ /** * @file gadget-ms.c * @example gadget-ms.c * This is an example of how to create gadget with mass storage function * with two luns. */ #include #include #include #include #include #include #define VENDOR 0x1d6b #define PRODUCT 0x0104 int main(int argc, char **argv) { usbg_state *s; usbg_gadget *g; usbg_config *c; usbg_function *f_ms; int ret = -EINVAL; int usbg_ret; struct usbg_gadget_attrs g_attrs = { .bcdUSB = 0x0200, .bDeviceClass = USB_CLASS_PER_INTERFACE, .bDeviceSubClass = 0x00, .bDeviceProtocol = 0x00, .bMaxPacketSize0 = 64, /* Max allowed ep0 packet size */ .idVendor = VENDOR, .idProduct = PRODUCT, .bcdDevice = 0x0001, /* Verson of device */ }; struct usbg_gadget_strs g_strs = { .serial = "0123456789", /* Serial number */ .manufacturer = "Foo Inc.", /* Manufacturer */ .product = "Bar Gadget" /* Product string */ }; struct usbg_f_ms_lun_attrs f_ms_luns_array[] = { { .id = -1, /* allows to place in any position */ .cdrom = 1, .ro = 0, .nofua = 0, .removable = 1, .file = "", .inquiry_string = "Empty" }, { .id = -1, /* allows to place in any position */ .cdrom = 0, .ro = 0, .nofua = 0, .removable = 1, .file = argv[1], .inquiry_string = "Non-empty" } }; struct usbg_f_ms_lun_attrs *f_ms_luns[] = { /* * When id in lun structure is below 0 we can place it in any * arbitrary position */ &f_ms_luns_array[1], &f_ms_luns_array[0], NULL, }; struct usbg_f_ms_attrs f_attrs = { .stall = 0, .nluns = 2, .luns = f_ms_luns, }; struct usbg_config_strs c_strs = { "1xMass Storage" }; if (argc < 2) { fprintf(stderr, "Usage: gadget-ms file\n"); goto out1; } usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB gadget init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out1; } usbg_ret = usbg_create_gadget(s, "g1", &g_attrs, &g_strs, &g); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on create gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_function(g, USBG_F_MASS_STORAGE, "my_reader", &f_attrs, &f_ms); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating mass storage function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } /* NULL can be passed to use kernel defaults */ usbg_ret = usbg_create_config(g, 1, "The only one", NULL, &c_strs, &c); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating config\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_add_config_function(c, "some_name_here", f_ms); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error adding ms function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_enable_gadget(g, DEFAULT_UDC); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error enabling gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } ret = 0; out2: usbg_cleanup(s); out1: return ret; } libusbgx-libusbgx-v0.3.0/examples/gadget-printer.c000066400000000000000000000060241467553526200222530ustar00rootroot00000000000000/* * Copyright (C) 2021 * * Aristo Chen * * 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. */ #include #include #include #include #include #define VENDOR 0x1d6b #define PRODUCT 0x0104 int main(void) { usbg_state *s; usbg_gadget *g; usbg_config *c; usbg_function *f_printer; int ret = -EINVAL; int usbg_ret; struct usbg_gadget_attrs g_attrs = { .bcdUSB = 0x0200, .bDeviceClass = USB_CLASS_PER_INTERFACE, .bDeviceSubClass = 0x00, .bDeviceProtocol = 0x00, .bMaxPacketSize0 = 64, /* Max allowed ep0 packet size */ .idVendor = VENDOR, .idProduct = PRODUCT, .bcdDevice = 0x0001, /* Verson of device */ }; struct usbg_gadget_strs g_strs = { .serial = "0123456789", /* Serial number */ .manufacturer = "Foo Inc.", /* Manufacturer */ .product = "Bar Gadget" /* Product string */ }; struct usbg_config_strs c_strs = { .configuration = "PRINTER"}; usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB gadget init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out1; } usbg_ret = usbg_create_gadget(s, "g1", &g_attrs, &g_strs, &g); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on create gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_function(g, USBG_F_PRINTER, "usb0", NULL, &f_printer); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating printer function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } /* NULL can be passed to use kernel defaults */ usbg_ret = usbg_create_config(g, 1, "The only one", NULL, &c_strs, &c); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating config\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_add_config_function(c, "printer.1", f_printer); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error adding function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_enable_gadget(g, DEFAULT_UDC); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error enabling gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } ret = 0; out2: usbg_cleanup(s); out1: return ret; } libusbgx-libusbgx-v0.3.0/examples/gadget-rndis-os-desc.c000066400000000000000000000101601467553526200232360ustar00rootroot00000000000000/* * Copyright (C) 2017 Samsung Electronics * * Krzysztof Opasiak * * 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. */ #include #include #include #include /** * @file gadget-rndis-os-desc.c * @example gadget-rndis-os-desc.c * This is an example of how to create an gadget with OS String support. */ #define VENDOR 0x1d6b #define PRODUCT 0x0104 int main(void) { usbg_state *s; usbg_gadget *g; usbg_config *c; usbg_function *f_rndis; int ret = -EINVAL; int usbg_ret; struct usbg_gadget_attrs g_attrs = { .bcdUSB = 0x0200, .bDeviceClass = USB_CLASS_PER_INTERFACE, .bDeviceSubClass = 0x00, .bDeviceProtocol = 0x00, .bMaxPacketSize0 = 64, /* Max allowed ep0 packet size */ .idVendor = VENDOR, .idProduct = PRODUCT, .bcdDevice = 0x0001, /* Verson of device */ }; struct usbg_gadget_strs g_strs = { .serial = "0123456789", /* Serial number */ .manufacturer = "Foo Inc.", /* Manufacturer */ .product = "Bar Gadget" /* Product string */ }; struct usbg_config_strs c_strs = { .configuration = "RNDIS", }; struct usbg_gadget_os_descs g_os_desc = { .use = true, .b_vendor_code = 0xBC, .qw_sign = "MSFT100", }; struct usbg_function_os_desc f_os_desc = { .compatible_id = "RNDIS", .sub_compatible_id = "5162001", }; usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB gadget init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out1; } usbg_ret = usbg_create_gadget(s, "g1", &g_attrs, &g_strs, &g); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on create gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_function(g, USBG_F_RNDIS, "usb0", NULL, &f_rndis); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating RNDIS function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_set_interf_os_desc(f_rndis, "rndis", &f_os_desc); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error setting function OS desc\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } /* NULL can be passed to use kernel defaults */ usbg_ret = usbg_create_config(g, 1, "The only one", NULL, &c_strs, &c); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating config\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_add_config_function(c, "rndis.usb0", f_rndis); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error adding rndis.usb0\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_set_gadget_os_descs(g, &g_os_desc); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error setting gadget OS desc\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_set_os_desc_config(g, c); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error setting gadget OS desc config\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_enable_gadget(g, DEFAULT_UDC); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error enabling gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } ret = 0; out2: usbg_cleanup(s); out1: return ret; } libusbgx-libusbgx-v0.3.0/examples/gadget-uac2.c000066400000000000000000000061521467553526200214240ustar00rootroot00000000000000/* * Copyright (C) 2018 Metanate Ltd * * John Keeping * * 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. */ #include #include #include #include #include #define VENDOR 0x1d6b #define PRODUCT 0x0104 int main() { usbg_state *s; usbg_gadget *g; usbg_config *c; usbg_function *f_uac2; int ret = -EINVAL; int usbg_ret; struct usbg_gadget_attrs g_attrs = { .bcdUSB = 0x0200, .bDeviceClass = USB_CLASS_PER_INTERFACE, .bDeviceSubClass = 0x00, .bDeviceProtocol = 0x00, .bMaxPacketSize0 = 64, /* Max allowed ep0 packet size */ .idVendor = VENDOR, .idProduct = PRODUCT, .bcdDevice = 0x0001, /* Verson of device */ }; struct usbg_gadget_strs g_strs = { .serial = "0123456789", /* Serial number */ .manufacturer = "Foo Inc.", /* Manufacturer */ .product = "Bar Gadget" /* Product string */ }; struct usbg_config_strs c_strs = { .configuration = "1xUAC2" }; struct usbg_f_uac2_attrs f_attrs = { .c_chmask = 3, .c_srate = 44100, .c_ssize = 4, .p_chmask = 3, .p_srate = 44100, .p_ssize = 4, }; usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on usbg init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out1; } usbg_ret = usbg_create_gadget(s, "g1", &g_attrs, &g_strs, &g); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_function(g, USBG_F_UAC2, "usb0", &f_attrs, &f_uac2); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_config(g, 1, "The only one", NULL, &c_strs, &c); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating config\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_add_config_function(c, "some_name", f_uac2); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error adding function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_enable_gadget(g, DEFAULT_UDC); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error enabling gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } ret = 0; out2: usbg_cleanup(s); out1: return ret; } libusbgx-libusbgx-v0.3.0/examples/gadget-uvc.c000066400000000000000000000107201467553526200213630ustar00rootroot00000000000000/* * Copyright (C) 2021 Pengutronix * * Michael Grzeschik * * 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. */ #include #include #include #include #include #include /** * @file gadget-uvc.c * @example gadget-uvc.c * This is an example of how to create an UVC gadget device. */ #define VENDOR 0x1d6b #define PRODUCT 0x0104 int main(void) { usbg_state *s; usbg_gadget *g; usbg_config *c; usbg_function *f_uvc; int ret = -EINVAL; int usbg_ret; struct usbg_gadget_attrs g_attrs = { .bcdUSB = 0x0200, .bDeviceClass = USB_CLASS_PER_INTERFACE, .bDeviceSubClass = 0x00, .bDeviceProtocol = 0x00, .bMaxPacketSize0 = 64, /* Max allowed ep0 packet size */ .idVendor = VENDOR, .idProduct = PRODUCT, .bcdDevice = 0x0001, /* Verson of device */ }; struct usbg_gadget_strs g_strs = { .serial = "0123456789", /* Serial number */ .manufacturer = "Foo Inc.", /* Manufacturer */ .product = "Bar Gadget" /* Product string */ }; struct usbg_config_strs c_strs = { .configuration = "UVC" }; struct usbg_f_uvc_frame_attrs uvc_frame_attrs_array[] = { { .bFrameIndex = 1, .dwFrameInterval = 2000000, .wHeight = 480, .wWidth = 640, }, { .bFrameIndex = 2, .dwFrameInterval = 2000000, .wHeight = 1080, .wWidth = 1920, }, { .bFrameIndex = 3, .dwFrameInterval = 333333, .wHeight = 1080, .wWidth = 1920, }, { .bFrameIndex = 4, .dwFrameInterval = 333333, .wHeight = 2160, .wWidth = 3840, } }; struct usbg_f_uvc_frame_attrs *uvc_frame_mjpeg_attrs[] = { &uvc_frame_attrs_array[0], &uvc_frame_attrs_array[1], &uvc_frame_attrs_array[2], &uvc_frame_attrs_array[3], NULL, }; struct usbg_f_uvc_frame_attrs *uvc_frame_uncompressed_attrs[] = { &uvc_frame_attrs_array[0], &uvc_frame_attrs_array[1], &uvc_frame_attrs_array[2], &uvc_frame_attrs_array[3], NULL, }; struct usbg_f_uvc_format_attrs uvc_format_attrs_array[] = { { .frames = uvc_frame_mjpeg_attrs, .format = "mjpeg/m", .bDefaultFrameIndex = 3, }, { .frames = uvc_frame_uncompressed_attrs, .format = "uncompressed/u", .bDefaultFrameIndex = 2, } }; struct usbg_f_uvc_format_attrs *uvc_format_attrs[] = { &uvc_format_attrs_array[0], &uvc_format_attrs_array[1], NULL, }; struct usbg_f_uvc_attrs uvc_attrs = { .formats = uvc_format_attrs, }; usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB gadget init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out1; } usbg_ret = usbg_create_gadget(s, "g1", &g_attrs, &g_strs, &g); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on create gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_create_function(g, USBG_F_UVC, "uvc", &uvc_attrs, &f_uvc); if(usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating uvc function\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } /* NULL can be passed to use kernel defaults */ usbg_ret = usbg_create_config(g, 1, "The only one", NULL, &c_strs, &c); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error creating config\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_add_config_function(c, "uvc.cam", f_uvc); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error adding acm.GS0\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } usbg_ret = usbg_enable_gadget(g, DEFAULT_UDC); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error enabling gadget\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } ret = 0; out2: usbg_cleanup(s); out1: return ret; } libusbgx-libusbgx-v0.3.0/examples/gadget-vid-pid-remove.c000066400000000000000000000061661467553526200234260ustar00rootroot00000000000000/* * Copyright (C) 2014 Samsung Electronics * * Krzysztof Opasiak * * 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. */ /** * @file gadget-vid-pid-remove.c * @example gadget-vid-pid-remove.c * This is an example of how to find and remove an gadget device with given * Vendor ID and product ID. */ #include #include #include #include #include #define VENDOR 0x1d6b #define PRODUCT 0x0104 int remove_gadget(usbg_gadget *g) { int usbg_ret; usbg_udc *u; /* Check if gadget is enabled */ u = usbg_get_gadget_udc(g); /* If gadget is enable we have to disable it first */ if (u) { usbg_ret = usbg_disable_gadget(g); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB disable gadget udc\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out; } } /* Remove gadget with USBG_RM_RECURSE flag to remove * also its configurations, functions and strings */ usbg_ret = usbg_rm_gadget(g, USBG_RM_RECURSE); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB gadget remove\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); } out: return usbg_ret; } int main(int argc, char **argv) { int usbg_ret; int ret = -EINVAL; usbg_state *s; usbg_gadget *g; struct usbg_gadget_attrs g_attrs; char *cp; int vendor = VENDOR, product = PRODUCT; if (argc >= 2) { cp = strchr(argv[1], ':'); if (!cp) { ret = -EINVAL; fprintf(stderr, "Usage: gadget-vid-pid-remove vid:pid\n"); goto out1; } *cp++ = 0; if (*argv[1]) vendor = strtoul(argv[1], NULL, 16); if (*cp) product = strtoul(cp, NULL, 16); } usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB state init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out1; } g = usbg_get_first_gadget(s); while (g != NULL) { /* Get current gadget attrs to be compared */ usbg_ret = usbg_get_gadget_attrs(g, &g_attrs); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB get gadget attrs\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out2; } /* Compare attrs with given values and remove if suitable */ if (g_attrs.idVendor == vendor && g_attrs.idProduct == product) { usbg_gadget *g_next = usbg_get_next_gadget(g); usbg_ret = remove_gadget(g); if (usbg_ret != USBG_SUCCESS) goto out2; g = g_next; } else { g = usbg_get_next_gadget(g); } } ret = 0; out2: usbg_cleanup(s); out1: return ret; } libusbgx-libusbgx-v0.3.0/examples/meson.build000066400000000000000000000024321467553526200213340ustar00rootroot00000000000000executable('show-gadgets', 'show-gadgets.c', dependencies: [ libusbgx_dep ], install: true) executable('gadget-acm-ecm', 'gadget-acm-ecm.c', dependencies: [ libusbgx_dep ], install: true) executable('gadget-vid-pid-remove', 'gadget-vid-pid-remove.c', dependencies: [ libusbgx_dep ], install: true) executable('gadget-ffs', 'gadget-ffs.c', dependencies: [ libusbgx_dep ], install: true) executable('gadget-export', 'gadget-export.c', dependencies: [ libusbgx_dep ], install: true) executable('gadget-import', 'gadget-import.c', dependencies: [ libusbgx_dep ], install: true) executable('gadget-rndis-os-desc', 'gadget-rndis-os-desc.c', dependencies: [ libusbgx_dep ], install: true) executable('gadget-printer', 'gadget-printer.c', dependencies: [ libusbgx_dep ], install: true) executable('gadget-ms', 'gadget-ms.c', dependencies: [ libusbgx_dep ], install: true) executable('gadget-midi', 'gadget-midi.c', dependencies: [ libusbgx_dep ], install: true) executable('gadget-hid', 'gadget-hid.c', dependencies: [ libusbgx_dep ], install: true) executable('gadget-uac2', 'gadget-uac2.c', dependencies: [ libusbgx_dep ], install: true) executable('gadget-uvc', 'gadget-uvc.c', dependencies: [ libusbgx_dep ], install: true) executable('show-udcs', 'show-udcs.c', dependencies: [ libusbgx_dep ], install: true) libusbgx-libusbgx-v0.3.0/examples/show-gadgets.c000066400000000000000000000224541467553526200217400ustar00rootroot00000000000000/* * Copyright (C) 2013 Linaro Limited * * Matt Porter * * Copyright (C) 2013 - 2015 Samsung Electronics * * Krzysztof Opasiak * * 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include /** * @file show-gadgets.c * @example show-gadgets.c * This example shows how to display all configured USB gadgets * in the system */ void show_gadget_strs(usbg_gadget *g, int lang) { int usbg_ret; struct usbg_gadget_strs g_strs; usbg_ret = usbg_get_gadget_strs(g, lang, &g_strs); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); return; } fprintf(stdout, " Language: \t0x%x\n", lang); fprintf(stdout, " Manufacturer\t%s\n", g_strs.manufacturer); fprintf(stdout, " Product\t\t%s\n", g_strs.product); fprintf(stdout, " Serial Number\t%s\n", g_strs.serial); usbg_free_gadget_strs(&g_strs); } void show_gadget(usbg_gadget *g) { const char *name, *udc; usbg_udc *u; int usbg_ret; struct usbg_gadget_attrs g_attrs; int *langs; int i; name = usbg_get_gadget_name(g); if (!name) { fprintf(stderr, "Unable to get gadget name\n"); return; } usbg_ret = usbg_get_gadget_attrs(g, &g_attrs); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); return; } fprintf(stdout, "ID %04x:%04x '%s'\n", g_attrs.idVendor, g_attrs.idProduct, name); u = usbg_get_gadget_udc(g); if (u) /* gadget is enabled */ udc = usbg_get_udc_name(u); else /* gadget is disabled */ udc = "\0"; fprintf(stdout, " UDC\t\t\t%s\n", udc); fprintf(stdout, " bcdUSB\t\t%x.%02x\n", g_attrs.bcdUSB >> 8, g_attrs.bcdUSB & 0x00ff); fprintf(stdout, " bDeviceClass\t\t0x%02x\n", g_attrs.bDeviceClass); fprintf(stdout, " bDeviceSubClass\t0x%02x\n", g_attrs.bDeviceSubClass); fprintf(stdout, " bDeviceProtocol\t0x%02x\n", g_attrs.bDeviceProtocol); fprintf(stdout, " bMaxPacketSize0\t%d\n", g_attrs.bMaxPacketSize0); fprintf(stdout, " idVendor\t\t0x%04x\n", g_attrs.idVendor); fprintf(stdout, " idProduct\t\t0x%04x\n", g_attrs.idProduct); fprintf(stdout, " bcdDevice\t\t%x.%02x\n", g_attrs.bcdDevice >> 8, g_attrs.bcdDevice & 0x00ff); usbg_ret = usbg_get_gadget_strs_langs(g, &langs); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); return; } for (i = 0; langs[i]; ++i) show_gadget_strs(g, langs[i]); } void show_function(usbg_function *f) { const char *instance; usbg_function_type type; int usbg_ret; union { struct usbg_f_net_attrs net; char *ffs_dev_name; struct usbg_f_ms_attrs ms; struct usbg_f_midi_attrs midi; int serial_port_num; char *phonet_ifname; struct usbg_f_hid_attrs hid; struct usbg_f_uac2_attrs uac2; } f_attrs; instance = usbg_get_function_instance(f); if (!instance) { fprintf(stderr, "Unable to get function instance name\n"); return; } type = usbg_get_function_type(f); usbg_ret = usbg_get_function_attrs(f, &f_attrs); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); return; } fprintf(stdout, " Function, type: %s instance: %s\n", usbg_get_function_type_str(type), instance); switch (type) { case USBG_F_ACM: case USBG_F_OBEX: case USBG_F_SERIAL: fprintf(stdout, " port_num\t\t%d\n", f_attrs.serial_port_num); break; case USBG_F_ECM: case USBG_F_SUBSET: case USBG_F_NCM: case USBG_F_EEM: case USBG_F_RNDIS: { struct usbg_f_net_attrs *f_net_attrs = &f_attrs.net; fprintf(stdout, " dev_addr\t\t%s\n", ether_ntoa(&f_net_attrs->dev_addr)); fprintf(stdout, " host_addr\t\t%s\n", ether_ntoa(&f_net_attrs->host_addr)); fprintf(stdout, " ifname\t\t%s\n", f_net_attrs->ifname); fprintf(stdout, " qmult\t\t%d\n", f_net_attrs->qmult); break; } case USBG_F_PHONET: fprintf(stdout, " ifname\t\t%s\n", f_attrs.phonet_ifname); break; case USBG_F_FFS: fprintf(stdout, " dev_name\t\t%s\n", f_attrs.ffs_dev_name); break; case USBG_F_MASS_STORAGE: { struct usbg_f_ms_attrs *attrs = &f_attrs.ms; int i; fprintf(stdout, " stall\t\t%d\n", attrs->stall); fprintf(stdout, " nluns\t\t%d\n", attrs->nluns); for (i = 0; i < attrs->nluns; ++i) { fprintf(stdout, " lun %d:\n", attrs->luns[i]->id); fprintf(stdout, " cdrom\t\t%d\n", attrs->luns[i]->cdrom); fprintf(stdout, " ro\t\t%d\n", attrs->luns[i]->ro); fprintf(stdout, " nofua\t\t%d\n", attrs->luns[i]->nofua); fprintf(stdout, " removable\t\t%d\n", attrs->luns[i]->removable); fprintf(stdout, " file\t\t%s\n", attrs->luns[i]->file); fprintf(stdout, " inquiry_string\t\t%s\n", attrs->luns[i]->inquiry_string); } break; } case USBG_F_MIDI: { struct usbg_f_midi_attrs *attrs = &f_attrs.midi; fprintf(stdout, " index\t\t%d\n", attrs->index); fprintf(stdout, " id\t\t\t%s\n", attrs->id); fprintf(stdout, " in_ports\t\t%d\n", attrs->in_ports); fprintf(stdout, " out_ports\t\t%d\n", attrs->out_ports); fprintf(stdout, " buflen\t\t%d\n", attrs->buflen); fprintf(stdout, " qlen\t\t%d\n", attrs->qlen); break; } case USBG_F_HID: { struct usbg_f_hid_attrs *attrs = &f_attrs.hid; int i; fprintf(stdout, " dev\t\t\t%d:%d\n", major(attrs->dev), minor(attrs->dev)); fprintf(stdout, " protocol\t\t%d\n", attrs->protocol); fprintf(stdout, " report_desc\t"); for (i = 0; i < attrs->report_desc.len; ++i) fprintf(stdout, "%x", attrs->report_desc.desc[i]); fprintf(stdout, "\n"); fprintf(stdout, " report_length\t%d\n", attrs->report_length); fprintf(stdout, " subclass\t\t%d\n", attrs->subclass); break; } case USBG_F_UAC2: { struct usbg_f_uac2_attrs *attrs = &f_attrs.uac2; fprintf(stdout, " c_chmask\t\t%d\n", attrs->c_chmask); fprintf(stdout, " c_srate\t\t%d\n", attrs->c_srate); fprintf(stdout, " c_ssize\t\t%d\n", attrs->c_ssize); fprintf(stdout, " p_chmask\t\t%d\n", attrs->p_chmask); fprintf(stdout, " p_srate\t\t%d\n", attrs->p_srate); fprintf(stdout, " p_ssize\t\t%d\n", attrs->p_ssize); break; } default: fprintf(stdout, " UNKNOWN\n"); } usbg_cleanup_function_attrs(f, &f_attrs); } void show_config_strs(usbg_config *c, int lang) { struct usbg_config_strs c_strs; int usbg_ret; usbg_ret = usbg_get_config_strs(c, lang, &c_strs); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); return; } fprintf(stdout, " Language: \t0x%x\n", lang); fprintf(stdout, " configuration\t%s\n", c_strs.configuration); usbg_free_config_strs(&c_strs); } void show_config(usbg_config *c) { usbg_binding *b; usbg_function *f; const char *label, *instance, *bname; usbg_function_type type; struct usbg_config_attrs c_attrs; int *langs; int usbg_ret, id, i; label = usbg_get_config_label(c); if (!label) { fprintf(stderr, "Unable to get config label\n"); return; } id = usbg_get_config_id(c); fprintf(stdout, " Configuration: '%s' ID: %d\n", label, id); usbg_ret = usbg_get_config_attrs(c, &c_attrs); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); return; } fprintf(stdout, " MaxPower\t\t%d\n", c_attrs.bMaxPower); fprintf(stdout, " bmAttributes\t0x%02x\n", c_attrs.bmAttributes); usbg_ret = usbg_get_config_strs_langs(c, &langs); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); return; } for (i = 0; langs[i]; ++i) show_config_strs(c, langs[i]); usbg_for_each_binding(b, c) { bname = usbg_get_binding_name(b); f = usbg_get_binding_target(b); instance = usbg_get_function_instance(f); type = usbg_get_function_type(f); if (!bname || !instance) { fprintf(stderr, "Unable to get binding details\n"); return; } fprintf(stdout, " %s -> %s %s\n", bname, usbg_get_function_type_str(type), instance); } } int main(void) { usbg_state *s; usbg_gadget *g; usbg_function *f; usbg_config *c; int usbg_ret; usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB gadget init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); return -EINVAL; } usbg_for_each_gadget(g, s) { show_gadget(g); usbg_for_each_function(f, g) show_function(f); usbg_for_each_config(c, g) show_config(c); } usbg_cleanup(s); return 0; } libusbgx-libusbgx-v0.3.0/examples/show-udcs.c000066400000000000000000000030221467553526200212460ustar00rootroot00000000000000/* * Copyright (C) 2014 Samsung Electronics * * Krzysztof Opasiak * * 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. */ /** * @file show-udcs.c * @example show-udcs.c * This is an example of how to learn about UDCs available in system * and find out what gadget are enabled on them. */ #include #include #include #include int main(void) { int usbg_ret; int ret = -EINVAL; usbg_state *s; usbg_gadget *g; usbg_udc *u; const char *udc_name, *gadget_name; usbg_ret = usbg_init("/sys/kernel/config", &s); if (usbg_ret != USBG_SUCCESS) { fprintf(stderr, "Error on USB state init\n"); fprintf(stderr, "Error: %s : %s\n", usbg_error_name(usbg_ret), usbg_strerror(usbg_ret)); goto out; } usbg_for_each_udc(u, s) { udc_name = usbg_get_udc_name(u); g = usbg_get_udc_gadget(u); if (g) /* some gadget is enabled */ gadget_name = usbg_get_gadget_name(g); else gadget_name = ""; fprintf(stdout, "%s <-> %s\n", udc_name, gadget_name); } ret = 0; usbg_cleanup(s); out: return ret; } libusbgx-libusbgx-v0.3.0/include/000077500000000000000000000000001467553526200167765ustar00rootroot00000000000000libusbgx-libusbgx-v0.3.0/include/usbg/000077500000000000000000000000001467553526200177365ustar00rootroot00000000000000libusbgx-libusbgx-v0.3.0/include/usbg/function/000077500000000000000000000000001467553526200215635ustar00rootroot00000000000000libusbgx-libusbgx-v0.3.0/include/usbg/function/9pfs.h000066400000000000000000000044501467553526200226200ustar00rootroot00000000000000/* * Copyright (C) 2024 Pengutronix * * Michael Grzeschik * * This library is free software; you can redistribute it 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. */ #ifndef USBG_FUNCTION_FS__ #define USBG_FUNCTION_FS__ #include #ifdef __cplusplus extern "C" { #endif struct usbg_f_9pfs; typedef struct usbg_f_9pfs usbg_f_9pfs; /** * @brief Convert from generic function to 9pfs * @param[in] f function to be converted to 9pfs. * Function should be of type function fs. * @return Converted function or NULL if function hasn't suitable type */ usbg_f_9pfs *usbg_to_9pfs(usbg_function *f); /** * @brief Convert form 9pfs to a generic one * @param[in] 9pfs function to be converted to generic one * @return Generic usbg function */ usbg_function *usbg_from_9pfs(usbg_f_9pfs *p9fs); /** * @brief Get the device name which should be used while mounting * 9pfs instace into newly allocated storage * @param[in] pf Pointer to net function * @param[out] dev_name Newly allocated string containing device name * @return 0 on success usbg_error if error occurred. * @note returned dev_name should be free() by caller */ int usbg_f_9pfs_get_dev_name(usbg_f_9pfs *p9fs, char **dev_name); /** * @brief Get the device name which should be used while mounting * 9pfs instace into user buffer * @param[in] pf Pointer to fs function * @param[out] buf Place where ifname should be stored * @param[in] len Size of buffer * @return Number of bytes placed into buf (excluding '\0') or the number of * characters which would have been written to the buffer if enough * space had been available. (just like snprintf() family). This may * also return negative error code from usbg_error. */ int usbg_f_9pfs_get_dev_name_s(usbg_f_9pfs *p9fs, char *buf, int len); #ifdef __cplusplus } #endif #endif /* USBG_FUNCTION_FS__ */ libusbgx-libusbgx-v0.3.0/include/usbg/function/ffs.h000066400000000000000000000043431467553526200225160ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_FUNCTION_FS__ #define USBG_FUNCTION_FS__ #include #ifdef __cplusplus extern "C" { #endif struct usbg_f_fs; typedef struct usbg_f_fs usbg_f_fs; /** * @brief Convert from generic function to fs function * @param[in] f function to be converted to fs funciton. * Function should be of type function fs. * @return Converted function or NULL if function hasn't suitable type */ usbg_f_fs *usbg_to_fs_function(usbg_function *f); /** * @brief Convert form fs function to a generic one * @param[in] pf function to be converted to generic one * @return Generic usbg function */ usbg_function *usbg_from_fs_function(usbg_f_fs *ff); /** * @brief Get the device name which should be used while mounting * functionfs instace into newly allocated storage * @param[in] pf Pointer to net function * @param[out] dev_name Newly allocated string containing device name * @return 0 on success usbg_error if error occurred. * @note returned dev_name should be free() by caller */ int usbg_f_fs_get_dev_name(usbg_f_fs *ff, char **dev_name); /** * @brief Get the device name which should be used while mounting * functionfs instace into user buffer * @param[in] pf Pointer to fs function * @param[out] buf Place where ifname should be stored * @param[in] len Size of buffer * @return Number of bytes placed into buf (excluding '\0') or the number of * characters which would have been written to the buffer if enough * space had been available. (just like snprintf() family). This may * also return negative error code from usbg_error. */ int usbg_f_fs_get_dev_name_s(usbg_f_fs *ff, char *buf, int len); #ifdef __cplusplus } #endif #endif /* USBG_FUNCTION_FS__ */ libusbgx-libusbgx-v0.3.0/include/usbg/function/hid.h000066400000000000000000000205631467553526200225060ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_FUNCTION_HID__ #define USBG_FUNCTION_HID__ #include #include #include #ifdef __cplusplus extern "C" { #endif struct usbg_f_hid; typedef struct usbg_f_hid usbg_f_hid; struct usbg_f_hid_report_desc { char *desc; unsigned int len; }; struct usbg_f_hid_attrs { dev_t dev; unsigned int protocol; struct usbg_f_hid_report_desc report_desc; unsigned int report_length; unsigned int subclass; }; enum usbg_f_hid_attr { USBG_F_HID_ATTR_MIN = 0, USBG_F_HID_DEV = USBG_F_HID_ATTR_MIN, USBG_F_HID_PROTOCOL, USBG_F_HID_REPORT_DESC, USBG_F_HID_REPORT_LENGTH, USBG_F_HID_SUBCLASS, USBG_F_HID_ATTR_MAX }; union usbg_f_hid_attr_val { dev_t dev; unsigned int protocol; struct usbg_f_hid_report_desc report_desc; unsigned int report_length; unsigned int subclass; }; #define USBG_F_HID_UINT_TO_ATTR_VAL(WHAT) \ USBG_TO_UNION(usbg_f_hid_attr_val, protocol, WHAT) #define USBG_F_HID_RDESC_TO_ATTR_VAL(WHAT) \ USBG_TO_UNION(usbg_f_hid_attr_val, report_desc, WHAT) /** * @brief Cast from generic function to hid function * @param[in] f function to be converted to hid funciton. * Function should be one of type hid. * @return Converted hid function or NULL if function hasn't suitable type */ usbg_f_hid *usbg_to_hid_function(usbg_function *f); /** * @brief Cast form hid function to generic one * @param[in] hf function to be converted to generic one * @return Generic usbg function */ usbg_function *usbg_from_hid_function(usbg_f_hid *hf); /** * @brief Get attributes of given hid function * @param[in] hf Pointer to hid function * @param[out] attrs Structure to be filled with data * @return 0 on success usbg_error if error occurred. */ int usbg_f_hid_get_attrs(usbg_f_hid *hf, struct usbg_f_hid_attrs *attrs); /** * @brief Set attributes of given hid function * @param[in] hf Pointer to hid function * @param[in] attrs to be set * @return 0 on success usbg_error if error occurred. */ int usbg_f_hid_set_attrs(usbg_f_hid *hf, const struct usbg_f_hid_attrs *attrs); /** * @brief Cleanup HID report descriptor structure after usage * @param[in] report_desc to be cleaned up */ static inline void usbg_f_hid_cleanup_report_desc( struct usbg_f_hid_report_desc *report_desc) { if (report_desc->desc) { free(report_desc->desc); /* Just for safety */ report_desc->desc = NULL; } } /** * @brief Cleanup attributes structure after usage * @param[in] attrs to be cleaned up */ static inline void usbg_f_hid_cleanup_attrs(struct usbg_f_hid_attrs *attrs) { if (attrs) usbg_f_hid_cleanup_report_desc(&attrs->report_desc); } /** * @brief Get the value of single attribute * @param[in] hf Pointer to hid function * @param[in] attr Code of attribute which value should be taken * @param[out] val Current value of this attribute * @return 0 on success usbg_error if error occurred. */ int usbg_f_hid_get_attr_val(usbg_f_hid *hf, enum usbg_f_hid_attr attr, union usbg_f_hid_attr_val *val); /** * @brief Set the value of single attribute * @param[in] hf Pointer to hid function * @param[in] attr Code of attribute which value should be set * @param[in] val Value of attribute which should be set * @return 0 on success usbg_error if error occurred. */ int usbg_f_hid_set_attr_val(usbg_f_hid *hf, enum usbg_f_hid_attr attr, union usbg_f_hid_attr_val val); /** * @brief Get the minor and major of corresponding character device * @param[in] hf Pointer to hid function * @param[out] dev Minor and major of corresponding * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_hid_get_dev(usbg_f_hid *hf, dev_t *dev) { return usbg_f_hid_get_attr_val(hf, USBG_F_HID_DEV, (union usbg_f_hid_attr_val *)dev); } /** * @brief Get HID protocol code * @param[in] hf Pointer to hid function * @param[out] protocol code * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_hid_get_protocol(usbg_f_hid *hf, unsigned int *protocol) { return usbg_f_hid_get_attr_val(hf, USBG_F_HID_PROTOCOL, (union usbg_f_hid_attr_val *)protocol); } /** * @brief Set HID protocol code * @param[in] hf Pointer to hid function * @param[out] protocol code * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_hid_set_protocol(usbg_f_hid *hf, unsigned int protocol) { return usbg_f_hid_set_attr_val(hf, USBG_F_HID_PROTOCOL, USBG_F_HID_UINT_TO_ATTR_VAL(protocol)); } /** * @brief Get HID report descriptor * @param[in] hf Pointer to hid function * @param[out] report_desc Report descriptor * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_hid_get_report_desc(usbg_f_hid *hf, struct usbg_f_hid_report_desc *report_desc) { return usbg_f_hid_get_attr_val(hf, USBG_F_HID_REPORT_DESC, (union usbg_f_hid_attr_val *)report_desc); } /** * @brief Set HID report descriptor * @param[in] hf Pointer to hid function * @param[out] report_desc Report descriptor * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_hid_set_report_desc(usbg_f_hid *hf, struct usbg_f_hid_report_desc report_desc) { return usbg_f_hid_set_attr_val(hf, USBG_F_HID_REPORT_DESC, USBG_F_HID_RDESC_TO_ATTR_VAL(report_desc)); } /** * @brief Get HID report descriptor * @param[in] hf Pointer to hid function * @param[out] report_desc Report descriptor * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_hid_get_report_desc_raw(usbg_f_hid *hf, char **desc, unsigned int *len) { struct usbg_f_hid_report_desc report_desc; int ret; ret = usbg_f_hid_get_attr_val(hf, USBG_F_HID_REPORT_DESC, (union usbg_f_hid_attr_val *)&report_desc); if (ret != USBG_SUCCESS) return ret; *desc = report_desc.desc; *len = report_desc.len; return USBG_SUCCESS; } /** * @brief Set HID report descriptor * @param[in] hf Pointer to hid function * @param[out] report_desc Report descriptor * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_hid_set_report_desc_raw(usbg_f_hid *hf, char *desc, unsigned int len) { struct usbg_f_hid_report_desc report_desc = { .desc = desc, .len = len, }; return usbg_f_hid_set_attr_val(hf, USBG_F_HID_REPORT_DESC, USBG_F_HID_RDESC_TO_ATTR_VAL(report_desc)); } /** * @brief Get HID report length * @param[in] hf Pointer to hid function * @param[out] report_length Length of HID report * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_hid_get_report_length(usbg_f_hid *hf, unsigned int *report_length) { return usbg_f_hid_get_attr_val(hf, USBG_F_HID_REPORT_LENGTH, (union usbg_f_hid_attr_val *)report_length); } /** * @brief Set HID report length * @param[in] hf Pointer to hid function * @param[out] report_length Length of HID report * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_hid_set_report_length(usbg_f_hid *hf, unsigned int report_length) { return usbg_f_hid_set_attr_val(hf, USBG_F_HID_REPORT_LENGTH, USBG_F_HID_UINT_TO_ATTR_VAL(report_length)); } /** * @brief Get HID subclass code * @param[in] hf Pointer to hid function * @param[out] subclass code * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_hid_get_subclass(usbg_f_hid *hf, unsigned int *subclass) { return usbg_f_hid_get_attr_val(hf, USBG_F_HID_SUBCLASS, (union usbg_f_hid_attr_val *)subclass); } /** * @brief Set HID subclass code * @param[in] hf Pointer to hid function * @param[out] subclass code * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_hid_set_subclass(usbg_f_hid *hf, unsigned int subclass) { return usbg_f_hid_set_attr_val(hf, USBG_F_HID_SUBCLASS, USBG_F_HID_UINT_TO_ATTR_VAL(subclass)); } #ifdef __cplusplus } #endif #endif /* USBG_FUNCTION_MIDI__ */ libusbgx-libusbgx-v0.3.0/include/usbg/function/loopback.h000066400000000000000000000113161467553526200235300ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_FUNCTION_LOOPBACK__ #define USBG_FUNCTION_LOOPBACK__ #include #ifdef __cplusplus extern "C" { #endif struct usbg_f_loopback; typedef struct usbg_f_loopback usbg_f_loopback; struct usbg_f_loopback_attrs { unsigned int buflen; unsigned int qlen; }; enum usbg_f_loopback_attr { USBG_F_LOOPBACK_ATTR_MIN = 0, USBG_F_LOOPBACK_BUFLEN = USBG_F_LOOPBACK_ATTR_MIN, USBG_F_LOOPBACK_QLEN, USBG_F_LOOPBACK_ATTR_MAX }; /** * @brief Cast from generic function to loopback function * @param[in] f function to be converted to loopback funciton. * Function should be of type loopback. * @return Converted loopback function or NULL if function hasn't suitable type */ usbg_f_loopback *usbg_to_loopback_function(usbg_function *f); /** * @brief Cast form loopback function to generic one * @param[in] lf function to be converted to generic one * @return Generic usbg function */ usbg_function *usbg_from_loopback_function(usbg_f_loopback *lf); /** * @brief Get attributes of given loopback function * @param[in] lf Pointer to loopback function * @param[out] attrs Structure to be filled with data * @return 0 on success usbg_error if error occurred. */ int usbg_f_loopback_get_attrs(usbg_f_loopback *lf, struct usbg_f_loopback_attrs *attrs); /** * @brief Set attributes of given loopback function * @param[in] lf Pointer to loopback function * @param[in] attrs to be set * @return 0 on success usbg_error if error occurred. */ int usbg_f_loopback_set_attrs(usbg_f_loopback *lf, const struct usbg_f_loopback_attrs *attrs); /** * @brief Get the value of single attribute * @param[in] lf Pointer to loopback function * @param[in] attr Code of attribute which value should be taken * @param[out] val Current value of this attribute * @return 0 on success usbg_error if error occurred. */ int usbg_f_loopback_get_attr_val(usbg_f_loopback *lf, enum usbg_f_loopback_attr attr, int *val); /** * @brief Set the value of single attribute * @param[in] lf Pointer to loopback function * @param[in] attr Code of attribute which value should be set * @param[in] val Value of attribute which should be set * @return 0 on success usbg_error if error occurred. */ int usbg_f_loopback_set_attr_val(usbg_f_loopback *lf, enum usbg_f_loopback_attr attr, int val); /** * @brief Get the size of request buffer * @details This is the maximum number of bytes which can be received * using single usb_request. * @param[in] lf Pointer to loopback function * @param[out] buflen size of request buffer * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_loopback_get_buflen(usbg_f_loopback *lf, int *buflen) { return usbg_f_loopback_get_attr_val(lf, USBG_F_LOOPBACK_BUFLEN, buflen); } /** * @brief Set the size of request buffer * @details This is the maximum number of bytes which can be received * using single usb_request. * @param[in] lf Pointer to loopback function * @param[in] buflen size of request buffer * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_loopback_set_buflen(usbg_f_loopback *lf, int buflen) { return usbg_f_loopback_set_attr_val(lf, USBG_F_LOOPBACK_BUFLEN, buflen); } /** * @brief Get the value of request queue length * @details This length is the number of OUT requests which can be received * by function without requesting any IN transfers by host * @param[in] lf Pointer to loopback function * @param[out] qlen Current queue length * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_loopback_get_qlen(usbg_f_loopback *lf, int *qlen) { return usbg_f_loopback_get_attr_val(lf, USBG_F_LOOPBACK_QLEN, qlen); } /** * @brief Set the value of request queue length * @details This length is the number of OUT requests which can be received * by function without requesting any IN transfers by host * @param[in] lf Pointer to loopback function * @param[in] qlen Current queue length * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_loopback_set_qlen(usbg_f_loopback *lf, int qlen) { return usbg_f_loopback_set_attr_val(lf, USBG_F_LOOPBACK_QLEN, qlen); } #ifdef __cplusplus } #endif #endif /* USBG_FUNCTION_LOOPBACK__ */ libusbgx-libusbgx-v0.3.0/include/usbg/function/midi.h000066400000000000000000000221431467553526200226600ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_FUNCTION_MIDI__ #define USBG_FUNCTION_MIDI__ #include #include #ifdef __cplusplus extern "C" { #endif struct usbg_f_midi; typedef struct usbg_f_midi usbg_f_midi; struct usbg_f_midi_attrs { int index; const char *id; unsigned int in_ports; unsigned int out_ports; unsigned int buflen; unsigned int qlen; }; enum usbg_f_midi_attr { USBG_F_MIDI_ATTR_MIN = 0, USBG_F_MIDI_INDEX = USBG_F_MIDI_ATTR_MIN, USBG_F_MIDI_ID, USBG_F_MIDI_IN_PORTS, USBG_F_MIDI_OUT_PORTS, USBG_F_MIDI_BUFLEN, USBG_F_MIDI_QLEN, USBG_F_MIDI_ATTR_MAX }; union usbg_f_midi_attr_val { int index; const char *id; unsigned int in_ports; unsigned int out_ports; unsigned int buflen; unsigned int qlen; }; #define USBG_F_MIDI_INT_TO_ATTR_VAL(WHAT) \ USBG_TO_UNION(usbg_f_midi_attr_val, index, WHAT) #define USBG_F_MIDI_UINT_TO_ATTR_VAL(WHAT) \ USBG_TO_UNION(usbg_f_midi_attr_val, qlen, WHAT) #define USBG_F_MIDI_CCHAR_PTR_TO_ATTR_VAL(WHAT) \ USBG_TO_UNION(usbg_f_midi_attr_val, id, WHAT) /** * @brief Cast from generic function to midi function * @param[in] f function to be converted to midi funciton. * Function should be one of type midi. * @return Converted midi function or NULL if function hasn't suitable type */ usbg_f_midi *usbg_to_midi_function(usbg_function *f); /** * @brief Cast form midi function to generic one * @param[in] mf function to be converted to generic one * @return Generic usbg function */ usbg_function *usbg_from_midi_function(usbg_f_midi *mf); /** * @brief Get attributes of given midi function * @param[in] mf Pointer to midi function * @param[out] attrs Structure to be filled with data * @return 0 on success usbg_error if error occurred. */ int usbg_f_midi_get_attrs(usbg_f_midi *mf, struct usbg_f_midi_attrs *attrs); /** * @brief Set attributes of given midi function * @param[in] mf Pointer to midi function * @param[in] attrs to be set * @return 0 on success usbg_error if error occurred. */ int usbg_f_midi_set_attrs(usbg_f_midi *mf, const struct usbg_f_midi_attrs *attrs); /** * @brief Cleanup attributes structure after usage * @param[in] attrs to be cleaned up */ static inline void usbg_f_midi_cleanup_attrs(struct usbg_f_midi_attrs *attrs) { if (attrs) { free((char *)attrs->id); /* Just for safety */ attrs->id = NULL; } } /** * @brief Get the value of single attribute * @param[in] mf Pointer to midi function * @param[in] attr Code of attribute which value should be taken * @param[out] val Current value of this attribute * @return 0 on success usbg_error if error occurred. */ int usbg_f_midi_get_attr_val(usbg_f_midi *mf, enum usbg_f_midi_attr attr, union usbg_f_midi_attr_val *val); /** * @brief Set the value of single attribute * @param[in] mf Pointer to midi function * @param[in] attr Code of attribute which value should be set * @param[in] val Value of attribute which should be set * @return 0 on success usbg_error if error occurred. */ int usbg_f_midi_set_attr_val(usbg_f_midi *mf, enum usbg_f_midi_attr attr, union usbg_f_midi_attr_val val); /** * @brief Get the index value of MIDI adapter * @param[in] mf Pointer to midi function * @param[out] index Current index value of MIDI adapter * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_midi_get_index(usbg_f_midi *mf, int *index) { return usbg_f_midi_get_attr_val(mf, USBG_F_MIDI_INDEX, (union usbg_f_midi_attr_val *)index); } /** * @brief Set the index value of MIDI adapter * @param[in] mf Pointer to midi function * @param[in] index value which should be set * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_midi_set_index(usbg_f_midi *mf, int index) { return usbg_f_midi_set_attr_val(mf, USBG_F_MIDI_INDEX, USBG_F_MIDI_INT_TO_ATTR_VAL(index)); } /** * @brief Get the value of ID string for associated MIDI adapter * into newly allocated storage * @param[in] mf Pointer to midi function * @param[out] id Newly allocated string containing id string of MIDI adapter * @return 0 on success usbg_error if error occurred. * @note returned id should be free() by caller */ static inline int usbg_f_midi_get_id(usbg_f_midi *mf, char **id) { return usbg_f_midi_get_attr_val(mf, USBG_F_MIDI_ID, (union usbg_f_midi_attr_val *)id); } /** * @brief Get the value of ID string for associated MIDI adapter * into user buffer * @param[in] mf Pointer to midi function * @param[out] buf Place where id should be stored * @param[in] len Size of buffer * @return Number of bytes placed into buf (excluding '\0') or the number of * characters which would have been written to the buffer if enough * space had been available. (just like snprintf() family). This may * also return negative error code from usbg_error. * @note returned id should be free() by caller */ int usbg_f_midi_get_id_s(usbg_f_midi *mf, char *buf, int len); /** * @brief Set the value of ID string for associated MIDI adapter * @param[in] mf Pointer to midi function * @param[in] id string for MIDI adapter * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_midi_set_id(usbg_f_midi *mf, const char *id) { return usbg_f_midi_set_attr_val(mf, USBG_F_MIDI_ID, USBG_F_MIDI_CCHAR_PTR_TO_ATTR_VAL(id)); } /** * @brief Get the number of in ports of MIDI adapter * @param[in] mf Pointer to midi function * @param[out] in_ports Number of in ports of MIDI adapter * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_midi_get_in_ports(usbg_f_midi *mf, unsigned *in_ports) { return usbg_f_midi_get_attr_val(mf, USBG_F_MIDI_IN_PORTS, (union usbg_f_midi_attr_val *)in_ports); } /** * @brief Set the number of in ports of MIDI adapter * @param[in] mf Pointer to midi function * @param[in] in_ports number of in ports of MIDI adapters which should be set * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_midi_set_in_ports(usbg_f_midi *mf, unsigned in_ports) { return usbg_f_midi_set_attr_val(mf, USBG_F_MIDI_IN_PORTS, USBG_F_MIDI_UINT_TO_ATTR_VAL(in_ports)); } /** * @brief Get the number of out ports of MIDI adapter * @param[in] mf Pointer to midi function * @param[out] out_ports Number of out ports of MIDI adapter * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_midi_get_out_ports(usbg_f_midi *mf, unsigned *out_ports) { return usbg_f_midi_get_attr_val(mf, USBG_F_MIDI_OUT_PORTS, (union usbg_f_midi_attr_val *)out_ports); } /** * @brief Set the number of out ports of MIDI adapter * @param[in] mf Pointer to midi function * @param[in] out_ports number of out ports of MIDI adapters which should be set * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_midi_set_out_ports(usbg_f_midi *mf, unsigned out_ports) { return usbg_f_midi_set_attr_val(mf, USBG_F_MIDI_OUT_PORTS, USBG_F_MIDI_UINT_TO_ATTR_VAL(out_ports)); } /** * @brief Get the size of request buffer * @details This is the maximum number of bytes which can be received * using single usb_request. * @param[in] lf Pointer to midi function * @param[out] buflen Current queue length * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_midi_get_buflen(usbg_f_midi *mf, int *buflen) { return usbg_f_midi_get_attr_val(mf, USBG_F_MIDI_BUFLEN, (union usbg_f_midi_attr_val *)buflen); } /** * @brief Set the size of request buffer * @details This is the maximum number of bytes which can be received * using single usb_request. * @param[in] lf Pointer to midi function * @param[in] buflen Current queue length * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_midi_set_buflen(usbg_f_midi *mf, unsigned buflen) { return usbg_f_midi_set_attr_val(mf, USBG_F_MIDI_BUFLEN, USBG_F_MIDI_UINT_TO_ATTR_VAL(buflen)); } /** * @brief Get the value of request queue length * @param[in] lf Pointer to midi function * @param[out] qlen Current queue length * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_midi_get_qlen(usbg_f_midi *mf, unsigned *qlen) { return usbg_f_midi_get_attr_val(mf, USBG_F_MIDI_QLEN, (union usbg_f_midi_attr_val *)qlen); } /** * @brief Set the value of request queue length * @param[in] lf Pointer to midi function * @param[in] qlen Current queue length * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_midi_set_qlen(usbg_f_midi *mf, unsigned qlen) { return usbg_f_midi_set_attr_val(mf, USBG_F_MIDI_QLEN, USBG_F_MIDI_UINT_TO_ATTR_VAL(qlen)); } #ifdef __cplusplus } #endif #endif /* USBG_FUNCTION_MIDI__ */ libusbgx-libusbgx-v0.3.0/include/usbg/function/ms.h000066400000000000000000000317451467553526200223650ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_FUNCTION_MS__ #define USBG_FUNCTION_MS__ #include #include #ifdef __cplusplus extern "C" { #endif typedef struct usbg_f_ms usbg_f_ms; struct usbg_f_ms_lun_attrs { int id; bool cdrom; bool ro; bool nofua; bool removable; const char *file; const char *inquiry_string; }; struct usbg_f_ms_attrs { bool stall; int nluns; struct usbg_f_ms_lun_attrs **luns; }; enum usbg_f_ms_lun_attr { USBG_F_MS_LUN_ATTR_MIN = 0, USBG_F_MS_LUN_CDROM = USBG_F_MS_LUN_ATTR_MIN, USBG_F_MS_LUN_RO, USBG_F_MS_LUN_NOFUA, USBG_F_MS_LUN_REMOVABLE, USBG_F_MS_LUN_FILE, USBG_F_MS_LUN_INQUIRY_STRING, USBG_F_MS_LUN_ATTR_MAX }; union usbg_f_ms_lun_attr_val { bool cdrom; bool ro; bool nofua; bool removable; const char *file; const char *inquiry_string; }; #define USBG_F_MS_LUN_BOOL_TO_ATTR_VAL(WHAT) \ USBG_TO_UNION(usbg_f_ms_lun_attr_val, cdrom, WHAT) #define USBG_F_MS_LUN_CCHAR_PTR_TO_ATTR_VAL(WHAT) \ USBG_TO_UNION(usbg_f_ms_lun_attr_val, file, WHAT) /** * @brief Cast from generic function to mass storage function * @param[in] f function to be converted to ms funciton. * Should be one of types: * ecm, subset, ncm, eem, rndis * @return Converted ms function or NULL if function hasn't suitable type */ usbg_f_ms *usbg_to_ms_function(usbg_function *f); /** * @brief Cast form ms function to generic one * @param[in] mf function to be converted to generic one * @return Generic usbg function */ usbg_function *usbg_from_ms_function(usbg_f_ms *mf); /** * @brief Create new LUN in choosen funcion * @note LUN ids should be contiguous (so id for new LUN should be * current value nluns) * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun to be created * @param[in] lattrs LUN attributes to be set (may be NULL to use defaults) * @return 0 on success usbg_error if error occurred. */ int usbg_f_ms_create_lun(usbg_f_ms *mf, int lun_id, struct usbg_f_ms_lun_attrs *lattrs); /** * @brief Remove LUN from choosen funcion * @note LUN ids should be contiguous (so you should remove LUN with id equal * to nluns - 1) * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun to be created * @return 0 on success usbg_error if error occurred. */ int usbg_f_ms_rm_lun(usbg_f_ms *mf, int lun_id); /** * @brief Get attributes of choosen LUN * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[out] lattrs Structure to be filled with data * @return 0 on success usbg_error if error occurred. */ int usbg_f_ms_get_lun_attrs(usbg_f_ms *mf, int lun_id, struct usbg_f_ms_lun_attrs *lattrs); /** * @brief Set attributes of choosen LUN * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[in] lattrs Lun attributes to be set * @return 0 on success usbg_error if error occurred. * @note The id value in lattrs is ignored by this function */ int usbg_f_ms_set_lun_attrs(usbg_f_ms *mf, int lun_id, const struct usbg_f_ms_lun_attrs *lattrs); /** * @brief Cleanup LUN attributes structure after usage * @param[in] attrs to be cleaned up */ static inline void usbg_f_ms_cleanup_lun_attrs(struct usbg_f_ms_lun_attrs *lattrs) { if (lattrs) { free((char *)lattrs->file); lattrs->file = NULL; free((char *)lattrs->inquiry_string); lattrs->inquiry_string = NULL; } } /** * @brief Get the value of single LUN attribute * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[in] lattr Code of attribute which value should be taken * @param[out] val Current value of this attribute * @return 0 on success usbg_error if error occurred. */ int usbg_f_ms_get_lun_attr_val(usbg_f_ms *mf, int lun_id, enum usbg_f_ms_lun_attr lattr, union usbg_f_ms_lun_attr_val *val); /** * @brief Set the value of single LUN attribute * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[in] lattr Code of attribute which value should be set * @param[in] val Value of attribute which should be set * @return 0 on success usbg_error if error occurred. */ int usbg_f_ms_set_lun_attr_val(usbg_f_ms *mf, int lun_id, enum usbg_f_ms_lun_attr lattr, const union usbg_f_ms_lun_attr_val val); /** * @brief Get the value which determines if lun is visible as a cdrom * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[out] cdrom Current value of stall attribute * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_ms_get_lun_cdrom(usbg_f_ms *mf, int lun_id, bool *cdrom) { return usbg_f_ms_get_lun_attr_val(mf, lun_id, USBG_F_MS_LUN_CDROM, (union usbg_f_ms_lun_attr_val *)cdrom); } /** * @brief Set the value which determines if lun is visible as a cdrom * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[in] cdrom Value of stall attribute which should be set * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_ms_set_lun_cdrom(usbg_f_ms *mf, int lun_id, bool cdrom) { return usbg_f_ms_set_lun_attr_val(mf, lun_id, USBG_F_MS_LUN_CDROM, USBG_F_MS_LUN_BOOL_TO_ATTR_VAL(cdrom)); } /** * @brief Get the value which determines if lun is read only * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[out] ro Indicates if LUN is read only * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_ms_get_lun_ro(usbg_f_ms *mf, int lun_id, bool *ro) { return usbg_f_ms_get_lun_attr_val(mf, lun_id, USBG_F_MS_LUN_RO, (union usbg_f_ms_lun_attr_val *)ro); } /** * @brief Set the value which determines if lun read only * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[in] ro True if LUN should be read only * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_ms_set_lun_ro(usbg_f_ms *mf, int lun_id, bool ro) { return usbg_f_ms_set_lun_attr_val(mf, lun_id, USBG_F_MS_LUN_RO, USBG_F_MS_LUN_BOOL_TO_ATTR_VAL(ro)); } /** * @brief Get the value which determines if lun should ignore * the FUA (Force Unit Access) flag in SCSI commands * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[out] nofua Indicates if FUA bit is ignored * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_ms_get_lun_nofua(usbg_f_ms *mf, int lun_id, bool *nofua) { return usbg_f_ms_get_lun_attr_val(mf, lun_id, USBG_F_MS_LUN_NOFUA, (union usbg_f_ms_lun_attr_val *)nofua); } /** * @brief Set the value which determines if lun should ignore * the FUA (Force Unit Access) flag in SCSI commands * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[in] nofua True if LUN should ignore FUA bit * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_ms_set_lun_nofua(usbg_f_ms *mf, int lun_id, bool nofua) { return usbg_f_ms_set_lun_attr_val(mf, lun_id, USBG_F_MS_LUN_NOFUA, USBG_F_MS_LUN_BOOL_TO_ATTR_VAL(nofua)); } /** * @brief Get the value which determines if lun is removable * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[out] removable Indicates if LUN is removable * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_ms_get_lun_removable(usbg_f_ms *mf, int lun_id, bool *removable) { return usbg_f_ms_get_lun_attr_val(mf, lun_id, USBG_F_MS_LUN_REMOVABLE, (union usbg_f_ms_lun_attr_val *)removable); } /** * @brief Set the value which determines if lun removable * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[in] removable True if LUN should be removable * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_ms_set_lun_removable(usbg_f_ms *mf, int lun_id, bool removable) { return usbg_f_ms_set_lun_attr_val(mf, lun_id, USBG_F_MS_LUN_REMOVABLE, USBG_F_MS_LUN_BOOL_TO_ATTR_VAL(removable)); } /** * @brief Get the name of file which is used as backend storage by this LUN * into newly allocated storage * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[out] file Newly allocated string name of file used as backend * storage * @return 0 on success usbg_error if error occurred. * @note returned file should be free() by caller */ static inline int usbg_f_ms_get_lun_file(usbg_f_ms *mf, int lun_id, char **file) { return usbg_f_ms_get_lun_attr_val(mf, lun_id, USBG_F_MS_LUN_FILE, (union usbg_f_ms_lun_attr_val *)file); } /** * @brief Get the name of file which is used as backend storage by this LUN * into user buffer * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[out] buf Place where file should be stored * @param[in] len Size of buffer * @return Number of bytes placed into buf (excluding '\0') or the number of * characters which would have been written to the buffer if enough * space had been available. (just like snprintf() family). This may * also return negative error code from usbg_error. */ int usbg_f_ms_get_lun_file_s(usbg_f_ms *mf, int lun_id, char *buf, int len); /** * @brief Set the name of file which is used as backend storage by this LUN * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[in] file Name of file which should be used as backend storage * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_ms_set_lun_file(usbg_f_ms *mf, int lun_id, const char *file) { return usbg_f_ms_set_lun_attr_val(mf, lun_id, USBG_F_MS_LUN_FILE, USBG_F_MS_LUN_CCHAR_PTR_TO_ATTR_VAL(file)); } /** * @brief Get the inquiry string of LUN which is used as name in SCSI inquiry * by this LUN into newly allocated storage * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[out] inquiry_string Newly allocated string name of LUN used in SCSI * inquiry * @return 0 on success usbg_error if error occurred. * @note returned inquiry_string should be free() by caller */ static inline int usbg_f_ms_get_lun_inquiry_string(usbg_f_ms *mf, int lun_id, char **inquiry_string) { return usbg_f_ms_get_lun_attr_val(mf, lun_id, USBG_F_MS_LUN_INQUIRY_STRING, (union usbg_f_ms_lun_attr_val *)inquiry_string); } /** * @brief Set the inquiry string which is used as name in SCSI inquiry by this LUN * @param[in] mf Pointer to ms function * @param[in] lun_id ID of lun * @param[in] inquiry_string Name of LUN which used in SCSI inquiry * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_ms_set_lun_inquiry_string(usbg_f_ms *mf, int lun_id, const char *inquiry_string) { return usbg_f_ms_set_lun_attr_val(mf, lun_id, USBG_F_MS_LUN_INQUIRY_STRING, USBG_F_MS_LUN_CCHAR_PTR_TO_ATTR_VAL(inquiry_string)); } /** * @brief Get attributes of given ms function * @param[in] mf Pointer to ms function * @param[out] attrs Structure to be filled with data * @return 0 on success usbg_error if error occurred. */ int usbg_f_ms_get_attrs(usbg_f_ms *mf, struct usbg_f_ms_attrs *attrs); /** * @brief Set attributes of given ms function * @param[in] mf Pointer to ms function * @param[in] attrs to be set * @return 0 on success usbg_error if error occurred. */ int usbg_f_ms_set_attrs(usbg_f_ms *mf, const struct usbg_f_ms_attrs *attrs); /** * @brief Cleanup attributes structure after usage * @param[in] attrs to be cleaned up */ static inline void usbg_f_ms_cleanup_attrs(struct usbg_f_ms_attrs *attrs) { int i; if (!attrs) return; for (i = 0; i < attrs->nluns; ++i) { if (!attrs->luns[i]) continue; usbg_f_ms_cleanup_lun_attrs(attrs->luns[i]); free(attrs->luns[i]); } free(attrs->luns); attrs->luns = NULL; } /** * @brief Get the value of device side MAC address * @param[in] mf Pointer to ms function * @param[out] stall Current value of stall attribute * @return 0 on success usbg_error if error occurred. */ int usbg_f_ms_get_stall(usbg_f_ms *mf, bool *stall); /** * @brief Set the value of device side MAC address * @param[in] mf Pointer to ms function * @param[in] stall Value of stall attribute which should be set * @return 0 on success usbg_error if error occurred. */ int usbg_f_ms_set_stall(usbg_f_ms *mf, bool stall); /** * @brief Get the value of device side MAC address * @param[in] mf Pointer to ms function * @param[out] nluns Current number of LUNs * @return 0 on success usbg_error if error occurred. */ int usbg_f_ms_get_nluns(usbg_f_ms *mf, int *nluns); #ifdef __cplusplus } #endif #endif /* USBG_FUNCTION_MS__ */ libusbgx-libusbgx-v0.3.0/include/usbg/function/net.h000066400000000000000000000226521467553526200225310ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_FUNCTION_NET__ #define USBG_FUNCTION_NET__ #include #include #ifdef __cplusplus extern "C" { #endif struct usbg_f_net; typedef struct usbg_f_net usbg_f_net; struct usbg_f_net_attrs { struct ether_addr dev_addr; struct ether_addr host_addr; const char *ifname; int qmult; unsigned int class_; unsigned int subclass; unsigned int protocol; }; enum usbg_f_net_attr { USBG_F_NET_ATTR_MIN = 0, USBG_F_NET_DEV_ADDR = USBG_F_NET_ATTR_MIN, USBG_F_NET_HOST_ADDR, USBG_F_NET_IFNAME, USBG_F_NET_QMULT, USBG_F_NET_CLASS, USBG_F_NET_SUBCLASS, USBG_F_NET_PROTOCOL, USBG_F_NET_ATTR_MAX }; union usbg_f_net_attr_val { struct ether_addr dev_addr; struct ether_addr host_addr; const char *ifname; unsigned int qmult; unsigned int class_; unsigned int subclass; unsigned int protocol; }; #define USBG_F_NET_ETHER_ADDR_TO_ATTR_VAL(WHAT) \ USBG_TO_UNION(usbg_f_net_attr_val, dev_addr, WHAT) #define USBG_F_NET_INT_TO_ATTR_VAL(WHAT) \ USBG_TO_UNION(usbg_f_net_attr_val, qmult, WHAT) /** * @brief Cast from generic function to net function * @param[in] f function to be converted to net funciton. * Should be one of types: * ecm, subset, ncm, eem, rndis * @return Converted net function or NULL if function hasn't suitable type */ usbg_f_net *usbg_to_net_function(usbg_function *f); /** * @brief Cast form net function to generic one * @param[in] nf function to be converted to generic one * @return Generic usbg function */ usbg_function *usbg_from_net_function(usbg_f_net *nf); /** * @brief Get attributes of given net function * @param[in] nf Pointer to net function * @param[out] attrs Structure to be filled with data * @return 0 on success usbg_error if error occurred. */ int usbg_f_net_get_attrs(usbg_f_net *nf, struct usbg_f_net_attrs *attrs); /** * @brief Set attributes of given net function * @param[in] nf Pointer to net function * @param[in] attrs to be set * @return 0 on success usbg_error if error occurred. */ int usbg_f_net_set_attrs(usbg_f_net *nf, const struct usbg_f_net_attrs *attrs); /** * @brief Cleanup attributes structure after usage * @param[in] attrs to be cleaned up */ static inline void usbg_f_net_cleanup_attrs(struct usbg_f_net_attrs *attrs) { if (attrs) { free((char *)attrs->ifname); attrs->ifname = NULL; } } /** * @brief Get the value of single attribute * @param[in] nf Pointer to net function * @param[in] attr Code of attribute which value should be taken * @param[out] val Current value of this attribute * @return 0 on success usbg_error if error occurred. */ int usbg_f_net_get_attr_val(usbg_f_net *nf, enum usbg_f_net_attr attr, union usbg_f_net_attr_val *val); /** * @brief Set the value of single attribute * @param[in] nf Pointer to net function * @param[in] attr Code of attribute which value should be set * @param[in] val Value of attribute which should be set * @return 0 on success usbg_error if error occurred. */ int usbg_f_net_set_attr_val(usbg_f_net *nf, enum usbg_f_net_attr attr, const union usbg_f_net_attr_val val); /** * @brief Get the value of device side MAC address * @param[in] nf Pointer to net function * @param[out] val Current value of this attribute * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_net_get_dev_addr(usbg_f_net *nf, struct ether_addr *addr) { union usbg_f_net_attr_val val = { .dev_addr = *addr, }; return usbg_f_net_get_attr_val(nf, USBG_F_NET_DEV_ADDR, &val); } /** * @brief Set the value of device side MAC address * @param[in] nf Pointer to net function * @param[out] val Value of attribute which should be set * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_net_set_dev_addr(usbg_f_net *nf, const struct ether_addr *addr) { return usbg_f_net_set_attr_val(nf, USBG_F_NET_DEV_ADDR, USBG_F_NET_ETHER_ADDR_TO_ATTR_VAL(*addr)); } /** * @brief Get the value of host side MAC address * @param[in] nf Pointer to net function * @param[out] val Current value of this attribute * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_net_get_host_addr(usbg_f_net *nf, struct ether_addr *addr) { union usbg_f_net_attr_val val = { .host_addr = *addr, }; return usbg_f_net_get_attr_val(nf, USBG_F_NET_HOST_ADDR, &val); } /** * @brief Set the value of host side MAC address * @param[in] nf Pointer to net function * @param[in] val Value of attribute which should be set * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_net_set_host_addr(usbg_f_net *nf, const struct ether_addr *addr) { return usbg_f_net_set_attr_val(nf, USBG_F_NET_HOST_ADDR, USBG_F_NET_ETHER_ADDR_TO_ATTR_VAL(*addr)); } /** * @brief Get the value of interface name associated with this function * into newly allocated storage * @param[in] nf Pointer to net function * @param[out] ifname Newly allocated string containing name of interface * @return 0 on success usbg_error if error occurred. * @note returned ifname should be free() by caller */ static inline int usbg_f_net_get_ifname(usbg_f_net *nf, char **ifname) { return usbg_f_net_get_attr_val(nf, USBG_F_NET_IFNAME, (union usbg_f_net_attr_val *)ifname); } /** * @brief Get the value of interface name associated with this function * into user buffer * @param[in] nf Pointer to net function * @param[out] buf Place where ifname should be stored * @param[in] len Size of buffer * @return Number of bytes placed into buf (excluding '\0') or the number of * characters which would have been written to the buffer if enough * space had been available. (just like snprintf() family). This may * also return negative error code from usbg_error. */ int usbg_f_net_get_ifname_s(usbg_f_net *nf, char *buf, int len); /** * @brief Get the value of request queue length multiplier * @param[in] nf Pointer to net function * @param[out] qmult Current multiplier of queue len * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_net_get_qmult(usbg_f_net *nf, unsigned int *qmult) { return usbg_f_net_get_attr_val(nf, USBG_F_NET_QMULT, (union usbg_f_net_attr_val *)qmult); } /** * @brief Set the value of request queue length multiplier * @param[in] nf Pointer to net function * @param[in] qmult Multiplier of queue len which should be set * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_net_set_qmult(usbg_f_net *nf, unsigned int qmult) { return usbg_f_net_set_attr_val(nf, USBG_F_NET_QMULT, USBG_F_NET_INT_TO_ATTR_VAL(qmult)); } /** * @brief Get the value of usb function class * @param[in] nf Pointer to net function * @param[out] class_ Current class identification * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_net_get_class(usbg_f_net *nf, unsigned int *class_) { return usbg_f_net_get_attr_val(nf, USBG_F_NET_CLASS, (union usbg_f_net_attr_val *)class_); } /** * @brief Set the value of usb function class * @param[in] nf Pointer to net function * @param[in] class_ Class identification * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_net_set_class(usbg_f_net *nf, unsigned int class_) { return usbg_f_net_set_attr_val(nf, USBG_F_NET_CLASS, USBG_F_NET_INT_TO_ATTR_VAL(class_)); } /** * @brief Get the value of usb function subclass * @param[in] nf Pointer to net function * @param[out] subclass Current subclass identification * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_net_get_subclass(usbg_f_net *nf, int *subclass) { return usbg_f_net_get_attr_val(nf, USBG_F_NET_SUBCLASS, (union usbg_f_net_attr_val *)subclass); } /** * @brief Set the value of usb function subclass * @param[in] nf Pointer to net function * @param[in] subclass Subclass identification * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_net_set_subclass(usbg_f_net *nf, unsigned int subclass) { return usbg_f_net_set_attr_val(nf, USBG_F_NET_SUBCLASS, USBG_F_NET_INT_TO_ATTR_VAL(subclass)); } /** * @brief Get the value of usb function protocol * @param[in] nf Pointer to net function * @param[out] protocol Current protocol identification * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_net_get_protocol(usbg_f_net *nf, int *protocol) { return usbg_f_net_get_attr_val(nf, USBG_F_NET_PROTOCOL, (union usbg_f_net_attr_val *)protocol); } /** * @brief Set the value of usb function protocol * @param[in] nf Pointer to net function * @param[in] protocol protocol identification * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_net_set_protocol(usbg_f_net *nf, unsigned int protocol) { return usbg_f_net_set_attr_val(nf, USBG_F_NET_PROTOCOL, USBG_F_NET_INT_TO_ATTR_VAL(protocol)); } #ifdef __cplusplus } #endif #endif /* USBG_FUNCTION_NET__ */ libusbgx-libusbgx-v0.3.0/include/usbg/function/phonet.h000066400000000000000000000044151467553526200232350ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_FUNCTION_PHONET__ #define USBG_FUNCTION_PHONET__ #include #ifdef __cplusplus extern "C" { #endif struct usbg_f_phonet; typedef struct usbg_f_phonet usbg_f_phonet; /** * @brief Convert from generic function to phonet function * @param[in] f function to be converted to phonet funciton. * Function should be of type phonet. * @return Converted phonet function or NULL if function hasn't suitable type */ usbg_f_phonet *usbg_to_phonet_function(usbg_function *f); /** * @brief Convert form phonet function to generic one * @param[in] pf function to be converted to generic one * @return Generic usbg function */ usbg_function *usbg_from_phonet_function(usbg_f_phonet *pf); /** * @brief Get the value of interface name associated with this function * into newly allocated storage * @param[in] pf Pointer to net function * @param[out] ifname Newly allocated string containing name of interface * @return 0 on success usbg_error if error occurred. * @note returned ifname should be free() by caller */ int usbg_f_phonet_get_ifname(usbg_f_phonet *pf, char **ifname); /** * @brief Get the value of interface name associated with this function * into user buffer * @param[in] pf Pointer to phonet function * @param[out] buf Place where ifname should be stored * @param[in] len Size of buffer * @return Number of bytes placed into buf (excluding '\0') or the number of * characters which would have been written to the buffer if enough * space had been available. (just like snprintf() family). This may * also return negative error code from usbg_error. */ int usbg_f_phonet_get_ifname_s(usbg_f_phonet *pf, char *buf, int len); #ifdef __cplusplus } #endif #endif /* USBG_FUNCTION_PHONET__ */ libusbgx-libusbgx-v0.3.0/include/usbg/function/printer.h000066400000000000000000000024631467553526200234240ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_FUNCTION_PRINTER__ #define USBG_FUNCTION_PRINTER__ #include #include #ifdef __cplusplus extern "C" { #endif struct usbg_f_printer; typedef struct usbg_f_printer usbg_f_printer; struct usbg_f_printer_attrs { const char *pnp_string; int q_len; }; enum usbg_f_printer_attr { USBG_F_PRINTER_ATTR_MIN = 0, USBG_F_PRINTER_PNP_STRING = USBG_F_PRINTER_ATTR_MIN, USBG_F_PRINTER_Q_LEN, USBG_F_PRINTER_ATTR_MAX }; union usbg_f_printer_attr_val { const char *pnp_string; int q_len; }; #define USBG_F_PRINTER_ETHER_ADDR_TO_ATTR_VAL(WHAT) \ USBG_TO_UNION(usbg_f_printer_attr_val, dev_addr, WHAT) #define USBG_F_PRINTER_INT_TO_ATTR_VAL(WHAT) \ USBG_TO_UNION(usbg_f_printer_attr_val, qmult, WHAT) #ifdef __cplusplus } #endif #endif /* USBG_FUNCTION_PRINTER__ */ libusbgx-libusbgx-v0.3.0/include/usbg/function/serial.h000066400000000000000000000031261467553526200232150ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_FUNCTION_SERIAL__ #define USBG_FUNCTION_SERIAL__ #include #ifdef __cplusplus extern "C" { #endif struct usbg_f_serial; typedef struct usbg_f_serial usbg_f_serial; /** * @brief Convert from generic function to serial function * @param[in] f function to be converted to serial funciton. * Function should be one of types: serial, ACM, OBEX. * @return Converted serial function or NULL if function hasn't suitable type */ usbg_f_serial *usbg_to_serial_function(usbg_function *f); /** * @brief Convert form serial function to generic one * @param[in] sf function to be converted to generic one * @return Generic usbg function */ usbg_function *usbg_from_serial_function(usbg_f_serial *sf); /** * @brief Get the id of device side tty port (/dev/ttyGS) * @param[in] sf Pointer to serial function * @param[out] port_num the id of device side tty port * @return 0 on success usbg_error if error occurred. */ int usbg_f_serial_get_port_num(usbg_f_serial *sf, int *port_num); #ifdef __cplusplus } #endif #endif /* USBG_FUNCTION_SERIAL__ */ libusbgx-libusbgx-v0.3.0/include/usbg/function/uac2.h000066400000000000000000000224151467553526200225720ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_FUNCTION_UAC2__ #define USBG_FUNCTION_UAC2__ #include #include #ifdef __cplusplus extern "C" { #endif struct usbg_f_uac2; typedef struct usbg_f_uac2 usbg_f_uac2; typedef short aligned_uchar __attribute__((aligned(sizeof(int)))); typedef short aligned_short __attribute__((aligned(sizeof(int)))); struct usbg_f_uac2_attrs { int c_chmask; int c_srate; int c_ssize; int p_chmask; int p_srate; int p_ssize; aligned_uchar p_hs_bint; aligned_uchar c_hs_bint; const char * c_sync; unsigned int req_number; unsigned int fb_max; bool p_mute_present; bool p_volume_present; aligned_short p_volume_min; aligned_short p_volume_max; aligned_short p_volume_res; bool c_mute_present; bool c_volume_present; aligned_short c_volume_min; aligned_short c_volume_max; aligned_short c_volume_res; const char *function_name; }; enum usbg_f_uac2_attr { USBG_F_UAC2_ATTR_MIN = 0, USBG_F_UAC2_C_CHMASK = USBG_F_UAC2_ATTR_MIN, USBG_F_UAC2_C_SRATE, USBG_F_UAC2_C_SSIZE, USBG_F_UAC2_P_CHMASK, USBG_F_UAC2_P_SRATE, USBG_F_UAC2_P_SSIZE, USBG_F_UAC2_P_HS_BINT, USBG_F_UAC2_C_HS_BINT, USBG_F_UAC2_C_SYNC, USBG_F_UAC2_REQ_NUMBER, USBG_F_UAC2_FB_MAX, USBG_F_UAC2_P_MUTE_PRESENT, USBG_F_UAC2_P_VOLUME_PRESENT, USBG_F_UAC2_P_VOLUME_MIN, USBG_F_UAC2_P_VOLUME_MAX, USBG_F_UAC2_P_VOLUME_RES, USBG_F_UAC2_C_MUTE_PRESENT, USBG_F_UAC2_C_VOLUME_PRESENT, USBG_F_UAC2_C_VOLUME_MIN, USBG_F_UAC2_C_VOLUME_MAX, USBG_F_UAC2_C_VOLUME_RES, USBG_F_UAC2_FUNCTION_NAME, USBG_F_UAC2_ATTR_MAX }; union usbg_f_uac2_attr_val { int c_chmask; int c_srate; int c_ssize; int p_chmask; int p_srate; int p_ssize; char p_hs_bint; char c_hs_bint; const char * c_sync; unsigned int req_number; unsigned int fb_max; bool p_mute_present; bool p_volume_present; int p_volume_min; int p_volume_max; int p_volume_res; bool c_mute_present; bool c_volume_present; int c_volume_min; int c_volume_max; int c_volume_res; const char * function_name; }; #define USBG_F_UAC2_INT_TO_ATTR_VAL(WHAT) \ USBG_TO_UNION(usbg_f_uac2_attr_val, c_chmask, WHAT) /** * @brief Cast from generic function to uac2 function * @param[in] f function to be converted to uac2 funciton. * Function should be one of type uac2. * @return Converted uac2 function or NULL if function hasn't suitable type */ usbg_f_uac2 *usbg_to_uac2_function(usbg_function *f); /** * @brief Cast form uac2 function to generic one * @param[in] af function to be converted to generic one * @return Generic usbg function */ usbg_function *usbg_from_uac2_function(usbg_f_uac2 *af); /** * @brief Get attributes of given uac2 function * @param[in] af Pointer to uac2 function * @param[out] attrs Structure to be filled with data * @return 0 on success usbg_error if error occurred. */ int usbg_f_uac2_get_attrs(usbg_f_uac2 *af, struct usbg_f_uac2_attrs *attrs); /** * @brief Set attributes of given uac2 function * @param[in] af Pointer to uac2 function * @param[in] attrs to be set * @return 0 on success usbg_error if error occurred. */ int usbg_f_uac2_set_attrs(usbg_f_uac2 *af, const struct usbg_f_uac2_attrs *attrs); /** * @brief Cleanup attributes structure after usage * @param[in] attrs to be cleaned up */ static inline void usbg_f_uac2_cleanup_attrs(struct usbg_f_uac2_attrs *attrs) { } /** * @brief Get the value of single attribute * @param[in] af Pointer to uac2 function * @param[in] attr Code of attribute which value should be taken * @param[out] val Current value of this attribute * @return 0 on success usbg_error if error occurred. */ int usbg_f_uac2_get_attr_val(usbg_f_uac2 *af, enum usbg_f_uac2_attr attr, union usbg_f_uac2_attr_val *val); /** * @brief Set the value of single attribute * @param[in] af Pointer to uac2 function * @param[in] attr Code of attribute which value should be set * @param[in] val Value of attribute which should be set * @return 0 on success usbg_error if error occurred. */ int usbg_f_uac2_set_attr_val(usbg_f_uac2 *af, enum usbg_f_uac2_attr attr, union usbg_f_uac2_attr_val val); /** * @brief Get the capture channel mask of UAC2 adapter * @param[in] af Pointer to uac2 function * @param[out] index Current capture channel mask of UAC2 adapter * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_uac2_get_c_chmask(usbg_f_uac2 *af, int *c_chmask) { return usbg_f_uac2_get_attr_val(af, USBG_F_UAC2_C_CHMASK, (union usbg_f_uac2_attr_val *)c_chmask); } /** * @brief Set the capture channel mask of UAC2 adapter * @param[in] af Pointer to uac2 function * @param[in] capture channel mask which should be set * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_uac2_set_c_chmask(usbg_f_uac2 *af, int c_chmask) { return usbg_f_uac2_set_attr_val(af, USBG_F_UAC2_C_CHMASK, USBG_F_UAC2_INT_TO_ATTR_VAL(c_chmask)); } /** * @brief Get the capture sample rate of UAC2 adapter * @param[in] af Pointer to uac2 function * @param[out] index Current sample rate mask of UAC2 adapter * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_uac2_get_c_srate(usbg_f_uac2 *af, int *c_srate) { return usbg_f_uac2_get_attr_val(af, USBG_F_UAC2_C_SRATE, (union usbg_f_uac2_attr_val *)c_srate); } /** * @brief Set the capture sample rate of UAC2 adapter * @param[in] af Pointer to uac2 function * @param[in] capture sample rate which should be set * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_uac2_set_c_srate(usbg_f_uac2 *af, int c_srate) { return usbg_f_uac2_set_attr_val(af, USBG_F_UAC2_C_SRATE, USBG_F_UAC2_INT_TO_ATTR_VAL(c_srate)); } /** * @brief Get the capture sample size of UAC2 adapter * @param[in] af Pointer to uac2 function * @param[out] index Current sample size mask of UAC2 adapter * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_uac2_get_c_ssize(usbg_f_uac2 *af, int *c_ssize) { return usbg_f_uac2_get_attr_val(af, USBG_F_UAC2_C_SSIZE, (union usbg_f_uac2_attr_val *)c_ssize); } /** * @brief Set the capture sample size of UAC2 adapter * @param[in] af Pointer to uac2 function * @param[in] capture sample size which should be set * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_uac2_set_c_ssize(usbg_f_uac2 *af, int c_ssize) { return usbg_f_uac2_set_attr_val(af, USBG_F_UAC2_C_SSIZE, USBG_F_UAC2_INT_TO_ATTR_VAL(c_ssize)); } /** * @brief Get the playback channel mask of UAC2 adapter * @param[in] af Pointer to uac2 function * @param[out] index Current playback channel mask of UAC2 adapter * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_uac2_get_p_chmask(usbg_f_uac2 *af, int *p_chmask) { return usbg_f_uac2_get_attr_val(af, USBG_F_UAC2_P_CHMASK, (union usbg_f_uac2_attr_val *)p_chmask); } /** * @brief Set the playback channel mask of UAC2 adapter * @param[in] af Pointer to uac2 function * @param[in] playback channel mask which should be set * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_uac2_set_p_chmask(usbg_f_uac2 *af, int p_chmask) { return usbg_f_uac2_set_attr_val(af, USBG_F_UAC2_P_CHMASK, USBG_F_UAC2_INT_TO_ATTR_VAL(p_chmask)); } /** * @brief Get the playback sample rate of UAC2 adapter * @param[in] af Pointer to uac2 function * @param[out] index Current sample rate mask of UAC2 adapter * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_uac2_get_p_srate(usbg_f_uac2 *af, int *p_srate) { return usbg_f_uac2_get_attr_val(af, USBG_F_UAC2_P_SRATE, (union usbg_f_uac2_attr_val *)p_srate); } /** * @brief Set the playback sample rate of UAC2 adapter * @param[in] af Pointer to uac2 function * @param[in] playback sample rate which should be set * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_uac2_set_p_srate(usbg_f_uac2 *af, int p_srate) { return usbg_f_uac2_set_attr_val(af, USBG_F_UAC2_P_SRATE, USBG_F_UAC2_INT_TO_ATTR_VAL(p_srate)); } /** * @brief Get the playback sample size of UAC2 adapter * @param[in] af Pointer to uac2 function * @param[out] index Current sample size mask of UAC2 adapter * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_uac2_get_p_ssize(usbg_f_uac2 *af, int *p_ssize) { return usbg_f_uac2_get_attr_val(af, USBG_F_UAC2_P_SSIZE, (union usbg_f_uac2_attr_val *)p_ssize); } /** * @brief Set the playback sample size of UAC2 adapter * @param[in] af Pointer to uac2 function * @param[in] playback sample size which should be set * @return 0 on success usbg_error if error occurred. */ static inline int usbg_f_uac2_set_p_ssize(usbg_f_uac2 *af, int p_ssize) { return usbg_f_uac2_set_attr_val(af, USBG_F_UAC2_P_SSIZE, USBG_F_UAC2_INT_TO_ATTR_VAL(p_ssize)); } #ifdef __cplusplus } #endif #endif /* USBG_FUNCTION_UAC2__ */ libusbgx-libusbgx-v0.3.0/include/usbg/function/uvc.h000066400000000000000000000075341467553526200225420ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_FUNCTION_UVC__ #define USBG_FUNCTION_UVC__ #include #ifdef __cplusplus extern "C" { #endif struct usbg_f_uvc; typedef struct usbg_f_uvc usbg_f_uvc; struct usbg_f_uvc_config_attrs { int streaming_maxburst; int streaming_maxpacket; int streaming_interval; const char *function_name; }; struct usbg_f_uvc_frame_attrs { int bFrameIndex; int bmCapabilities; int dwMinBitRate; int dwMaxBitRate; int dwMaxVideoFrameBufferSize; int dwDefaultFrameInterval; int dwFrameInterval; int wWidth; int wHeight; }; struct usbg_f_uvc_format_attrs { int bmaControls; int bFormatIndex; int bDefaultFrameIndex; int bAspectRatioX; int bAspectRatioY; int bmInterlaceFlags; const char *format; int bBitsPerPixel; const char * guidFormat; struct usbg_f_uvc_frame_attrs **frames; }; struct usbg_f_uvc_attrs { struct usbg_f_uvc_format_attrs **formats; }; enum usbg_f_uvc_config_attr { USBG_F_UVC_CONFIG_ATTR_MIN = 0, USBG_F_UVC_CONFIG_MAXBURST = USBG_F_UVC_CONFIG_ATTR_MIN, USBG_F_UVC_CONFIG_MAXPACKET, USBG_F_UVC_CONFIG_INTERVAL, USBG_F_UVC_CONFIG_FUNCTION_NAME, USBG_F_UVC_CONFIG_ATTR_MAX }; enum usbg_f_uvc_frame_attr { USBG_F_UVC_FRAME_ATTR_MIN = 0, USBG_F_UVC_FRAME_INDEX = USBG_F_UVC_FRAME_ATTR_MIN, USBG_F_UVC_FRAME_CAPABILITIES, USBG_F_UVC_FRAME_MIN_BITRATE, USBG_F_UVC_FRAME_MAX_BITRATE, USBG_F_UVC_FRAME_MAX_VIDEO_BUFFERSIZE, USBG_F_UVC_FRAME_DEFAULT_INTERVAL, USBG_F_UVC_FRAME_INTERVAL, USBG_F_UVC_FRAME_HEIGHT, USBG_F_UVC_FRAME_WIDTH, USBG_F_UVC_FRAME_ATTR_MAX }; enum usbg_f_uvc_format_attr { USBG_F_UVC_FORMAT_ATTR_MIN = 0, USBG_F_UVC_FORMAT_CONTROLS = USBG_F_UVC_FORMAT_ATTR_MIN, USBG_F_UVC_FORMAT_INTERLACE_FLAGS, USBG_F_UVC_FORMAT_ASPECTRATIO_Y, USBG_F_UVC_FORMAT_ASPECTRATIO_X, USBG_F_UVC_FORMAT_DEFAULT_FRAME_INDEX, USBG_F_UVC_FORMAT_FORMAT_INDEX, USBG_F_UVC_FORMAT_BITS_PER_PIXEL, USBG_F_UVC_FORMAT_GUID_FORMAT, USBG_F_UVC_FORMAT_ATTR_MAX }; union usbg_f_uvc_config_attr_val { int streaming_maxburst; int streaming_maxpacket; int streaming_interval; const char *function_name; }; union usbg_f_uvc_frame_attr_val { int bmCapabilities; int dwMinBitRate; int dwMaxBitRate; int dwMaxVideoFrameBufferSize; int dwDefaultFrameInterval; int dwFrameInterval; int wWidth; int wHeight; }; union usbg_f_uvc_format_attr_val { int bmaControls; int bFormatIndex; int bDefaultFrameIndex; int bAspectRatioX; int bAspectRatioY; int bmInterlaceFlags; int bBitsPerPixel; const char * guidFormat; }; /** * @brief Cast from generic function to uvc function * @param[in] f function to be converted to uvc funciton. * Should be one of types: * ecm, subset, ncm, eem, rndis * @return Converted uvc function or NULL if function hasn't suitable type */ usbg_f_uvc *usbg_to_uvc_function(usbg_function *f); /** * @brief Cast form uvc function to generic one * @param[in] uvc function to be converted to generic one * @return Generic usbg function */ usbg_function *usbg_from_uvc_function(usbg_f_uvc *ff); /** * @brief Cleanup attributes structure after usage * @param[in] attrs to be cleaned up */ static inline void usbg_f_uvc_cleanup_attrs(struct usbg_f_uvc_attrs *attrs) { } int usbg_f_uvc_get_attrs(usbg_f_uvc *uvcf, struct usbg_f_uvc_attrs *attrs); int usbg_f_uvc_set_attrs(usbg_f_uvc *uvcf, const struct usbg_f_uvc_attrs *attrs); #ifdef __cplusplus } #endif #endif /* USBG_FUNCTION_UVC__ */ libusbgx-libusbgx-v0.3.0/include/usbg/usbg.h000066400000000000000000001144011467553526200210500ustar00rootroot00000000000000/* * Copyright (C) 2013 Linaro Limited * * Matt Porter * * Copyright (C) 2013 - 2015 Samsung Electronics * * Krzysztof Opasiak * * This library is free software; you can redistribute it 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. */ #ifndef __USBG_H__ #define __USBG_H__ #include #include #include #include #include #include #include /* For FILE * */ #include #include "usbg_version.h" #ifdef __cplusplus extern "C" { #endif /** * @file include/usbg/usbg.h * @todo Clean up static buffers in structures */ /** * @addtogroup libusbgx * Public API for USB gadget-configfs library * @{ */ #define DEFAULT_UDC NULL #define LANG_US_ENG 0x0409 #define DEFAULT_CONFIG_LABEL "config" #define GUID_BIN_LENGTH 16 #define GUID_CHAR_LENGTH 36 /* 32 bytes + 4 dashes */ /* This one has to be at least 18 bytes to hold network address */ #define USBG_MAX_STR_LENGTH 256 #define USBG_MAX_NAME_LENGTH 40 /* Dev name for ffs is a part of function name, we subtract 4 char for "ffs." */ #define USBG_MAX_DEV_LENGTH (USBG_MAX_NAME_LENGTH - 4) #define USBG_TO_UNION(UNAME, FIELD, WHAT) \ ((union UNAME){ .FIELD = WHAT, }) /** * @brief Additional option for usbg_rm_* functions. * @details This option allows to remove all content * of gadget/config/function recursively. */ #define USBG_RM_RECURSE 1 /* * Internal structures */ struct usbg_state; struct usbg_gadget; struct usbg_config; struct usbg_function; struct usbg_binding; struct usbg_udc; /** * @brief State of the gadget devices in the system */ typedef struct usbg_state usbg_state; /** * @brief USB gadget device */ typedef struct usbg_gadget usbg_gadget; /** * @brief USB configuration */ typedef struct usbg_config usbg_config; /** * @brief USB function */ typedef struct usbg_function usbg_function; /** * @brief USB function to config binding */ typedef struct usbg_binding usbg_binding; /** * @brief USB device controller */ typedef struct usbg_udc usbg_udc; /** * @typedef usbg_gadget_attr * @brief Gadget attributes which can be set using * usbg_set_gadget_attr() function. */ typedef enum { USBG_GADGET_ATTR_MIN = 0, USBG_BCD_USB = USBG_GADGET_ATTR_MIN, USBG_B_DEVICE_CLASS, USBG_B_DEVICE_SUB_CLASS, USBG_B_DEVICE_PROTOCOL, USBG_B_MAX_PACKET_SIZE_0, USBG_ID_VENDOR, USBG_ID_PRODUCT, USBG_BCD_DEVICE, USBG_GADGET_ATTR_MAX, } usbg_gadget_attr; /** * @brief USB gadget device attributes */ struct usbg_gadget_attrs { uint16_t bcdUSB; uint8_t bDeviceClass; uint8_t bDeviceSubClass; uint8_t bDeviceProtocol; uint8_t bMaxPacketSize0; uint16_t idVendor; uint16_t idProduct; uint16_t bcdDevice; }; typedef enum { USBG_GADGET_STR_MIN = 0, USBG_STR_MANUFACTURER = USBG_GADGET_STR_MIN, USBG_STR_PRODUCT, USBG_STR_SERIAL_NUMBER, USBG_GADGET_STR_MAX, } usbg_gadget_str; /** * @brief USB gadget device strings */ struct usbg_gadget_strs { char *manufacturer; char *product; char *serial; }; /** * @brief USB gadget Microsoft OS Descriptors */ struct usbg_gadget_os_descs { bool use; uint8_t b_vendor_code; char *qw_sign; }; /** * @typedef usbg_gadget_os_desc_strs * @brief Microsoft OS Descriptors strings */ typedef enum { USBG_GADGET_OS_DESC_MIN = 0, OS_DESC_USE = USBG_GADGET_OS_DESC_MIN, OS_DESC_B_VENDOR_CODE, OS_DESC_QW_SIGN, USBG_GADGET_OS_DESC_MAX, } usbg_gadget_os_desc_strs; /** * @brief USB configuration attributes */ struct usbg_config_attrs { uint8_t bmAttributes; uint8_t bMaxPower; }; /** * @brief USB configuration strings */ struct usbg_config_strs { char *configuration; }; /** * @typedef usbg_function_type * @brief Supported USB function types */ typedef enum { USBG_FUNCTION_TYPE_MIN = 0, USBG_F_SERIAL = USBG_FUNCTION_TYPE_MIN, USBG_F_ACM, USBG_F_OBEX, USBG_F_ECM, USBG_F_SUBSET, USBG_F_NCM, USBG_F_EEM, USBG_F_RNDIS, USBG_F_PHONET, USBG_F_FFS, USBG_F_MASS_STORAGE, USBG_F_MIDI, USBG_F_LOOPBACK, USBG_F_HID, USBG_F_UAC2, USBG_F_UVC, USBG_F_PRINTER, USBG_F_9PFS, USBG_FUNCTION_TYPE_MAX, } usbg_function_type; /** * @brief USB OS Descriptor function attributes */ struct usbg_function_os_desc { char *compatible_id; char *sub_compatible_id; }; /* Error codes */ /** * @typedef usbg_error * @brief Errors which could be returned by library functions */ typedef enum { USBG_SUCCESS = 0, USBG_ERROR_NO_MEM = -1, USBG_ERROR_NO_ACCESS = -2, USBG_ERROR_INVALID_PARAM = -3, USBG_ERROR_NOT_FOUND = -4, USBG_ERROR_IO = -5, USBG_ERROR_EXIST = -6, USBG_ERROR_NO_DEV = -7, USBG_ERROR_BUSY = -8, USBG_ERROR_NOT_SUPPORTED = -9, USBG_ERROR_PATH_TOO_LONG = -10, USBG_ERROR_INVALID_FORMAT = -11, USBG_ERROR_MISSING_TAG = -12, USBG_ERROR_INVALID_TYPE = -13, USBG_ERROR_INVALID_VALUE = -14, USBG_ERROR_NOT_EMPTY = -15, USBG_ERROR_OTHER_ERROR = -99 } usbg_error; /** * @brief Get the error name as a constant string * @param e error code * @return Constant string with error name */ extern const char *usbg_error_name(usbg_error e); /** * @brief Get the short description of error * @param e error code * @return Constant string with error description */ extern const char *usbg_strerror(usbg_error e); /* Library init and cleanup */ /** * @brief Initialize the libusbgx library state * @param configfs_path Path to the mounted configfs filesystem * @param state Pointer to be filled with pointer to usbg_state * @return 0 on success, usbg_error on error */ extern int usbg_init(const char *configfs_path, usbg_state **state); /** * @brief Clean up the libusbgx library state * @param s Pointer to state */ extern void usbg_cleanup(usbg_state *s); /** * @brief Get ConfigFS path * @param s Pointer to state * @return Path to configfs or NULL if error occurred * @warning Returned buffer should not be edited! * Returned string is valid as long as passed usbg_state is valid. * For example path is valid until usbg_cleanup() call. */ extern const char *usbg_get_configfs_path(usbg_state *s); /** * @brief Get ConfigFS path into user buffer * @param[in] s Pointer to state * @param[out] buf Place where path should be stored * @param[in] len Size of buffer * @return Number of bytes placed into buf (excluding '\0') or the number of * characters which would have been written to the buffer if enough * space had been available. (just like snprintf() family). */ extern int usbg_get_configfs_path_s(usbg_state *s, char *buf, int len); /* USB gadget queries */ /** * @brief Get a gadget device by name * @param s Pointer to state * @param name Name of the gadget device * @return Pointer to gadget or NULL if a matching gadget isn't found */ extern usbg_gadget *usbg_get_gadget(usbg_state *s, const char *name); /** * @brief Get a function by name * @param g Pointer to gadget * @param type Function type * @param instance Instance of function * @return Pointer to function or NULL if a matching function isn't found */ extern usbg_function *usbg_get_function(usbg_gadget *g, usbg_function_type type, const char *instance); /** * @brief Get a configuration by name * @param g Pointer to gadget * @param id Identify of configuration * @param label Configuration label. If not NULL this function will return * valid value only if configuration with given id exist and has this label. * If NULL this function will return config with given id (if such exist) * and ignore this param. * @return Pointer to config or NULL if a matching config isn't found */ extern usbg_config *usbg_get_config(usbg_gadget *g, int id, const char *label); /** * @brief Get a udc by name * @param s Pointer to state * @param name Name of the udc * @return Pointer to udc or NULL if a matching udc isn't found */ extern usbg_udc *usbg_get_udc(usbg_state *s, const char *name); /* USB gadget/config/function/binding removal */ /** * @brief Remove binding between configuration and function * @details This function frees also the memory allocated for binding * @param b Binding to be removed * @return 0 on success, usbg_error if error occurred */ extern int usbg_rm_binding(usbg_binding *b); /** * @brief Remove configuration * @details This function frees also the memory allocated for configuration * @param c Configuration to be removed * @param opts Additional options for configuration removal. * @return 0 on success, usbg_error if error occurred */ extern int usbg_rm_config(usbg_config *c, int opts); /** * @brief Remove existing USB function * @details This function frees also the memory allocated for function * @param f Function to be removed * @param opts Additional options for configuration removal. * @return 0 on success, usbg_error if error occurred */ extern int usbg_rm_function(usbg_function *f, int opts); /** * @brief Remove existing USB gadget * @details This function frees also the memory allocated for gadget * @param g Gadget to be removed * @param opts Additional options for configuration removal. * @return 0 on success, usbg_error if error occurred */ extern int usbg_rm_gadget(usbg_gadget *g, int opts); /** * @brief Remove configuration strings for given language * @param c Pointer to configuration * @param lang Language of strings which should be deleted * @return 0 on success, usbg_error if error occurred */ extern int usbg_rm_config_strs(usbg_config *c, int lang); /** * @brief Remove gadget strings for given language * @param g Pointer to gadget * @param lang Language of strings which should be deleted * @return 0 on success, usbg_error if error occurred */ extern int usbg_rm_gadget_strs(usbg_gadget *g, int lang); /* USB gadget allocation and configuration */ /** * @brief Create a new USB gadget device * @param s Pointer to state * @param name Name of the gadget * @param idVendor Gadget vendor ID * @param idProduct Gadget product ID * @param g Pointer to be filled with pointer to gadget * @return 0 on success usbg_error if error occurred */ extern int usbg_create_gadget_vid_pid(usbg_state *s, const char *name, uint16_t idVendor, uint16_t idProduct, usbg_gadget **g); /** * @brief Create a new USB gadget device and set given attributes * and strings * @param s Pointer to state * @param name Name of the gadget * @param g_attrs Gadget attributes to be set. If NULL setting is omitted. * @param g_strs Gadget strings to be set. If NULL setting is omitted. * @param g Pointer to be filled with pointer to gadget * @note Given strings are assumed to be in US English * @return 0 on success usbg_error if error occurred */ extern int usbg_create_gadget(usbg_state *s, const char *name, const struct usbg_gadget_attrs *g_attrs, const struct usbg_gadget_strs *g_strs, usbg_gadget **g); /** * @brief Get string representing selected gadget attribute * @param attr code of selected attribute * @return String suitable for given attribute or NULL if such * string has not been found */ extern const char *usbg_get_gadget_attr_str(usbg_gadget_attr attr); /** * @brief Lookup attr code based on its name * @param name of attribute * @return code of suitable attribute or usbg_error */ extern int usbg_lookup_gadget_attr(const char *name); /** * @brief Lookup str code based on its name * @param name of string * @return code of suitable string or usbg_error */ extern int usbg_lookup_gadget_str(const char *name); /** * @brief Get name of selected gadget string * @param str Gadget string code * @return Name of string associated with this code */ extern const char *usbg_get_gadget_str_name(usbg_gadget_str str); /** * @brief Get name of selected OS Descriptor string * @param str OS Descriptor string code * @return Name of OS Descriptor associated with this code */ extern const char *usbg_get_gadget_os_desc_name(usbg_gadget_os_desc_strs str); /** * @brief Set selected attribute to value * @param g Pointer to gadget * @param attr Code of selected attribute * @param val value to be set * @return 0 on success, usbg_error otherwise * @note val is of type int but value provided to this function should * be suitable to place it in type dedicated for selected attr (uint16 or uint8) */ extern int usbg_set_gadget_attr(usbg_gadget *g, usbg_gadget_attr attr, int val); /** * @brief Get value of selected attribute * @param g Pointer to gadget * @param attr Code of selected attribute * @return Value of selected attribute (always above zero) or * usbg_error if error occurred. * @note User should use only lowest one or two bytes as attribute value * depending on attribute size (see usbg_gadget_attrs for details). */ extern int usbg_get_gadget_attr(usbg_gadget *g, usbg_gadget_attr attr); /** * @brief Set the USB gadget attributes * @param g Pointer to gadget * @param g_attrs Gadget attributes * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_attrs(usbg_gadget *g, const struct usbg_gadget_attrs *g_attrs); /** * @brief Get the USB gadget strings * @param g Pointer to gadget * @param g_attrs Structure to be filled * @return 0 on success usbg_error if error occurred */ extern int usbg_get_gadget_attrs(usbg_gadget *g, struct usbg_gadget_attrs *g_attrs); /** * @brief Get gadget name * @param g Pointer to gadget * @return Gadget name or NULL if error occurred. * @warning Returned buffer should not be edited! * Returned string is valid as long as passed usbg_gadget is valid. * For example gadget name is valid until someone remove gadget. */ extern const char *usbg_get_gadget_name(usbg_gadget *g); /** * @brief Get gadget name into user buffer * @param[in] g Pointer to state * @param[out] buf Place where name should be stored * @param[in] len Size of buffer * @return Number of bytes placed into buf (excluding '\0') or the number of * characters which would have been written to the buffer if enough * space had been available. (just like snprintf() family). */ extern int usbg_get_gadget_name_s(usbg_gadget *g, char *buf, int len); /** * @brief Set the USB gadget vendor id * @param g Pointer to gadget * @param idVendor USB device vendor id * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_vendor_id(usbg_gadget *g, uint16_t idVendor); /** * @brief Set the USB gadget product id * @param g Pointer to gadget * @param idProduct USB device product id * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_product_id(usbg_gadget *g, uint16_t idProduct); /** * @brief Set the USB gadget device class code * @param g Pointer to gadget * @param bDeviceClass USB device class code * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_device_class(usbg_gadget *g, uint8_t bDeviceClass); /** * @brief Set the USB gadget protocol code * @param g Pointer to gadget * @param bDeviceProtocol USB protocol code * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_device_protocol(usbg_gadget *g, uint8_t bDeviceProtocol); /** * @brief Set the USB gadget device subclass code * @param g Pointer to gadget * @param bDeviceSubClass USB device subclass code * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_device_subclass(usbg_gadget *g, uint8_t bDeviceSubClass); /** * @brief Set the maximum packet size for a gadget * @param g Pointer to gadget * @param bMaxPacketSize0 Maximum packet size * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_device_max_packet(usbg_gadget *g, uint8_t bMaxPacketSize0); /** * @brief Set the gadget device BCD release number * @param g Pointer to gadget * @param bcdDevice BCD release number * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_device_bcd_device(usbg_gadget *g, uint16_t bcdDevice); /** * @brief Set the gadget device BCD USB version * @param g Pointer to gadget * @param bcdUSB BCD USB version * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_device_bcd_usb(usbg_gadget *g, uint16_t bcdUSB); /** * @brief Get the USB gadget strings * @param g Pointer to gadget * @param lang Language of strings * @param g_strs Structure to be filled * @return 0 on success usbg_error if error occurred */ extern int usbg_get_gadget_strs(usbg_gadget *g, int lang, struct usbg_gadget_strs *g_strs); /** * @brief Get the array of languages available in this gadget * @param g Pointer to gadget * @param langs array of available language codes * @return 0 on success usbg_error if error occurred */ extern int usbg_get_gadget_strs_langs(usbg_gadget *g, int **langs); /** * @brief Free gadget strings * @details This function releases the memory allocated for strings * not for struct usbg_gadget_strs itself. * @param g_strs Strings to be released */ static inline void usbg_free_gadget_strs(struct usbg_gadget_strs *g_strs) { if (!g_strs) return; free(g_strs->manufacturer); free(g_strs->product); free(g_strs->serial); } /** * @brief Set selected string * @param g Pointer to gadget * @param str Code of selected string * @param val value to be set * @return 0 on success, usbg_error otherwise */ extern int usbg_set_gadget_str(usbg_gadget *g, usbg_gadget_str str, int lang, const char *val); /** * @brief Set the USB gadget strings * @param g Pointer to gadget * @param lang USB language ID * @param g_strs Gadget attributes * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_strs(usbg_gadget *g, int lang, const struct usbg_gadget_strs *g_strs); /** * @brief Set the serial number for a gadget * @param g Pointer to gadget * @param lang USB language ID * @param ser Serial number * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_serial_number(usbg_gadget *g, int lang, const char *ser); /** * @brief Set the manufacturer name for a gadget * @param g Pointer to gadget * @param lang USB language ID * @param mnf Manufacturer * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_manufacturer(usbg_gadget *g, int lang, const char *mnf); /** * @brief Set the product name for a gadget * @param g Pointer to gadget * @param lang USB language ID * @param prd Product * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_product(usbg_gadget *g, int lang, const char *prd); /** * @brief Get the USB gadget OS Descriptor * @param g Pointer to gadget * @param g_os_descs Structure to be filled * @return 0 on success usbg_error if error occurred */ extern int usbg_get_gadget_os_descs(usbg_gadget *g, struct usbg_gadget_os_descs *g_os_descs); /** * @brief Free OS Descriptor attributes * @details This function releases the memory allocated for USB * gadget OS Descriptor atrributes. * @param g_os_desc OS Descriptor attributes to be released */ static inline void usbg_free_gadget_os_desc( struct usbg_gadget_os_descs *g_os_desc) { if (!g_os_desc) return; free(g_os_desc->qw_sign); } /** * @brief Set the USB gadget OS Descriptor * @param g Pointer to gadget * @param g_os_descs Structure to be filled * @return 0 on success usbg_error if error occurred */ extern int usbg_set_gadget_os_descs(usbg_gadget *g, const struct usbg_gadget_os_descs *g_os_descs); /* USB function allocation and configuration */ /** * @brief Create a new USB gadget function and set its attributes * @param g Pointer to gadget * @param type Type of function * @param instance Function instance name * @param f_attrs Function specific attributes to be set. * If NULL setting is omitted. * @param f Pointer to be filled with pointer to function * @note Given strings are assumed to be in US English * @return 0 on success usbg_error if error occurred */ extern int usbg_create_function(usbg_gadget *g, usbg_function_type type, const char *instance, void *f_attrs, usbg_function **f); /** * @brief Get function instance name * @param f Pointer to function * @return instance name or NULL if error occurred. * @warning Returned buffer should not be edited! * Returned string is valid as long as passed usbg_function is valid. * For example instance name is valid until someone remove this function. */ extern const char *usbg_get_function_instance(usbg_function *f); /** * @brief Get function instance name into user buffer * @param[in] f Pointer to function * @param[out] buf Place where instance name should be stored * @param[in] len Size of buffer * @return Number of bytes placed into buf (excluding '\0') or the number of * characters which would have been written to the buffer if enough * space had been available. (just like snprintf() family). */ extern int usbg_get_function_instance_s(usbg_function *f, char *buf, int len); /** * @brief Get function type as a string * @param type Function type * @return String suitable for given function type */ extern const char *usbg_get_function_type_str(usbg_function_type type); /** * @brief Lookup function type suitable for given name * @param name Name of function * @return Function type enum or negative error code */ extern int usbg_lookup_function_type(const char *name); /** * @brief Cleanup content of function attributes * @param f_attrs function attributes which should be cleaned up. * @note This function should be called to free * additional memory allocated by usbg_get_function_attrs(). * @warning None of attributes in passed structure should be * accessed after returning from this function. */ extern void usbg_cleanup_function_attrs(usbg_function *f, void *f_attrs); /** * @brief Get type of given function * @param f Pointer to function * @return usbg_function_type (0 or above) or * usbg_error (below 0) if error occurred */ extern usbg_function_type usbg_get_function_type(usbg_function *f); /** * @brief Get attributes of given function * @param f Pointer to function * @param f_attrs Union to be filled * @return 0 on success usbg_error if error occurred. * @warning memory pointed by f_attrs should be big enough to hold attributes * specific for given function type. This function can by dangerous. * That's why it is strongly recomended to use set/get function provided * by each function type. */ extern int usbg_get_function_attrs(usbg_function *f, void *f_attrs); /** * @brief Set attributes of given function * @param f Pointer to function * @param f_attrs Attributes to be set * @return 0 on success, usbg_error if error occurred */ extern int usbg_set_function_attrs(usbg_function *f, void *f_attrs); /** * @brief Get OS Descriptor compatibility of given function * @param f Pointer to function * @param iname Interface name * @param f_os_desc OS Descriptor compatibility to be filled * @return 0 on success, usbg_error if error occurred */ extern int usbg_get_interf_os_desc(usbg_function *f, const char *iname, struct usbg_function_os_desc *f_os_desc); /** * @brief Free OS Descriptor function attributes * @details This function releases the memory allocated for function * atrributes for struct usbg_function_os_desc. * @param f_os_desc OS Descriptor function attributes to be released */ static inline void usbg_free_interf_os_desc( struct usbg_function_os_desc *f_os_desc) { if (!f_os_desc) return; free(f_os_desc->compatible_id); free(f_os_desc->sub_compatible_id); } /** * @brief Set OS Descriptor compatibility of given function * @param f Pointer to function * @param iname Interface name * @param f_os_desc OS Descriptor compatibility to be set * @return 0 on success, usbg_error if error occurred */ extern int usbg_set_interf_os_desc(usbg_function *f, const char *iname, const struct usbg_function_os_desc *f_os_desc); /* USB configurations allocation and configuration */ /** * @brief Create a new USB gadget configuration * @param g Pointer to gadget * @param id Identify of configuration * @param label configuration label, if NULL, default is used * @param c_attrs Configuration attributes to be set * @param c_strs Configuration strings to be set * @param c Pointer to be filled with pointer to configuration * @note Given strings are assumed to be in US English * @return 0 on success usbg_error if error occurred */ extern int usbg_create_config(usbg_gadget *g, int id, const char *label, const struct usbg_config_attrs *c_attrs, const struct usbg_config_strs *c_strs, usbg_config **c); /** * @brief Get config label * @param c Pointer to config * @return config label or NULL if error occurred. * @warning Returned buffer should not be edited! * Returned string is valid as long as passed usbg_config is valid. * For example config label is valid until someone remove this function. */ extern const char *usbg_get_config_label(usbg_config *c); /** * @brief Get config label into user buffer * @param[in] c Pointer to config * @param[out] buf Place where label should be stored * @param[in] len Size of buffer * @return Number of bytes placed into buf (excluding '\0') or the number of * characters which would have been written to the buffer if enough * space had been available. (just like snprintf() family). */ extern int usbg_get_config_label_s(usbg_config *c, char *buf, int len); /** * @brief Get config id * @param c Pointer to config * @return Configuration id or usbg_error if error occurred. */ extern int usbg_get_config_id(usbg_config *c); /** * @brief Set the USB configuration attributes * @param c Pointer to configuration * @param c_attrs Configuration attributes * @return 0 on success or usbg_error if error occurred. */ extern int usbg_set_config_attrs(usbg_config *c, const struct usbg_config_attrs *c_attrs); /** * @brief Get the USB configuration strings * @param c Pointer to configuration * @param c_attrs Structure to be filled * @return 0 on success or usbg_error if error occurred. */ extern int usbg_get_config_attrs(usbg_config *c, struct usbg_config_attrs *c_attrs); /** * @brief Set the configuration maximum power * @param c Pointer to config * @param bMaxPower Maximum power (in 2 mA units) * @return 0 on success or usbg_error if error occurred. */ extern int usbg_set_config_max_power(usbg_config *c, int bMaxPower); /** * @brief Set the configuration bitmap attributes * @param c Pointer to config * @param bmAttributes Configuration characteristics * @return 0 on success or usbg_error if error occurred. */ extern int usbg_set_config_bm_attrs(usbg_config *c, int bmAttributes); /** * @brief Get the USB configuration strings * @param c Pointer to configuration * @param lang Language of strings * @param c_strs Structure to be filled * @return 0 on success or usbg_error if error occurred. */ extern int usbg_get_config_strs(usbg_config *c, int lang, struct usbg_config_strs *c_strs); /** * @brief Get the array of languages available in this config * @param c Pointer to configuration * @param langs array of available language codes * @return 0 on success usbg_error if error occurred */ extern int usbg_get_config_strs_langs(usbg_config *c, int **langs); /** * @brief Free configuration strings * @details This function releases the memory allocated for strings * not for struct usbg_config_strs itself. * @param c_strs Strings to be released */ static inline void usbg_free_config_strs(struct usbg_config_strs *c_strs) { if (!c_strs) return; free(c_strs->configuration); } /** * @brief Set the USB configuration strings * @param c Pointer to configuration * @param lang USB language ID * @param c_strs Configuration strings * @return 0 on success, usbg_error on failure. */ extern int usbg_set_config_strs(usbg_config *c, int lang, const struct usbg_config_strs *c_strs); /** * @brief Set the configuration string * @param c Pointer to config * @param lang USB language ID * @param string Configuration description * @return 0 on success, usbg_error on failure. */ extern int usbg_set_config_string(usbg_config *c, int lang, const char *string); /** * @brief Add a function to a configuration * @param c Pointer to config * @param name Name of configuration function binding * @param f Pointer to function * @return 0 on success, usbg_error on failure. */ extern int usbg_add_config_function(usbg_config *c, const char *name, usbg_function *f); /** * @brief Get target function of given binding * @param b Binding between configuration and function * @return Pointer to USB function which is target for this binding */ extern usbg_function *usbg_get_binding_target(usbg_binding *b); /** * @brief Get binding name * @param b Pointer to binding * @return Binding name or NULL if error occurred. * @warning Returned buffer should not be edited! * Returned string is valid as long as passed usbg_binding is valid. * For example binding name is valid until someone remove this binding. */ extern const char *usbg_get_binding_name(usbg_binding *b); /** * @brief Get binding name into user buffer * @param[in] b Pointer to binding * @param[out] buf Place where binding name should be stored * @param[in] len Size of buffer * @return Number of bytes placed into buf (excluding '\0') or the number of * characters which would have been written to the buffer if enough * space had been available. (just like snprintf() family). */ extern int usbg_get_binding_name_s(usbg_binding *b, char *buf, int len); /** * @brief Get configuration selected for OS Descriptors * @param g Pointer to gadget * @return usbg_config or NULL */ usbg_config *usbg_get_os_desc_binding(usbg_gadget *g); /** * @brief Set configuration for OS Descriptors * @param g Pointer to gadget * @param c Pointer to config * @return 0 on success, usbg_error on failure. */ extern int usbg_set_os_desc_config(usbg_gadget *g, usbg_config *c); /* USB gadget setup and teardown */ /** * @brief Enable a USB gadget device * @param g Pointer to gadget * @param udc where gadget should be assigned. * If NULL, default one (first) is used. * @return 0 on success or usbg_error if error occurred. */ extern int usbg_enable_gadget(usbg_gadget *g, usbg_udc *udc); /** * @brief Disable a USB gadget device * @param g Pointer to gadget * @return 0 on success or usbg_error if error occurred. */ extern int usbg_disable_gadget(usbg_gadget *g); /** * @brief Get name of udc * @param u Pointer to udc * @return UDC name or NULL if error occurred. * @warning Returned buffer should not be edited! * Returned string is valid as long as passed usbg_state is valid. * For example UDC name is valid until usbg_cleanup(). */ extern const char *usbg_get_udc_name(usbg_udc *u); /** * @brief Get udc name into user buffer * @param[in] u Pointer to udc * @param[out] buf Place where udc name should be stored * @param[in] len Size of buffer * @return Number of bytes placed into buf (excluding '\0') or the number of * characters which would have been written to the buffer if enough * space had been available. (just like snprintf() family). */ extern int usbg_get_udc_name_s(usbg_udc *u, char *buf, int len); /** * @brief Get udc to which gadget is bound * @param g Pointer to gadget * @return Pointer to UDC or NULL if gadget is not enabled */ extern usbg_udc *usbg_get_gadget_udc(usbg_gadget *g); /** * @brief Get gadget which is attached to this UDC * @param u Pointer to udc * @return Pointer to gadget or NULL if UDC is free */ extern usbg_gadget *usbg_get_udc_gadget(usbg_udc *u); /** * @def usbg_for_each_gadget(g, s) * Iterates over each gadget */ #define usbg_for_each_gadget(g, s) \ for (g = usbg_get_first_gadget(s); \ g != NULL; \ g = usbg_get_next_gadget(g)) /** * @def usbg_for_each_function(f, g) * Iterates over each function */ #define usbg_for_each_function(f, g) \ for (f = usbg_get_first_function(g); \ f != NULL; \ f = usbg_get_next_function(f)) /** * @def usbg_for_each_config(c, g) * Iterates over each config */ #define usbg_for_each_config(c, g) \ for (c = usbg_get_first_config(g); \ c != NULL; \ c = usbg_get_next_config(c)) /** * @def usbg_for_each_binding(b, c) * Iterates over each binding */ #define usbg_for_each_binding(b, c) \ for (b = usbg_get_first_binding(c); \ b != NULL; \ b = usbg_get_next_binding(b)) /** * @def usbg_for_each_udc(b, c) * Iterates over each udc */ #define usbg_for_each_udc(u, s) \ for (u = usbg_get_first_udc(s); \ u != NULL; \ u = usbg_get_next_udc(u)) /** * @brief Get first gadget in gadget list * @param s State of library * @return Pointer to gadget or NULL if list is empty. * @note Gadgets are sorted in strings (name) order */ extern usbg_gadget *usbg_get_first_gadget(usbg_state *s); /** * @brief Get first function in function list * @param g Pointer of gadget * @return Pointer to function or NULL if list is empty. * @note Functions are sorted in strings (name) order */ extern usbg_function *usbg_get_first_function(usbg_gadget *g); /** * @brief Get first config in config list * @param g Pointer of gadget * @return Pointer to configuration or NULL if list is empty. * @note Configs are sorted in strings (name) order */ extern usbg_config *usbg_get_first_config(usbg_gadget *g); /** * @brief Get first binding in binding list * @param c Pointer to configuration * @return Pointer to binding or NULL if list is empty. * @note Bindings are sorted in strings (name) order */ extern usbg_binding *usbg_get_first_binding(usbg_config *c); /** * @brief Get first udc in udc list * @param s State of library * @return Pointer to udc or NULL if list is empty. * @note UDCs are sorted in strings (name) order */ extern usbg_udc *usbg_get_first_udc(usbg_state *s); /** * @brief Get the next gadget on a list. * @param g Pointer to current gadget * @return Next gadget or NULL if end of list. */ extern usbg_gadget *usbg_get_next_gadget(usbg_gadget *g); /** * @brief Get the next function on a list. * @param f Pointer to current function * @return Next function or NULL if end of list. */ extern usbg_function *usbg_get_next_function(usbg_function *f); /** * @brief Get the next config on a list. * @param c Pointer to current config * @return Next config or NULL if end of list. */ extern usbg_config *usbg_get_next_config(usbg_config *c); /** * @brief Get the next binding on a list. * @param b Pointer to current binding * @return Next binding or NULL if end of list. */ extern usbg_binding *usbg_get_next_binding(usbg_binding *b); /** * @brief Get the next udc on a list. * @param u Pointer to current udc * @return Next udc or NULL if end of list. */ extern usbg_udc *usbg_get_next_udc(usbg_udc *u); /* Import / Export API */ /** * @brief Exports usb function to file * @param f Pointer to function to be exported * @param stream where function should be saved * @return 0 on success, usbg_error otherwise */ extern int usbg_export_function(usbg_function *f, FILE *stream); /** * @brief Exports configuration to file * @param c Pointer to configuration to be exported * @param stream where configuration should be saved * @return 0 on success, usbg_error otherwise */ extern int usbg_export_config(usbg_config *c, FILE *stream); /** * @brief Exports whole gadget to file * @param g Pointer to gadget to be exported * @param stream where gadget should be saved * @return 0 on success, usbg_error otherwise */ extern int usbg_export_gadget(usbg_gadget *g, FILE *stream); /** * @brief Imports usb function from file and adds it to given gadget * @param g Gadget where function should be placed * @param stream from which function should be imported * @param instance name which should be used for new function * @param f place for pointer to imported function * if NULL this param will be ignored. * @return 0 on success, usbg_error otherwise */ extern int usbg_import_function(usbg_gadget *g, FILE *stream, const char *instance, usbg_function **f); /** * @brief Imports usb configuration from file and adds it to given gadget * @param g Gadget where configuration should be placed * @param stream from which configuration should be imported * @param id which should be used for new configuration * @param c place for pointer to imported configuration * if NULL this param will be ignored. * @return 0 on success, usbg_error otherwise */ extern int usbg_import_config(usbg_gadget *g, FILE *stream, int id, usbg_config **c); /** * @brief Imports usb gadget from file * @param s current state of library * @param stream from which gadget should be imported * @param name which should be used for new gadget * @param g place for pointer to imported gadget * if NULL this param will be ignored. * @return 0 on success, usbg_error otherwise */ extern int usbg_import_gadget(usbg_state *s, FILE *stream, const char *name, usbg_gadget **g); /** * @brief Get text of error which occurred during last function import * @param g gadget where function import error occurred * @return Text of error or NULL if no error data */ extern const char *usbg_get_func_import_error_text(usbg_gadget *g); /** * @brief Get line number where function import error occurred * @param g gadget where function import error occurred * @return line number or value below 0 if no error data */ extern int usbg_get_func_import_error_line(usbg_gadget *g); /** * @brief Get text of error which occurred during last config import * @param g gadget where config import error occurred * @return Text of error or NULL if no error data */ extern const char *usbg_get_config_import_error_text(usbg_gadget *g); /** * @brief Get line number where config import error occurred * @param g gadget where config import error occurred * @return line number or value below 0 if no error data */ extern int usbg_get_config_import_error_line(usbg_gadget *g); /** * @brief Get text of error which occurred during last gadget import * @param s where gadget import error occurred * @return Text of error or NULL if no error data */ extern const char *usbg_get_gadget_import_error_text(usbg_state *s); /** * @brief Get line number where gadget import error occurred * @param s where gadget import error occurred * @return line number or value below 0 if no error data */ extern int usbg_get_gadget_import_error_line(usbg_state *s); /** * @} */ #ifdef __cplusplus } #endif #endif /* __USBG_H__ */ libusbgx-libusbgx-v0.3.0/include/usbg/usbg_internal.h000066400000000000000000000257701467553526200227560ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_INTERNAL_H #define USBG_INTERNAL_H #include #include #include #include #include #ifdef HAS_GADGET_SCHEMES #include "usbg_internal_libconfig.h" #else #include "usbg_internal_none.h" #endif #ifdef __cplusplus extern "C" { #endif /** * @file include/usbg/usbg_internal.h */ #ifndef offsetof #define offsetof(type, member) __builtin_offsetof (type, member) #endif /* offsetof */ #ifndef container_of #define container_of(ptr, type, field) ({ \ const typeof(((type *)0)->field) *member = (ptr); \ (type *)( (char *)member - offsetof(type, field) ); \ }) #endif /* container_of */ #define USBG_MAX_PATH_LENGTH PATH_MAX /* ConfigFS just like SysFS uses page size as max size of file content */ #define USBG_MAX_FILE_SIZE 4096 struct usbg_function_type { /* Name of this function type */ char *name; /* OS Descriptor interface name */ char **os_desc_iname; /* Called to allocate instance of function */ int (*alloc_inst)(struct usbg_function_type *, usbg_function_type, const char *, const char *, usbg_gadget *, struct usbg_function **); /* Called to free memory used by function */ void (*free_inst)(struct usbg_function_type *, struct usbg_function *); /* * Called when user would like to remove this function. * If this callback is provided it will be always called * before rmdir on function directory. This function * should check received flags and remove composed function * attributes (directories) only if USBG_RM_RECURSE flag * has been passed. */ int (*remove)(struct usbg_function *, int); /* Set the value of all given attributes */ int (*set_attrs)(struct usbg_function *, void *); /* Get the value of all function attributes */ int (*get_attrs)(struct usbg_function *, void *); /* Free the additional memory allocated for function attributes */ void (*cleanup_attrs)(struct usbg_function *, void *); /* Should import all function attributes from libconfig format */ int (*import)(struct usbg_function *, config_setting_t *); /* Should export all functions attributes to libconfig format */ int (*export)(struct usbg_function *, config_setting_t *); }; struct usbg_state { char *path; char *configfs_path; TAILQ_HEAD(ghead, usbg_gadget) gadgets; TAILQ_HEAD(uhead, usbg_udc) udcs; config_t *last_failed_import; }; struct usbg_gadget { char *name; char *path; TAILQ_ENTRY(usbg_gadget) gnode; TAILQ_HEAD(chead, usbg_config) configs; TAILQ_HEAD(fhead, usbg_function) functions; usbg_state *parent; config_t *last_failed_import; usbg_udc *udc; usbg_config *os_desc_binding; }; struct usbg_config { TAILQ_ENTRY(usbg_config) cnode; TAILQ_HEAD(bhead, usbg_binding) bindings; usbg_gadget *parent; char *name; char *path; char *label; int id; }; struct usbg_function { TAILQ_ENTRY(usbg_function) fnode; usbg_gadget *parent; char *name; char *path; char *instance; /* Only for internal library usage */ char *label; usbg_function_type type; struct usbg_function_type *ops; }; struct usbg_binding { TAILQ_ENTRY(usbg_binding) bnode; usbg_config *parent; usbg_function *target; char *name; char *path; }; struct usbg_udc { TAILQ_ENTRY(usbg_udc) unode; usbg_state *parent; usbg_gadget *gadget; char *name; }; #define ARRAY_SIZE(array) (sizeof(array)/sizeof(*array)) #define ARRAY_SIZE_SENTINEL(array, size) \ static void __attribute__ ((unused)) array##_size_sentinel() \ { \ char array##_smaller_than_expected[ \ (int)(ARRAY_SIZE(array) - size)] \ __attribute__ ((unused)); \ \ char array##_larger_than_expected[ \ (int)(size - ARRAY_SIZE(array))] \ __attribute__ ((unused)); \ } #define ERROR(msg, ...) do {\ fprintf(stderr, "%s() "msg" \n", \ __func__, ##__VA_ARGS__);\ fflush(stderr);\ } while (0) #define ERRORNO(msg, ...) do {\ fprintf(stderr, "%s() %s: "msg" \n", \ __func__, strerror(errno), ##__VA_ARGS__);\ fflush(stderr);\ } while (0) /* Insert in string order */ #define INSERT_TAILQ_STRING_ORDER(HeadPtr, HeadType, NameField, ToInsert, NodeField) \ do { \ if (TAILQ_EMPTY((HeadPtr)) || \ (strcmp((ToInsert)->NameField, TAILQ_FIRST((HeadPtr))->NameField) < 0)) \ TAILQ_INSERT_HEAD((HeadPtr), (ToInsert), NodeField); \ else if (strcmp((ToInsert)->NameField, TAILQ_LAST((HeadPtr), HeadType)->NameField) > 0) \ TAILQ_INSERT_TAIL((HeadPtr), (ToInsert), NodeField); \ else { \ typeof(ToInsert) _cur; \ TAILQ_FOREACH(_cur, (HeadPtr), NodeField) { \ if (strcmp((ToInsert)->NameField, _cur->NameField) > 0) \ continue; \ TAILQ_INSERT_BEFORE(_cur, (ToInsert), NodeField); \ break; \ } \ } \ } while (0) #define STRINGS_DIR "strings" #define CONFIGS_DIR "configs" #define FUNCTIONS_DIR "functions" #define GADGETS_DIR "usb_gadget" #define OS_DESC_DIR "os_desc" static inline int file_select(const struct dirent *dent) { if ((strcmp(dent->d_name, ".") == 0) || (strcmp(dent->d_name, "..") == 0)) return 0; else return 1; } int usbg_translate_error(int error); char *usbg_ether_ntoa_r(const struct ether_addr *addr, char *buf); int usbg_read_buf(const char *path, const char *name, const char *file, char *buf); int usbg_read_buf_limited(const char *path, const char *name, const char *file, char *buf, int len); int usbg_read_int(const char *path, const char *name, const char *file, int base, int *dest); #define usbg_read_dec(p, n, f, d) usbg_read_int(p, n, f, 10, d) #define usbg_read_hex(p, n, f, d) usbg_read_int(p, n, f, 16, d) int usbg_read_bool(const char *path, const char *name, const char *file, bool *dest); int usbg_read_string(const char *path, const char *name, const char *file, char *buf); int usbg_read_string_limited(const char *path, const char *name, const char *file, char *buf, int len); int usbg_read_string_alloc(const char *path, const char *name, const char *file, char **dest); int usbg_read_buf_alloc(const char *path, const char *name, const char *file, char **dest, int len); int usbg_write_buf(const char *path, const char *name, const char *file, const char *buf, int len); int usbg_write_int(const char *path, const char *name, const char *file, int value, const char *str); #define usbg_write_dec(p, n, f, v) usbg_write_int(p, n, f, v, "%d\n") #define usbg_write_hex(p, n, f, v) usbg_write_int(p, n, f, v, "0x%x\n") #define usbg_write_hex16(p, n, f, v) usbg_write_int(p, n, f, v, "0x%04x\n") #define usbg_write_hex8(p, n, f, v) usbg_write_int(p, n, f, v, "0x%02x\n") #define usbg_write_bool(p, n, f, v) usbg_write_dec(p, n, f, !!v) int usbg_write_string(const char *path, const char *name, const char *file, const char *buf); int usbg_rm_file(const char *path, const char *name); int usbg_rm_dir(const char *path, const char *name); int usbg_rm_all_dirs(const char *path); int usbg_check_dir(const char *path); #define usbg_config_is_int(node) (config_setting_type(node) == CONFIG_TYPE_INT) #define usbg_config_is_string(node) \ (config_setting_type(node) == CONFIG_TYPE_STRING) int usbg_init_function(struct usbg_function *f, struct usbg_function_type *ops, usbg_function_type type, const char *type_name, const char *instance, const char *path, struct usbg_gadget *parent); void usbg_cleanup_function(struct usbg_function *f); #define GENERIC_ALLOC_INST(prefix, _type, _member) \ static int prefix##_alloc_inst(struct usbg_function_type *type, \ usbg_function_type type_code, \ const char *instance, const char *path, \ struct usbg_gadget *parent, \ struct usbg_function **f) \ { \ _type *ff; \ int ret; \ \ ff = malloc(sizeof(*ff)); \ if (!ff) \ return USBG_ERROR_NO_MEM; \ \ ret = usbg_init_function(&ff->_member, type, type_code, \ type->name, instance, path, parent); \ if (ret != USBG_SUCCESS) \ goto free_func; \ \ *f = &ff->_member; \ \ return ret; \ \ free_func: \ free(ff); \ return ret; \ } #define GENERIC_FREE_INST(prefix, _type, _member) \ static void prefix##_free_inst(struct usbg_function_type *type, \ struct usbg_function *f) \ { \ _type *ff = container_of(f, _type, _member); \ \ usbg_cleanup_function(&ff->_member); \ free(ff); \ } typedef int (*usbg_attr_get_func)(const char *, const char *, const char *, void *); typedef int (*usbg_attr_set_func)(const char *, const char *, const char *, void *); static inline int usbg_get_dec(const char *path, const char *name, const char *attr, void *val) { return usbg_read_dec(path, name, attr, (int *)val); } static inline int usbg_set_dec(const char *path, const char *name, const char *attr, void *val) { return usbg_write_dec(path, name, attr, *((int *)val)); } static inline int usbg_get_bool(const char *path, const char *name, const char *attr, void *val) { return usbg_read_bool(path, name, attr, (bool *)val); } static inline int usbg_set_bool(const char *path, const char *name, const char *attr, void *val) { return usbg_write_bool(path, name, attr, *((bool *)val)); } static inline int usbg_get_string(const char *path, const char *name, const char *attr, void *val) { return usbg_read_string_alloc(path, name, attr, (char **)val); } static inline int usbg_set_string(const char *path, const char *name, const char *attr, void *val) { return usbg_write_string(path, name, attr, *(char **)val); } int usbg_get_ether_addr(const char *path, const char *name, const char *attr, void *val); int usbg_set_ether_addr(const char *path, const char *name, const char *attr, void *val); int usbg_get_dev(const char *path, const char *name, const char *attr, void *val); int usbg_write_guid(const char *path, const char *name, const char *file, const char *buf); /* * return: * 0 - if not found * usbg_error on error (less than 0) * above 0 when found suitable value */ typedef int (*usbg_import_node_func)(config_setting_t *root, const char *node_name, void *val); /* return 0 on success, usbg_error otherwise */ typedef int (*usbg_export_node_func)(config_setting_t *root, const char *node_name, void *val); #ifdef __cplusplus } #endif #endif /* USBG_INTERNAL_H */ libusbgx-libusbgx-v0.3.0/include/usbg/usbg_internal_libconfig.h000066400000000000000000000034551467553526200247660ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_INTERNAL_LIBCONFIG_H #define USBG_INTERNAL_LIBCONFIG_H #include #include #ifdef __cplusplus extern "C" { #endif int usbg_get_config_node_int(config_setting_t *root, const char *node_name, void *val); int usbg_get_config_node_bool(config_setting_t *root, const char *node_name, void *val); int usbg_get_config_node_string(config_setting_t *root, const char *node_name, void *val); int usbg_get_config_node_ether_addr(config_setting_t *root, const char *node_name, void *val); int usbg_set_config_node_int(config_setting_t *root, const char *node_name, void *val); int usbg_set_config_node_int_hex(config_setting_t *root, const char *node_name, void *val); int usbg_set_config_node_bool(config_setting_t *root, const char *node_name, void *val); int usbg_set_config_node_string(config_setting_t *root, const char *node_name, void *val); int usbg_set_config_node_ether_addr(config_setting_t *root, const char *node_name, void *val); int usbg_set_config_node_dev(config_setting_t *root, const char *node_name, void *val); int usbg_set_config_node_guid(config_setting_t *root, const char *node_name, void *val); #ifdef __cplusplus } #endif #endif /* USBG_INTERNAL_LIBCONFIG_H */ libusbgx-libusbgx-v0.3.0/include/usbg/usbg_internal_none.h000066400000000000000000000027471467553526200237740ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_INTERNAL_LIBCONFIG_H #define USBG_INTERNAL_LIBCONFIG_H #ifdef __cplusplus extern "C" { #endif #define usbg_get_config_node_int NULL #define usbg_get_config_node_bool NULL #define usbg_get_config_node_string NULL #define usbg_get_config_node_ether_addr NULL #define usbg_set_config_node_int NULL #define usbg_set_config_node_int_hex NULL #define usbg_set_config_node_bool NULL #define usbg_set_config_node_string NULL #define usbg_set_config_node_ether_addr NULL #define usbg_set_config_node_dev NULL #define usbg_set_config_node_guid NULL /* * This define comes from libconfig header. * * This is a kind of hack to allow compile libusbgx without * gadget schemes support but our test with libconfig support. */ #ifndef __libconfig_h typedef struct _should_not_be_used config_t; typedef struct _should_not_be_used config_setting_t; void config_destroy(config_t *config); #endif /* __libconfig_h */ #ifdef __cplusplus } #endif #endif /* USBG_INTERNAL_LIBCONFIG_H */ libusbgx-libusbgx-v0.3.0/include/usbg/usbg_version.h.in000066400000000000000000000015031467553526200232200ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #ifndef USBG_VERSION_H #define USBG_VERSION_H /** * Make API version integer from major, minor and micro numbers */ #define USBG_MAKE_VERSION(major, minor, micro) \ ((major << 24) | (minor << 16) | micro) /** * Version of libusbgx's that is available. */ #define USBG_VERSION @USBG_VERSION_HEX@ #endif libusbgx-libusbgx-v0.3.0/install-headers.sh000077500000000000000000000006371467553526200207770ustar00rootroot00000000000000#!/bin/sh install -d "${DESTDIR}/${MESON_INSTALL_PREFIX}/include/usbg/function" install -m 0644 "${MESON_BUILD_ROOT}/usbg_version.h" "${DESTDIR}/${MESON_INSTALL_PREFIX}/include/usbg" install -m 0644 "${MESON_SOURCE_ROOT}/include/usbg/usbg.h" "${DESTDIR}/${MESON_INSTALL_PREFIX}/include/usbg" install -m 0644 "${MESON_SOURCE_ROOT}/include/usbg/function/"* "${DESTDIR}/${MESON_INSTALL_PREFIX}/include/usbg/function" libusbgx-libusbgx-v0.3.0/libusbgx.pc.in000066400000000000000000000003551467553526200201260ustar00rootroot00000000000000prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: libusbgx Description: USB gadget-configfs library Requires: @REQUIRES@ Version: @PACKAGE_VERSION@ Libs: -L${libdir} -lusbgx Cflags: -I${includedir} libusbgx-libusbgx-v0.3.0/m4/000077500000000000000000000000001467553526200156735ustar00rootroot00000000000000libusbgx-libusbgx-v0.3.0/m4/.gitignore000066400000000000000000000000151467553526200176570ustar00rootroot00000000000000* !.gitignorelibusbgx-libusbgx-v0.3.0/meson.build000066400000000000000000000043461467553526200175240ustar00rootroot00000000000000project( 'libusbgx', [ 'c', 'cpp' ], version: '0.3.0', license: 'LGPL2.1', default_options: [ 'warning_level=1', 'werror=true', ] ) add_project_arguments([ '-D_GNU_SOURCE' ], language: 'c') cc = meson.get_compiler('c') config = configuration_data() version = meson.project_version() version_hex = run_command('sh', '-c', 'printf "0x%02x%02x%04x" $(printf "%s" "@0@" | sed -e "s/\./ /g")'.format(version), check: true).stdout().strip() config.set('USBG_VERSION_HEX', version_hex) dependencies = [] sources = [] c_flags = [] libconfig = dependency('libconfig', required: get_option('gadget-schemes')) libdl = cc.find_library('dl', required: get_option('tests')) cmocka = dependency('cmocka', required: get_option('tests')) doxygen = find_program('doxygen', required: get_option('doxygen')) if libconfig.found() c_flags = ['-DHAS_GADGET_SCHEMES'] dependencies += libconfig endif inc = include_directories('include', '.') subdir('src') configure_file( input: 'include/usbg/usbg_version.h.in', output: 'usbg_version.h', configuration: config ) meson.add_install_script('install-headers.sh') libusbgx = library( 'usbgx', sources, version: '2.0.0', dependencies: dependencies, include_directories: inc, c_args: c_flags, install: true, ) # For subproject: libusbgx_dep = declare_dependency( include_directories: inc, link_with: libusbgx, ) if get_option('examples') subdir('examples') endif if cmocka.found() subdir('tests') endif if doxygen.found() cfg = configuration_data() if cmocka.found() cfg.set('BUILD_TESTS_TRUE', '') else cfg.set('BUILD_TESTS_TRUE', 'X') endif configure_file( input: 'doxygen.cfg.in', output: 'doxygen.cfg', configuration: cfg ) env = environment() env.set('PROJECT', meson.project_name()) env.set('VERSION', version) env.set('DOCDIR', meson.current_build_dir() + '/doc') env.set('SRCDIR', meson.current_source_dir()) run_command(doxygen, meson.current_build_dir() + '/doxygen.cfg', env: env, check: true, ) endif pkgconfig = import('pkgconfig') pkgconfig.generate( libraries: libusbgx, version: meson.project_version(), filebase: meson.project_name(), name: meson.project_name(), description: 'USB gadget-configfs library', ) # TODO: install doxygen? # TODO: install cmake files libusbgx-libusbgx-v0.3.0/meson_options.txt000066400000000000000000000005271467553526200210140ustar00rootroot00000000000000option('examples', type: 'boolean', value: false, description: 'Build examples') option('tests', type: 'feature', value: 'auto', description: 'Build unit tests') option('gadget-schemes', type: 'feature', value: 'auto', description: 'Enable gadget schemes') option('doxygen', type: 'feature', value: 'auto', description: 'Build documentation') libusbgx-libusbgx-v0.3.0/packaging/000077500000000000000000000000001467553526200172775ustar00rootroot00000000000000libusbgx-libusbgx-v0.3.0/packaging/libusbgx.manifest000066400000000000000000000001111467553526200226370ustar00rootroot00000000000000 libusbgx-libusbgx-v0.3.0/packaging/libusbgx.spec000066400000000000000000000040461467553526200217760ustar00rootroot00000000000000Name: libusbgx Version: 0.3.0 Release: 0 License: LGPL-2.1+ and GPL-2.0+ Summary: USB gadget with ConfigFS Library Group: Base/Device Management Source0: libusbgx-%{version}.tar.gz Source1001: libusbgx.manifest BuildRequires: pkg-config BuildRequires: pkgconfig(libconfig) %description libusbgx is a librarary for all USB gadget operations using ConfigFS. %package devel Summary: USB gadget with ConfigFS Library Group: Development/Libraries Requires: %{name} = %{version}-%{release} %description devel Development package for libusbgx. Contains headers and binaries required for compilation of applications which use libusbgx. %package examples Summary: Examples of libusbgx usage Group: Applications/Other Requires: %{name} = %{version}-%{release} %description examples Sample applications which shows how to use libusbgx. %prep %setup -q cp %{SOURCE1001} . %reconfigure %build make %install %make_install %post -p /sbin/ldconfig %postun -p /sbin/ldconfig %files %manifest %{name}.manifest %defattr(-,root,root) %license COPYING.LGPL %{_libdir}/libusbgx.so.* %{_libdir}/libusbgx.so.*.*.* %files devel %manifest %{name}.manifest %defattr(-,root,root) %{_includedir}/usbg/usbg.h %{_includedir}/usbg/usbg_version.h %{_includedir}/usbg/function/ffs.h %{_includedir}/usbg/function/loopback.h %{_includedir}/usbg/function/midi.h %{_includedir}/usbg/function/ms.h %{_includedir}/usbg/function/net.h %{_includedir}/usbg/function/phonet.h %{_includedir}/usbg/function/serial.h %{_includedir}/usbg/function/hid.h %{_includedir}/usbg/function/uac2.h %{_libdir}/pkgconfig/libusbgx.pc %{_libdir}/libusbgx.so %files examples %manifest %{name}.manifest %license COPYING %{_bindir}/gadget-acm-ecm %{_bindir}/show-gadgets %{_bindir}/gadget-vid-pid-remove %{_bindir}/gadget-ffs %{_bindir}/gadget-midi %{_bindir}/gadget-ms %{_bindir}/gadget-hid %{_bindir}/gadget-export %{_bindir}/gadget-import %{_bindir}/gadget-uac2 %{_bindir}/gadget-printer %{_bindir}/show-udcs %{_bindir}/gadget-rndis-os-desc %changelog libusbgx-libusbgx-v0.3.0/src/000077500000000000000000000000001467553526200161425ustar00rootroot00000000000000libusbgx-libusbgx-v0.3.0/src/Makefile.am000066400000000000000000000012401467553526200201730ustar00rootroot00000000000000AUTOMAKE_OPTIONS = std-options subdir-objects lib_LTLIBRARIES = libusbgx.la libusbgx_la_SOURCES = usbg.c usbg_error.c usbg_common.c function/ether.c function/ffs.c function/midi.c function/ms.c function/phonet.c function/serial.c function/loopback.c function/hid.c function/uac2.c function/uvc.c function/printer.c function/9pfs.c if TEST_GADGET_SCHEMES libusbgx_la_SOURCES += usbg_schemes_libconfig.c usbg_common_libconfig.c else libusbgx_la_SOURCES += usbg_schemes_none.c endif libusbgx_la_LDFLAGS = $(LIBCONFIG_LIBS) libusbgx_la_LDFLAGS += -version-info 3:0:0 libusbgx_la_CFLAGS = $(LIBCONFIG_CFLAGS) AM_CPPFLAGS=-I$(top_srcdir)/include/ -I$(top_builddir)/include/usbg libusbgx-libusbgx-v0.3.0/src/function/000077500000000000000000000000001467553526200177675ustar00rootroot00000000000000libusbgx-libusbgx-v0.3.0/src/function/9pfs.c000066400000000000000000000047721467553526200210260ustar00rootroot00000000000000/* * Copyright (C) 2024 Pengutronix * * Michael Grzeschik * * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include "usbg/function/9pfs.h" #include #ifdef HAS_GADGET_SCHEMES #include #endif struct usbg_f_9pfs { struct usbg_function func; }; GENERIC_ALLOC_INST(p9fs, struct usbg_f_9pfs, func); GENERIC_FREE_INST(p9fs, struct usbg_f_9pfs, func); static int p9fs_set_attrs(struct usbg_function *f, void *f_attrs) { const char *dev_name = *(const char **)f_attrs; return dev_name && dev_name[0] ? USBG_ERROR_INVALID_PARAM : USBG_SUCCESS; } static int p9fs_get_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_9pfs_get_dev_name(usbg_to_9pfs(f), f_attrs); } static void p9fs_cleanup_attrs(struct usbg_function *f, void *f_attrs) { free(*(char **)f_attrs); } static int p9fs_libconfig_import(struct usbg_function *f, config_setting_t *root) { return USBG_SUCCESS; } static int p9fs_libconfig_export(struct usbg_function *f, config_setting_t *root) { return USBG_SUCCESS; } struct usbg_function_type usbg_f_type_9pfs = { .name = "usb9pfs", .alloc_inst = p9fs_alloc_inst, .free_inst = p9fs_free_inst, .set_attrs = p9fs_set_attrs, .get_attrs = p9fs_get_attrs, .cleanup_attrs = p9fs_cleanup_attrs, .import = p9fs_libconfig_import, .export = p9fs_libconfig_export, }; /* API implementation */ usbg_f_9pfs *usbg_to_9pfs(usbg_function *f) { return f->ops == &usbg_f_type_9pfs ? container_of(f, struct usbg_f_9pfs, func) : NULL; } usbg_function *usbg_from_9pfs(usbg_f_9pfs *p9fs) { return &p9fs->func; } int usbg_f_9pfs_get_dev_name(usbg_f_9pfs *p9fs, char **dev_name) { if (!p9fs || !dev_name) return USBG_ERROR_INVALID_PARAM; *dev_name = strdup(p9fs->func.instance); if (!*dev_name) return USBG_ERROR_NO_MEM; return 0; } int usbg_f_9pfs_get_dev_name_s(usbg_f_9pfs *p9fs, char *buf, int len) { if (!p9fs || !buf) return USBG_ERROR_INVALID_PARAM; return snprintf(buf, len, "%s", p9fs->func.instance); } libusbgx-libusbgx-v0.3.0/src/function/ether.c000066400000000000000000000157301467553526200212500ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include "usbg/function/net.h" #include #ifdef HAS_GADGET_SCHEMES #include #endif struct usbg_f_net { struct usbg_function func; }; #define NET_DEC_ATTR(_name) \ { \ .name = #_name, \ .ro = false, \ .offset = offsetof(struct usbg_f_net_attrs, _name), \ .get = usbg_get_dec, \ .set = usbg_set_dec, \ .import = usbg_get_config_node_int, \ .export = usbg_set_config_node_int, \ } #define NET_RO_STRING_ATTR(_name) \ { \ .name = #_name, \ .ro = true, \ .offset = offsetof(struct usbg_f_net_attrs, _name), \ .get = usbg_get_string, \ .export = usbg_set_config_node_string, \ } #define NET_ETHER_ADDR_ATTR(_name) \ { \ .name = #_name, \ .ro = false, \ .offset = offsetof(struct usbg_f_net_attrs, _name), \ .get = usbg_get_ether_addr, \ .set = usbg_set_ether_addr, \ .import = usbg_get_config_node_ether_addr, \ .export = usbg_set_config_node_ether_addr, \ } static struct { const char *name; bool ro; size_t offset; usbg_attr_get_func get; usbg_attr_set_func set; usbg_import_node_func import; usbg_export_node_func export; } net_attr[USBG_F_NET_ATTR_MAX] = { [USBG_F_NET_DEV_ADDR] = NET_ETHER_ADDR_ATTR(dev_addr), [USBG_F_NET_HOST_ADDR] = NET_ETHER_ADDR_ATTR(host_addr), [USBG_F_NET_IFNAME] = NET_RO_STRING_ATTR(ifname), [USBG_F_NET_QMULT] = NET_DEC_ATTR(qmult), [USBG_F_NET_CLASS] = NET_DEC_ATTR(class_), [USBG_F_NET_SUBCLASS] = NET_DEC_ATTR(subclass), [USBG_F_NET_PROTOCOL] = NET_DEC_ATTR(protocol) }; #undef NET_DEC_ATTR #undef NET_STRING_ATTR GENERIC_ALLOC_INST(ether, struct usbg_f_net, func) GENERIC_FREE_INST(ether, struct usbg_f_net, func) static int ether_set_attrs(struct usbg_function *f, void *f_attrs) { const struct usbg_f_net_attrs *attrs = f_attrs; /* ifname is read only so we accept only empty string for this param */ if (attrs->ifname && attrs->ifname[0]) return USBG_ERROR_INVALID_PARAM; return usbg_f_net_set_attrs(usbg_to_net_function(f), attrs); } static int ether_get_attrs(struct usbg_function *f, void *f_attrs) { struct usbg_f_net_attrs *attrs = f_attrs; return usbg_f_net_get_attrs(usbg_to_net_function(f), attrs); } static void ether_cleanup_attrs(struct usbg_function *f, void *f_attrs) { usbg_f_net_cleanup_attrs(f_attrs); } #ifdef HAS_GADGET_SCHEMES static int ether_libconfig_import(struct usbg_function *f, config_setting_t *root) { struct usbg_f_net *nf = usbg_to_net_function(f); union usbg_f_net_attr_val val; int i; int ret = 0; for (i = USBG_F_NET_ATTR_MIN; i < USBG_F_NET_ATTR_MAX; ++i) { if (net_attr[i].ro) continue; ret = net_attr[i].import(root, net_attr[i].name, &val); /* node not found */ if (ret == 0) continue; /* error */ if (ret < 0) break; ret = usbg_f_net_set_attr_val(nf, i, val); if (ret) break; } return ret; } static int ether_libconfig_export(struct usbg_function *f, config_setting_t *root) { struct usbg_f_net *nf = usbg_to_net_function(f); union usbg_f_net_attr_val val; int i; int ret = 0; for (i = USBG_F_NET_ATTR_MIN; i < USBG_F_NET_ATTR_MAX; ++i) { if (net_attr[i].ro) continue; ret = usbg_f_net_get_attr_val(nf, i, &val); if (ret) break; ret = net_attr[i].export(root, net_attr[i].name, &val); if (ret) break; } return ret; } #define ETHER_LIBCONFIG_DEP_OPS \ .import = ether_libconfig_import, \ .export = ether_libconfig_export #else #define ETHER_LIBCONFIG_DEP_OPS #endif /* HAS_GADGET_SCHEMES */ #define ETHER_FUNCTION_OPTS \ .alloc_inst = ether_alloc_inst, \ .free_inst = ether_free_inst, \ .set_attrs = ether_set_attrs, \ .get_attrs = ether_get_attrs, \ .cleanup_attrs = ether_cleanup_attrs, \ ETHER_LIBCONFIG_DEP_OPS struct usbg_function_type usbg_f_type_ecm = { .name = "ecm", ETHER_FUNCTION_OPTS }; struct usbg_function_type usbg_f_type_subset = { .name = "geth", ETHER_FUNCTION_OPTS }; static char *ncm_os_desc_ifnames[] = { "ncm", NULL }; struct usbg_function_type usbg_f_type_ncm = { .name = "ncm", .os_desc_iname = ncm_os_desc_ifnames, ETHER_FUNCTION_OPTS }; struct usbg_function_type usbg_f_type_eem = { .name = "eem", ETHER_FUNCTION_OPTS }; static char *rndis_os_desc_ifnames[] = { "rndis", NULL }; struct usbg_function_type usbg_f_type_rndis = { .name = "rndis", .os_desc_iname = rndis_os_desc_ifnames, ETHER_FUNCTION_OPTS }; /* API implementation */ usbg_f_net *usbg_to_net_function(usbg_function *f) { return f->ops == &usbg_f_type_ecm || f->ops == &usbg_f_type_subset || f->ops == &usbg_f_type_ncm || f->ops == &usbg_f_type_eem || f->ops == &usbg_f_type_rndis ? container_of(f, struct usbg_f_net, func) : NULL; } usbg_function *usbg_from_net_function(usbg_f_net *nf) { return &nf->func; } int usbg_f_net_get_attrs(usbg_f_net *nf, struct usbg_f_net_attrs *attrs) { int i; int ret = 0; for (i = USBG_F_NET_ATTR_MIN; i < USBG_F_NET_ATTR_MAX; ++i) { ret = usbg_f_net_get_attr_val(nf, i, (union usbg_f_net_attr_val *) ((char *)attrs + net_attr[i].offset)); if (ret) break; } return ret; } int usbg_f_net_set_attrs(usbg_f_net *nf, const struct usbg_f_net_attrs *attrs) { int i; int ret = 0; for (i = USBG_F_NET_ATTR_MIN; i < USBG_F_NET_ATTR_MAX; ++i) { if (net_attr[i].ro) continue; ret = usbg_f_net_set_attr_val(nf, i, *(union usbg_f_net_attr_val *) ((char *)attrs + net_attr[i].offset)); if (ret) break; } return ret; } int usbg_f_net_get_attr_val(usbg_f_net *nf, enum usbg_f_net_attr attr, union usbg_f_net_attr_val *val) { return net_attr[attr].get(nf->func.path, nf->func.name, net_attr[attr].name, val); } int usbg_f_net_set_attr_val(usbg_f_net *nf, enum usbg_f_net_attr attr, union usbg_f_net_attr_val val) { return net_attr[attr].ro ? USBG_ERROR_INVALID_PARAM : net_attr[attr].set(nf->func.path, nf->func.name, net_attr[attr].name, &val); } int usbg_f_net_get_ifname_s(usbg_f_net *nf, char *buf, int len) { struct usbg_function *f; int ret; if (!nf || !buf) return USBG_ERROR_INVALID_PARAM; f = &nf->func; /* * TODO: * Rework usbg_common to make this function consistent with doc. * This below is only an ugly hack */ ret = usbg_read_string_limited(f->path, f->name, "ifname", buf, len); if (ret) goto out; ret = strlen(buf); out: return ret; } libusbgx-libusbgx-v0.3.0/src/function/ffs.c000066400000000000000000000045701467553526200207170ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include "usbg/function/ffs.h" #include #ifdef HAS_GADGET_SCHEMES #include #endif struct usbg_f_fs { struct usbg_function func; }; GENERIC_ALLOC_INST(ffs, struct usbg_f_fs, func) GENERIC_FREE_INST(ffs, struct usbg_f_fs, func) static int ffs_set_attrs(struct usbg_function *f, void *f_attrs) { const char *dev_name = *(const char **)f_attrs; return dev_name && dev_name[0] ? USBG_ERROR_INVALID_PARAM : USBG_SUCCESS; } static int ffs_get_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_fs_get_dev_name(usbg_to_fs_function(f), f_attrs); } static void ffs_cleanup_attrs(struct usbg_function *f, void *f_attrs) { free(*(char **)f_attrs); } static int ffs_libconfig_import(struct usbg_function *f, config_setting_t *root) { return USBG_SUCCESS; } static int ffs_libconfig_export(struct usbg_function *f, config_setting_t *root) { return USBG_SUCCESS; } struct usbg_function_type usbg_f_type_ffs = { .name = "ffs", .alloc_inst = ffs_alloc_inst, .free_inst = ffs_free_inst, .set_attrs = ffs_set_attrs, .get_attrs = ffs_get_attrs, .cleanup_attrs = ffs_cleanup_attrs, .import = ffs_libconfig_import, .export = ffs_libconfig_export, }; /* API implementation */ usbg_f_fs *usbg_to_fs_function(usbg_function *f) { return f->ops == &usbg_f_type_ffs ? container_of(f, struct usbg_f_fs, func) : NULL; } usbg_function *usbg_from_fs_function(usbg_f_fs *ff) { return &ff->func; } int usbg_f_fs_get_dev_name(usbg_f_fs *ff, char **dev_name) { if (!ff || !dev_name) return USBG_ERROR_INVALID_PARAM; *dev_name = strdup(ff->func.instance); if (!*dev_name) return USBG_ERROR_NO_MEM; return 0; } int usbg_f_fs_get_dev_name_s(usbg_f_fs *ff, char *buf, int len) { if (!ff || !buf) return USBG_ERROR_INVALID_PARAM; return snprintf(buf, len, "%s", ff->func.instance); } libusbgx-libusbgx-v0.3.0/src/function/hid.c000066400000000000000000000173431467553526200207070ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include "usbg/function/hid.h" #include #include #ifdef HAS_GADGET_SCHEMES #include #endif struct usbg_f_hid { struct usbg_function func; }; #define HID_DEC_ATTR(_name) \ { \ .name = #_name, \ .ro = false, \ .offset = offsetof(struct usbg_f_hid_attrs, _name), \ .get = usbg_get_dec, \ .set = usbg_set_dec, \ .import = usbg_get_config_node_int, \ .export = usbg_set_config_node_int, \ } #define HID_DEV_ATTR_RO(_name) \ { \ .name = #_name, \ .ro = true, \ .offset = offsetof(struct usbg_f_hid_attrs, _name), \ .get = usbg_get_dev, \ .export = usbg_set_config_node_dev, \ } static int hid_get_report(const char *path, const char *name, const char *attr, void *val) { struct usbg_f_hid_report_desc *report_desc = val; char buf[USBG_MAX_FILE_SIZE]; int ret; ret = usbg_read_buf(path, name, attr, buf); if (ret < 0) return ret; report_desc->len = ret; if (ret == 0) { report_desc->desc = NULL; } else { report_desc->desc = malloc(report_desc->len); if (!report_desc->desc) return USBG_ERROR_NO_MEM; memcpy(report_desc->desc, buf, report_desc->len); } return 0; } static int hid_set_report(const char *path, const char *name, const char *attr, void *val) { struct usbg_f_hid_report_desc *report_desc = val; char *buf = report_desc->desc; int len = report_desc->len; int ret; if (len == 0) { buf = ""; len = 1; } ret = usbg_write_buf(path, name, attr, buf, len); if (ret > 0) ret = USBG_SUCCESS; return ret; } #ifdef HAS_GADGET_SCHEMES static int hid_get_config_node_report(config_setting_t *root, const char *node_name, void *val) { struct usbg_f_hid_report_desc *report_desc = val; char *buf; int tmp, i; config_setting_t *list_node, *node; int len; int ret; list_node = config_setting_get_member(root, node_name); if (!list_node) return 0; if (!config_setting_is_list(list_node)) return USBG_ERROR_INVALID_TYPE; len = config_setting_length(list_node); buf = malloc(len * sizeof(char)); if (!buf) return USBG_ERROR_NO_MEM; for (i = 0; i < len; ++i) { node = config_setting_get_elem(list_node, i); assert(node); if (!usbg_config_is_int(node)) { ret = USBG_ERROR_INVALID_TYPE; goto free_buf; } tmp = config_setting_get_int(node); if (tmp < 0 || tmp > 255) { ret = USBG_ERROR_INVALID_VALUE; goto free_buf; } buf[i] = (char)tmp; } report_desc->desc = buf; report_desc->len = len; return 1; free_buf: free(buf); return ret; } static int hid_set_config_node_report(config_setting_t *root, const char *node_name, void *val) { struct usbg_f_hid_report_desc *report_desc = val; config_setting_t *node; int i; int ret = 0; node = config_setting_add(root, node_name, CONFIG_TYPE_LIST); if (!node) return USBG_ERROR_NO_MEM; for (i = 0; i < report_desc->len; ++i) { int tmp = report_desc->desc[i]; ret = usbg_set_config_node_int_hex(node, NULL, &tmp); if (ret) return ret; } return 0; } #else #define hid_get_config_node_report NULL #define hid_set_config_node_report NULL #endif #define HID_RD_ATTR(_name) \ { \ .name = #_name, \ .ro = false, \ .offset = offsetof(struct usbg_f_hid_attrs, _name), \ .get = hid_get_report, \ .set = hid_set_report, \ .import = hid_get_config_node_report, \ .export = hid_set_config_node_report, \ } struct { const char *name; bool ro; size_t offset; usbg_attr_get_func get; usbg_attr_set_func set; usbg_import_node_func import; usbg_export_node_func export; } hid_attr[USBG_F_HID_ATTR_MAX] = { [USBG_F_HID_DEV] = HID_DEV_ATTR_RO(dev), [USBG_F_HID_PROTOCOL] = HID_DEC_ATTR(protocol), [USBG_F_HID_REPORT_DESC] = HID_RD_ATTR(report_desc), [USBG_F_HID_REPORT_LENGTH] = HID_DEC_ATTR(report_length), [USBG_F_HID_SUBCLASS] = HID_DEC_ATTR(subclass), }; #undef HID_DEC_ATTR #undef HID_DEV_ATTR_RO #undef HID_RD_ATTR GENERIC_ALLOC_INST(hid, struct usbg_f_hid, func) GENERIC_FREE_INST(hid, struct usbg_f_hid, func) static int hid_set_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_hid_set_attrs(usbg_to_hid_function(f), f_attrs); } static int hid_get_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_hid_get_attrs(usbg_to_hid_function(f), f_attrs); } static void hid_cleanup_attrs(struct usbg_function *f, void *f_attrs) { usbg_f_hid_cleanup_attrs(f_attrs); } #ifdef HAS_GADGET_SCHEMES static int hid_libconfig_import(struct usbg_function *f, config_setting_t *root) { struct usbg_f_hid *hf = usbg_to_hid_function(f); union usbg_f_hid_attr_val val; int i; int ret = 0; for (i = USBG_F_HID_ATTR_MIN; i < USBG_F_HID_ATTR_MAX; ++i) { if (hid_attr[i].ro) continue; ret = hid_attr[i].import(root, hid_attr[i].name, &val); /* node not found */ if (ret == 0) continue; /* error */ if (ret < 0) break; ret = usbg_f_hid_set_attr_val(hf, i, val); if (ret) break; } return ret; } static int hid_libconfig_export(struct usbg_function *f, config_setting_t *root) { struct usbg_f_hid *hf = usbg_to_hid_function(f); union usbg_f_hid_attr_val val; int i; int ret = 0; for (i = USBG_F_HID_ATTR_MIN; i < USBG_F_HID_ATTR_MAX; ++i) { ret = usbg_f_hid_get_attr_val(hf, i, &val); if (ret) break; ret = hid_attr[i].export(root, hid_attr[i].name, &val); if (ret) break; } return ret; } #endif /* HAS_GADGET_SCHEMES */ struct usbg_function_type usbg_f_type_hid = { .name = "hid", .alloc_inst = hid_alloc_inst, .free_inst = hid_free_inst, .set_attrs = hid_set_attrs, .get_attrs = hid_get_attrs, .cleanup_attrs = hid_cleanup_attrs, #ifdef HAS_GADGET_SCHEMES .import = hid_libconfig_import, .export = hid_libconfig_export, #endif }; /* API implementation */ usbg_f_hid *usbg_to_hid_function(usbg_function *f) { return f->ops == &usbg_f_type_hid ? container_of(f, struct usbg_f_hid, func) : NULL; } usbg_function *usbg_from_hid_function(usbg_f_hid *hf) { return &hf->func; } int usbg_f_hid_get_attrs(usbg_f_hid *hf, struct usbg_f_hid_attrs *attrs) { int i; int ret = 0; for (i = USBG_F_HID_ATTR_MIN; i < USBG_F_HID_ATTR_MAX; ++i) { ret = usbg_f_hid_get_attr_val(hf, i, (union usbg_f_hid_attr_val *) ((char *)attrs + hid_attr[i].offset)); if (ret) break; } return ret; } int usbg_f_hid_set_attrs(usbg_f_hid *hf, const struct usbg_f_hid_attrs *attrs) { int i; int ret = 0; for (i = USBG_F_HID_ATTR_MIN; i < USBG_F_HID_ATTR_MAX; ++i) { if (hid_attr[i].ro) continue; ret = usbg_f_hid_set_attr_val(hf, i, *(union usbg_f_hid_attr_val *) ((char *)attrs + hid_attr[i].offset)); if (ret) break; } return ret; } int usbg_f_hid_get_attr_val(usbg_f_hid *hf, enum usbg_f_hid_attr attr, union usbg_f_hid_attr_val *val) { return hid_attr[attr].get(hf->func.path, hf->func.name, hid_attr[attr].name, val); } int usbg_f_hid_set_attr_val(usbg_f_hid *hf, enum usbg_f_hid_attr attr, union usbg_f_hid_attr_val val) { return hid_attr[attr].ro ? USBG_ERROR_INVALID_PARAM : hid_attr[attr].set(hf->func.path, hf->func.name, hid_attr[attr].name, &val); } libusbgx-libusbgx-v0.3.0/src/function/loopback.c000066400000000000000000000107301467553526200217260ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include "usbg/function/loopback.h" #ifdef HAS_GADGET_SCHEMES #include #endif struct usbg_f_loopback { struct usbg_function func; }; static const char *loopback_attr_names[USBG_F_LOOPBACK_ATTR_MAX] = { [USBG_F_LOOPBACK_BUFLEN] = "buflen", [USBG_F_LOOPBACK_QLEN] = "qlen", }; static size_t loopback_offsets[USBG_F_LOOPBACK_ATTR_MAX] = { [USBG_F_LOOPBACK_BUFLEN] = offsetof(struct usbg_f_loopback_attrs, buflen), [USBG_F_LOOPBACK_QLEN] = offsetof(struct usbg_f_loopback_attrs, qlen), }; GENERIC_ALLOC_INST(loopback, struct usbg_f_loopback, func) GENERIC_FREE_INST(loopback, struct usbg_f_loopback, func) static int loopback_set_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_loopback_set_attrs(usbg_to_loopback_function(f), f_attrs); } static int loopback_get_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_loopback_get_attrs(usbg_to_loopback_function(f), f_attrs); } #ifdef HAS_GADGET_SCHEMES static int loopback_libconfig_export(struct usbg_function *f, config_setting_t *root) { struct usbg_f_loopback *lf = usbg_to_loopback_function(f); config_setting_t *node; int i, tmp, cfg_ret; int ret = 0; for (i = USBG_F_LOOPBACK_ATTR_MIN; i < USBG_F_LOOPBACK_ATTR_MAX; ++i) { ret = usbg_f_loopback_get_attr_val(lf, i, &tmp); if (ret) break; if (tmp < 0) { ret = USBG_ERROR_INVALID_VALUE; break; } node = config_setting_add(root, loopback_attr_names[i], CONFIG_TYPE_INT); if (!node) { ret = USBG_ERROR_NO_MEM; break; } cfg_ret = config_setting_set_int(node, tmp); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; break; } } return ret; } static int loopback_libconfig_import(struct usbg_function *f, config_setting_t *root) { struct usbg_f_loopback *lf = usbg_to_loopback_function(f); config_setting_t *node; int i, tmp; int ret = 0; for (i = USBG_F_LOOPBACK_ATTR_MIN; i < USBG_F_LOOPBACK_ATTR_MAX; ++i) { node = config_setting_get_member(root, loopback_attr_names[i]); if (!node) continue; tmp = config_setting_get_int(node); if (tmp < 0) { ret = USBG_ERROR_INVALID_PARAM; break; } ret = usbg_f_loopback_set_attr_val(lf, i, tmp); if (ret) break; } return ret; } #endif /* HAS_GADGET_SCHEMES */ struct usbg_function_type usbg_f_type_loopback = { .name = "Loopback", .alloc_inst = loopback_alloc_inst, .free_inst = loopback_free_inst, .set_attrs = loopback_set_attrs, .get_attrs = loopback_get_attrs, #ifdef HAS_GADGET_SCHEMES .import = loopback_libconfig_import, .export = loopback_libconfig_export, #endif }; /* API implementation */ usbg_f_loopback *usbg_to_loopback_function(usbg_function *f) { return f->ops == &usbg_f_type_loopback ? container_of(f, struct usbg_f_loopback, func) : NULL; } usbg_function *usbg_from_loopback_function(usbg_f_loopback *lf) { return &lf->func; } int usbg_f_loopback_get_attrs(usbg_f_loopback *lf, struct usbg_f_loopback_attrs *attrs) { int i; int ret = 0; for (i = USBG_F_LOOPBACK_ATTR_MIN; i < USBG_F_LOOPBACK_ATTR_MAX; ++i) { ret = usbg_f_loopback_get_attr_val(lf, i, (int *)((char *)attrs + loopback_offsets[i])); if (ret) break; } return ret; } int usbg_f_loopback_set_attrs(usbg_f_loopback *lf, const struct usbg_f_loopback_attrs *attrs) { int i; int ret; for (i = USBG_F_LOOPBACK_ATTR_MIN; i < USBG_F_LOOPBACK_ATTR_MAX; ++i) { ret = usbg_f_loopback_set_attr_val(lf, i, *(int *)((char *)attrs + loopback_offsets[i])); if (ret) break; } return ret; } int usbg_f_loopback_get_attr_val(usbg_f_loopback *lf, enum usbg_f_loopback_attr attr, int *val) { return usbg_read_dec(lf->func.path, lf->func.name, loopback_attr_names[attr], val); } int usbg_f_loopback_set_attr_val(usbg_f_loopback *lf, enum usbg_f_loopback_attr attr, int val) { return usbg_write_dec(lf->func.path, lf->func.name, loopback_attr_names[attr], val); } libusbgx-libusbgx-v0.3.0/src/function/midi.c000066400000000000000000000126401467553526200210600ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include "usbg/function/midi.h" #include #ifdef HAS_GADGET_SCHEMES #include #endif struct usbg_f_midi { struct usbg_function func; }; #define MIDI_DEC_ATTR(_name) \ { \ .name = #_name, \ .offset = offsetof(struct usbg_f_midi_attrs, _name), \ .get = usbg_get_dec, \ .set = usbg_set_dec, \ .import = usbg_get_config_node_int, \ .export = usbg_set_config_node_int, \ } #define MIDI_STRING_ATTR(_name) \ { \ .name = #_name, \ .offset = offsetof(struct usbg_f_midi_attrs, _name), \ .get = usbg_get_string, \ .set = usbg_set_string, \ .import = usbg_get_config_node_string, \ .export = usbg_set_config_node_string, \ } struct { const char *name; size_t offset; usbg_attr_get_func get; usbg_attr_set_func set; usbg_import_node_func import; usbg_export_node_func export; } midi_attr[USBG_F_MIDI_ATTR_MAX] = { [USBG_F_MIDI_INDEX] = MIDI_DEC_ATTR(index), [USBG_F_MIDI_ID] = MIDI_STRING_ATTR(id), [USBG_F_MIDI_IN_PORTS] = MIDI_DEC_ATTR(in_ports), [USBG_F_MIDI_OUT_PORTS] = MIDI_DEC_ATTR(out_ports), [USBG_F_MIDI_BUFLEN] = MIDI_DEC_ATTR(buflen), [USBG_F_MIDI_QLEN] = MIDI_DEC_ATTR(qlen), }; #undef MIDI_DEC_ATTR #undef MIDI_STRING_ATTR GENERIC_ALLOC_INST(midi, struct usbg_f_midi, func) GENERIC_FREE_INST(midi, struct usbg_f_midi, func) static int midi_set_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_midi_set_attrs(usbg_to_midi_function(f), f_attrs); } static int midi_get_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_midi_get_attrs(usbg_to_midi_function(f), f_attrs); } static void midi_cleanup_attrs(struct usbg_function *f, void *f_attrs) { usbg_f_midi_cleanup_attrs(f_attrs); } #ifdef HAS_GADGET_SCHEMES static int midi_libconfig_import(struct usbg_function *f, config_setting_t *root) { struct usbg_f_midi *mf = usbg_to_midi_function(f); union usbg_f_midi_attr_val val; int i; int ret = 0; for (i = USBG_F_MIDI_ATTR_MIN; i < USBG_F_MIDI_ATTR_MAX; ++i) { ret = midi_attr[i].import(root, midi_attr[i].name, &val); /* node not found */ if (ret == 0) continue; /* error */ if (ret < 0) break; ret = usbg_f_midi_set_attr_val(mf, i, val); if (ret) break; } return ret; } static int midi_libconfig_export(struct usbg_function *f, config_setting_t *root) { struct usbg_f_midi *mf = usbg_to_midi_function(f); union usbg_f_midi_attr_val val; int i; int ret = 0; for (i = USBG_F_MIDI_ATTR_MIN; i < USBG_F_MIDI_ATTR_MAX; ++i) { ret = usbg_f_midi_get_attr_val(mf, i, &val); if (ret) break; ret = midi_attr[i].export(root, midi_attr[i].name, &val); if (ret) break; } return ret; } #endif /* HAS_GADGET_SCHEMES */ struct usbg_function_type usbg_f_type_midi = { .name = "midi", .alloc_inst = midi_alloc_inst, .free_inst = midi_free_inst, .set_attrs = midi_set_attrs, .get_attrs = midi_get_attrs, .cleanup_attrs = midi_cleanup_attrs, #ifdef HAS_GADGET_SCHEMES .import = midi_libconfig_import, .export = midi_libconfig_export, #endif }; /* API implementation */ usbg_f_midi *usbg_to_midi_function(usbg_function *f) { return f->ops == &usbg_f_type_midi ? container_of(f, struct usbg_f_midi, func) : NULL; } usbg_function *usbg_from_midi_function(usbg_f_midi *mf) { return &mf->func; } int usbg_f_midi_get_attrs(usbg_f_midi *mf, struct usbg_f_midi_attrs *attrs) { int i; int ret = 0; for (i = USBG_F_MIDI_ATTR_MIN; i < USBG_F_MIDI_ATTR_MAX; ++i) { ret = usbg_f_midi_get_attr_val(mf, i, (union usbg_f_midi_attr_val *) ((char *)attrs + midi_attr[i].offset)); if (ret) break; } return ret; } int usbg_f_midi_set_attrs(usbg_f_midi *mf, const struct usbg_f_midi_attrs *attrs) { int i; int ret = 0; for (i = USBG_F_MIDI_ATTR_MIN; i < USBG_F_MIDI_ATTR_MAX; ++i) { ret = usbg_f_midi_set_attr_val(mf, i, *(union usbg_f_midi_attr_val *) ((char *)attrs + midi_attr[i].offset)); if (ret) break; } return ret; } int usbg_f_midi_get_attr_val(usbg_f_midi *mf, enum usbg_f_midi_attr attr, union usbg_f_midi_attr_val *val) { return midi_attr[attr].get(mf->func.path, mf->func.name, midi_attr[attr].name, val); } int usbg_f_midi_set_attr_val(usbg_f_midi *mf, enum usbg_f_midi_attr attr, union usbg_f_midi_attr_val val) { return midi_attr[attr].set(mf->func.path, mf->func.name, midi_attr[attr].name, &val); } int usbg_f_midi_get_id_s(usbg_f_midi *mf, char *buf, int len) { struct usbg_function *f; int ret; if (!mf || !buf) return USBG_ERROR_INVALID_PARAM; f = &mf->func; /* * TODO: * Rework usbg_common to make this function consistent with doc. * This below is only an ugly hack */ ret = usbg_read_string_limited(f->path, f->name, "id", buf, len); if (ret) goto out; ret = strlen(buf); out: return ret; } libusbgx-libusbgx-v0.3.0/src/function/ms.c000066400000000000000000000340271467553526200205600ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include "usbg/function/ms.h" #include #include #include #include #include #ifdef HAS_GADGET_SCHEMES #include #endif #define MAX_LUNS 16 struct usbg_f_ms { struct usbg_function func; bool luns[MAX_LUNS]; bool luns_initiated; }; #define MS_LUN_BOOL_ATTR(_name) \ { \ .name = #_name, \ .offset = offsetof(struct usbg_f_ms_lun_attrs, _name), \ .get = usbg_get_bool, \ .set = usbg_set_bool, \ .import = usbg_get_config_node_bool, \ .export = usbg_set_config_node_bool, \ } #define MS_LUN_STRING_ATTR(_name) \ { \ .name = #_name, \ .offset = offsetof(struct usbg_f_ms_lun_attrs, _name), \ .get = usbg_get_string, \ .set = usbg_set_string, \ .export = usbg_set_config_node_string, \ .import = usbg_get_config_node_string, \ } static struct { const char *name; size_t offset; usbg_attr_get_func get; usbg_attr_set_func set; usbg_import_node_func import; usbg_export_node_func export; } ms_lun_attr[USBG_F_MS_LUN_ATTR_MAX] = { [USBG_F_MS_LUN_CDROM] = MS_LUN_BOOL_ATTR(cdrom), [USBG_F_MS_LUN_RO] = MS_LUN_BOOL_ATTR(ro), [USBG_F_MS_LUN_NOFUA] = MS_LUN_BOOL_ATTR(nofua), [USBG_F_MS_LUN_REMOVABLE] = MS_LUN_BOOL_ATTR(removable), [USBG_F_MS_LUN_FILE] = MS_LUN_STRING_ATTR(file), [USBG_F_MS_LUN_INQUIRY_STRING] = MS_LUN_STRING_ATTR(inquiry_string), }; static inline int lun_select(const struct dirent *dent) { int ret; int id; ret = file_select(dent); if (!ret) goto out; ret = sscanf(dent->d_name, "lun.%d", &id); out: return ret; } static inline int lun_sort(const struct dirent **d1, const struct dirent **d2) { int ret; int id1, id2; ret = sscanf((*d1)->d_name, "lun.%d", &id1); if (ret != 1) goto err; ret = sscanf((*d2)->d_name, "lun.%d", &id2); if (ret != 1) goto err; if (id1 < id2) ret = 1; return id1 < id2 ? -1 : id1 > id2; err: /* * This should not happened because dentries has been * already checked by lun_select function. This * error procedure is just in case. */ return -1; } int init_luns(struct usbg_f_ms *ms) { struct dirent **dent; char lpath[USBG_MAX_PATH_LENGTH]; int nmb, i, id; int ret = 0; ret = snprintf(lpath, sizeof(lpath), "%s/%s/", ms->func.path, ms->func.name); if (ret >= sizeof(lpath)) { ret = USBG_ERROR_PATH_TOO_LONG; return ret; } nmb = scandir(lpath, &dent, lun_select, lun_sort); if (nmb < 0) { ret = usbg_translate_error(errno); return ret; } for (i = 0; i < nmb; ++i) { /* don't check the error as we know that name is valid */ sscanf(dent[i]->d_name, "lun.%d", &id); ms->luns[id] = true; free(dent[i]); } free(dent); return 0; } static inline bool *get_lun_mask(struct usbg_f_ms *ms) { if (!ms->luns_initiated) { int ret = init_luns(ms); if (!ret) ms->luns_initiated = true; } return ms->luns; } GENERIC_ALLOC_INST(ms_internal, struct usbg_f_ms, func) static int ms_alloc_inst(struct usbg_function_type *type, usbg_function_type type_code, const char *instance, const char *path, struct usbg_gadget *parent, struct usbg_function **f) { struct usbg_f_ms *mf; int ret; ret = ms_internal_alloc_inst(type, type_code, instance, path, parent, f); if (ret) goto out; mf = usbg_to_ms_function(*f); for (int i = 0; i < MAX_LUNS; i++) mf->luns[i] = 0; mf->luns_initiated = false; out: return ret; } GENERIC_FREE_INST(ms, struct usbg_f_ms, func) static int ms_set_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_ms_set_attrs(usbg_to_ms_function(f), (struct usbg_f_ms_attrs *)f_attrs); } static void ms_cleanup_attrs(struct usbg_function *f, void *f_attrs) { usbg_f_ms_cleanup_attrs((struct usbg_f_ms_attrs *)f_attrs); } static int ms_get_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_ms_get_attrs(usbg_to_ms_function(f), (struct usbg_f_ms_attrs *)f_attrs); } #ifdef HAS_GADGET_SCHEMES static int ms_import_lun_attrs(struct usbg_f_ms *mf, int lun_id, config_setting_t *root) { union usbg_f_ms_lun_attr_val val; int i; int ret = 0; for (i = USBG_F_MS_LUN_ATTR_MIN; i < USBG_F_MS_LUN_ATTR_MAX; ++i) { ret = ms_lun_attr[i].import(root, ms_lun_attr[i].name, &val); /* node not found */ if (ret == 0) continue; /* error */ if (ret < 0) break; ret = usbg_f_ms_set_lun_attr_val(mf, lun_id, i, val); if (ret) break; } return ret; } static int ms_libconfig_import(struct usbg_function *f, config_setting_t *root) { struct usbg_f_ms *mf = usbg_to_ms_function(f); config_setting_t *luns_node, *node; bool *luns; bool stall; int i, nluns; int ret; ret = usbg_get_config_node_bool(root, "stall", &stall); if (ret > 0) ret = usbg_f_ms_set_stall(mf, stall); if (ret < 0) goto out; luns_node = config_setting_get_member(root, "luns"); if (!luns_node) { ret = USBG_ERROR_INVALID_PARAM; goto out; } if (!config_setting_is_list(luns_node)) { ret = USBG_ERROR_INVALID_TYPE; goto out; } nluns = config_setting_length(luns_node); luns = get_lun_mask(mf); for (i = 0; i < nluns; ++i) { node = config_setting_get_elem(luns_node, i); if (!node) { ret = USBG_ERROR_INVALID_FORMAT; goto out; } if (!config_setting_is_group(node)) { ret = USBG_ERROR_INVALID_TYPE; goto out; } if (!luns[i]) { ret = usbg_f_ms_create_lun(mf, i, NULL); if (ret) goto out; } ret = ms_import_lun_attrs(mf, i, node); if (ret) goto out; } ret = 0; out: return ret; } static int ms_export_lun_attrs(struct usbg_f_ms *mf, int lun_id, config_setting_t *root) { union usbg_f_ms_lun_attr_val val; int i; int ret = 0; for (i = USBG_F_MS_LUN_ATTR_MIN; i < USBG_F_MS_LUN_ATTR_MAX; ++i) { ret = usbg_f_ms_get_lun_attr_val(mf, lun_id, i, &val); if (ret) break; ret = ms_lun_attr[i].export(root, ms_lun_attr[i].name, &val); if (ret) break; } return ret; } static int ms_libconfig_export(struct usbg_function *f, config_setting_t *root) { struct usbg_f_ms *mf = usbg_to_ms_function(f); bool *luns; bool stall; int i; config_setting_t *luns_node, *node; int ret; ret = usbg_f_ms_get_stall(mf, &stall); if (ret) goto out; ret = usbg_set_config_node_bool(root, "stall", &stall); if (ret) goto out; luns_node = config_setting_add(root, "luns", CONFIG_TYPE_LIST); if (!luns_node) goto out; luns = get_lun_mask(mf); for (i = 0; i < MAX_LUNS; ++i) { if (!luns[i]) continue; node = config_setting_add(luns_node, "", CONFIG_TYPE_GROUP); if (!node) goto out; ret = ms_export_lun_attrs(mf, i, node); if (ret) goto out; } out: return ret; } #endif /* HAS_GADGET_SCHEMES */ static int ms_remove(struct usbg_function *f, int opts) { struct usbg_f_ms *mf = usbg_to_ms_function(f); bool *luns; int i; int ret = USBG_SUCCESS; luns = get_lun_mask(mf); /* LUN0 cannot be removed */ for (i = 1; i < MAX_LUNS; ++i) { if (!luns[i]) continue; ret = usbg_f_ms_rm_lun(mf, i); if (ret) break; } return ret; } struct usbg_function_type usbg_f_type_ms = { .name = "mass_storage", .alloc_inst = ms_alloc_inst, .free_inst = ms_free_inst, .set_attrs = ms_set_attrs, .get_attrs = ms_get_attrs, .cleanup_attrs = ms_cleanup_attrs, #ifdef HAS_GADGET_SCHEMES .import = ms_libconfig_import, .export = ms_libconfig_export, #endif .remove = ms_remove, }; /* API implementation */ usbg_f_ms *usbg_to_ms_function(usbg_function *f) { return f->ops == &usbg_f_type_ms ? container_of(f, struct usbg_f_ms, func) : NULL; } usbg_function *usbg_from_ms_function(usbg_f_ms *mf) { return &mf->func; } int usbg_f_ms_get_attrs(usbg_f_ms *mf, struct usbg_f_ms_attrs *attrs) { int i; const bool *luns; struct usbg_f_ms_lun_attrs **lun_attrs; int nluns; int ret; ret = usbg_f_ms_get_stall(mf, &attrs->stall); if (ret) goto out; luns = get_lun_mask(mf); usbg_f_ms_get_nluns(mf, &nluns); lun_attrs = calloc(nluns + 1, sizeof(*lun_attrs)); if (!lun_attrs) return USBG_ERROR_NO_MEM; for (i = 0; i < MAX_LUNS; ++i) { if (!luns[i]) continue; lun_attrs[i] = malloc(sizeof(*lun_attrs[i])); if (!lun_attrs[i]) { ret = USBG_ERROR_NO_MEM; goto free_lun_attrs; } ret = usbg_f_ms_get_lun_attrs(mf, i, lun_attrs[i]); if (ret) goto free_current_lun_attrs; } attrs->nluns = nluns; attrs->luns = lun_attrs; return 0; free_current_lun_attrs: free(lun_attrs[i]); lun_attrs[i] = NULL; free_lun_attrs: for (i = 0; i < nluns; ++i) { usbg_f_ms_cleanup_lun_attrs(lun_attrs[i]); free(lun_attrs[i]); } free(lun_attrs); out: return ret; } int usbg_f_ms_set_attrs(usbg_f_ms *mf, const struct usbg_f_ms_attrs *attrs) { int i, j; const bool *luns; int luns_to_be[MAX_LUNS]; struct usbg_f_ms_lun_attrs **lun_attrs; int nluns; int ret; ret = usbg_f_ms_set_stall(mf, attrs->stall); if (ret) goto out; luns = get_lun_mask(mf); usbg_f_ms_get_nluns(mf, &nluns); for (i = 0; i < MAX_LUNS; ++i) luns_to_be[i] = -1; for (lun_attrs = attrs->luns, i = 0; lun_attrs[i]; ++i) { int id = lun_attrs[i]->id; id = id >= 0 ? id : i; luns_to_be[id] = i; } for (i = 0; i < MAX_LUNS; ++i) { if (luns[i]) { /* LUN exist and should exist so we set attr only */ if (luns_to_be[i] >= 0) ret = usbg_f_ms_set_lun_attrs(mf, i, attrs->luns[i]); /* LUN exist but should not so let's remove it */ else ret = usbg_f_ms_rm_lun(mf, i); } else if (luns_to_be[i] >= 0) { ret = usbg_f_ms_create_lun(mf, i, attrs->luns[i]); } if (ret) goto cleanup_luns; } return 0; cleanup_luns: for (j = 0; j < i ; ++j) if (!luns[j] && luns_to_be[j] >= 0) usbg_f_ms_rm_lun(mf, j); out: return ret; } int usbg_f_ms_get_stall(usbg_f_ms *mf, bool *stall) { return usbg_read_bool(mf->func.path, mf->func.name, "stall", stall); } int usbg_f_ms_set_stall(usbg_f_ms *mf, bool stall) { return usbg_write_bool(mf->func.path, mf->func.name, "stall", stall); } int usbg_f_ms_get_nluns(usbg_f_ms *mf, int *nluns) { int i; const bool *luns; *nluns = 0; for (luns = get_lun_mask(mf), i = 0; i < MAX_LUNS; ++i) *nluns += luns[i] ? 1 : 0; return 0; } int usbg_f_ms_create_lun(usbg_f_ms *mf, int lun_id, struct usbg_f_ms_lun_attrs *lattrs) { int ret; bool *luns; char lpath[USBG_MAX_PATH_LENGTH]; if (lun_id >= MAX_LUNS) return USBG_ERROR_INVALID_PARAM; luns = get_lun_mask(mf); if (luns[lun_id]) return USBG_ERROR_EXIST; ret = snprintf(lpath, sizeof(lpath), "%s/%s/lun.%d/", mf->func.path, mf->func.name, lun_id); if (ret >= sizeof(lpath)) return USBG_ERROR_PATH_TOO_LONG; ret = mkdir(lpath, S_IRWXU|S_IRWXG|S_IRWXO); if (ret) return usbg_translate_error(errno); if (lattrs) { ret = usbg_f_ms_set_lun_attrs(mf, lun_id, lattrs); if (ret) goto remove_lun; } luns[lun_id] = true; return 0; remove_lun: rmdir(lpath); return ret; } int usbg_f_ms_rm_lun(usbg_f_ms *mf, int lun_id) { int ret; bool *luns; char lpath[USBG_MAX_PATH_LENGTH]; if (lun_id >= MAX_LUNS) return USBG_ERROR_INVALID_PARAM; luns = get_lun_mask(mf); if (!luns[lun_id]) return USBG_ERROR_INVALID_PARAM; ret = snprintf(lpath, sizeof(lpath), "%s/%s/lun.%d/", mf->func.path, mf->func.name, lun_id); if (ret >= sizeof(lpath)) return USBG_ERROR_PATH_TOO_LONG; ret = rmdir(lpath); if (ret) return usbg_translate_error(errno); luns[lun_id] = false; return ret; } int usbg_f_ms_get_lun_attrs(usbg_f_ms *mf, int lun_id, struct usbg_f_ms_lun_attrs *lattrs) { int i; int ret = 0; for (i = USBG_F_MS_LUN_ATTR_MIN; i < USBG_F_MS_LUN_ATTR_MAX; ++i) { ret = usbg_f_ms_get_lun_attr_val(mf, lun_id, i, (union usbg_f_ms_lun_attr_val *) ((char *)lattrs + ms_lun_attr[i].offset)); if (ret) break; } lattrs->id = lun_id; return ret; } int usbg_f_ms_set_lun_attrs(usbg_f_ms *mf, int lun_id, const struct usbg_f_ms_lun_attrs *lattrs) { int i; int ret = 0; for (i = USBG_F_MS_LUN_ATTR_MIN; i < USBG_F_MS_LUN_ATTR_MAX; ++i) { ret = usbg_f_ms_set_lun_attr_val(mf, lun_id, i, *(union usbg_f_ms_lun_attr_val *) ((char *)lattrs + ms_lun_attr[i].offset)); if (ret) break; } return ret; } int usbg_f_ms_get_lun_attr_val(usbg_f_ms *mf, int lun_id, enum usbg_f_ms_lun_attr lattr, union usbg_f_ms_lun_attr_val *val) { char lpath[USBG_MAX_PATH_LENGTH]; int ret; ret = snprintf(lpath, sizeof(lpath), "%s/%s/lun.%d/", mf->func.path, mf->func.name, lun_id); if (ret >= sizeof(lpath)) return USBG_ERROR_PATH_TOO_LONG; return ms_lun_attr[lattr].get(lpath, "", ms_lun_attr[lattr].name, val); } int usbg_f_ms_set_lun_attr_val(usbg_f_ms *mf, int lun_id, enum usbg_f_ms_lun_attr lattr, union usbg_f_ms_lun_attr_val val) { char lpath[USBG_MAX_PATH_LENGTH]; int ret; ret = snprintf(lpath, sizeof(lpath), "%s/%s/lun.%d/", mf->func.path, mf->func.name, lun_id); if (ret >= sizeof(lpath)) return USBG_ERROR_PATH_TOO_LONG; return ms_lun_attr[lattr].set(lpath, "", ms_lun_attr[lattr].name, &val); } int usbg_f_ms_get_lun_file_s(usbg_f_ms *mf, int lun_id, char *buf, int len) { char lpath[USBG_MAX_PATH_LENGTH]; int ret; if (!mf || !buf) return USBG_ERROR_INVALID_PARAM; ret = snprintf(lpath, sizeof(lpath), "%s/%s/lun.%d/", mf->func.path, mf->func.name, lun_id); if (ret >= sizeof(lpath)) return USBG_ERROR_PATH_TOO_LONG; /* * TODO: * Rework usbg_common to make this function consistent with doc. * This below is only an ugly hack */ ret = usbg_read_string_limited(lpath, "", "filename", buf, len); if (ret) goto out; ret = strlen(buf); out: return ret; } libusbgx-libusbgx-v0.3.0/src/function/phonet.c000066400000000000000000000053271467553526200214370ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include "usbg/function/phonet.h" #include #ifdef HAS_GADGET_SCHEMES #include #endif struct usbg_f_phonet { struct usbg_function func; }; GENERIC_ALLOC_INST(phonet, struct usbg_f_phonet, func) GENERIC_FREE_INST(phonet, struct usbg_f_phonet, func) static int phonet_set_attrs(struct usbg_function *f, void *f_attrs) { const char *ifname = *(const char **)f_attrs; return ifname && ifname[0] ? USBG_ERROR_INVALID_PARAM : USBG_SUCCESS; } static int phonet_get_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_phonet_get_ifname(usbg_to_phonet_function(f), f_attrs); } static void phonet_cleanup_attrs(struct usbg_function *f, void *f_attrs) { free(*(char **)f_attrs); } static int phonet_libconfig_import(struct usbg_function *f, config_setting_t *root) { return USBG_SUCCESS; } static int phonet_libconfig_export(struct usbg_function *f, config_setting_t *root) { return USBG_SUCCESS; } struct usbg_function_type usbg_f_type_phonet = { .name = "phonet", .alloc_inst = phonet_alloc_inst, .free_inst = phonet_free_inst, .set_attrs = phonet_set_attrs, .get_attrs = phonet_get_attrs, .cleanup_attrs = phonet_cleanup_attrs, .import = phonet_libconfig_import, .export = phonet_libconfig_export, }; /* API implementation */ usbg_f_phonet *usbg_to_phonet_function(usbg_function *f) { return f->ops == &usbg_f_type_phonet ? container_of(f, struct usbg_f_phonet, func) : NULL; } usbg_function *usbg_from_phonet_function(usbg_f_phonet *pf) { return &pf->func; } int usbg_f_phonet_get_ifname(usbg_f_phonet *pf, char **ifname) { struct usbg_function *f = &pf->func; if (!pf || !ifname) return USBG_ERROR_INVALID_PARAM; return usbg_read_string_alloc(f->path, f->name, "ifname", ifname); } int usbg_f_phonet_get_ifname_s(usbg_f_phonet *pf, char *buf, int len) { struct usbg_function *f = &pf->func; int ret; if (!pf || !buf) return USBG_ERROR_INVALID_PARAM; /* * TODO: * Rework usbg_common to make this function consistent with doc. * This below is only an ugly hack */ ret = usbg_read_string_limited(f->path, f->name, "ifname", buf, len); if (ret) goto out; ret = strlen(buf); out: return ret; } libusbgx-libusbgx-v0.3.0/src/function/printer.c000066400000000000000000000017661467553526200216300ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #ifdef HAS_GADGET_SCHEMES #include #endif struct usbg_f_printer { struct usbg_function func; }; GENERIC_ALLOC_INST(printer, struct usbg_f_printer, func) GENERIC_FREE_INST(printer, struct usbg_f_printer, func) #define PRINTER_FUNCTION_OPTS \ .alloc_inst = printer_alloc_inst, \ .free_inst = printer_free_inst struct usbg_function_type usbg_f_type_printer = { .name = "printer", PRINTER_FUNCTION_OPTS}; libusbgx-libusbgx-v0.3.0/src/function/serial.c000066400000000000000000000046471467553526200214250ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include "usbg/function/serial.h" #ifdef HAS_GADGET_SCHEMES #include #endif struct usbg_f_serial { struct usbg_function func; }; GENERIC_ALLOC_INST(serial, struct usbg_f_serial, func) GENERIC_FREE_INST(serial, struct usbg_f_serial, func) static int serial_set_attrs(struct usbg_function *f, void *f_attrs) { int port_num = *(int *)f_attrs; return port_num ? USBG_ERROR_INVALID_PARAM : USBG_SUCCESS; } static int serial_get_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_serial_get_port_num(usbg_to_serial_function(f), f_attrs); } static int serial_libconfig_import(struct usbg_function *f, config_setting_t *root) { return USBG_SUCCESS; } static int serial_libconfig_export(struct usbg_function *f, config_setting_t *root) { return USBG_SUCCESS; } /* We don' import nor export port_num as it is read only */ #define SERIAL_FUNCTION_OPTS \ .alloc_inst = serial_alloc_inst, \ .free_inst = serial_free_inst, \ .set_attrs = serial_set_attrs, \ .get_attrs = serial_get_attrs, \ .export = serial_libconfig_export, \ .import = serial_libconfig_import struct usbg_function_type usbg_f_type_acm = { .name = "acm", SERIAL_FUNCTION_OPTS, }; struct usbg_function_type usbg_f_type_serial = { .name = "gser", SERIAL_FUNCTION_OPTS, }; struct usbg_function_type usbg_f_type_obex = { .name = "obex", SERIAL_FUNCTION_OPTS, }; /* API implementation */ usbg_f_serial *usbg_to_serial_function(usbg_function *f) { return f->ops == &usbg_f_type_acm || f->ops == &usbg_f_type_serial || f->ops == &usbg_f_type_obex ? container_of(f, struct usbg_f_serial, func) : NULL; } usbg_function *usbg_from_serial_function(usbg_f_serial *sf) { return &sf->func; } int usbg_f_serial_get_port_num(usbg_f_serial *sf, int *port_num) { return usbg_read_dec(sf->func.path, sf->func.name, "port_num", port_num); } libusbgx-libusbgx-v0.3.0/src/function/uac2.c000066400000000000000000000143541467553526200207740ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include "usbg/function/uac2.h" #include #ifdef HAS_GADGET_SCHEMES #include #endif struct usbg_f_uac2 { struct usbg_function func; }; #define UAC2_BOOL_ATTR(_name) \ { \ .name = #_name, \ .offset = offsetof(struct usbg_f_uac2_attrs, _name), \ .get = usbg_get_bool, \ .set = usbg_set_bool, \ .import = usbg_get_config_node_bool, \ .export = usbg_set_config_node_bool, \ } #define UAC2_STRING_ATTR(_name) \ { \ .name = #_name, \ .offset = offsetof(struct usbg_f_uac2_attrs, _name), \ .get = usbg_get_string, \ .set = usbg_set_string, \ .export = usbg_set_config_node_string, \ .import = usbg_get_config_node_string, \ } #define UAC2_DEC_ATTR(_name) \ { \ .name = #_name, \ .offset = offsetof(struct usbg_f_uac2_attrs, _name), \ .get = usbg_get_dec, \ .set = usbg_set_dec, \ .import = usbg_get_config_node_int, \ .export = usbg_set_config_node_int, \ } static struct { const char *name; size_t offset; usbg_attr_get_func get; usbg_attr_set_func set; usbg_import_node_func import; usbg_export_node_func export; } uac2_attr[USBG_F_UAC2_ATTR_MAX] = { [USBG_F_UAC2_C_CHMASK] = UAC2_DEC_ATTR(c_chmask), [USBG_F_UAC2_C_SRATE] = UAC2_DEC_ATTR(c_srate), [USBG_F_UAC2_C_SSIZE] = UAC2_DEC_ATTR(c_ssize), [USBG_F_UAC2_P_CHMASK] = UAC2_DEC_ATTR(p_chmask), [USBG_F_UAC2_P_SRATE] = UAC2_DEC_ATTR(p_srate), [USBG_F_UAC2_P_SSIZE] = UAC2_DEC_ATTR(p_ssize), [USBG_F_UAC2_P_HS_BINT] = UAC2_DEC_ATTR(p_hs_bint), [USBG_F_UAC2_C_HS_BINT] = UAC2_DEC_ATTR(c_hs_bint), [USBG_F_UAC2_C_SYNC] = UAC2_STRING_ATTR(c_sync), [USBG_F_UAC2_REQ_NUMBER] = UAC2_DEC_ATTR(req_number), [USBG_F_UAC2_FB_MAX] = UAC2_DEC_ATTR(fb_max), [USBG_F_UAC2_P_MUTE_PRESENT] = UAC2_BOOL_ATTR(p_mute_present), [USBG_F_UAC2_P_VOLUME_PRESENT] = UAC2_BOOL_ATTR(p_volume_present), [USBG_F_UAC2_P_VOLUME_MIN] = UAC2_DEC_ATTR(p_volume_min), [USBG_F_UAC2_P_VOLUME_MAX] = UAC2_DEC_ATTR(p_volume_max), [USBG_F_UAC2_P_VOLUME_RES] = UAC2_DEC_ATTR(p_volume_res), [USBG_F_UAC2_C_MUTE_PRESENT] = UAC2_BOOL_ATTR(c_mute_present), [USBG_F_UAC2_C_VOLUME_PRESENT] = UAC2_BOOL_ATTR(c_volume_present), [USBG_F_UAC2_C_VOLUME_MIN] = UAC2_DEC_ATTR(c_volume_min), [USBG_F_UAC2_C_VOLUME_MAX] = UAC2_DEC_ATTR(c_volume_max), [USBG_F_UAC2_C_VOLUME_RES] = UAC2_DEC_ATTR(c_volume_res), [USBG_F_UAC2_FUNCTION_NAME] = UAC2_STRING_ATTR(function_name), }; #undef UAC2_DEC_ATTR GENERIC_ALLOC_INST(uac2, struct usbg_f_uac2, func) GENERIC_FREE_INST(uac2, struct usbg_f_uac2, func) static int uac2_set_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_uac2_set_attrs(usbg_to_uac2_function(f), f_attrs); } static int uac2_get_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_uac2_get_attrs(usbg_to_uac2_function(f), f_attrs); } static void uac2_cleanup_attrs(struct usbg_function *f, void *f_attrs) { usbg_f_uac2_cleanup_attrs(f_attrs); } #ifdef HAS_GADGET_SCHEMES static int uac2_libconfig_import(struct usbg_function *f, config_setting_t *root) { struct usbg_f_uac2 *af = usbg_to_uac2_function(f); union usbg_f_uac2_attr_val val; int i; int ret = 0; for (i = USBG_F_UAC2_ATTR_MIN; i < USBG_F_UAC2_ATTR_MAX; ++i) { ret = uac2_attr[i].import(root, uac2_attr[i].name, &val); /* node not found */ if (ret == 0) continue; /* error */ if (ret < 0) break; ret = usbg_f_uac2_set_attr_val(af, i, val); if (ret) break; } return ret; } static int uac2_libconfig_export(struct usbg_function *f, config_setting_t *root) { struct usbg_f_uac2 *af = usbg_to_uac2_function(f); union usbg_f_uac2_attr_val val; int i; int ret = 0; for (i = USBG_F_UAC2_ATTR_MIN; i < USBG_F_UAC2_ATTR_MAX; ++i) { ret = usbg_f_uac2_get_attr_val(af, i, &val); if (ret) break; ret = uac2_attr[i].export(root, uac2_attr[i].name, &val); if (ret) break; } return ret; } #endif /* HAS_GADGET_SCHEMES */ struct usbg_function_type usbg_f_type_uac2 = { .name = "uac2", .alloc_inst = uac2_alloc_inst, .free_inst = uac2_free_inst, .set_attrs = uac2_set_attrs, .get_attrs = uac2_get_attrs, .cleanup_attrs = uac2_cleanup_attrs, #ifdef HAS_GADGET_SCHEMES .import = uac2_libconfig_import, .export = uac2_libconfig_export, #endif }; /* API implementation */ usbg_f_uac2 *usbg_to_uac2_function(usbg_function *f) { return f->ops == &usbg_f_type_uac2 ? container_of(f, struct usbg_f_uac2, func) : NULL; } usbg_function *usbg_from_uac2_function(usbg_f_uac2 *af) { return &af->func; } int usbg_f_uac2_get_attrs(usbg_f_uac2 *af, struct usbg_f_uac2_attrs *attrs) { int i; int ret = 0; for (i = USBG_F_UAC2_ATTR_MIN; i < USBG_F_UAC2_ATTR_MAX; ++i) { ret = usbg_f_uac2_get_attr_val(af, i, (union usbg_f_uac2_attr_val *) ((char *)attrs + uac2_attr[i].offset)); if (ret) break; } return ret; } int usbg_f_uac2_set_attrs(usbg_f_uac2 *af, const struct usbg_f_uac2_attrs *attrs) { int i; int ret = 0; for (i = USBG_F_UAC2_ATTR_MIN; i < USBG_F_UAC2_ATTR_MAX; ++i) { ret = usbg_f_uac2_set_attr_val(af, i, *(union usbg_f_uac2_attr_val *) ((char *)attrs + uac2_attr[i].offset)); if (ret) break; } return ret; } int usbg_f_uac2_get_attr_val(usbg_f_uac2 *af, enum usbg_f_uac2_attr attr, union usbg_f_uac2_attr_val *val) { return uac2_attr[attr].get(af->func.path, af->func.name, uac2_attr[attr].name, val); } int usbg_f_uac2_set_attr_val(usbg_f_uac2 *af, enum usbg_f_uac2_attr attr, union usbg_f_uac2_attr_val val) { return uac2_attr[attr].set(af->func.path, af->func.name, uac2_attr[attr].name, &val); } libusbgx-libusbgx-v0.3.0/src/function/uvc.c000066400000000000000000000752671467553526200207510ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include "usbg/function/uvc.h" #include #include #include #include #include #ifdef HAS_GADGET_SCHEMES #include #endif #define UVC_PATH_CONTROL "control" #define UVC_PATH_HEADER "header/h" #define UVC_PATH_CLASS_FS "class/fs/h" #define UVC_PATH_CLASS_HS "class/hs/h" #define UVC_PATH_CLASS_SS "class/ss/h" #define UVC_PATH_STREAMING "streaming" #define UVC_PATH_STREAMING_UNCOMPRESSED "uncompressed/u" #define UVC_PATH_STREAMING_MJPEG "mjpeg/m" #define MAX_FRAMES 16 #define MAX_FORMATS 2 const char * format_names[MAX_FORMATS] = { UVC_PATH_STREAMING_MJPEG, UVC_PATH_STREAMING_UNCOMPRESSED, }; struct formats { bool frames[MAX_FRAMES]; bool frames_initiated; }; struct usbg_f_uvc { struct usbg_function func; struct formats formats[MAX_FORMATS]; bool formats_initiated; }; #define UVC_DEC_ATTR(_name) \ { \ .name = #_name, \ .offset = offsetof(struct usbg_f_uvc_config_attrs, _name), \ .get = usbg_get_dec, \ .set = usbg_set_dec, \ .import = usbg_get_config_node_int, \ .export = usbg_set_config_node_int, \ } #define UVC_STRING_ATTR(_name) \ { \ .name = #_name, \ .offset = offsetof(struct usbg_f_uvc_config_attrs, _name), \ .get = usbg_get_string, \ .set = usbg_set_string, \ .export = usbg_set_config_node_string, \ .import = usbg_get_config_node_string, \ } struct { const char *name; size_t offset; usbg_attr_get_func get; usbg_attr_set_func set; usbg_import_node_func import; usbg_export_node_func export; } uvc_config_attr[USBG_F_UVC_CONFIG_ATTR_MAX] = { [USBG_F_UVC_CONFIG_MAXBURST] = UVC_DEC_ATTR(streaming_maxburst), [USBG_F_UVC_CONFIG_MAXPACKET] = UVC_DEC_ATTR(streaming_maxpacket), [USBG_F_UVC_CONFIG_INTERVAL] = UVC_DEC_ATTR(streaming_interval), [USBG_F_UVC_CONFIG_FUNCTION_NAME] = UVC_STRING_ATTR(function_name), }; #undef UVC_DEC_ATTR #undef UVC_STRING_ATTR #define UVC_DEC_ATTR(_name) \ { \ .name = #_name, \ .offset = offsetof(struct usbg_f_uvc_frame_attrs, _name), \ .get = usbg_get_dec, \ .set = usbg_set_dec, \ .import = usbg_get_config_node_int, \ .export = usbg_set_config_node_int, \ } struct { const char *name; size_t offset; usbg_attr_get_func get; usbg_attr_set_func set; usbg_import_node_func import; usbg_export_node_func export; } uvc_frame_attr[USBG_F_UVC_FRAME_ATTR_MAX] = { [USBG_F_UVC_FRAME_INDEX] = UVC_DEC_ATTR(bFrameIndex), [USBG_F_UVC_FRAME_CAPABILITIES] = UVC_DEC_ATTR(bmCapabilities), [USBG_F_UVC_FRAME_MIN_BITRATE] = UVC_DEC_ATTR(dwMinBitRate), [USBG_F_UVC_FRAME_MAX_BITRATE] = UVC_DEC_ATTR(dwMaxBitRate), [USBG_F_UVC_FRAME_MAX_VIDEO_BUFFERSIZE] = UVC_DEC_ATTR(dwMaxVideoFrameBufferSize), [USBG_F_UVC_FRAME_DEFAULT_INTERVAL] = UVC_DEC_ATTR(dwDefaultFrameInterval), [USBG_F_UVC_FRAME_INTERVAL] = UVC_DEC_ATTR(dwFrameInterval), [USBG_F_UVC_FRAME_HEIGHT] = UVC_DEC_ATTR(wHeight), [USBG_F_UVC_FRAME_WIDTH] = UVC_DEC_ATTR(wWidth), }; #undef UVC_DEC_ATTR #define UVC_DEC_ATTR(_name) \ { \ .name = #_name, \ .offset = offsetof(struct usbg_f_uvc_format_attrs, _name), \ .get = usbg_get_dec, \ .set = usbg_set_dec, \ .import = usbg_get_config_node_int, \ .export = usbg_set_config_node_int, \ } #define UVC_DEC_ATTR_RO(_name) \ { \ .name = #_name, \ .ro = true, \ .offset = offsetof(struct usbg_f_uvc_format_attrs, _name), \ .get = usbg_get_dec, \ .export = usbg_set_config_node_int, \ } static inline int usbg_get_guid(const char *path, const char *name, const char *attr, void *val) { return usbg_read_buf_alloc(path, name, attr, (char **)val, GUID_BIN_LENGTH); } static inline int usbg_set_guid(const char *path, const char *name, const char *attr, void *val) { return usbg_write_guid(path, name, attr, *(char **)val); } #define UVC_GUID_ATTR(_name) \ { \ .name = #_name, \ .offset = offsetof(struct usbg_f_uvc_format_attrs, _name), \ .get = usbg_get_guid, \ .set = usbg_set_guid, \ .export = usbg_set_config_node_guid, \ .import = usbg_get_config_node_string, \ } struct { const char *name; size_t offset; bool ro; usbg_attr_get_func get; usbg_attr_set_func set; usbg_import_node_func import; usbg_export_node_func export; } uvc_format_attr[USBG_F_UVC_FORMAT_ATTR_MAX] = { [USBG_F_UVC_FORMAT_CONTROLS] = UVC_DEC_ATTR_RO(bmaControls), [USBG_F_UVC_FORMAT_INTERLACE_FLAGS] = UVC_DEC_ATTR_RO(bmInterlaceFlags), [USBG_F_UVC_FORMAT_ASPECTRATIO_X] = UVC_DEC_ATTR_RO(bAspectRatioX), [USBG_F_UVC_FORMAT_ASPECTRATIO_Y] = UVC_DEC_ATTR_RO(bAspectRatioY), [USBG_F_UVC_FORMAT_DEFAULT_FRAME_INDEX] = UVC_DEC_ATTR(bDefaultFrameIndex), [USBG_F_UVC_FORMAT_GUID_FORMAT] = UVC_GUID_ATTR(guidFormat), [USBG_F_UVC_FORMAT_BITS_PER_PIXEL] = UVC_DEC_ATTR(bBitsPerPixel), [USBG_F_UVC_FORMAT_FORMAT_INDEX] = UVC_DEC_ATTR_RO(bFormatIndex), }; #undef UVC_DEC_ATTR #undef UVC_DEC_ATTR_RO static inline int frame_select(const struct dirent *dent) { int ret; int id; ret = file_select(dent); if (!ret) goto out; ret = sscanf(dent->d_name, "frame.%d", &id); out: return ret; } static inline int frame_sort(const struct dirent **d1, const struct dirent **d2) { int ret; int id1, id2; ret = sscanf((*d1)->d_name, "frame.%d", &id1); if (ret != 1) goto err; ret = sscanf((*d2)->d_name, "frame.%d", &id2); if (ret != 1) goto err; return id1 < id2 ? -1 : id1 > id2; err: /* * This should not happened because dentries has been * already checked by frame_select function. This * error procedure is just in case. */ return -1; } int init_frames(struct usbg_f_uvc *uvc, int j) { struct dirent **dent; char fpath[USBG_MAX_PATH_LENGTH]; int nmb, i, id, ret = 0; nmb = snprintf(fpath, sizeof(fpath), "%s/%s/" UVC_PATH_STREAMING "/%s/", uvc->func.path, uvc->func.name, format_names[j]); if (nmb >= sizeof(fpath)) { ret = USBG_ERROR_PATH_TOO_LONG; return ret; } nmb = scandir(fpath, &dent, frame_select, frame_sort); if (nmb < 0) { ret = usbg_translate_error(errno); return ret; } for (i = 0; i < nmb; ++i) { /* don't check the error as we know that name is valid */ sscanf(dent[i]->d_name, "frame.%d", &id); uvc->formats[j].frames[id] = true; free(dent[i]); } free(dent); uvc->formats[j].frames_initiated = true; return 0; } static inline struct formats *get_formats_mask(struct usbg_f_uvc *uvc) { int i, ret; if (!uvc->formats_initiated) { uvc->formats_initiated = true; for (i = 0; i < MAX_FORMATS; ++i) { ret = init_frames(uvc, i); if (ret) uvc->formats_initiated = false; } } return uvc->formats; } GENERIC_ALLOC_INST(uvc_internal, struct usbg_f_uvc, func) static int uvc_alloc_inst(struct usbg_function_type *type, usbg_function_type type_code, const char *instance, const char *path, struct usbg_gadget *parent, struct usbg_function **f) { struct usbg_f_uvc *uvcf; int ret; ret = uvc_internal_alloc_inst(type, type_code, instance, path, parent, f); if (ret) goto out; uvcf = usbg_to_uvc_function(*f); if (!uvcf) return -ENOMEM; memset(uvcf->formats, 0, sizeof(uvcf->formats)); uvcf->formats_initiated = false; out: return ret; } GENERIC_FREE_INST(uvc, struct usbg_f_uvc, func) static int uvc_set_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_uvc_set_attrs(usbg_to_uvc_function(f), f_attrs); } static int uvc_get_attrs(struct usbg_function *f, void *f_attrs) { return usbg_f_uvc_get_attrs(usbg_to_uvc_function(f), f_attrs); } static void uvc_cleanup_attrs(struct usbg_function *f, void *f_attrs) { usbg_f_uvc_cleanup_attrs(f_attrs); } int usbg_f_uvc_get_config_attr_val(usbg_f_uvc *uvcf, enum usbg_f_uvc_config_attr iattr, union usbg_f_uvc_config_attr_val *val) { char ipath[USBG_MAX_PATH_LENGTH]; int nmb; nmb = snprintf(ipath, sizeof(ipath), "%s/%s/", uvcf->func.path, uvcf->func.name); if (nmb >= sizeof(ipath)) return USBG_ERROR_PATH_TOO_LONG; return uvc_config_attr[iattr].get(ipath, "", uvc_config_attr[iattr].name, val); } int usbg_f_uvc_set_config_attr_val(usbg_f_uvc *uvcf, enum usbg_f_uvc_config_attr iattr, union usbg_f_uvc_config_attr_val val) { char ipath[USBG_MAX_PATH_LENGTH]; int nmb; nmb = snprintf(ipath, sizeof(ipath), "%s/%s/", uvcf->func.path, uvcf->func.name); if (nmb >= sizeof(ipath)) return USBG_ERROR_PATH_TOO_LONG; return uvc_config_attr[iattr].set(ipath, "", uvc_config_attr[iattr].name, &val); } int usbg_f_uvc_get_config_attrs(usbg_f_uvc *uvcf, struct usbg_f_uvc_config_attrs *iattrs) { int i; int ret = 0; for (i = USBG_F_UVC_CONFIG_ATTR_MIN; i < USBG_F_UVC_CONFIG_ATTR_MAX; ++i) { ret = usbg_f_uvc_get_config_attr_val(uvcf, i, (union usbg_f_uvc_config_attr_val *) ((char *)iattrs + uvc_config_attr[i].offset)); if (ret) break; } return ret; } int usbg_f_uvc_set_config_attrs(usbg_f_uvc *uvcf, const struct usbg_f_uvc_config_attrs *iattrs) { int i; int ret = 0; for (i = USBG_F_UVC_FRAME_ATTR_MIN; i < USBG_F_UVC_FRAME_ATTR_MAX; ++i) { ret = usbg_f_uvc_set_config_attr_val(uvcf, i, *(union usbg_f_uvc_config_attr_val *) ((char *)iattrs + uvc_config_attr[i].offset)); if (ret) break; } return ret; } int usbg_f_uvc_get_frame_attr_val(usbg_f_uvc *uvcf, const char* format, int frame_id, enum usbg_f_uvc_frame_attr fattr, union usbg_f_uvc_frame_attr_val *val) { char fpath[USBG_MAX_PATH_LENGTH]; int nmb; nmb = snprintf(fpath, sizeof(fpath), "%s/%s/" UVC_PATH_STREAMING "/%s/frame.%d/", uvcf->func.path, uvcf->func.name, format, frame_id); if (nmb >= sizeof(fpath)) return USBG_ERROR_PATH_TOO_LONG; return uvc_frame_attr[fattr].get(fpath, "", uvc_frame_attr[fattr].name, val); } int usbg_f_uvc_set_frame_attr_val(usbg_f_uvc *uvcf, const char* format, int frame_id, enum usbg_f_uvc_frame_attr fattr, union usbg_f_uvc_frame_attr_val val) { char fpath[USBG_MAX_PATH_LENGTH]; int nmb; nmb = snprintf(fpath, sizeof(fpath), "%s/%s/" UVC_PATH_STREAMING "/%s/frame.%d/", uvcf->func.path, uvcf->func.name, format, frame_id); if (nmb >= sizeof(fpath)) return USBG_ERROR_PATH_TOO_LONG; return uvc_frame_attr[fattr].set(fpath, "", uvc_frame_attr[fattr].name, &val); } int usbg_f_uvc_get_frame_attrs(usbg_f_uvc *uvcf, const char* format, int frame_id, struct usbg_f_uvc_frame_attrs *fattrs) { int i; int ret = 0; for (i = USBG_F_UVC_FRAME_ATTR_MIN; i < USBG_F_UVC_FRAME_ATTR_MAX; ++i) { ret = usbg_f_uvc_get_frame_attr_val(uvcf, format, frame_id, i, (union usbg_f_uvc_frame_attr_val *) ((char *)fattrs + uvc_frame_attr[i].offset)); if (ret) break; } fattrs->bFrameIndex = frame_id; return ret; } int usbg_f_uvc_set_frame_attrs(usbg_f_uvc *uvcf, const char* format, int frame_id, const struct usbg_f_uvc_frame_attrs *fattrs) { int i; int ret = 0; for (i = USBG_F_UVC_FRAME_ATTR_MIN; i < USBG_F_UVC_FRAME_ATTR_MAX; ++i) { ret = usbg_f_uvc_set_frame_attr_val(uvcf, format, frame_id, i, *(union usbg_f_uvc_frame_attr_val *) ((char *)fattrs + uvc_frame_attr[i].offset)); if (ret) break; } return ret; } int usbg_f_uvc_get_format_attr_val(usbg_f_uvc *uvcf, const char* format, enum usbg_f_uvc_format_attr fattr, union usbg_f_uvc_format_attr_val *val) { char fpath[USBG_MAX_PATH_LENGTH]; int nmb; nmb = snprintf(fpath, sizeof(fpath), "%s/%s/" UVC_PATH_STREAMING "/%s/", uvcf->func.path, uvcf->func.name, format); if (nmb >= sizeof(fpath)) return USBG_ERROR_PATH_TOO_LONG; return uvc_format_attr[fattr].get(fpath, "", uvc_format_attr[fattr].name, val); } int usbg_f_uvc_set_format_attr_val(usbg_f_uvc *uvcf, const char* format, enum usbg_f_uvc_format_attr fattr, union usbg_f_uvc_format_attr_val val) { char fpath[USBG_MAX_PATH_LENGTH]; int nmb; nmb = snprintf(fpath, sizeof(fpath), "%s/%s/" UVC_PATH_STREAMING "/%s/", uvcf->func.path, uvcf->func.name, format); if (nmb >= sizeof(fpath)) return USBG_ERROR_PATH_TOO_LONG; return uvc_format_attr[fattr].set(fpath, "", uvc_format_attr[fattr].name, &val); } int usbg_f_uvc_get_format_attrs(usbg_f_uvc *uvcf, const char* format, struct usbg_f_uvc_format_attrs *fattrs) { int i; int ret = 0; for (i = USBG_F_UVC_FORMAT_ATTR_MIN; i < USBG_F_UVC_FORMAT_ATTR_MAX; ++i) { ret = usbg_f_uvc_get_format_attr_val(uvcf, format, i, (union usbg_f_uvc_format_attr_val *) ((char *)fattrs + uvc_format_attr[i].offset)); if (ret) break; } return ret; } int usbg_f_uvc_set_format_attrs(usbg_f_uvc *uvcf, const char* format, const struct usbg_f_uvc_format_attrs *fattrs) { int i; int ret = 0; for (i = USBG_F_UVC_FORMAT_ATTR_MIN; i < USBG_F_UVC_FORMAT_ATTR_MAX; ++i) { ret = usbg_f_uvc_set_format_attr_val(uvcf, format, i, *(union usbg_f_uvc_format_attr_val *) ((char *)fattrs + uvc_format_attr[i].offset)); if (ret) break; } return ret; } static int uvc_create_dir(const char *path) { char tmp[USBG_MAX_PATH_LENGTH]; int nmb, ret = USBG_SUCCESS; char *p = NULL; size_t len; nmb = snprintf(tmp, sizeof(tmp), "%s", path); if(nmb >= sizeof(tmp)) return USBG_ERROR_PATH_TOO_LONG; len = strlen(tmp); if(tmp[len - 1] == '/') tmp[len - 1] = 0; for (p = tmp + 1; *p; p++) { if(*p == '/') { *p = 0; if((mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) != 0) && errno != EEXIST) { ret = usbg_translate_error(errno); break; } *p = '/'; } } if(ret != USBG_SUCCESS) return ret; if((mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) != 0) && errno != EEXIST) return usbg_translate_error(errno); return ret; } static int uvc_link(char *path, char *to, char *from) { char oldname[USBG_MAX_PATH_LENGTH]; char newname[USBG_MAX_PATH_LENGTH]; int ret = USBG_SUCCESS; int nmb; nmb = snprintf(oldname, sizeof(oldname), "%s/%s", path, to); if (nmb >= sizeof(oldname)) return USBG_ERROR_PATH_TOO_LONG; nmb = snprintf(newname, sizeof(newname), "%s/%s", path, from); if (nmb >= sizeof(newname)) return USBG_ERROR_PATH_TOO_LONG; if(symlink(oldname, newname)) return usbg_translate_error(errno); return ret; } static int uvc_set_class(usbg_f_uvc *uvcf, char *cs) { char path[USBG_MAX_PATH_LENGTH]; char header_path[USBG_MAX_PATH_LENGTH]; int nmb; int ret; nmb = snprintf(path, sizeof(path), "%s/%s/%s", uvcf->func.path, uvcf->func.name, cs); if (nmb >= sizeof(path)) return USBG_ERROR_PATH_TOO_LONG; nmb = snprintf(header_path, sizeof(header_path), "%s/" UVC_PATH_HEADER, path); if (nmb >= sizeof(header_path)) return USBG_ERROR_PATH_TOO_LONG; ret = uvc_create_dir(header_path); if (ret != USBG_SUCCESS) return ret; if (!strncmp(cs, UVC_PATH_STREAMING, strlen(UVC_PATH_STREAMING))) { char check_path[USBG_MAX_PATH_LENGTH]; struct stat buffer; nmb = snprintf(check_path, sizeof(check_path), "%s/" UVC_PATH_STREAMING_UNCOMPRESSED, path); if (nmb >= sizeof(check_path)) return USBG_ERROR_PATH_TOO_LONG; ret = stat(check_path, &buffer); if (!ret) { ret = uvc_link(path, UVC_PATH_STREAMING_UNCOMPRESSED, "header/h/u"); if (ret != USBG_SUCCESS) return ret; } nmb = snprintf(check_path, sizeof(check_path), "%s/" UVC_PATH_STREAMING_MJPEG, path); if (nmb >= sizeof(check_path)) return USBG_ERROR_PATH_TOO_LONG; ret = stat(check_path, &buffer); if (!ret) { ret = uvc_link(path, UVC_PATH_STREAMING_MJPEG, "header/h/m"); if (ret != USBG_SUCCESS) return ret; } ret = uvc_link(path, UVC_PATH_HEADER, UVC_PATH_CLASS_HS); if (ret) return ret; } ret = uvc_link(path, UVC_PATH_HEADER, UVC_PATH_CLASS_FS); if (ret) return ret; return uvc_link(path, UVC_PATH_HEADER, UVC_PATH_CLASS_SS); } #ifdef HAS_GADGET_SCHEMES int usbg_f_uvc_get_nframes(const bool *frames) { int nframes = 0; int i; if (!frames) return USBG_ERROR_INVALID_PARAM; for (i = 0; i < MAX_FRAMES; ++i) nframes += frames[i] ? 1 : 0; return nframes; } int usbg_f_uvc_create_frame(usbg_f_uvc *uvcf, const char* format, bool *frames, int frame_id, struct usbg_f_uvc_frame_attrs *fattrs) { char frame_path[USBG_MAX_PATH_LENGTH]; int nmb; int ret; if (frame_id >= MAX_FRAMES) return USBG_ERROR_INVALID_PARAM; if (frames[frame_id]) return USBG_ERROR_EXIST; nmb = snprintf(frame_path, sizeof(frame_path), "%s/%s/" UVC_PATH_STREAMING "/%s/frame.%d/", uvcf->func.path, uvcf->func.name, format, frame_id); if (nmb >= sizeof(frame_path)) return USBG_ERROR_PATH_TOO_LONG; ret = uvc_create_dir(frame_path); if (ret) return usbg_translate_error(errno); if (fattrs) { ret = usbg_f_uvc_set_frame_attrs(uvcf, format, frame_id, fattrs); if (ret) goto remove_frame; } frames[frame_id] = true; return 0; remove_frame: rmdir(frame_path); return ret; } static int uvc_import_frame_attrs(struct usbg_f_uvc *uvcf, const char* format, int frame_id, config_setting_t *root) { union usbg_f_uvc_frame_attr_val val; int ret = 0; int i; for (i = USBG_F_UVC_FRAME_ATTR_MIN; i < USBG_F_UVC_FRAME_ATTR_MAX; ++i) { ret = uvc_frame_attr[i].import(root, uvc_frame_attr[i].name, &val); /* node not found */ if (ret == 0) continue; /* error */ if (ret < 0) break; ret = usbg_f_uvc_set_frame_attr_val(uvcf, format, frame_id, i, val); if (ret) break; } return ret; } static int uvc_import_format_attrs(struct usbg_f_uvc *uvcf, const char* format, config_setting_t *root) { union usbg_f_uvc_format_attr_val val; int ret = 0; int i; for (i = USBG_F_UVC_FORMAT_ATTR_MIN; i < USBG_F_UVC_FORMAT_ATTR_MAX; ++i) { if (uvc_format_attr[i].ro) continue; ret = uvc_format_attr[i].import(root, uvc_format_attr[i].name, &val); /* node not found */ if (ret == 0) continue; /* error */ if (ret < 0) break; ret = usbg_f_uvc_set_format_attr_val(uvcf, format, i, val); if (ret) break; } return ret; } static int uvc_import_format(struct usbg_f_uvc *uvcf, const char *format, bool *frames, config_setting_t *root) { config_setting_t *frames_node, *node; int i, nframes; int ret = 0; frames_node = config_setting_get_member(root, "frames"); if (!frames_node) { ret = USBG_ERROR_INVALID_PARAM; goto out; } if (!config_setting_is_list(frames_node)) { ret = USBG_ERROR_INVALID_TYPE; goto out; } nframes = config_setting_length(frames_node); for (i = 0; i < nframes; ++i) { node = config_setting_get_elem(frames_node, i); if (!node) { ret = USBG_ERROR_INVALID_FORMAT; goto out; } if (!config_setting_is_group(node)) { ret = USBG_ERROR_INVALID_TYPE; goto out; } if (!frames[i]) { ret = usbg_f_uvc_create_frame(uvcf, format, frames, i, NULL); if (ret) goto out; } ret = uvc_import_frame_attrs(uvcf, format, i, node); if (ret) goto out; } out: return ret; } static int uvc_import_config(struct usbg_f_uvc *uvcf, config_setting_t *root) { union usbg_f_uvc_config_attr_val val; config_setting_t *config_node; int ret = 0; int i; config_node = config_setting_get_member(root, "config"); if (!config_node) { ret = USBG_ERROR_INVALID_PARAM; return ret; } if (!config_setting_is_group(config_node)) { ret = USBG_ERROR_INVALID_TYPE; return ret; } for (i = USBG_F_UVC_CONFIG_ATTR_MIN; i < USBG_F_UVC_CONFIG_ATTR_MAX; ++i) { ret = uvc_config_attr[i].import(config_node, uvc_config_attr[i].name, &val); /* node not found */ if (ret == 0) continue; /* error */ if (ret < 0) break; ret = usbg_f_uvc_set_config_attr_val(uvcf, i, val); if (ret) break; } return ret; } static int uvc_libconfig_import(struct usbg_function *f, config_setting_t *root) { struct usbg_f_uvc *uvcf = usbg_to_uvc_function(f); config_setting_t *formats_node, *node; int nmb, ret, i, nformats; char fp[USBG_MAX_PATH_LENGTH]; const char *format; struct formats *formats; formats_node = config_setting_get_member(root, "formats"); if (!formats_node) { ret = USBG_ERROR_INVALID_PARAM; goto out; } if (!config_setting_is_group(formats_node)) { ret = USBG_ERROR_INVALID_TYPE; goto out; } nformats = config_setting_length(formats_node); formats = get_formats_mask(uvcf); for (i = 0; i < nformats; ++i) { node = config_setting_get_elem(formats_node, i); if (!node) { ret = USBG_ERROR_INVALID_FORMAT; goto out; } if (!config_setting_is_group(node)) { ret = USBG_ERROR_INVALID_TYPE; goto out; } format = config_setting_name(node); nmb = snprintf(fp, sizeof(fp), "%s/%c", format, format[0]); if (nmb >= sizeof(fp)) return USBG_ERROR_PATH_TOO_LONG; ret = uvc_import_format(uvcf, fp, formats[i].frames, node); if (ret) goto out; ret = uvc_import_format_attrs(uvcf, fp, node); if (ret) goto out; } ret = uvc_import_config(uvcf, root); if (ret != USBG_SUCCESS) return ret; ret = uvc_set_class(uvcf, UVC_PATH_CONTROL); if (ret != USBG_SUCCESS) return ret; ret = uvc_set_class(uvcf, UVC_PATH_STREAMING); if (ret != USBG_SUCCESS) return ret; out: return ret; } static int uvc_export_config(struct usbg_f_uvc *uvcf, config_setting_t *root) { config_setting_t *config_node; union usbg_f_uvc_config_attr_val val; int i; int ret = 0; config_node = config_setting_add(root, "config", CONFIG_TYPE_GROUP); if (!config_node) goto out; for (i = USBG_F_UVC_CONFIG_ATTR_MIN; i < USBG_F_UVC_CONFIG_ATTR_MAX; ++i) { ret = usbg_f_uvc_get_config_attr_val(uvcf, i, &val); if (ret) break; ret = uvc_config_attr[i].export(config_node, uvc_config_attr[i].name, &val); if (ret) break; } out: return ret; } static int uvc_export_format_attrs(struct usbg_f_uvc *uvcf, const char *format, config_setting_t *root) { union usbg_f_uvc_format_attr_val val; int ret = 0; int i; for (i = USBG_F_UVC_FORMAT_ATTR_MIN; i < USBG_F_UVC_FORMAT_ATTR_MAX; ++i) { ret = usbg_f_uvc_get_format_attr_val(uvcf, format, i, &val); if (ret) break; ret = uvc_format_attr[i].export(root, uvc_format_attr[i].name, &val); if (ret) break; } if (ret == USBG_ERROR_NOT_FOUND) ret = 0; return ret; } static int uvc_export_frame_attrs(struct usbg_f_uvc *uvcf, const char *format, int frame_id, config_setting_t *root) { union usbg_f_uvc_frame_attr_val val; int ret = 0; int i; for (i = USBG_F_UVC_FRAME_ATTR_MIN; i < USBG_F_UVC_FRAME_ATTR_MAX; ++i) { ret = usbg_f_uvc_get_frame_attr_val(uvcf, format, frame_id, i, &val); if (ret) break; ret = uvc_frame_attr[i].export(root, uvc_frame_attr[i].name, &val); if (ret) break; } if (ret == USBG_ERROR_NOT_FOUND) ret = 0; return ret; } static int uvc_export_frames(struct usbg_f_uvc *uvcf, const char *format, bool *frames, config_setting_t *root) { config_setting_t *frames_node, *node; int i, nframes; int ret = 0; frames_node = config_setting_add(root, "frames", CONFIG_TYPE_LIST); if (!frames_node) { ret = USBG_ERROR_INVALID_FORMAT; goto out; } nframes = usbg_f_uvc_get_nframes(frames); if (nframes < 0) return nframes; for (i = 0; i < nframes; ++i) { node = config_setting_add(frames_node, "", CONFIG_TYPE_GROUP); if (!node) goto out; ret = uvc_export_frame_attrs(uvcf, format, i, node); if (ret) goto out; } out: return ret; } static int uvc_libconfig_export(struct usbg_function *f, config_setting_t *root) { struct usbg_f_uvc *uvcf = usbg_to_uvc_function(f); config_setting_t *formats_node, *node; char fp[USBG_MAX_PATH_LENGTH]; struct formats *formats; int i, ret = 0; char *p; formats_node = config_setting_add(root, "formats", CONFIG_TYPE_GROUP); if (!formats_node) { ret = USBG_ERROR_INVALID_PARAM; goto out; } formats = get_formats_mask(uvcf); for (i = 0; i < MAX_FORMATS; ++i) { /* remove trailing /m and /u from format */ strcpy(fp, format_names[i]); p = fp + strlen(fp) - 2; *p = '\0'; node = config_setting_add(formats_node, fp, CONFIG_TYPE_GROUP); if (!node) goto out; ret = uvc_export_frames(uvcf, format_names[i], formats[i].frames, node); if (ret) goto out; ret = uvc_export_format_attrs(uvcf, format_names[i], node); if (ret) goto out; } ret = uvc_export_config(uvcf, root); out: return ret; } #endif static int uvc_set_format(char *format_path, const char *format, const struct usbg_f_uvc_format_attrs *attrs) { return usbg_write_dec(format_path, format, "bDefaultFrameIndex", attrs->bDefaultFrameIndex); } static int uvc_set_frame(char *format_path, const char *format, const struct usbg_f_uvc_frame_attrs *attrs) { char frame_path[USBG_MAX_PATH_LENGTH]; char full_frame_path[USBG_MAX_PATH_LENGTH]; char frame_name[32]; int nmb, ret; nmb = snprintf(frame_name, sizeof(frame_name), "frame.%d", attrs->bFrameIndex); if (nmb >= sizeof(frame_name)) return USBG_ERROR_PATH_TOO_LONG; nmb = snprintf(frame_path, sizeof(frame_path), "%s/%s", format_path, format); if (nmb >= sizeof(frame_path)) return USBG_ERROR_PATH_TOO_LONG; nmb = snprintf(full_frame_path, sizeof(frame_path), "%s/%s", frame_path, frame_name); if (nmb >= sizeof(full_frame_path)) return USBG_ERROR_PATH_TOO_LONG; ret = uvc_create_dir(full_frame_path); if (ret != USBG_SUCCESS) return ret; ret = usbg_write_dec(frame_path, frame_name, "dwFrameInterval", attrs->dwFrameInterval); if (ret != USBG_SUCCESS) return ret; ret = usbg_write_dec(frame_path, frame_name, "dwDefaultFrameInterval", attrs->dwDefaultFrameInterval); if (ret != USBG_SUCCESS) return ret; ret = usbg_write_dec(frame_path, frame_name, "dwMaxVideoFrameBufferSize", attrs->dwMaxVideoFrameBufferSize); if (ret != USBG_SUCCESS) return ret; ret = usbg_write_dec(frame_path, frame_name, "dwMinBitRate", attrs->dwMinBitRate); if (ret != USBG_SUCCESS) return ret; ret = usbg_write_dec(frame_path, frame_name, "dwMaxBitRate", attrs->dwMaxBitRate); if (ret != USBG_SUCCESS) return ret; ret = usbg_write_dec(frame_path, frame_name, "wHeight", attrs->wHeight); if (ret != USBG_SUCCESS) return ret; return usbg_write_dec(frame_path, frame_name, "wWidth", attrs->wWidth); } static int uvc_set_streaming(char *func_path, const char *format, const struct usbg_f_uvc_format_attrs *attrs) { struct usbg_f_uvc_frame_attrs **frame_attrs; char streaming_path[USBG_MAX_PATH_LENGTH]; int nmb, ret, i; nmb = snprintf(streaming_path, sizeof(streaming_path), "%s/" UVC_PATH_STREAMING, func_path); if (nmb >= sizeof(streaming_path)) return USBG_ERROR_PATH_TOO_LONG; for(frame_attrs = attrs->frames, i = 0; frame_attrs[i]; ++i) { if (frame_attrs[i]) { ret = uvc_set_frame(streaming_path, format, frame_attrs[i]); if(ret != USBG_SUCCESS) ERROR("Error: %d", ret); } } ret = uvc_set_format(streaming_path, format, attrs); if(ret != USBG_SUCCESS) ERROR("Error: %d", ret); return ret; } static int dir_nftw_cb(const char *pathname, const struct stat *sbuf, int type, struct FTW *ftwb) { (void) sbuf; (void) type; (void) ftwb; int ret; ret = remove(pathname); if (ret < -1) ERROR("failed to remove %s - %s", pathname, strerror(ret)); return 0; } int remove_dir(const char *dirpath) { const int max_open_descs = 8; int ret; ret = nftw(dirpath, dir_nftw_cb, max_open_descs, FTW_DEPTH | FTW_MOUNT | FTW_PHYS); if (ret < 0) { ERROR("nftw failed"); return ret; } return 0; } static int content_nftw_cb(const char *pathname, const struct stat *sbuf, int type, struct FTW *ftwb) { (void) sbuf; (void) type; (void) ftwb; int ret; if(ftwb->level == 0) return 0; ret = remove(pathname); if(ret < -1) ERROR("failed to remove %s - %s", pathname, strerror(ret)); return 0; } int remove_dir_content(const char *dirpath) { const int max_open_descs = 8; int ret; /* traverse in reverse order (handle directory after it's content), stay within the same file system and do not follow symbolic links */ ret = nftw(dirpath, content_nftw_cb, max_open_descs, FTW_DEPTH | FTW_MOUNT | FTW_PHYS); if (ret < 0) { ERROR("nftw failed"); return ret; } return 0; } static int uvc_remove(struct usbg_function *f, int opts) { usbg_f_uvc *uvcf = usbg_to_uvc_function(f); char streaming_path[USBG_MAX_PATH_LENGTH]; char control_path[USBG_MAX_PATH_LENGTH]; char path[USBG_MAX_PATH_LENGTH]; int nmb, ret = USBG_SUCCESS; nmb = snprintf(path, sizeof(path), "%s/%s", uvcf->func.path, uvcf->func.name); if (nmb >= sizeof(path)) return USBG_ERROR_PATH_TOO_LONG; nmb = snprintf(streaming_path, sizeof(streaming_path), "%s/streaming", path); if (nmb >= sizeof(streaming_path)) return USBG_ERROR_PATH_TOO_LONG; nmb = snprintf(control_path, sizeof(control_path), "%s/control", path); if (nmb >= sizeof(control_path)) return USBG_ERROR_PATH_TOO_LONG; if(remove_dir_content(streaming_path) < 0) return USBG_ERROR_PATH_TOO_LONG; if(remove_dir_content(control_path) < 0) return USBG_ERROR_PATH_TOO_LONG; if(remove_dir(streaming_path) < 0) return USBG_ERROR_PATH_TOO_LONG; if(remove_dir(control_path) < 0) return USBG_ERROR_PATH_TOO_LONG; return ret; } struct usbg_function_type usbg_f_type_uvc = { .name = "uvc", .alloc_inst = uvc_alloc_inst, .free_inst = uvc_free_inst, .set_attrs = uvc_set_attrs, .get_attrs = uvc_get_attrs, .cleanup_attrs = uvc_cleanup_attrs, #ifdef HAS_GADGET_SCHEMES .import = uvc_libconfig_import, .export = uvc_libconfig_export, #endif .remove = uvc_remove, }; /* API implementation */ usbg_f_uvc *usbg_to_uvc_function(usbg_function *f) { return f->ops == &usbg_f_type_uvc ? container_of(f, struct usbg_f_uvc, func) : NULL; } usbg_function *usbg_from_uvc_function(usbg_f_uvc *ff) { return &ff->func; } int usbg_f_uvc_get_attrs(usbg_f_uvc *uvcf, struct usbg_f_uvc_attrs *attrs) { return USBG_SUCCESS; } int usbg_f_uvc_set_attrs(usbg_f_uvc *uvcf, const struct usbg_f_uvc_attrs *attrs) { char path[USBG_MAX_PATH_LENGTH]; struct usbg_f_uvc_format_attrs **format_attrs; int ret = USBG_SUCCESS; int nmb, i; if (!attrs) return USBG_ERROR_INVALID_PARAM; nmb = snprintf(path, sizeof(path), "%s/%s", uvcf->func.path, uvcf->func.name); if (nmb >= sizeof(path)) return USBG_ERROR_PATH_TOO_LONG; for(format_attrs = attrs->formats, i = 0; format_attrs[i]; ++i) { ret = uvc_set_streaming(path, format_attrs[i]->format, format_attrs[i]); if(ret != USBG_SUCCESS) ERROR("Error: %d", ret); } ret = uvc_set_class(uvcf, UVC_PATH_CONTROL); if (ret != USBG_SUCCESS) return ret; ret = uvc_set_class(uvcf, UVC_PATH_STREAMING); if (ret != USBG_SUCCESS) return ret; return ret; } libusbgx-libusbgx-v0.3.0/src/meson.build000066400000000000000000000007231467553526200203060ustar00rootroot00000000000000sources += files( 'usbg.c', 'usbg_error.c', 'usbg_common.c', 'function/ether.c', 'function/ffs.c', 'function/midi.c', 'function/ms.c', 'function/phonet.c', 'function/serial.c', 'function/loopback.c', 'function/hid.c', 'function/uac2.c', 'function/uvc.c', 'function/printer.c', 'function/9pfs.c', ) if libconfig.found() sources += files( 'usbg_schemes_libconfig.c', 'usbg_common_libconfig.c' ) else sources += files('usbg_schemes_none.c') endif libusbgx-libusbgx-v0.3.0/src/usbg.c000066400000000000000000001520231467553526200172510ustar00rootroot00000000000000/* * Copyright (C) 2013 Linaro Limited * * Matt Porter * * Copyright (C) 2013 - 2015 Samsung Electronics * * Krzysztof Opasiak * * This library is free software; you can redistribute it 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include "usbg/usbg_internal.h" /** * @file usbg.c */ extern struct usbg_function_type usbg_f_type_acm; extern struct usbg_function_type usbg_f_type_serial; extern struct usbg_function_type usbg_f_type_obex; extern struct usbg_function_type usbg_f_type_ecm; extern struct usbg_function_type usbg_f_type_subset; extern struct usbg_function_type usbg_f_type_ncm; extern struct usbg_function_type usbg_f_type_eem; extern struct usbg_function_type usbg_f_type_rndis; extern struct usbg_function_type usbg_f_type_ffs; extern struct usbg_function_type usbg_f_type_midi; extern struct usbg_function_type usbg_f_type_ms; extern struct usbg_function_type usbg_f_type_phonet; extern struct usbg_function_type usbg_f_type_loopback; extern struct usbg_function_type usbg_f_type_hid; extern struct usbg_function_type usbg_f_type_uac2; extern struct usbg_function_type usbg_f_type_uvc; extern struct usbg_function_type usbg_f_type_printer; extern struct usbg_function_type usbg_f_type_9pfs; /** * @var function_types * @brief Types of functions supported by library */ struct usbg_function_type* function_types[] = { [USBG_F_ACM] = &usbg_f_type_acm, [USBG_F_SERIAL] = &usbg_f_type_serial, [USBG_F_OBEX] = &usbg_f_type_obex, [USBG_F_ECM] = &usbg_f_type_ecm, [USBG_F_SUBSET] = &usbg_f_type_subset, [USBG_F_NCM] = &usbg_f_type_ncm, [USBG_F_EEM] = &usbg_f_type_eem, [USBG_F_RNDIS] = &usbg_f_type_rndis, [USBG_F_FFS] = &usbg_f_type_ffs, [USBG_F_MIDI] = &usbg_f_type_midi, [USBG_F_MASS_STORAGE] = &usbg_f_type_ms, [USBG_F_PHONET] = &usbg_f_type_phonet, [USBG_F_LOOPBACK] = &usbg_f_type_loopback, [USBG_F_HID] = &usbg_f_type_hid, [USBG_F_UAC2] = &usbg_f_type_uac2, [USBG_F_UVC] = &usbg_f_type_uvc, [USBG_F_PRINTER] = &usbg_f_type_printer, [USBG_F_9PFS] = &usbg_f_type_9pfs, }; ARRAY_SIZE_SENTINEL(function_types, USBG_FUNCTION_TYPE_MAX) const char *gadget_attr_names[] = { "bcdUSB", "bDeviceClass", "bDeviceSubClass", "bDeviceProtocol", "bMaxPacketSize0", "idVendor", "idProduct", "bcdDevice" }; ARRAY_SIZE_SENTINEL(gadget_attr_names, USBG_GADGET_ATTR_MAX) const char *gadget_str_names[] = { "manufacturer", "product", "serialnumber", }; ARRAY_SIZE_SENTINEL(gadget_str_names, USBG_GADGET_STR_MAX) const char *gadget_os_desc_names[] = { "use", "b_vendor_code", "qw_sign", }; ARRAY_SIZE_SENTINEL(gadget_os_desc_names, USBG_GADGET_OS_DESC_MAX) int usbg_lookup_function_type(const char *name) { int i = USBG_FUNCTION_TYPE_MIN; if (!name) return USBG_ERROR_INVALID_PARAM; do { if (!strcmp(name, function_types[i]->name)) return i; i++; } while (i != USBG_FUNCTION_TYPE_MAX); return USBG_ERROR_NOT_FOUND; } const char *usbg_get_function_type_str(usbg_function_type type) { return type >= USBG_FUNCTION_TYPE_MIN && type < USBG_FUNCTION_TYPE_MAX ? function_types[type]->name : NULL; } int usbg_lookup_gadget_attr(const char *name) { int i = USBG_GADGET_ATTR_MIN; if (!name) return USBG_ERROR_INVALID_PARAM; do { if (!strcmp(name, gadget_attr_names[i])) return i; i++; } while (i != USBG_GADGET_ATTR_MAX); return USBG_ERROR_NOT_FOUND; } int usbg_lookup_gadget_str(const char *name) { int i = USBG_GADGET_STR_MIN; if (!name) return USBG_ERROR_INVALID_PARAM; do { if (!strcmp(name, gadget_str_names[i])) return i; i++; } while (i != USBG_GADGET_STR_MAX); return USBG_ERROR_NOT_FOUND; } const char *usbg_get_gadget_attr_str(usbg_gadget_attr attr) { return attr >= USBG_GADGET_ATTR_MIN && attr < USBG_GADGET_ATTR_MAX ? gadget_attr_names[attr] : NULL; } const char *usbg_get_gadget_str_name(usbg_gadget_str str) { return str >= USBG_GADGET_STR_MIN && str < USBG_GADGET_STR_MAX ? gadget_str_names[str] : NULL; } const char *usbg_get_gadget_os_desc_name(usbg_gadget_os_desc_strs str) { return str >= USBG_GADGET_OS_DESC_MIN && str < USBG_GADGET_OS_DESC_MAX ? gadget_os_desc_names[str] : NULL; } static int usbg_split_function_instance_type(const char *full_name, usbg_function_type *f_type, const char **instance) { const char *dot; char *type_name = NULL; int f_type_ret; usbg_error ret = USBG_ERROR_INVALID_PARAM; dot = strchr(full_name, '.'); if (!dot || dot == full_name || *(dot + 1) == '\0') goto out; *instance = dot + 1; type_name = strndup(full_name, dot - full_name); if (!type_name) { ret = USBG_ERROR_NO_MEM; goto out; } f_type_ret = usbg_lookup_function_type(type_name); if (f_type_ret >= 0) { *f_type = (usbg_function_type)f_type_ret; ret = USBG_SUCCESS; } else { ret = USBG_ERROR_NOT_SUPPORTED; } out: free(type_name); return ret; } static int usbg_split_config_label_id(const char *full_name, char **label) { int ret = USBG_ERROR_INVALID_PARAM; char *dot, *endptr, *id_string; dot = strrchr(full_name, '.'); id_string = dot + 1; if (!dot || dot == full_name || *id_string == '\0' || isspace(*id_string)) goto out; *label = strndup(full_name, dot - full_name); if (!*label) goto out; errno = 0; /* clear errno */ ret = strtol(id_string, &endptr, 10); if (errno) { /* error occurred */ ret = usbg_translate_error(errno); free(*label); *label = NULL; goto out; } if (*endptr != '\0' || ret < 0 || ret > 255) ret = USBG_ERROR_INVALID_PARAM; out: return ret; } static int bindings_select(const struct dirent *dent) { if (dent->d_type == DT_LNK) return 1; else return 0; } static inline void usbg_free_binding(usbg_binding *b) { free(b->path); free(b->name); free(b); } static inline void usbg_free_function(usbg_function *f) { if (f->ops->free_inst) f->ops->free_inst(f->ops, f); } static void usbg_free_config(usbg_config *c) { usbg_binding *b; while (!TAILQ_EMPTY(&c->bindings)) { b = TAILQ_FIRST(&c->bindings); TAILQ_REMOVE(&c->bindings, b, bnode); usbg_free_binding(b); } free(c->path); free(c->name); free(c->label); free(c); } static void usbg_free_gadget(usbg_gadget *g) { usbg_config *c; usbg_function *f; if (g->last_failed_import) { config_destroy(g->last_failed_import); free(g->last_failed_import); } while (!TAILQ_EMPTY(&g->configs)) { c = TAILQ_FIRST(&g->configs); TAILQ_REMOVE(&g->configs, c, cnode); usbg_free_config(c); } while (!TAILQ_EMPTY(&g->functions)) { f = TAILQ_FIRST(&g->functions); TAILQ_REMOVE(&g->functions, f, fnode); usbg_free_function(f); } free(g->path); free(g->name); free(g); } static void usbg_free_udc(usbg_udc *u) { free(u->name); free(u); } static void usbg_free_state(usbg_state *s) { usbg_gadget *g; usbg_udc *u; while (!TAILQ_EMPTY(&s->gadgets)) { g = TAILQ_FIRST(&s->gadgets); TAILQ_REMOVE(&s->gadgets, g, gnode); usbg_free_gadget(g); } while (!TAILQ_EMPTY(&s->udcs)) { u = TAILQ_FIRST(&s->udcs); TAILQ_REMOVE(&s->udcs, u, unode); usbg_free_udc(u); } if (s->last_failed_import) { config_destroy(s->last_failed_import); free(s->last_failed_import); } free(s->path); free(s->configfs_path); free(s); } static usbg_gadget *usbg_allocate_gadget(const char *path, const char *name, usbg_state *parent) { usbg_gadget *g; g = malloc(sizeof(*g)); if (!g) goto out; TAILQ_INIT(&g->functions); TAILQ_INIT(&g->configs); g->last_failed_import = NULL; g->name = strdup(name); g->path = strdup(path); g->parent = parent; g->udc = NULL; g->os_desc_binding = NULL; if (!(g->name) || !(g->path)) goto cleanup; return g; cleanup: free(g->name); free(g->path); free(g); out: return NULL; } static usbg_config *usbg_allocate_config(const char *path, const char *label, int id, usbg_gadget *parent) { usbg_config *c; int ret; c = malloc(sizeof(*c)); if (!c) goto out; TAILQ_INIT(&c->bindings); ret = asprintf(&(c->name), "%s.%d", label, id); if (ret < 0) goto free_config; c->path = strdup(path); c->label = strdup(label); c->parent = parent; c->id = id; if (!(c->path) || !(c->label)) goto cleanup; return c; cleanup: free(c->name); free(c->path); free(c->label); free_config: free(c); out: return NULL; } static usbg_function * usbg_allocate_function(const char *path, usbg_function_type type, const char *instance, usbg_gadget *parent) { usbg_function *f; int ret; ret = function_types[type]->alloc_inst(function_types[type], type, instance, path, parent, &f); return ret == 0 ? f : NULL; } static usbg_binding *usbg_allocate_binding(const char *path, const char *name, usbg_config *parent) { usbg_binding *b; b = malloc(sizeof(*b)); if (!b) goto out; b->name = strdup(name); b->path = strdup(path); b->parent = parent; if (!(b->name) || !(b->path)) goto cleanup; return b; cleanup: free(b->name); free(b->path); free(b); out: return NULL; } static usbg_udc *usbg_allocate_udc(usbg_state *parent, const char *name) { usbg_udc *u; u = malloc(sizeof(*u)); if (!u) goto out; u->gadget = NULL; u->parent = parent; u->name = strdup(name); if (!u->name) goto cleanup; return u; cleanup: free(u); out: return NULL; } static int usbg_parse_functions(const char *path, usbg_gadget *g) { usbg_function *f; int i, n; int ret = USBG_SUCCESS; struct dirent **dent; char fpath[USBG_MAX_PATH_LENGTH]; n = snprintf(fpath, sizeof(fpath), "%s/%s/%s", path, g->name, FUNCTIONS_DIR); if (n >= sizeof(fpath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } n = scandir(fpath, &dent, file_select, alphasort); if (n < 0) { ret = usbg_translate_error(errno); goto out; } for (i = 0; i < n; i++) { if (ret == USBG_SUCCESS) { const char *instance; usbg_function_type type; ret = usbg_split_function_instance_type( dent[i]->d_name, &type, &instance); if (ret == USBG_SUCCESS) { f = usbg_allocate_function(fpath, type, instance, g); if (f) TAILQ_INSERT_TAIL(&g->functions, f, fnode); else ret = USBG_ERROR_NO_MEM; } } free(dent[i]); } free(dent); out: return ret; } static int usbg_parse_config_attrs(const char *path, const char *name, struct usbg_config_attrs *c_attrs) { int buf, ret; ret = usbg_read_dec(path, name, "MaxPower", &buf); if (ret == USBG_SUCCESS) { c_attrs->bMaxPower = (uint8_t)buf; ret = usbg_read_hex(path, name, "bmAttributes", &buf); if (ret == USBG_SUCCESS) c_attrs->bmAttributes = (uint8_t)buf; } return ret; } static int usbg_parse_config_strs(const char *path, const char *name, int lang, struct usbg_config_strs *c_strs) { DIR *dir; int ret; int nmb; char spath[USBG_MAX_PATH_LENGTH]; nmb = snprintf(spath, sizeof(spath), "%s/%s/%s/0x%x", path, name, STRINGS_DIR, lang); if (nmb >= sizeof(spath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } /* Check if directory exist */ dir = opendir(spath); if (!dir) { ret = usbg_translate_error(errno); goto out; } closedir(dir); ret = usbg_read_string_alloc(spath, "", "configuration", &c_strs->configuration); out: return ret; } static int usbg_parse_config_binding(usbg_config *c, char *bpath, int path_size) { int nmb; int ret; char target[USBG_MAX_PATH_LENGTH]; char *target_name; const char *instance; usbg_function_type type; usbg_function *f; usbg_binding *b; nmb = readlink(bpath, target, sizeof(target) - 1 ); if (nmb < 0) { ret = usbg_translate_error(errno); goto out; } /* readlink() don't add this, * so we have to do it manually */ target[nmb] = '\0'; /* Target contains a full path * but we need only function dir name */ target_name = strrchr(target, '/') + 1; ret = usbg_split_function_instance_type(target_name, &type, &instance); if (ret != USBG_SUCCESS) goto out; f = usbg_get_function(c->parent, type, instance); if (!f) { ret = USBG_ERROR_OTHER_ERROR; goto out; } /* We have to cut last part of path */ bpath[path_size] = '\0'; /* path_to_config_dir \0 config_name */ b = usbg_allocate_binding(bpath, bpath + path_size + 1, c); if (!b) { ret = USBG_ERROR_NO_MEM; goto out; } b->target = f; TAILQ_INSERT_TAIL(&c->bindings, b, bnode); out: return ret; } static int usbg_parse_config_bindings(usbg_config *c) { int i, n, nmb; int ret = USBG_SUCCESS; struct dirent **dent; char bpath[USBG_MAX_PATH_LENGTH]; int end; end = snprintf(bpath, sizeof(bpath), "%s/%s", c->path, c->name); if (end >= sizeof(bpath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } n = scandir(bpath, &dent, bindings_select, alphasort); if (n < 0) { ret = usbg_translate_error(errno); goto out; } for (i = 0; i < n; i++) { if (ret == USBG_SUCCESS) { nmb = snprintf(&(bpath[end]), sizeof(bpath) - end, "/%s", dent[i]->d_name); ret = nmb < sizeof(bpath) - end ? usbg_parse_config_binding(c, bpath, end) : USBG_ERROR_PATH_TOO_LONG; } /* ret == USBG_SUCCESS */ free(dent[i]); } free(dent); out: return ret; } static int usbg_parse_gadget_os_desc_binding(usbg_gadget *g) { int i, n, nmb, id; int ret = USBG_SUCCESS; struct dirent **dent; char bpath[USBG_MAX_PATH_LENGTH]; char target[USBG_MAX_PATH_LENGTH]; char *target_name; usbg_config *c; char *label = NULL; int end; end = snprintf(bpath, sizeof(bpath), "%s/%s/%s", g->path, g->name, OS_DESC_DIR); if (end >= sizeof(bpath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } n = scandir(bpath, &dent, bindings_select, alphasort); if (n < 0) { ret = usbg_translate_error(errno); goto out; } /* Not having any binding is ok */ if (n < 1) { ret = USBG_SUCCESS; free(dent); goto out; } /* * Only one configuration can be bound to os_descx, n should * equal 1. */ nmb = snprintf(&(bpath[end]), sizeof(bpath) - end, "/%s", dent[0]->d_name); for (i = 0; i < n; i++) free(dent[i]); free(dent); if (nmb >= sizeof(bpath) - end) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } nmb = readlink(bpath, target, sizeof(target) - 1 ); if (nmb < 0) { ret = usbg_translate_error(errno); goto out; } /* readlink() don't add this, so we have to do it manually */ target[nmb] = '\0'; /* Target contains a full path but we only need function dir name */ target_name = strrchr(target, '/') + 1; id = usbg_split_config_label_id(target_name, &label); if (id <= 0) { ret = id; goto out; } c = usbg_get_config(g, id, label); if (!c) { ret = USBG_ERROR_NO_MEM; goto out; } g->os_desc_binding = c; out: return ret; } static int usbg_parse_config(const char *path, const char *name, usbg_gadget *g) { int ret; char *label = NULL; usbg_config *c; ret = usbg_split_config_label_id(name, &label); if (ret <= 0) goto out; c = usbg_allocate_config(path, label, ret, g); if (!c) { ret = USBG_ERROR_NO_MEM; goto out; } ret = usbg_parse_config_bindings(c); if (ret != USBG_SUCCESS) goto free_config; TAILQ_INSERT_TAIL(&g->configs, c, cnode); goto out; free_config: usbg_free_config(c); out: free(label); return ret; } static int usbg_parse_configs(const char *path, usbg_gadget *g) { int i, n; int ret = USBG_SUCCESS; struct dirent **dent; char cpath[USBG_MAX_PATH_LENGTH]; n = snprintf(cpath, sizeof(cpath), "%s/%s/%s", path, g->name, CONFIGS_DIR); if (n >= sizeof(cpath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } n = scandir(cpath, &dent, file_select, alphasort); if (n < 0) { ret = usbg_translate_error(errno); goto out; } for (i = 0; i < n; i++) { ret = ret == USBG_SUCCESS ? usbg_parse_config(cpath, dent[i]->d_name, g) : ret; free(dent[i]); } free(dent); out: return ret; } static int usbg_parse_gadget_attrs(const char *path, const char *name, struct usbg_gadget_attrs *g_attrs) { int buf, ret; /* Actual attributes */ ret = usbg_read_hex(path, name, "bcdUSB", &buf); if (ret == USBG_SUCCESS) g_attrs->bcdUSB = (uint16_t) buf; else goto out; ret = usbg_read_hex(path, name, "bDeviceClass", &buf); if (ret == USBG_SUCCESS) g_attrs->bDeviceClass = (uint8_t)buf; else goto out; ret = usbg_read_hex(path, name, "bDeviceSubClass", &buf); if (ret == USBG_SUCCESS) g_attrs->bDeviceSubClass = (uint8_t)buf; else goto out; ret = usbg_read_hex(path, name, "bDeviceProtocol", &buf); if (ret == USBG_SUCCESS) g_attrs->bDeviceProtocol = (uint8_t) buf; else goto out; ret = usbg_read_hex(path, name, "bMaxPacketSize0", &buf); if (ret == USBG_SUCCESS) g_attrs->bMaxPacketSize0 = (uint8_t) buf; else goto out; ret = usbg_read_hex(path, name, "idVendor", &buf); if (ret == USBG_SUCCESS) g_attrs->idVendor = (uint16_t) buf; else goto out; ret = usbg_read_hex(path, name, "idProduct", &buf); if (ret == USBG_SUCCESS) g_attrs->idProduct = (uint16_t) buf; else goto out; ret = usbg_read_hex(path, name, "bcdDevice", &buf); if (ret == USBG_SUCCESS) g_attrs->bcdDevice = (uint16_t) buf; else goto out; out: return ret; } static int usbg_parse_gadget_strs(const char *path, const char *name, int lang, struct usbg_gadget_strs *g_strs) { int ret; int nmb; DIR *dir; char spath[USBG_MAX_PATH_LENGTH]; nmb = snprintf(spath, sizeof(spath), "%s/%s/%s/0x%x", path, name, STRINGS_DIR, lang); if (nmb >= sizeof(spath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } /* Check if directory exist */ dir = opendir(spath); if (!dir) { ret = usbg_translate_error(errno); goto out; } closedir(dir); g_strs->manufacturer = g_strs->product = g_strs->serial = NULL; ret = usbg_read_string_alloc(spath, "", "manufacturer", &g_strs->manufacturer); if (ret != USBG_SUCCESS) goto out; ret = usbg_read_string_alloc(spath, "", "product", &g_strs->product); if (ret != USBG_SUCCESS) goto free_mnf; ret = usbg_read_string_alloc(spath, "", "serialnumber", &g_strs->serial); if (ret != USBG_SUCCESS) goto free_product; return ret; free_product: free(g_strs->product); free_mnf: free(g_strs->manufacturer); out: return ret; } static int usbg_parse_gadget_os_descs(const char *path, const char *name, struct usbg_gadget_os_descs *g_os_descs) { int ret; int nmb; char spath[USBG_MAX_PATH_LENGTH]; int val; nmb = snprintf(spath, sizeof(spath), "%s/%s/%s", path, name, OS_DESC_DIR); if (nmb >= sizeof(spath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } ret = usbg_read_string_alloc(spath, "", "qw_sign", &g_os_descs->qw_sign); if (ret != USBG_SUCCESS) goto out; ret = usbg_read_hex(spath, "", "b_vendor_code", &val); if (ret != USBG_SUCCESS) goto out; g_os_descs->b_vendor_code = (unsigned char)val; ret = usbg_read_int(spath, "", "use", 10, &val); if (ret != USBG_SUCCESS) goto out; g_os_descs->use = val ? true : false; out: return ret; } static inline int usbg_parse_gadget(usbg_gadget *g) { int ret; char buf[USBG_MAX_STR_LENGTH]; /* UDC bound to, if any */ ret = usbg_read_string(g->path, g->name, "UDC", buf); if (ret != USBG_SUCCESS) goto out; g->udc = usbg_get_udc(g->parent, buf); if (g->udc) g->udc->gadget = g; ret = usbg_parse_functions(g->path, g); if (ret != USBG_SUCCESS) goto out; ret = usbg_parse_configs(g->path, g); if (ret != USBG_SUCCESS) goto out; ret = usbg_parse_gadget_os_desc_binding(g); out: return ret; } static int usbg_parse_gadgets(const char *path, usbg_state *s) { usbg_gadget *g; int i, n; int ret = USBG_SUCCESS; struct dirent **dent; n = scandir(path, &dent, file_select, alphasort); if (n < 0) { ret = usbg_translate_error(errno); goto out; } for (i = 0; i < n; i++) { /* Check if earlier gadgets * has been created correctly */ if (ret == USBG_SUCCESS) { /* Create new gadget and insert it into list */ g = usbg_allocate_gadget(path, dent[i]->d_name, s); if (g) { ret = usbg_parse_gadget(g); if (ret == USBG_SUCCESS) TAILQ_INSERT_TAIL(&s->gadgets, g, gnode); else usbg_free_gadget(g); } else { ret = USBG_ERROR_NO_MEM; } } free(dent[i]); } free(dent); out: return ret; } static int usbg_parse_udcs(usbg_state *s) { usbg_udc *u; int n, i; int ret = USBG_SUCCESS; struct dirent **dent; n = scandir("/sys/class/udc", &dent, file_select, alphasort); if (n < 0) { ret = usbg_translate_error(errno); goto out; } for (i = 0; i < n; ++i) { if (ret == USBG_SUCCESS) { u = usbg_allocate_udc(s, dent[i]->d_name); if (u) TAILQ_INSERT_TAIL(&s->udcs, u, unode); else ret = USBG_ERROR_NO_MEM; } free(dent[i]); } free(dent); out: return ret; } static usbg_state *usbg_allocate_state(const char *configfs_path, char *path) { usbg_state *s; s = malloc(sizeof(*s)); if (!s) goto err; s->configfs_path = strdup(configfs_path); if (!s->configfs_path) goto cpath_failed; /* State takes the ownership of path and should free it */ s->path = path; s->last_failed_import = NULL; TAILQ_INIT(&s->gadgets); TAILQ_INIT(&s->udcs); return s; cpath_failed: free(s); err: return NULL; } static int usbg_parse_state(usbg_state *s) { int ret; /* * USBG_ERROR_NOT_FOUND is returned if we are running on machine where * there is no udc support in kernel (no /sys/class/udc dir). * This check allows to run library on such machine or if we don't * have rights to read this directory. * User will be able to finish init function and manage gadgets but * wont be able to bind it as there is no UDC. */ ret = usbg_parse_udcs(s); if (ret != USBG_SUCCESS && ret != USBG_ERROR_NOT_FOUND && ret != USBG_ERROR_NO_ACCESS) { ERROR("Unable to parse udcs"); goto out; } ret = usbg_parse_gadgets(s->path, s); if (ret != USBG_SUCCESS) ERROR("unable to parse %s\n", s->path); out: return ret; } /* * User API */ int usbg_init(const char *configfs_path, usbg_state **state) { int ret; DIR *dir; char *path; usbg_state *s; ret = asprintf(&path, "%s/" GADGETS_DIR, configfs_path); if (ret < 0) return USBG_ERROR_NO_MEM; else ret = USBG_SUCCESS; /* Check if directory exist */ dir = opendir(path); if (!dir) { ERRORNO("couldn't init gadget state\n"); ret = usbg_translate_error(errno); goto err; } closedir(dir); s = usbg_allocate_state(configfs_path, path); if (!s) { ret = USBG_ERROR_NO_MEM; goto err; } ret = usbg_parse_state(s); if (ret != USBG_SUCCESS) { ERROR("couldn't init gadget state\n"); usbg_free_state(s); goto out; } *state = s; return ret; err: free(path); out: return ret; } void usbg_cleanup(usbg_state *s) { usbg_free_state(s); } const char *usbg_get_configfs_path(usbg_state *s) { return s ? s->configfs_path : NULL; } int usbg_get_configfs_path_s(usbg_state *s, char *buf, int len) { if (!s || !buf) return USBG_ERROR_INVALID_PARAM; return snprintf(buf, len, "%s", s->configfs_path); } usbg_gadget *usbg_get_gadget(usbg_state *s, const char *name) { usbg_gadget *g; TAILQ_FOREACH(g, &s->gadgets, gnode) if (!strcmp(g->name, name)) return g; return NULL; } usbg_function *usbg_get_function(usbg_gadget *g, usbg_function_type type, const char *instance) { usbg_function *f = NULL; TAILQ_FOREACH(f, &g->functions, fnode) if (f->type == type && (!strcmp(f->instance, instance))) break; return f; } usbg_config *usbg_get_config(usbg_gadget *g, int id, const char *label) { usbg_config *c = NULL; TAILQ_FOREACH(c, &g->configs, cnode) if (c->id == id && (!label || !strcmp(c->label, label))) break; return c; } usbg_udc *usbg_get_udc(usbg_state *s, const char *name) { usbg_udc *u; TAILQ_FOREACH(u, &s->udcs, unode) if (!strcmp(u->name, name)) return u; return NULL; } usbg_binding *usbg_get_binding(usbg_config *c, const char *name) { usbg_binding *b; TAILQ_FOREACH(b, &c->bindings, bnode) if (!strcmp(b->name, name)) return b; return NULL; } usbg_binding *usbg_get_link_binding(usbg_config *c, usbg_function *f) { usbg_binding *b; TAILQ_FOREACH(b, &c->bindings, bnode) if (b->target == f) return b; return NULL; } int usbg_rm_binding(usbg_binding *b) { int ret = USBG_SUCCESS; usbg_config *c; if (!b) return USBG_ERROR_INVALID_PARAM; c = b->parent; ret = usbg_rm_file(b->path, b->name); if (ret) goto out; TAILQ_REMOVE(&(c->bindings), b, bnode); usbg_free_binding(b); out: return ret; } usbg_config *usbg_get_os_desc_binding(usbg_gadget *g) { return g->os_desc_binding; } int usbg_rm_config(usbg_config *c, int opts) { int ret = USBG_ERROR_INVALID_PARAM; usbg_gadget *g; if (!c) return ret; g = c->parent; if (opts & USBG_RM_RECURSE) { /* * Recursive flag was given * so remove all bindings and strings */ char spath[USBG_MAX_PATH_LENGTH]; int nmb; usbg_binding *b; if (c->parent->os_desc_binding == c) { ret = usbg_set_os_desc_config(g, NULL); if (ret != USBG_SUCCESS) goto out; } while (!TAILQ_EMPTY(&c->bindings)) { b = TAILQ_FIRST(&c->bindings); ret = usbg_rm_binding(b); if (ret != USBG_SUCCESS) goto out; } nmb = snprintf(spath, sizeof(spath), "%s/%s/%s", c->path, c->name, STRINGS_DIR); if (nmb >= sizeof(spath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } ret = usbg_rm_all_dirs(spath); if (ret != USBG_SUCCESS) goto out; } ret = usbg_rm_dir(c->path, c->name); if (ret == USBG_SUCCESS) { TAILQ_REMOVE(&(g->configs), c, cnode); usbg_free_config(c); } out: return ret; } int usbg_rm_function(usbg_function *f, int opts) { int ret = USBG_ERROR_INVALID_PARAM; usbg_gadget *g; if (!f) return ret; g = f->parent; if (opts & USBG_RM_RECURSE) { /* Recursive flag was given * so remove all bindings to this function */ usbg_config *c; usbg_binding *b; TAILQ_FOREACH(c, &g->configs, cnode) { b = TAILQ_FIRST(&c->bindings); while (b != NULL) { if (b->target == f) { usbg_binding *b_next = TAILQ_NEXT(b, bnode); ret = usbg_rm_binding(b); if (ret != USBG_SUCCESS) return ret; b = b_next; } else { b = TAILQ_NEXT(b, bnode); } } /* while */ } /* TAILQ_FOREACH */ } if (f->ops->remove) { ret = f->ops->remove(f, opts); if (ret != USBG_SUCCESS) goto out; } ret = usbg_rm_dir(f->path, f->name); if (ret == USBG_SUCCESS) { TAILQ_REMOVE(&(g->functions), f, fnode); usbg_free_function(f); } out: return ret; } int usbg_rm_gadget(usbg_gadget *g, int opts) { int ret = USBG_ERROR_INVALID_PARAM; usbg_state *s; if (!g) goto out; s = g->parent; if (opts & USBG_RM_RECURSE) { /* Recursive flag was given * so remove all configs and functions * using recursive flags */ usbg_config *c; usbg_function *f; int nmb; char spath[USBG_MAX_PATH_LENGTH]; while (!TAILQ_EMPTY(&g->configs)) { c = TAILQ_FIRST(&g->configs); ret = usbg_rm_config(c, opts); if (ret != USBG_SUCCESS) goto out; } while (!TAILQ_EMPTY(&g->functions)) { f = TAILQ_FIRST(&g->functions); ret = usbg_rm_function(f, opts); if (ret != USBG_SUCCESS) goto out; } nmb = snprintf(spath, sizeof(spath), "%s/%s/%s", g->path, g->name, STRINGS_DIR); if (nmb >= sizeof(spath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } ret = usbg_rm_all_dirs(spath); if (ret != USBG_SUCCESS) goto out; } ret = usbg_rm_dir(g->path, g->name); if (ret == USBG_SUCCESS) { TAILQ_REMOVE(&(s->gadgets), g, gnode); usbg_free_gadget(g); } out: return ret; } int usbg_rm_config_strs(usbg_config *c, int lang) { int ret = USBG_SUCCESS; int nmb; char path[USBG_MAX_PATH_LENGTH]; if (!c) return USBG_ERROR_INVALID_PARAM; nmb = snprintf(path, sizeof(path), "%s/%s/%s/0x%x", c->path, c->name, STRINGS_DIR, lang); if (nmb < sizeof(path)) ret = usbg_rm_dir(path, ""); else ret = USBG_ERROR_PATH_TOO_LONG; return ret; } int usbg_rm_gadget_strs(usbg_gadget *g, int lang) { int ret = USBG_SUCCESS; int nmb; char path[USBG_MAX_PATH_LENGTH]; if (!g) return USBG_ERROR_INVALID_PARAM; nmb = snprintf(path, sizeof(path), "%s/%s/%s/0x%x", g->path, g->name, STRINGS_DIR, lang); if (nmb < sizeof(path)) ret = usbg_rm_dir(path, ""); else ret = USBG_ERROR_PATH_TOO_LONG; return ret; } static int usbg_create_empty_gadget(usbg_state *s, const char *name, usbg_gadget **g) { char gpath[USBG_MAX_PATH_LENGTH]; char buf[USBG_MAX_STR_LENGTH]; int nmb; usbg_gadget *gad; int ret = USBG_SUCCESS; nmb = snprintf(gpath, sizeof(gpath), "%s/%s", s->path, name); if (nmb >= sizeof(gpath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } *g = usbg_allocate_gadget(s->path, name, s); if (!*g) { ret = USBG_ERROR_NO_MEM; goto out; } gad = *g; /* alias only */ ret = mkdir(gpath, S_IRWXU|S_IRWXG|S_IRWXO); if (ret != 0) { ret = usbg_translate_error(errno); goto free_gadget; } /* Should be empty but read the default */ ret = usbg_read_string(gad->path, gad->name, "UDC", buf); if (ret != USBG_SUCCESS) goto rm_gdir; gad->udc = usbg_get_udc(s, buf); if (gad->udc) gad->udc->gadget = gad; return 0; rm_gdir: rmdir(gpath); free_gadget: usbg_free_gadget(*g); *g = NULL; out: return ret; } int usbg_create_gadget_vid_pid(usbg_state *s, const char *name, uint16_t idVendor, uint16_t idProduct, usbg_gadget **g) { int ret; usbg_gadget *gad; if (!s || !g) return USBG_ERROR_INVALID_PARAM; gad = usbg_get_gadget(s, name); if (gad) { ERROR("duplicate gadget name\n"); return USBG_ERROR_EXIST; } ret = usbg_create_empty_gadget(s, name, g); gad = *g; if (ret != USBG_SUCCESS) goto out; ret = usbg_write_hex16(s->path, name, "idVendor", idVendor); if (ret != USBG_SUCCESS) goto rm_gadget; ret = usbg_write_hex16(s->path, name, "idProduct", idProduct); if (ret != USBG_SUCCESS) goto rm_gadget; INSERT_TAILQ_STRING_ORDER(&s->gadgets, ghead, name, gad, gnode); return 0; rm_gadget: usbg_rm_dir(gad->path, gad->name); usbg_free_gadget(gad); out: return ret; } int usbg_create_gadget(usbg_state *s, const char *name, const struct usbg_gadget_attrs *g_attrs, const struct usbg_gadget_strs *g_strs, usbg_gadget **g) { usbg_gadget *gad; int ret; if (!s || !g) return USBG_ERROR_INVALID_PARAM; gad = usbg_get_gadget(s, name); if (gad) { ERROR("duplicate gadget name\n"); return USBG_ERROR_EXIST; } ret = usbg_create_empty_gadget(s, name, g); gad = *g; /* Check if gadget creation was successful and set attrs and strings */ if (ret != USBG_SUCCESS) goto out; if (g_attrs) { ret = usbg_set_gadget_attrs(gad, g_attrs); if (ret != USBG_SUCCESS) goto rm_gadget; } if (g_strs) { ret = usbg_set_gadget_strs(gad, LANG_US_ENG, g_strs); if (ret != USBG_SUCCESS) goto rm_gadget; } INSERT_TAILQ_STRING_ORDER(&s->gadgets, ghead, name, gad, gnode); return 0; rm_gadget: usbg_rm_dir(gad->path, gad->name); usbg_free_gadget(gad); out: return ret; } int usbg_get_gadget_attrs(usbg_gadget *g, struct usbg_gadget_attrs *g_attrs) { return g && g_attrs ? usbg_parse_gadget_attrs(g->path, g->name, g_attrs) : USBG_ERROR_INVALID_PARAM; } const char *usbg_get_gadget_name(usbg_gadget *g) { return g ? g->name : NULL; } int usbg_get_gadget_name_s(usbg_gadget *g, char *buf, int len) { if (!g || !buf) return USBG_ERROR_INVALID_PARAM; return snprintf(buf, len, "%s", g->name); } const char *usbg_get_udc_name(usbg_udc *u) { return u ? u->name : NULL; } int usbg_get_udc_name_s(usbg_udc *u, char *buf, int len) { if (!u || !buf) return USBG_ERROR_INVALID_PARAM; return snprintf(buf, len, "%s", u->name); } int usbg_set_gadget_attr(usbg_gadget *g, usbg_gadget_attr attr, int val) { const char *attr_name; int ret = USBG_ERROR_INVALID_PARAM; if (!g) goto out; attr_name = usbg_get_gadget_attr_str(attr); if (!attr_name) goto out; ret = usbg_write_hex(g->path, g->name, attr_name, val); out: return ret; } int usbg_get_gadget_attr(usbg_gadget *g, usbg_gadget_attr attr) { const char *attr_name; int ret = USBG_ERROR_INVALID_PARAM; if (!g) goto out; attr_name = usbg_get_gadget_attr_str(attr); if (!attr_name) goto out; usbg_read_hex(g->path, g->name, attr_name, &ret); out: return ret; } usbg_udc *usbg_get_gadget_udc(usbg_gadget *g) { usbg_udc *u = NULL; char buf[USBG_MAX_STR_LENGTH]; int ret; if (!g || !g->udc) goto out; /* * if gadget was enabled we have to check if kernel * didn't modify the UDC file due to some errors. * For example some FFS daemon could just get * a segmentation fault or sth */ ret = usbg_read_string(g->path, g->name, "UDC", buf); if (ret != USBG_SUCCESS) goto out; if (!strcmp(g->udc->name, buf)) { /* Gadget is still assigned to this UDC */ u = g->udc; } else { /* Kernel decided to detach this gadget */ g->udc->gadget = NULL; g->udc = NULL; } out: return u; } usbg_gadget *usbg_get_udc_gadget(usbg_udc *u) { usbg_gadget *g = NULL; usbg_udc *u_checked; if (!u || !u->gadget) goto out; /* * if gadget was enabled on this UDC we have to check if kernel * didn't modify this due to some errors. * For example some FFS daemon could just get a segmentation fault * what causes detach of gadget */ u_checked = usbg_get_gadget_udc(u->gadget); if (u_checked) { g = u->gadget; } else { u->gadget->udc = NULL; u->gadget = NULL; } out: return g; } int usbg_set_gadget_attrs(usbg_gadget *g, const struct usbg_gadget_attrs *g_attrs) { int ret; if (!g || !g_attrs) return USBG_ERROR_INVALID_PARAM; ret = usbg_write_hex16(g->path, g->name, "bcdUSB", g_attrs->bcdUSB); if (ret != USBG_SUCCESS) goto out; ret = usbg_write_hex8(g->path, g->name, "bDeviceClass", g_attrs->bDeviceClass); if (ret != USBG_SUCCESS) goto out; ret = usbg_write_hex8(g->path, g->name, "bDeviceSubClass", g_attrs->bDeviceSubClass); if (ret != USBG_SUCCESS) goto out; ret = usbg_write_hex8(g->path, g->name, "bDeviceProtocol", g_attrs->bDeviceProtocol); if (ret != USBG_SUCCESS) goto out; ret = usbg_write_hex8(g->path, g->name, "bMaxPacketSize0", g_attrs->bMaxPacketSize0); if (ret != USBG_SUCCESS) goto out; ret = usbg_write_hex16(g->path, g->name, "idVendor", g_attrs->idVendor); if (ret != USBG_SUCCESS) goto out; ret = usbg_write_hex16(g->path, g->name, "idProduct", g_attrs->idProduct); if (ret != USBG_SUCCESS) goto out; ret = usbg_write_hex16(g->path, g->name, "bcdDevice", g_attrs->bcdDevice); out: return ret; } int usbg_set_gadget_vendor_id(usbg_gadget *g, uint16_t idVendor) { return g ? usbg_write_hex16(g->path, g->name, "idVendor", idVendor) : USBG_ERROR_INVALID_PARAM; } int usbg_set_gadget_product_id(usbg_gadget *g, uint16_t idProduct) { return g ? usbg_write_hex16(g->path, g->name, "idProduct", idProduct) : USBG_ERROR_INVALID_PARAM; } int usbg_set_gadget_device_class(usbg_gadget *g, uint8_t bDeviceClass) { return g ? usbg_write_hex8(g->path, g->name, "bDeviceClass", bDeviceClass) : USBG_ERROR_INVALID_PARAM; } int usbg_set_gadget_device_protocol(usbg_gadget *g, uint8_t bDeviceProtocol) { return g ? usbg_write_hex8(g->path, g->name, "bDeviceProtocol", bDeviceProtocol) : USBG_ERROR_INVALID_PARAM; } int usbg_set_gadget_device_subclass(usbg_gadget *g, uint8_t bDeviceSubClass) { return g ? usbg_write_hex8(g->path, g->name, "bDeviceSubClass", bDeviceSubClass) : USBG_ERROR_INVALID_PARAM; } int usbg_set_gadget_device_max_packet(usbg_gadget *g, uint8_t bMaxPacketSize0) { return g ? usbg_write_hex8(g->path, g->name, "bMaxPacketSize0", bMaxPacketSize0) : USBG_ERROR_INVALID_PARAM; } int usbg_set_gadget_device_bcd_device(usbg_gadget *g, uint16_t bcdDevice) { return g ? usbg_write_hex16(g->path, g->name, "bcdDevice", bcdDevice) : USBG_ERROR_INVALID_PARAM; } int usbg_set_gadget_device_bcd_usb(usbg_gadget *g, uint16_t bcdUSB) { return g ? usbg_write_hex16(g->path, g->name, "bcdUSB", bcdUSB) : USBG_ERROR_INVALID_PARAM; } int usbg_get_gadget_strs(usbg_gadget *g, int lang, struct usbg_gadget_strs *g_strs) { return g && g_strs ? usbg_parse_gadget_strs(g->path, g->name, lang, g_strs) : USBG_ERROR_INVALID_PARAM; } static int usbg_get_strs_langs_by_path(const char *epath, const char *name, int **langs) { int i, n; struct dirent **dent; char spath[USBG_MAX_PATH_LENGTH]; int *buf; int ret = USBG_SUCCESS; n = snprintf(spath, sizeof(spath), "%s/%s/%s", epath, name, STRINGS_DIR); if (n >= sizeof(spath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } n = scandir(spath, &dent, file_select, alphasort); if (n < 0) { ret = usbg_translate_error(errno); goto out; } buf = calloc(n + 1, sizeof(*buf)); if (buf) /* Keep the buffer 0 terminated */ buf[n] = 0; else ret = USBG_ERROR_NO_MEM; for (i = 0; i < n; i++) { if (ret == USBG_SUCCESS) { char *pos; unsigned long int res; res = strtoul(dent[i]->d_name, &pos, 16); if (*pos == '\0' && res < 65535) buf[i] = (int)res; else ret = USBG_ERROR_OTHER_ERROR; } free(dent[i]); } free(dent); if (ret == USBG_SUCCESS) *langs = buf; else free(buf); out: return ret; } int usbg_get_gadget_strs_langs(usbg_gadget *g, int **langs) { return usbg_get_strs_langs_by_path(g->path, g->name, langs); } int usbg_get_config_strs_langs(usbg_config *c, int **langs) { return usbg_get_strs_langs_by_path(c->path, c->name, langs); } int usbg_set_gadget_str(usbg_gadget *g, usbg_gadget_str str, int lang, const char *val) { const char *str_name; int ret = USBG_ERROR_INVALID_PARAM; char path[USBG_MAX_PATH_LENGTH]; int nmb; if (!g) goto out; str_name = usbg_get_gadget_str_name(str); if (!str_name) goto out; nmb = snprintf(path, sizeof(path), "%s/%s/%s/0x%x", g->path, g->name, STRINGS_DIR, lang); if (nmb >= sizeof(path)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } ret = usbg_check_dir(path); if (ret != USBG_SUCCESS) goto out; ret = usbg_write_string(path, "", str_name, val); out: return ret; } int usbg_set_gadget_strs(usbg_gadget *g, int lang, const struct usbg_gadget_strs *g_strs) { char path[USBG_MAX_PATH_LENGTH]; int nmb; int ret = USBG_ERROR_INVALID_PARAM; if (!g || !g_strs) goto out; nmb = snprintf(path, sizeof(path), "%s/%s/%s/0x%x", g->path, g->name, STRINGS_DIR, lang); if (nmb >= sizeof(path)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } ret = usbg_check_dir(path); if (ret != USBG_SUCCESS) goto out; #define SET_GADGET_STR(file, field) \ if (g_strs->field) { \ ret = usbg_write_string(path, "", #file, \ g_strs->field); \ if (ret != USBG_SUCCESS) \ goto out; \ } SET_GADGET_STR(manufacturer, manufacturer); SET_GADGET_STR(product, product); SET_GADGET_STR(serialnumber, serial); #undef SET_GADGET_STR out: return ret; } int usbg_set_gadget_serial_number(usbg_gadget *g, int lang, const char *serno) { char path[USBG_MAX_PATH_LENGTH]; int nmb; int ret = USBG_ERROR_INVALID_PARAM; if (!g || !serno) goto out; nmb = snprintf(path, sizeof(path), "%s/%s/%s/0x%x", g->path, g->name, STRINGS_DIR, lang); if (nmb >= sizeof(path)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } ret = usbg_check_dir(path); if (ret == USBG_SUCCESS) ret = usbg_write_string(path, "", "serialnumber", serno); out: return ret; } int usbg_set_gadget_manufacturer(usbg_gadget *g, int lang, const char *mnf) { char path[USBG_MAX_PATH_LENGTH]; int nmb; int ret = USBG_ERROR_INVALID_PARAM; if (!g || !mnf) goto out; nmb = snprintf(path, sizeof(path), "%s/%s/%s/0x%x", g->path, g->name, STRINGS_DIR, lang); if (nmb >= sizeof(path)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } ret = usbg_check_dir(path); if (ret == USBG_SUCCESS) ret = usbg_write_string(path, "", "manufacturer", mnf); out: return ret; } int usbg_set_gadget_product(usbg_gadget *g, int lang, const char *prd) { char path[USBG_MAX_PATH_LENGTH]; int nmb; int ret = USBG_ERROR_INVALID_PARAM; if (!g || !prd) goto out; nmb = snprintf(path, sizeof(path), "%s/%s/%s/0x%x", g->path, g->name, STRINGS_DIR, lang); if (nmb >= sizeof(path)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } ret = usbg_check_dir(path); if (ret == USBG_SUCCESS) ret = usbg_write_string(path, "", "product", prd); out: return ret; } int usbg_get_gadget_os_descs(usbg_gadget *g, struct usbg_gadget_os_descs *g_os_descs) { return g && g_os_descs ? usbg_parse_gadget_os_descs(g->path, g->name, g_os_descs) : USBG_ERROR_INVALID_PARAM; } int usbg_set_gadget_os_descs(usbg_gadget *g, const struct usbg_gadget_os_descs *g_os_descs) { int ret; int nmb; char spath[USBG_MAX_PATH_LENGTH]; nmb = snprintf(spath, sizeof(spath), "%s/%s/%s", g->path, g->name, OS_DESC_DIR); if (nmb >= sizeof(spath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } ret = usbg_check_dir(spath); if (ret != USBG_SUCCESS) goto out; ret = usbg_write_string(spath, "", "qw_sign", g_os_descs->qw_sign); if (ret != USBG_SUCCESS) goto out; ret = usbg_write_hex8(spath, "", "b_vendor_code", g_os_descs->b_vendor_code); if (ret != USBG_SUCCESS) goto out; ret = usbg_write_dec(spath, "", "use", g_os_descs->use); if (ret != USBG_SUCCESS) goto out; out: return ret; } int usbg_create_function(usbg_gadget *g, usbg_function_type type, const char *instance, void *f_attrs, usbg_function **f) { char fpath[USBG_MAX_PATH_LENGTH]; usbg_function *func; int ret = USBG_ERROR_INVALID_PARAM; int n, free_space; if (!g || !f || !instance || *instance == '\0') return ret; func = usbg_get_function(g, type, instance); if (func) { ERROR("duplicate function name\n"); ret = USBG_ERROR_EXIST; goto out; } n = snprintf(fpath, sizeof(fpath), "%s/%s/%s", g->path, g->name, FUNCTIONS_DIR); if (n >= sizeof(fpath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } *f = usbg_allocate_function(fpath, type, instance, g); func = *f; if (!func) { ERROR("allocating function\n"); ret = USBG_ERROR_NO_MEM; goto out; } free_space = sizeof(fpath) - n; n = snprintf(&(fpath[n]), free_space, "/%s", func->name); if (n >= free_space) { ret = USBG_ERROR_PATH_TOO_LONG; goto free_func; } ret = mkdir(fpath, S_IRWXU | S_IRWXG | S_IRWXO); if (ret) { ret = usbg_translate_error(errno); goto free_func; } if (f_attrs) { ret = usbg_set_function_attrs(func, f_attrs); if (ret != USBG_SUCCESS) goto remove_dir; } INSERT_TAILQ_STRING_ORDER(&g->functions, fhead, name, func, fnode); return USBG_SUCCESS; remove_dir: usbg_rm_dir(fpath, ""); free_func: usbg_free_function(func); out: return ret; } int usbg_get_interf_os_desc(usbg_function *f, const char *iname, struct usbg_function_os_desc *f_os_desc) { int ret = USBG_ERROR_NOT_SUPPORTED; int nmb; char spath[USBG_MAX_PATH_LENGTH]; if (!iname) return ret; nmb = snprintf(spath, sizeof(spath), "%s/%s/%s/interface.%s", f->path, f->name, OS_DESC_DIR, iname); if (nmb >= sizeof(spath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } ret = usbg_read_string_alloc(spath, "", "compatible_id", &f_os_desc->compatible_id); if (ret < 0) goto out; ret = usbg_read_string_alloc(spath, "", "sub_compatible_id", &f_os_desc->sub_compatible_id); if (ret < 0) goto free_compatible; return ret; free_compatible: free(f_os_desc->compatible_id); out: return ret; } int usbg_set_interf_os_desc(usbg_function *f, const char *iname, const struct usbg_function_os_desc *f_os_desc) { int ret = USBG_ERROR_NOT_SUPPORTED; int nmb; char spath[USBG_MAX_PATH_LENGTH]; if (!iname) return ret; nmb = snprintf(spath, sizeof(spath), "%s/%s/%s/interface.%s", f->path, f->name, OS_DESC_DIR, iname); if (nmb >= sizeof(spath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } ret = usbg_write_string(spath, "", "compatible_id", f_os_desc->compatible_id); if (ret < 0) return ret; ret = usbg_write_string(spath, "", "sub_compatible_id", f_os_desc->sub_compatible_id); out: return ret; } int usbg_create_config(usbg_gadget *g, int id, const char *label, const struct usbg_config_attrs *c_attrs, const struct usbg_config_strs *c_strs, usbg_config **c) { char cpath[USBG_MAX_PATH_LENGTH]; usbg_config *conf = NULL; int ret = USBG_ERROR_INVALID_PARAM; int n, free_space; if (!g || !c || id <= 0 || id > 255) goto out; if (!label) label = DEFAULT_CONFIG_LABEL; conf = usbg_get_config(g, id, NULL); if (conf) { ERROR("duplicate configuration id\n"); ret = USBG_ERROR_EXIST; goto out; } n = snprintf(cpath, sizeof(cpath), "%s/%s/%s", g->path, g->name, CONFIGS_DIR); if (n >= sizeof(cpath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } *c = usbg_allocate_config(cpath, label, id, g); conf = *c; if (!conf) { ERROR("allocating configuration\n"); ret = USBG_ERROR_NO_MEM; goto out; } free_space = sizeof(cpath) - n; /* Append string at the end of previous one */ n = snprintf(&(cpath[n]), free_space, "/%s", (*c)->name); if (n >= free_space) { ret = USBG_ERROR_PATH_TOO_LONG; usbg_free_config(conf); goto out; } ret = mkdir(cpath, S_IRWXU | S_IRWXG | S_IRWXO); if (ret) { ret = usbg_translate_error(errno); goto free_config; } if (c_attrs) { ret = usbg_set_config_attrs(conf, c_attrs); if (ret != USBG_SUCCESS) goto rm_config; } if (c_strs) { ret = usbg_set_config_string(conf, LANG_US_ENG, c_strs->configuration); if (ret != USBG_SUCCESS) goto rm_config; } INSERT_TAILQ_STRING_ORDER(&g->configs, chead, name, conf, cnode); return 0; rm_config: rmdir(cpath); free_config: usbg_free_config(conf); out: return ret; } const char *usbg_get_config_label(usbg_config *c) { return c ? c->label : NULL; } int usbg_get_config_label_s(usbg_config *c, char *buf, int len) { if (!c || !buf) return USBG_ERROR_INVALID_PARAM; return snprintf(buf, len, "%s", c->label); } int usbg_get_config_id(usbg_config *c) { return c ? c->id : USBG_ERROR_INVALID_PARAM; } const char *usbg_get_function_instance(usbg_function *f) { return f ? f->instance : NULL; } int usbg_get_function_instance_s(usbg_function *f, char *buf, int len) { if (!f || !buf) return USBG_ERROR_INVALID_PARAM; return snprintf(buf, len, "%s", f->instance); } int usbg_set_config_attrs(usbg_config *c, const struct usbg_config_attrs *c_attrs) { int ret = USBG_ERROR_INVALID_PARAM; if (!c || !c_attrs) goto out; ret = usbg_write_dec(c->path, c->name, "MaxPower", c_attrs->bMaxPower); if (ret != USBG_SUCCESS) goto out; ret = usbg_write_hex8(c->path, c->name, "bmAttributes", c_attrs->bmAttributes); if (ret != USBG_SUCCESS) goto out; out: return ret; } int usbg_get_config_attrs(usbg_config *c, struct usbg_config_attrs *c_attrs) { return c && c_attrs ? usbg_parse_config_attrs(c->path, c->name, c_attrs) : USBG_ERROR_INVALID_PARAM; } int usbg_set_config_max_power(usbg_config *c, int bMaxPower) { return c ? usbg_write_dec(c->path, c->name, "MaxPower", bMaxPower) : USBG_ERROR_INVALID_PARAM; } int usbg_set_config_bm_attrs(usbg_config *c, int bmAttributes) { return c ? usbg_write_hex8(c->path, c->name, "bmAttributes", bmAttributes) : USBG_ERROR_INVALID_PARAM; } int usbg_get_config_strs(usbg_config *c, int lang, struct usbg_config_strs *c_strs) { return c && c_strs ? usbg_parse_config_strs(c->path, c->name, lang, c_strs) : USBG_ERROR_INVALID_PARAM; } int usbg_set_config_strs(usbg_config *c, int lang, const struct usbg_config_strs *c_strs) { return usbg_set_config_string(c, lang, c_strs->configuration); } int usbg_set_config_string(usbg_config *c, int lang, const char *str) { char path[USBG_MAX_PATH_LENGTH]; int nmb; int ret = USBG_ERROR_INVALID_PARAM; if (!c || !str) goto out; nmb = snprintf(path, sizeof(path), "%s/%s/%s/0x%x", c->path, c->name, STRINGS_DIR, lang); if (nmb >= sizeof(path)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } ret = usbg_check_dir(path); if (ret != USBG_SUCCESS) goto out; ret = usbg_write_string(path, "", "configuration", str); out: return ret; } int usbg_add_config_function(usbg_config *c, const char *name, usbg_function *f) { char bpath[USBG_MAX_PATH_LENGTH]; char fpath[USBG_MAX_PATH_LENGTH]; usbg_binding *b; int free_space, nmb; int ret = USBG_SUCCESS; if (!c || !f) { ret = USBG_ERROR_INVALID_PARAM; goto out; } if (!name) name = f->name; b = usbg_get_binding(c, name); if (b) { ERROR("duplicate binding name\n"); ret = USBG_ERROR_EXIST; goto out; } b = usbg_get_link_binding(c, f); if (b) { ERROR("duplicate binding link\n"); ret = USBG_ERROR_EXIST; goto out; } nmb = snprintf(fpath, sizeof(fpath), "%s/%s", f->path, f->name); if (nmb >= sizeof(fpath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } nmb = snprintf(bpath, sizeof(bpath), "%s/%s", c->path, c->name); if (nmb >= sizeof(bpath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } b = usbg_allocate_binding(bpath, name, c); if (!b) { ret = USBG_ERROR_NO_MEM; goto out; } free_space = sizeof(bpath) - nmb; b->target = f; nmb = snprintf(&(bpath[nmb]), free_space, "/%s", name); if (nmb >= free_space) { ret = USBG_ERROR_PATH_TOO_LONG; goto free_binding; } ret = symlink(fpath, bpath); if (ret != 0) { ret = usbg_translate_error(errno); goto free_binding; } b->target = f; INSERT_TAILQ_STRING_ORDER(&c->bindings, bhead, name, b, bnode); return 0; free_binding: usbg_free_binding(b); out: return ret; } usbg_function *usbg_get_binding_target(usbg_binding *b) { return b ? b->target : NULL; } const char *usbg_get_binding_name(usbg_binding *b) { return b ? b->name : NULL; } int usbg_get_binding_name_s(usbg_binding *b, char *buf, int len) { if (!b || !buf) return USBG_ERROR_INVALID_PARAM; return snprintf(buf, len, "%s", b->name); } static int usbg_create_os_desc_link(usbg_gadget *g, usbg_config *c) { char bpath[USBG_MAX_PATH_LENGTH]; char cpath[USBG_MAX_PATH_LENGTH]; int nmb; int ret; nmb = snprintf(cpath, sizeof(cpath), "%s/%s", c->path, c->name); if (nmb >= sizeof(cpath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } nmb = snprintf(bpath, sizeof(bpath), "%s/%s/%s/%s", g->path, g->name, OS_DESC_DIR, c->name); if (nmb >= sizeof(bpath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } ret = symlink(cpath, bpath); if (ret != 0) { ret = usbg_translate_error(errno); goto out; } g->os_desc_binding = c; return USBG_SUCCESS; out: return ret; } static int usbg_rm_os_desc_link(usbg_gadget *g) { char bpath[USBG_MAX_PATH_LENGTH]; struct dirent **dent; int end, n, i; int ret; end = snprintf(bpath, sizeof(bpath), "%s/%s/%s", g->path, g->name, OS_DESC_DIR); if (end >= sizeof(bpath)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } n = scandir(bpath, &dent, bindings_select, alphasort); if (n < 0) { ret = usbg_translate_error(errno); goto out; } if (n < 1) { ret = USBG_ERROR_NOT_FOUND; goto free_dent; } ret = usbg_rm_file(bpath, dent[0]->d_name); for (i = 0; i < n; i++) free(dent[i]); free_dent: free(dent); out: return ret; } int usbg_set_os_desc_config(usbg_gadget *g, usbg_config *c) { int ret; if (!g) return USBG_ERROR_INVALID_PARAM; if (c) { if (g->os_desc_binding) { ERROR("os desc binding exist\n"); return USBG_ERROR_EXIST; } ret = usbg_create_os_desc_link(g, c); } else { ret = usbg_rm_os_desc_link(g); } return ret; } int usbg_enable_gadget(usbg_gadget *g, usbg_udc *udc) { int ret = USBG_ERROR_INVALID_PARAM; if (!g) return ret; if (!udc) { udc = usbg_get_first_udc(g->parent); if (!udc) return ret; } ret = usbg_write_string(g->path, g->name, "UDC", udc->name); if (ret != USBG_SUCCESS) goto out; /* If gadget has been detached and we didn't noticed * it we have to clean up now. */ if (g->udc) g->udc->gadget = NULL; g->udc = udc; udc->gadget = g; out: return ret; } int usbg_disable_gadget(usbg_gadget *g) { int ret = USBG_ERROR_INVALID_PARAM; if (!g) return ret; ret = usbg_write_string(g->path, g->name, "UDC", "\n"); if (ret != USBG_SUCCESS) goto out; if (g->udc) g->udc->gadget = NULL; g->udc = NULL; out: return ret; } /* * USB function */ usbg_function_type usbg_get_function_type(usbg_function *f) { return f ? f->type : USBG_ERROR_INVALID_PARAM; } int usbg_get_function_attrs(usbg_function *f, void *f_attrs) { return f && f_attrs ? f->ops->get_attrs(f, f_attrs) : USBG_ERROR_INVALID_PARAM; } void usbg_cleanup_function_attrs(usbg_function *f, void *f_attrs) { if (f->ops->cleanup_attrs) f->ops->cleanup_attrs(f, f_attrs); } int usbg_set_function_attrs(usbg_function *f, void *f_attrs) { int ret = USBG_ERROR_INVALID_PARAM; if (!f || !f_attrs) return ret; return f->ops->set_attrs(f, f_attrs); } usbg_gadget *usbg_get_first_gadget(usbg_state *s) { return s ? TAILQ_FIRST(&s->gadgets) : NULL; } usbg_function *usbg_get_first_function(usbg_gadget *g) { return g ? TAILQ_FIRST(&g->functions) : NULL; } usbg_config *usbg_get_first_config(usbg_gadget *g) { return g ? TAILQ_FIRST(&g->configs) : NULL; } usbg_binding *usbg_get_first_binding(usbg_config *c) { return c ? TAILQ_FIRST(&c->bindings) : NULL; } usbg_udc *usbg_get_first_udc(usbg_state *s) { return s ? TAILQ_FIRST(&s->udcs) : NULL; } usbg_gadget *usbg_get_next_gadget(usbg_gadget *g) { return g ? TAILQ_NEXT(g, gnode) : NULL; } usbg_function *usbg_get_next_function(usbg_function *f) { return f ? TAILQ_NEXT(f, fnode) : NULL; } usbg_config *usbg_get_next_config(usbg_config *c) { return c ? TAILQ_NEXT(c, cnode) : NULL; } usbg_binding *usbg_get_next_binding(usbg_binding *b) { return b ? TAILQ_NEXT(b, bnode) : NULL; } usbg_udc *usbg_get_next_udc(usbg_udc *u) { return u ? TAILQ_NEXT(u, unode) : NULL; } libusbgx-libusbgx-v0.3.0/src/usbg_common.c000066400000000000000000000215011467553526200206150ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include #include #include #include #include #include #include #include #include int usbg_write_guid(const char *path, const char *name, const char *file, const char *buf) { char guidbin[GUID_BIN_LENGTH]; int ret; if (strlen(buf) != GUID_CHAR_LENGTH) return USBG_ERROR_INVALID_PARAM; ret = sscanf(buf, "%02hhx%02hhx%02hhx%02hhx-%02hhx%02hhx-%02hhx%02hhx-%02hhx%02hhx-%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx", &guidbin[0], &guidbin[1], &guidbin[2], &guidbin[3], &guidbin[4], &guidbin[5], &guidbin[6], &guidbin[7], &guidbin[8], &guidbin[9], &guidbin[10], &guidbin[11], &guidbin[12], &guidbin[13], &guidbin[14], &guidbin[15]); if (ret != GUID_BIN_LENGTH) return USBG_ERROR_INVALID_PARAM; ret = usbg_write_buf(path, name, file, guidbin, GUID_BIN_LENGTH); if (ret > 0) ret = 0; return ret; } int usbg_read_buf_limited(const char *path, const char *name, const char *file, char *buf, int len) { char p[USBG_MAX_PATH_LENGTH]; FILE *fp; int nmb; int ret = USBG_SUCCESS; nmb = snprintf(p, sizeof(p), "%s/%s/%s", path, name, file); if (nmb >= sizeof(p)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } fp = fopen(p, "r"); if (!fp) { /* Set error correctly */ ret = usbg_translate_error(errno); goto out; } ret= (int)fread(buf, sizeof(char), len, fp); if (ret < len && ferror(fp)) ret = USBG_ERROR_IO; fclose(fp); out: return ret; } int usbg_read_buf(const char *path, const char *name, const char *file, char *buf) { return usbg_read_buf_limited(path, name, file, buf, USBG_MAX_STR_LENGTH); } int usbg_read_int(const char *path, const char *name, const char *file, int base, int *dest) { char buf[USBG_MAX_STR_LENGTH]; char *pos; int ret; ret = usbg_read_buf(path, name, file, buf); if (ret >= 0) { ret = 0; *dest = strtol(buf, &pos, base); if (!pos) ret = USBG_ERROR_OTHER_ERROR; } return ret; } int usbg_read_bool(const char *path, const char *name, const char *file, bool *dest) { int buf; int ret; ret = usbg_read_dec(path, name, file, &buf); if (ret != USBG_SUCCESS) goto out; *dest = !!buf; out: return ret; } int usbg_read_string(const char *path, const char *name, const char *file, char *buf) { return usbg_read_string_limited(path, name, file, buf, USBG_MAX_STR_LENGTH); } int usbg_read_string_limited(const char *path, const char *name, const char *file, char *buf, int len) { char *p = NULL; int ret; ret = usbg_read_buf_limited(path, name, file, buf, len); /* Check whether read was successful */ if (ret >= 0) { /* Truncate bufer if needed */ buf[ret < len - 1 ? ret : len -1] = '\0'; ret = 0; if ((p = strchr(buf, '\n')) != NULL) *p = '\0'; } else { /* Set this as empty string */ *buf = '\0'; } return ret; } int usbg_read_string_alloc(const char *path, const char *name, const char *file, char **dest) { char buf[USBG_MAX_FILE_SIZE]; char *new_buf = NULL; int ret; ret = usbg_read_string_limited(path, name, file, buf, sizeof(buf)); if (ret != USBG_SUCCESS) goto out; new_buf = strdup(buf); if (!new_buf) { ret = USBG_ERROR_NO_MEM; goto out; } *dest = new_buf; out: return ret; } int usbg_read_buf_alloc(const char *path, const char *name, const char *file, char **dest, int len) { char buf[USBG_MAX_FILE_SIZE]; char *new_buf = NULL; int ret; ret = usbg_read_buf_limited(path, name, file, buf, len); if (ret != len) goto out; ret = 0; new_buf = malloc(len); if (!new_buf) { ret = USBG_ERROR_NO_MEM; goto out; } memcpy(new_buf, buf, len); *dest = new_buf; out: return ret; } int usbg_write_buf(const char *path, const char *name, const char *file, const char *buf, int len) { char p[USBG_MAX_PATH_LENGTH]; FILE *fp; int nmb; int ret = USBG_SUCCESS; nmb = snprintf(p, sizeof(p), "%s/%s/%s", path, name, file); if (nmb >= sizeof(p)) { ret = USBG_ERROR_PATH_TOO_LONG; goto out; } fp = fopen(p, "w"); if (!fp) { /* Set error correctly */ ret = usbg_translate_error(errno); goto out; } nmb = fwrite(buf, sizeof(char), len, fp); if (nmb < len) { if (ferror(fp)) nmb = usbg_translate_error(errno); else nmb = USBG_ERROR_IO; } ret = fclose(fp); if (ret < 0) ret = usbg_translate_error(errno); else ret = nmb; out: return ret; } int usbg_write_int(const char *path, const char *name, const char *file, int value, const char *str) { char buf[USBG_MAX_STR_LENGTH]; int nmb; int ret; nmb = snprintf(buf, USBG_MAX_STR_LENGTH, str, value); if (nmb >= USBG_MAX_STR_LENGTH) return USBG_ERROR_INVALID_PARAM; ret = usbg_write_buf(path, name, file, buf, nmb); if (ret > 0) ret = 0; return ret; } int usbg_write_string(const char *path, const char *name, const char *file, const char *buf) { int ret; if (!buf) return USBG_ERROR_INVALID_PARAM; ret = usbg_write_buf(path, name, file, buf, strlen(buf)); if (ret > 0) ret = 0; return ret; } int usbg_rm_file(const char *path, const char *name) { int ret = USBG_SUCCESS; int nmb; char buf[USBG_MAX_PATH_LENGTH]; nmb = snprintf(buf, sizeof(buf), "%s/%s", path, name); if (nmb < sizeof(buf)) { nmb = unlink(buf); if (nmb != 0) ret = usbg_translate_error(errno); } else { ret = USBG_ERROR_PATH_TOO_LONG; } return ret; } int usbg_rm_dir(const char *path, const char *name) { int ret = USBG_SUCCESS; int nmb; char buf[USBG_MAX_PATH_LENGTH]; nmb = snprintf(buf, sizeof(buf), "%s/%s", path, name); if (nmb < sizeof(buf)) { nmb = rmdir(buf); if (nmb != 0) ret = usbg_translate_error(errno); } else { ret = USBG_ERROR_PATH_TOO_LONG; } return ret; } int usbg_rm_all_dirs(const char *path) { int ret = USBG_SUCCESS; int n, i; struct dirent **dent; n = scandir(path, &dent, file_select, alphasort); if (n >= 0) { for (i = 0; i < n; ++i) { if (ret == USBG_SUCCESS) ret = usbg_rm_dir(path, dent[i]->d_name); free(dent[i]); } free(dent); } else { ret = usbg_translate_error(errno); } return ret; } int usbg_check_dir(const char *path) { int ret = USBG_SUCCESS; DIR *dir; /* Assume that user will always have read access to this directory */ dir = opendir(path); if (dir) closedir(dir); else if (errno != ENOENT || mkdir(path, S_IRWXU|S_IRWXG|S_IRWXO) != 0) ret = usbg_translate_error(errno); return ret; } char *usbg_ether_ntoa_r(const struct ether_addr *addr, char *buf) { sprintf(buf, "%02x:%02x:%02x:%02x:%02x:%02x", addr->ether_addr_octet[0], addr->ether_addr_octet[1], addr->ether_addr_octet[2], addr->ether_addr_octet[3], addr->ether_addr_octet[4], addr->ether_addr_octet[5]); return buf; } int usbg_init_function(struct usbg_function *f, struct usbg_function_type *ops, usbg_function_type type, const char *type_name, const char *instance, const char *path, struct usbg_gadget *parent) { int ret; ret = asprintf(&(f->name), "%s.%s", type_name, instance); if (ret < 0) return USBG_ERROR_NO_MEM; f->instance = f->name + strlen(type_name) + 1; f->path = strdup(path); f->parent = parent; f->type = type; f->ops = ops; f->label = NULL; memset(&f->fnode, 0, sizeof(f->fnode)); return 0; } int usbg_get_ether_addr(const char *path, const char *name, const char *attr, void *val) { struct ether_addr *addr; char str_addr[USBG_MAX_STR_LENGTH]; int ret; ret = usbg_read_string_limited(path, name, attr, str_addr, sizeof(str_addr)); if (ret) return ret; addr = ether_aton_r(str_addr, val); return addr ? 0 : USBG_ERROR_IO; } int usbg_set_ether_addr(const char *path, const char *name, const char *attr, void *val) { char str_addr[USBG_MAX_STR_LENGTH]; usbg_ether_ntoa_r(val, str_addr); return usbg_write_string(path, name, attr, str_addr); } int usbg_get_dev(const char *path, const char *name, const char *attr, void *val) { int major, minor; char str_dev[USBG_MAX_STR_LENGTH]; int ret; ret = usbg_read_string_limited(path, name, attr, str_dev, sizeof(str_dev)); if (ret < 0) return ret; ret = sscanf(str_dev, "%d:%d", &major, &minor); if (ret < 2) return USBG_ERROR_INVALID_VALUE; *(dev_t *)val = makedev(major, minor); return 0; } void usbg_cleanup_function(struct usbg_function *f) { free(f->path); free(f->name); free(f->label); } libusbgx-libusbgx-v0.3.0/src/usbg_common_libconfig.c000066400000000000000000000120101467553526200226240ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include "usbg/usbg_internal_libconfig.h" int usbg_get_config_node_int(config_setting_t *root, const char *node_name, void *val) { config_setting_t *node; node = config_setting_get_member(root, node_name); if (!node) return 0; if (!usbg_config_is_int(node)) return USBG_ERROR_INVALID_TYPE; *(int *)val = config_setting_get_int(node); return 1; } int usbg_get_config_node_bool(config_setting_t *root, const char *node_name, void *val) { config_setting_t *node; bool *value = val; int ret; node = config_setting_get_member(root, node_name); if (!node) return 0; ret = config_setting_type(node); switch (ret) { case CONFIG_TYPE_INT: *value = !!config_setting_get_int(node); break; case CONFIG_TYPE_BOOL: *value = config_setting_get_bool(node); break; default: return USBG_ERROR_INVALID_TYPE; } return 0; } int usbg_get_config_node_string(config_setting_t *root, const char *node_name, void *val) { config_setting_t *node; node = config_setting_get_member(root, node_name); if (!node) return 0; if (!usbg_config_is_string(node)) return USBG_ERROR_INVALID_TYPE; *(const char **)val = config_setting_get_string(node); return 1; } int usbg_get_config_node_ether_addr(config_setting_t *root, const char *node_name, void *val) { const char *str_addr; struct ether_addr *addr; int ret; ret = usbg_get_config_node_string(root, node_name, &str_addr); /* if not found or error */ if (ret == 0 || ret < 0) return ret; addr = ether_aton_r(str_addr, val); return addr ? 1 : USBG_ERROR_INVALID_VALUE; } int usbg_set_config_node_int(config_setting_t *root, const char *node_name, void *val) { config_setting_t *node; int ret = 0; node = config_setting_add(root, node_name, CONFIG_TYPE_INT); if (!node) return USBG_ERROR_NO_MEM; ret = config_setting_set_int(node, *(int *)val); return ret == CONFIG_TRUE ? 0 : USBG_ERROR_OTHER_ERROR; } int usbg_set_config_node_int_hex(config_setting_t *root, const char *node_name, void *val) { config_setting_t *node; int ret = 0; node = config_setting_add(root, node_name, CONFIG_TYPE_INT); if (!node) return USBG_ERROR_NO_MEM; ret = config_setting_set_format(node, CONFIG_FORMAT_HEX); if (ret != CONFIG_TRUE) return USBG_ERROR_OTHER_ERROR; ret = config_setting_set_int(node, *(int *)val); return ret == CONFIG_TRUE ? 0 : USBG_ERROR_OTHER_ERROR; } int usbg_set_config_node_bool(config_setting_t *root, const char *node_name, void *val) { config_setting_t *node; int ret = 0; node = config_setting_add(root, node_name, CONFIG_TYPE_BOOL); if (!node) return USBG_ERROR_NO_MEM; ret = config_setting_set_bool(node, *(bool *)val); return ret == CONFIG_TRUE ? 0 : USBG_ERROR_OTHER_ERROR; } int usbg_set_config_node_string(config_setting_t *root, const char *node_name, void *val) { config_setting_t *node; int ret = 0; node = config_setting_add(root, node_name, CONFIG_TYPE_STRING); if (!node) return USBG_ERROR_NO_MEM; ret = config_setting_set_string(node, *(char **)val); return ret == CONFIG_TRUE ? 0 : USBG_ERROR_OTHER_ERROR; } int usbg_set_config_node_ether_addr(config_setting_t *root, const char *node_name, void *val) { char str_addr[USBG_MAX_STR_LENGTH]; char *ptr = str_addr; usbg_ether_ntoa_r(val, str_addr); return usbg_set_config_node_string(root, node_name, &ptr); } int usbg_set_config_node_dev(config_setting_t *root, const char *node_name, void *val) { dev_t *dev = (dev_t *)val; config_setting_t *node; int tmp; int ret = 0; node = config_setting_add(root, node_name, CONFIG_TYPE_GROUP); if (!node) return USBG_ERROR_NO_MEM; tmp = major(*dev); ret = usbg_set_config_node_int(node, "major", &tmp); if (ret) return ret; tmp = minor(*dev); ret = usbg_set_config_node_int(node, "minor", &tmp); return ret; } int usbg_set_config_node_guid(config_setting_t *root, const char *node_name, void *val) { const unsigned char *bin = *(unsigned char **)val; config_setting_t *node; char guid[GUID_CHAR_LENGTH + 1]; int ret = 0; node = config_setting_add(root, node_name, CONFIG_TYPE_STRING); if (!node) return USBG_ERROR_NO_MEM; snprintf(guid, GUID_CHAR_LENGTH + 1, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", bin[0], bin[1], bin[2], bin[3], bin[4], bin[5], bin[6], bin[7], bin[8], bin[9], bin[10], bin[11], bin[12], bin[13], bin[14], bin[15]); ret = config_setting_set_string(node, guid); return ret == CONFIG_TRUE ? 0 : USBG_ERROR_OTHER_ERROR; } libusbgx-libusbgx-v0.3.0/src/usbg_error.c000066400000000000000000000075331467553526200204670ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include "usbg/usbg.h" #include "usbg/usbg_internal.h" #include int usbg_translate_error(int error) { int ret; switch (error) { case ENOMEM: ret = USBG_ERROR_NO_MEM; break; case EACCES: case EROFS: case EPERM: ret = USBG_ERROR_NO_ACCESS; break; case ENOENT: case ENOTDIR: ret = USBG_ERROR_NOT_FOUND; break; case ERANGE: case EINVAL: case USBG_ERROR_INVALID_PARAM: ret = USBG_ERROR_INVALID_PARAM; break; case EIO: ret = USBG_ERROR_IO; break; case EEXIST: ret = USBG_ERROR_EXIST; break; case ENODEV: ret = USBG_ERROR_NO_DEV; break; case EBUSY: ret = USBG_ERROR_BUSY; break; case ENOTEMPTY: ret = USBG_ERROR_NOT_EMPTY; break; default: ret = USBG_ERROR_OTHER_ERROR; } return ret; } const char *usbg_error_name(usbg_error e) { char *ret = "UNKNOWN"; switch (e) { case USBG_SUCCESS: ret = "USBG_SUCCESS"; break; case USBG_ERROR_NO_MEM: ret = "USBG_ERROR_NO_MEM"; break; case USBG_ERROR_NO_ACCESS: ret = "USBG_ERROR_NO_ACCESS"; break; case USBG_ERROR_INVALID_PARAM: ret = "USBG_ERROR_INVALID_PARAM"; break; case USBG_ERROR_NOT_FOUND: ret = "USBG_ERROR_NOT_FOUND"; break; case USBG_ERROR_IO: ret = "USBG_ERROR_IO"; break; case USBG_ERROR_EXIST: ret = "USBG_ERROR_EXIST"; break; case USBG_ERROR_NO_DEV: ret = "USBG_ERROR_NO_DEV"; break; case USBG_ERROR_BUSY: ret = "USBG_ERROR_BUSY"; break; case USBG_ERROR_NOT_SUPPORTED: ret = "USBG_ERROR_NOT_SUPPORTED"; break; case USBG_ERROR_PATH_TOO_LONG: ret = "USBG_ERROR_PATH_TOO_LONG"; break; case USBG_ERROR_INVALID_FORMAT: ret = "USBG_ERROR_INVALID_FORMAT"; break; case USBG_ERROR_MISSING_TAG: ret = "USBG_ERROR_MISSING_TAG"; break; case USBG_ERROR_INVALID_TYPE: ret = "USBG_ERROR_INVALID_TYPE"; break; case USBG_ERROR_INVALID_VALUE: ret = "USBG_ERROR_INVALID_VALUE"; break; case USBG_ERROR_NOT_EMPTY: ret = "USBG_ERROR_NOT_EMPTY"; break; case USBG_ERROR_OTHER_ERROR: ret = "USBG_ERROR_OTHER_ERROR"; break; } return ret; } const char *usbg_strerror(usbg_error e) { char *ret = "Unknown error"; switch (e) { case USBG_SUCCESS: ret = "Success"; break; case USBG_ERROR_NO_MEM: ret = "Insufficient memory"; break; case USBG_ERROR_NO_ACCESS: ret = "Access denied (insufficient permissions)"; break; case USBG_ERROR_INVALID_PARAM: ret = "Invalid parameter"; break; case USBG_ERROR_NOT_FOUND: ret = "Not found (file or directory removed)"; break; case USBG_ERROR_IO: ret = "Input/output error"; break; case USBG_ERROR_EXIST: ret = "Already exist"; break; case USBG_ERROR_NO_DEV: ret = "No such device (illegal device name)"; break; case USBG_ERROR_BUSY: ret = "Busy (gadget enabled)"; break; case USBG_ERROR_NOT_SUPPORTED: ret = "Function not supported"; break; case USBG_ERROR_PATH_TOO_LONG: ret = "Created path was too long to process it."; break; case USBG_ERROR_INVALID_FORMAT: ret = "Given file has incompatible format."; break; case USBG_ERROR_MISSING_TAG: ret = "One of mandatory tags is missing."; break; case USBG_ERROR_INVALID_TYPE: ret = "One of attributes has incompatible type."; break; case USBG_ERROR_INVALID_VALUE: ret = "Incorrect value provided as attribute."; break; case USBG_ERROR_NOT_EMPTY: ret = "Entity is not empty."; break; case USBG_ERROR_OTHER_ERROR: ret = "Other error"; break; } return ret; } libusbgx-libusbgx-v0.3.0/src/usbg_schemes_libconfig.c000066400000000000000000001210061467553526200227710ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include #include #include #include #include "usbg/usbg_internal.h" #define USBG_NAME_TAG "name" #define USBG_ATTRS_TAG "attrs" #define USBG_STRINGS_TAG "strings" #define USBG_OS_DESCS_TAG "os_descs" #define USBG_FUNCTIONS_TAG "functions" #define USBG_CONFIGS_TAG "configs" #define USBG_LANG_TAG "lang" #define USBG_TYPE_TAG "type" #define USBG_INSTANCE_TAG "instance" #define USBG_ID_TAG "id" #define USBG_FUNCTION_TAG "function" #define USBG_INTERFACE_TAG "interface" #define USBG_CONFIG_ID_TAG "config_id" #define USBG_TAB_WIDTH 4 static inline int generate_function_label(usbg_function *f, char *buf, int size) { return snprintf(buf, size, "%s_%s", usbg_get_function_type_str(f->type), f->instance); } static int usbg_export_binding(usbg_binding *b, config_setting_t *root) { config_setting_t *node; int ret = USBG_ERROR_NO_MEM; int cfg_ret; char label[USBG_MAX_NAME_LENGTH]; int nmb; #define CRETAE_ATTR_STRING(SOURCE, NAME) \ do { \ node = config_setting_add(root, NAME, CONFIG_TYPE_STRING); \ if (!node) \ goto out; \ cfg_ret = config_setting_set_string(node, SOURCE); \ if (cfg_ret != CONFIG_TRUE) { \ ret = USBG_ERROR_OTHER_ERROR; \ goto out; \ } \ } while (0) CRETAE_ATTR_STRING(b->name, USBG_NAME_TAG); nmb = generate_function_label(b->target, label, sizeof(label)); if (nmb >= sizeof(label)) { ret = USBG_ERROR_OTHER_ERROR; goto out; } CRETAE_ATTR_STRING(label, USBG_FUNCTION_TAG); #undef CRETAE_ATTR_STRING ret = USBG_SUCCESS; out: return ret; } static int usbg_export_config_bindings(usbg_config *c, config_setting_t *root) { usbg_binding *b; config_setting_t *node; int ret = USBG_SUCCESS; TAILQ_FOREACH(b, &c->bindings, bnode) { node = config_setting_add(root, NULL, CONFIG_TYPE_GROUP); if (!node) { ret = USBG_ERROR_NO_MEM; break; } ret = usbg_export_binding(b, node); if (ret != USBG_SUCCESS) break; } return ret; } static int usbg_export_config_strs_lang(usbg_config *c, int lang, config_setting_t *root) { config_setting_t *node; struct usbg_config_strs strs; int usbg_ret, cfg_ret; int ret = USBG_ERROR_NO_MEM; usbg_ret = usbg_get_config_strs(c, lang, &strs); if (usbg_ret != USBG_SUCCESS) { ret = usbg_ret; goto out; } node = config_setting_add(root, USBG_LANG_TAG, CONFIG_TYPE_INT); if (!node) goto out; cfg_ret = config_setting_set_format(node, CONFIG_FORMAT_HEX); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; goto out; } cfg_ret = config_setting_set_int(node, lang); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; goto out; } node = config_setting_add(root, "configuration" , CONFIG_TYPE_STRING); if (!node) goto out; cfg_ret = config_setting_set_string(node, strs.configuration); usbg_free_config_strs(&strs); ret = cfg_ret == CONFIG_TRUE ? USBG_SUCCESS : USBG_ERROR_OTHER_ERROR; out: return ret; } static int usbg_export_config_strings(usbg_config *c, config_setting_t *root) { config_setting_t *node; int usbg_ret = USBG_SUCCESS; int i; int *langs; usbg_ret = usbg_get_config_strs_langs(c, &langs); if (usbg_ret != USBG_SUCCESS) goto out; for (i = 0; langs[i]; ++i) { node = config_setting_add(root, NULL, CONFIG_TYPE_GROUP); if (!node) { usbg_ret = USBG_ERROR_NO_MEM; break; } usbg_ret = usbg_export_config_strs_lang(c, langs[i], node); if (usbg_ret != USBG_SUCCESS) break; } free(langs); out: return usbg_ret; } static int usbg_export_config_attrs(usbg_config *c, config_setting_t *root) { config_setting_t *node; struct usbg_config_attrs attrs; int usbg_ret, cfg_ret; int ret = USBG_ERROR_NO_MEM; usbg_ret = usbg_get_config_attrs(c, &attrs); if (usbg_ret) { ret = usbg_ret; goto out; } #define ADD_CONFIG_ATTR(attr_name) \ do { \ node = config_setting_add(root, #attr_name, CONFIG_TYPE_INT); \ if (!node) \ goto out; \ cfg_ret = config_setting_set_format(node, CONFIG_FORMAT_HEX); \ if (cfg_ret != CONFIG_TRUE) { \ ret = USBG_ERROR_OTHER_ERROR; \ goto out; \ } \ cfg_ret = config_setting_set_int(node, attrs.attr_name); \ if (cfg_ret != CONFIG_TRUE) { \ ret = USBG_ERROR_OTHER_ERROR; \ goto out; \ } \ } while (0) ADD_CONFIG_ATTR(bmAttributes); ADD_CONFIG_ATTR(bMaxPower); #undef ADD_CONFIG_ATTR ret = USBG_SUCCESS; out: return ret; } /* This function does not export configuration id because it is more of * a property of gadget which contains this config than config itself */ static int usbg_export_config_prep(usbg_config *c, config_setting_t *root) { config_setting_t *node; int ret = USBG_ERROR_NO_MEM; int usbg_ret; int cfg_ret; node = config_setting_add(root, USBG_NAME_TAG, CONFIG_TYPE_STRING); if (!node) goto out; cfg_ret = config_setting_set_string(node, c->label); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; goto out; } node = config_setting_add(root, USBG_ATTRS_TAG, CONFIG_TYPE_GROUP); if (!node) goto out; usbg_ret = usbg_export_config_attrs(c, node); if (usbg_ret != USBG_SUCCESS) { ret = usbg_ret; goto out; } node = config_setting_add(root, USBG_STRINGS_TAG, CONFIG_TYPE_LIST); if (!node) goto out; usbg_ret = usbg_export_config_strings(c, node); if (usbg_ret != USBG_SUCCESS) { ret = usbg_ret; goto out; } node = config_setting_add(root, USBG_FUNCTIONS_TAG, CONFIG_TYPE_LIST); if (!node) goto out; ret = usbg_export_config_bindings(c, node); out: return ret; } static int usbg_export_gadget_configs(usbg_gadget *g, config_setting_t *root) { usbg_config *c; config_setting_t *node, *id_node; int ret = USBG_SUCCESS; int cfg_ret; TAILQ_FOREACH(c, &g->configs, cnode) { node = config_setting_add(root, NULL, CONFIG_TYPE_GROUP); if (!node) { ret = USBG_ERROR_NO_MEM; break; } id_node = config_setting_add(node, USBG_ID_TAG, CONFIG_TYPE_INT); if (!id_node) { ret = USBG_ERROR_NO_MEM; break; } cfg_ret = config_setting_set_int(id_node, c->id); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; break; } ret = usbg_export_config_prep(c, node); if (ret != USBG_SUCCESS) break; } return ret; } static int usbg_export_function_attrs(usbg_function *f, config_setting_t *root) { int ret = USBG_ERROR_NOT_SUPPORTED; if (!f->ops->export) goto out; ret = f->ops->export(f, root); out: return ret; } static int usbg_set_config_node_os_desc(config_setting_t *root, const char *iname, struct usbg_function_os_desc *f_os_desc) { config_setting_t *groot; config_setting_t *node; int cfg_ret; int ret; groot = config_setting_add(root, NULL, CONFIG_TYPE_GROUP); if (!groot) return USBG_ERROR_NO_MEM; node = config_setting_add(groot, USBG_INTERFACE_TAG, CONFIG_TYPE_STRING); if (!node) return USBG_ERROR_NO_MEM; cfg_ret = config_setting_set_string(node, iname); if (cfg_ret != CONFIG_TRUE) return USBG_ERROR_OTHER_ERROR; if (f_os_desc->compatible_id) { ret = usbg_set_config_node_string(groot, "compatible_id", &f_os_desc->compatible_id); if (ret < 0) return ret; } if (f_os_desc->sub_compatible_id) { ret = usbg_set_config_node_string(groot, "sub_compatible_id", &f_os_desc->sub_compatible_id); if (ret < 0) return ret; } return USBG_SUCCESS; } static int usbg_export_function_os_descs(usbg_function *f, config_setting_t *root) { int ret = 0; struct usbg_function_os_desc f_os_desc; char **iname = f->ops->os_desc_iname; while (iname && *iname) { memset(&f_os_desc, 0, sizeof(f_os_desc)); ret = usbg_get_interf_os_desc(f, *iname, &f_os_desc); if (ret) break; ret = usbg_set_config_node_os_desc(root, *iname, &f_os_desc); usbg_free_interf_os_desc(&f_os_desc); if (ret < 0) break; ++iname; } return ret; } /* This function does not import instance name because this is more property * of a gadget than a function itself */ static int usbg_export_function_prep(usbg_function *f, config_setting_t *root) { config_setting_t *node; int ret = USBG_ERROR_NO_MEM; int cfg_ret; node = config_setting_add(root, USBG_TYPE_TAG, CONFIG_TYPE_STRING); if (!node) goto out; cfg_ret = config_setting_set_string(node, usbg_get_function_type_str( f->type)); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; goto out; } node = config_setting_add(root, USBG_ATTRS_TAG, CONFIG_TYPE_GROUP); if (!node) goto out; ret = usbg_export_function_attrs(f, node); if (ret) goto out; node = config_setting_add(root, USBG_OS_DESCS_TAG, CONFIG_TYPE_LIST); if (!node) goto out; /* OS Descriptors are optional */ ret = usbg_export_function_os_descs(f, node); if (ret == USBG_ERROR_NOT_SUPPORTED) ret = USBG_SUCCESS; out: return ret; } static int usbg_export_gadget_functions(usbg_gadget *g, config_setting_t *root) { usbg_function *f; config_setting_t *node, *inst_node; int ret = USBG_SUCCESS; int cfg_ret; char label[USBG_MAX_NAME_LENGTH]; char *func_label; int nmb; TAILQ_FOREACH(f, &g->functions, fnode) { if (f->label) { func_label = f->label; } else { nmb = generate_function_label(f, label, sizeof(label)); if (nmb >= sizeof(label)) { ret = USBG_ERROR_OTHER_ERROR; break; } func_label = label; } node = config_setting_add(root, func_label, CONFIG_TYPE_GROUP); if (!node) { ret = USBG_ERROR_NO_MEM; break; } /* Add instance name to identify in this gadget */ inst_node = config_setting_add(node, USBG_INSTANCE_TAG, CONFIG_TYPE_STRING); if (!inst_node) { ret = USBG_ERROR_NO_MEM; break; } cfg_ret = config_setting_set_string(inst_node, f->instance); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; break; } ret = usbg_export_function_prep(f, node); if (ret != USBG_SUCCESS) break; } return ret; } static int usbg_export_gadget_strs_lang(usbg_gadget *g, int lang, config_setting_t *root) { config_setting_t *node; struct usbg_gadget_strs strs; int usbg_ret, cfg_ret; int ret = USBG_ERROR_NO_MEM;; usbg_ret = usbg_get_gadget_strs(g, lang, &strs); if (usbg_ret != USBG_SUCCESS) { ret = usbg_ret; goto out; } node = config_setting_add(root, USBG_LANG_TAG, CONFIG_TYPE_INT); if (!node) goto out; cfg_ret = config_setting_set_format(node, CONFIG_FORMAT_HEX); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; goto out; } cfg_ret = config_setting_set_int(node, lang); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; goto out; } #define ADD_GADGET_STR(str_name, field) \ do { \ node = config_setting_add(root, str_name, CONFIG_TYPE_STRING); \ if (!node) \ goto out; \ cfg_ret = config_setting_set_string(node, strs.field); \ if (cfg_ret != CONFIG_TRUE) { \ ret = USBG_ERROR_OTHER_ERROR; \ goto out; \ } \ } while (0) ADD_GADGET_STR("manufacturer", manufacturer); ADD_GADGET_STR("product", product); ADD_GADGET_STR("serialnumber", serial); #undef ADD_GADGET_STR ret = USBG_SUCCESS; out: usbg_free_gadget_strs(&strs); return ret; } static int usbg_export_gadget_strings(usbg_gadget *g, config_setting_t *root) { config_setting_t *node; int *langs; int i; int usbg_ret = USBG_SUCCESS; usbg_ret = usbg_get_gadget_strs_langs(g, &langs); if (usbg_ret != USBG_SUCCESS) goto out; for (i = 0; langs[i]; ++i) { node = config_setting_add(root, NULL, CONFIG_TYPE_GROUP); if (!node) { usbg_ret = USBG_ERROR_NO_MEM; break; } usbg_ret = usbg_export_gadget_strs_lang(g, langs[i], node); if (usbg_ret != USBG_SUCCESS) break; } free(langs); out: return usbg_ret; } static int usbg_export_gadget_attrs(usbg_gadget *g, config_setting_t *root) { config_setting_t *node; struct usbg_gadget_attrs attrs; int usbg_ret, cfg_ret; int ret = USBG_ERROR_NO_MEM; usbg_ret = usbg_get_gadget_attrs(g, &attrs); if (usbg_ret) { ret = usbg_ret; goto out; } #define ADD_GADGET_ATTR(attr_name) \ do { \ node = config_setting_add(root, #attr_name, CONFIG_TYPE_INT); \ if (!node) \ goto out; \ cfg_ret = config_setting_set_format(node, CONFIG_FORMAT_HEX); \ if (cfg_ret != CONFIG_TRUE) { \ ret = USBG_ERROR_OTHER_ERROR; \ goto out; \ } \ cfg_ret = config_setting_set_int(node, attrs.attr_name); \ if (cfg_ret != CONFIG_TRUE) { \ ret = USBG_ERROR_OTHER_ERROR; \ goto out; \ } \ } while (0) ADD_GADGET_ATTR(bcdUSB); ADD_GADGET_ATTR(bDeviceClass); ADD_GADGET_ATTR(bDeviceSubClass); ADD_GADGET_ATTR(bDeviceProtocol); ADD_GADGET_ATTR(bMaxPacketSize0); ADD_GADGET_ATTR(idVendor); ADD_GADGET_ATTR(idProduct); ADD_GADGET_ATTR(bcdDevice); #undef ADD_GADGET_ATTR ret = 0; out: return ret; } static int usbg_export_gadget_os_descs(usbg_gadget *g, config_setting_t *root) { config_setting_t *node; struct usbg_gadget_os_descs g_os_descs = {0}; int usbg_ret, cfg_ret; int ret = USBG_ERROR_NO_MEM; if (g->os_desc_binding) { node = config_setting_add(root, USBG_CONFIG_ID_TAG, CONFIG_TYPE_INT); if (!node) goto out; cfg_ret = config_setting_set_int(node, g->os_desc_binding->id); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; goto out; } } usbg_ret = usbg_get_gadget_os_descs(g, &g_os_descs); if (usbg_ret) { ret = usbg_ret; goto out; } node = config_setting_add(root, "use", CONFIG_TYPE_INT); if (!node) goto out; cfg_ret = config_setting_set_int(node, g_os_descs.use); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; goto out; } node = config_setting_add(root, "qw_sign", CONFIG_TYPE_STRING); if (!node) goto out; cfg_ret = config_setting_set_string(node, g_os_descs.qw_sign); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; goto out; } node = config_setting_add(root, "b_vendor_code", CONFIG_TYPE_INT); if (!node) goto out; cfg_ret = config_setting_set_format(node, CONFIG_FORMAT_HEX); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; goto out; } cfg_ret = config_setting_set_int(node, g_os_descs.b_vendor_code); if (cfg_ret != CONFIG_TRUE) { ret = USBG_ERROR_OTHER_ERROR; goto out; } ret = 0; out: usbg_free_gadget_os_desc(&g_os_descs); return ret; } static int usbg_export_gadget_prep(usbg_gadget *g, config_setting_t *root) { config_setting_t *node; int ret = USBG_ERROR_NO_MEM; int usbg_ret; /* We don't export name tag because name should be given during * loading of gadget */ node = config_setting_add(root, USBG_ATTRS_TAG, CONFIG_TYPE_GROUP); if (!node) goto out; usbg_ret = usbg_export_gadget_attrs(g, node); if (usbg_ret) { ret = usbg_ret; goto out; } node = config_setting_add(root, USBG_OS_DESCS_TAG, CONFIG_TYPE_GROUP); if (!node) goto out; usbg_ret = usbg_export_gadget_os_descs(g, node); if (usbg_ret && usbg_ret != USBG_ERROR_NOT_FOUND) { ret = usbg_ret; goto out; } node = config_setting_add(root, USBG_STRINGS_TAG, CONFIG_TYPE_LIST); if (!node) goto out; usbg_ret = usbg_export_gadget_strings(g, node); if (usbg_ret) { ret = usbg_ret; goto out; } node = config_setting_add(root, USBG_FUNCTIONS_TAG, CONFIG_TYPE_GROUP); if (!node) goto out; usbg_ret = usbg_export_gadget_functions(g, node); if (usbg_ret) { ret = usbg_ret; goto out; } node = config_setting_add(root, USBG_CONFIGS_TAG, CONFIG_TYPE_LIST); if (!node) goto out; usbg_ret = usbg_export_gadget_configs(g, node); ret = usbg_ret; out: return ret; } /* Export gadget/function/config API implementation */ int usbg_export_function(usbg_function *f, FILE *stream) { config_t cfg; config_setting_t *root; int ret; if (!f || !stream) return USBG_ERROR_INVALID_PARAM; config_init(&cfg); /* Set format */ config_set_tab_width(&cfg, USBG_TAB_WIDTH); /* Always successful */ root = config_root_setting(&cfg); ret = usbg_export_function_prep(f, root); if (ret != USBG_SUCCESS) goto out; config_write(&cfg, stream); out: config_destroy(&cfg); return ret; } int usbg_export_config(usbg_config *c, FILE *stream) { config_t cfg; config_setting_t *root; int ret; if (!c || !stream) return USBG_ERROR_INVALID_PARAM; config_init(&cfg); /* Set format */ config_set_tab_width(&cfg, USBG_TAB_WIDTH); /* Always successful */ root = config_root_setting(&cfg); ret = usbg_export_config_prep(c, root); if (ret != USBG_SUCCESS) goto out; config_write(&cfg, stream); out: config_destroy(&cfg); return ret; } int usbg_export_gadget(usbg_gadget *g, FILE *stream) { config_t cfg; config_setting_t *root; int ret; if (!g || !stream) return USBG_ERROR_INVALID_PARAM; config_init(&cfg); /* Set format */ config_set_tab_width(&cfg, USBG_TAB_WIDTH); /* Always successful */ root = config_root_setting(&cfg); ret = usbg_export_gadget_prep(g, root); if (ret != USBG_SUCCESS) goto out; config_write(&cfg, stream); out: config_destroy(&cfg); return ret; } static int split_function_label(const char *label, usbg_function_type *type, const char **instance) { const char *floor; char buf[USBG_MAX_NAME_LENGTH]; int len; int function_type; int ret = USBG_ERROR_NOT_FOUND; /* We assume that function type string doesn't contain '_' */ floor = strchr(label, '_'); /* if phrase before _ is longer than max name length we may * stop looking */ len = floor - label; if (len >= USBG_MAX_NAME_LENGTH || floor == label) goto out; strncpy(buf, label, len); buf[len] = '\0'; function_type = usbg_lookup_function_type(buf); if (function_type < 0) goto out; *type = (usbg_function_type)function_type; *instance = floor + 1; ret = USBG_SUCCESS; out: return ret; } static void usbg_set_failed_import(config_t **to_set, config_t *failed) { if (*to_set != NULL) { config_destroy(*to_set); free(*to_set); } *to_set = failed; } static int usbg_import_function_attrs(config_setting_t *root, usbg_function *f) { int ret = USBG_ERROR_NOT_SUPPORTED; if (!f->ops->import) goto out; ret = f->ops->import(f, root); out: return ret; } static int usbg_get_config_node_os_desc(config_setting_t *node, struct usbg_function_os_desc *f_os_desc) { int ret; ret = usbg_get_config_node_string(node, "compatible_id", &f_os_desc->compatible_id); /* if error */ if (ret < 0) return ret; ret = usbg_get_config_node_string(node, "sub_compatible_id", &f_os_desc->sub_compatible_id); /* if error */ if (ret < 0) return ret; return USBG_SUCCESS; } static int find_string(const char *str, char **array) { int i; if (!array) return -ENOENT; for (i = 0; array[i]; ++i) if (strcmp(str, array[i]) == 0) return i; return -ENOENT; } static int usbg_import_function_os_descs(config_setting_t *root, usbg_function *f) { config_setting_t *node; int ret = USBG_SUCCESS; struct usbg_function_os_desc f_os_desc; char **allowed_names = f->ops->os_desc_iname; int count, i; count = config_setting_length(root); for (i = 0; i < count; ++i) { config_setting_t *interf_node; const char *interface; memset(&f_os_desc, 0, sizeof(f_os_desc)); node = config_setting_get_elem(root, i); if (!node) { ret = USBG_ERROR_OTHER_ERROR; break; } if (!config_setting_is_group(node)) { ret = USBG_ERROR_INVALID_TYPE; break; } /* Look for interface name */ interf_node = config_setting_get_member(node, USBG_INTERFACE_TAG); if (!interf_node) { ret = USBG_ERROR_MISSING_TAG; break; } interface = config_setting_get_string(interf_node); if (!interface) { ret = USBG_ERROR_OTHER_ERROR; break; } ret = find_string(interface, allowed_names); if (ret < 0) { ret = USBG_ERROR_NOT_SUPPORTED; break; } ret = usbg_get_config_node_os_desc(node, &f_os_desc); if (ret) break; ret = usbg_set_interf_os_desc(f, interface, &f_os_desc); /* no need to free as strings are allocated by libconfig */ if (ret) break; } return ret; } static int usbg_import_function_run(usbg_gadget *g, config_setting_t *root, const char *instance, usbg_function **f) { config_setting_t *node; const char *type_str; int usbg_ret; int function_type; int ret = USBG_ERROR_MISSING_TAG; /* function type is mandatory */ node = config_setting_get_member(root, USBG_TYPE_TAG); if (!node) goto out; type_str = config_setting_get_string(node); if (!type_str) { ret = USBG_ERROR_INVALID_TYPE; goto out; } /* Check if this type is supported */ function_type = usbg_lookup_function_type(type_str); if (function_type < 0) { ret = USBG_ERROR_NOT_SUPPORTED; goto out; } /* All data collected, let's get to work and create this function */ ret = usbg_create_function(g, (usbg_function_type)function_type, instance, NULL, f); if (ret != USBG_SUCCESS) goto out; /* Attrs are optional */ node = config_setting_get_member(root, USBG_ATTRS_TAG); if (node) { usbg_ret = usbg_import_function_attrs(node, *f); if (usbg_ret != USBG_SUCCESS) { ret = usbg_ret; goto out; } } node = config_setting_get_member(root, USBG_OS_DESCS_TAG); if (node) { usbg_ret = usbg_import_function_os_descs(node, *f); if (usbg_ret != USBG_SUCCESS) { ret = usbg_ret; goto out; } } out: return ret; } static usbg_function *usbg_lookup_function(usbg_gadget *g, const char *label) { usbg_function *f; int usbg_ret; /* check if such function has also been imported */ TAILQ_FOREACH(f, &g->functions, fnode) { if (f->label && !strcmp(f->label, label)) break; } /* if not let's check if label follows the naming convention */ if (!f) { usbg_function_type type; const char *instance; usbg_ret = split_function_label(label, &type, &instance); if (usbg_ret != USBG_SUCCESS) goto out; /* check if such function exist */ f = usbg_get_function(g, type, instance); } out: return f; } /* We have a string which should match with one of function names */ static int usbg_import_binding_string(config_setting_t *root, usbg_config *c) { const char *func_label; usbg_function *target; int ret; func_label = config_setting_get_string(root); if (!func_label) { ret = USBG_ERROR_OTHER_ERROR; goto out; } target = usbg_lookup_function(c->parent, func_label); if (!target) { ret = USBG_ERROR_NOT_FOUND; goto out; } ret = usbg_add_config_function(c, target->name, target); out: return ret; } static int usbg_import_binding_group(config_setting_t *root, usbg_config *c) { config_setting_t *node; const char *func_label, *name; usbg_function *target; int ret; node = config_setting_get_member(root, USBG_FUNCTION_TAG); if (!node) { ret = USBG_ERROR_MISSING_TAG; goto out; } /* It is allowed to provide link to existing function * or define unlabeled instance of function in this place */ if (usbg_config_is_string(node)) { func_label = config_setting_get_string(node); if (!func_label) { ret = USBG_ERROR_OTHER_ERROR; goto out; } target = usbg_lookup_function(c->parent, func_label); if (!target) { ret = USBG_ERROR_NOT_FOUND; goto out; } } else if (config_setting_is_group(node)) { config_setting_t *inst_node; const char *instance; inst_node = config_setting_get_member(node, USBG_INSTANCE_TAG); if (!inst_node) { ret = USBG_ERROR_MISSING_TAG; goto out; } instance = config_setting_get_string(inst_node); if (!instance) { ret = USBG_ERROR_OTHER_ERROR; goto out; } ret = usbg_import_function_run(c->parent, node, instance, &target); if (ret != USBG_SUCCESS) goto out; } else { ret = USBG_ERROR_INVALID_TYPE; goto out; } /* Name tag is optional. When no such tag, default one will be used */ node = config_setting_get_member(root, USBG_NAME_TAG); if (node) { if (!usbg_config_is_string(node)) { ret = USBG_ERROR_INVALID_TYPE; goto out; } name = config_setting_get_string(node); if (!name) { ret = USBG_ERROR_OTHER_ERROR; goto out; } } else { name = target->name; } ret = usbg_add_config_function(c, name, target); out: return ret; } static int usbg_import_config_bindings(config_setting_t *root, usbg_config *c) { config_setting_t *node; int ret = USBG_SUCCESS; int count, i; count = config_setting_length(root); for (i = 0; i < count; ++i) { node = config_setting_get_elem(root, i); if (usbg_config_is_string(node)) ret = usbg_import_binding_string(node, c); else if (config_setting_is_group(node)) ret = usbg_import_binding_group(node, c); else ret = USBG_ERROR_INVALID_TYPE; if (ret != USBG_SUCCESS) break; } return ret; } static int usbg_import_config_strs_lang(config_setting_t *root, usbg_config *c) { config_setting_t *node; int lang; struct usbg_config_strs c_strs = {0}; int ret = USBG_ERROR_INVALID_TYPE; node = config_setting_get_member(root, USBG_LANG_TAG); if (!node) { ret = USBG_ERROR_MISSING_TAG; goto out; } if (!usbg_config_is_int(node)) goto out; lang = config_setting_get_int(node); /* Configuration string is optional */ node = config_setting_get_member(root, "configuration"); if (node) { if (!usbg_config_is_string(node)) goto out; c_strs.configuration = (char *)config_setting_get_string(node); } ret = usbg_set_config_strs(c, lang, &c_strs); out: return ret; } static int usbg_import_config_strings(config_setting_t *root, usbg_config *c) { config_setting_t *node; int ret = USBG_SUCCESS; int count, i; count = config_setting_length(root); for (i = 0; i < count; ++i) { node = config_setting_get_elem(root, i); if (!config_setting_is_group(node)) { ret = USBG_ERROR_INVALID_TYPE; break; } ret = usbg_import_config_strs_lang(node, c); if (ret != USBG_SUCCESS) break; } return ret; } static int usbg_import_config_attrs(config_setting_t *root, usbg_config *c) { config_setting_t *node; int usbg_ret; int bmAttributes, bMaxPower; int ret = USBG_ERROR_INVALID_TYPE; node = config_setting_get_member(root, "bmAttributes"); if (node) { if (!usbg_config_is_int(node)) goto out; bmAttributes = config_setting_get_int(node); usbg_ret = usbg_set_config_bm_attrs(c, bmAttributes); if (usbg_ret != USBG_SUCCESS) { ret = usbg_ret; goto out; } } node = config_setting_get_member(root, "bMaxPower"); if (node) { if (!usbg_config_is_int(node)) goto out; bMaxPower = config_setting_get_int(node); usbg_ret = usbg_set_config_max_power(c, bMaxPower); if (usbg_ret != USBG_SUCCESS) { ret = usbg_ret; goto out; } } /* Empty attrs section is also considered to be valid */ ret = USBG_SUCCESS; out: return ret; } static int usbg_import_config_run(usbg_gadget *g, config_setting_t *root, int id, usbg_config **c) { config_setting_t *node; const char *name; usbg_config *newc; int usbg_ret; int ret = USBG_ERROR_MISSING_TAG; /* * Label is mandatory, * if attrs aren't present defaults are used */ node = config_setting_get_member(root, USBG_NAME_TAG); if (!node) goto out; name = config_setting_get_string(node); if (!name) { ret = USBG_ERROR_INVALID_TYPE; goto out; } /* Required data collected, let's create our config */ usbg_ret = usbg_create_config(g, id, name, NULL, NULL, &newc); if (usbg_ret != USBG_SUCCESS) { ret = usbg_ret; goto out; } /* Attrs are optional */ node = config_setting_get_member(root, USBG_ATTRS_TAG); if (node) { if (!config_setting_is_group(node)) { ret = USBG_ERROR_INVALID_TYPE; goto error2; } usbg_ret = usbg_import_config_attrs(node, newc); if (usbg_ret != USBG_SUCCESS) goto error; } /* Strings are also optional */ node = config_setting_get_member(root, USBG_STRINGS_TAG); if (node) { if (!config_setting_is_list(node)) { ret = USBG_ERROR_INVALID_TYPE; goto error2; } usbg_ret = usbg_import_config_strings(node, newc); if (usbg_ret != USBG_SUCCESS) goto error; } /* Functions too, because some config may not be * fully configured and not contain any function */ node = config_setting_get_member(root, USBG_FUNCTIONS_TAG); if (node) { if (!config_setting_is_list(node)) { ret = USBG_ERROR_INVALID_TYPE; goto error2; } usbg_ret = usbg_import_config_bindings(node, newc); if (usbg_ret != USBG_SUCCESS) goto error; } *c = newc; ret = USBG_SUCCESS; out: return ret; error: ret = usbg_ret; error2: /* We ignore returned value, if function fails * there is no way to handle it */ usbg_rm_config(newc, USBG_RM_RECURSE); return ret; } static int usbg_import_gadget_configs(config_setting_t *root, usbg_gadget *g) { config_setting_t *node, *id_node; int id; usbg_config *c; int ret = USBG_SUCCESS; int count, i; count = config_setting_length(root); for (i = 0; i < count; ++i) { node = config_setting_get_elem(root, i); if (!node) { ret = USBG_ERROR_OTHER_ERROR; break; } if (!config_setting_is_group(node)) { ret = USBG_ERROR_INVALID_TYPE; break; } /* Look for id */ id_node = config_setting_get_member(node, USBG_ID_TAG); if (!id_node) { ret = USBG_ERROR_MISSING_TAG; break; } if (!usbg_config_is_int(id_node)) { ret = USBG_ERROR_INVALID_TYPE; break; } id = config_setting_get_int(id_node); ret = usbg_import_config_run(g, node, id, &c); if (ret != USBG_SUCCESS) break; } return ret; } static int usbg_import_gadget_functions(config_setting_t *root, usbg_gadget *g) { config_setting_t *node, *inst_node; const char *instance; const char *label; usbg_function *f; int ret = USBG_SUCCESS; int count, i; count = config_setting_length(root); for (i = 0; i < count; ++i) { node = config_setting_get_elem(root, i); if (!node) { ret = USBG_ERROR_OTHER_ERROR; break; } if (!config_setting_is_group(node)) { ret = USBG_ERROR_INVALID_TYPE; break; } /* Look for instance name */ inst_node = config_setting_get_member(node, USBG_INSTANCE_TAG); if (!inst_node) { ret = USBG_ERROR_MISSING_TAG; break; } if (!usbg_config_is_string(inst_node)) { ret = USBG_ERROR_INVALID_TYPE; break; } instance = config_setting_get_string(inst_node); if (!instance) { ret = USBG_ERROR_OTHER_ERROR; break; } ret = usbg_import_function_run(g, node, instance, &f); if (ret != USBG_SUCCESS) break; /* Set the label given by user */ label = config_setting_name(node); if (!label) { ret = USBG_ERROR_OTHER_ERROR; break; } f->label = strdup(label); if (!f->label) { ret = USBG_ERROR_NO_MEM; break; } } return ret; } static int usbg_import_gadget_strs_lang(config_setting_t *root, usbg_gadget *g) { config_setting_t *node; int lang; struct usbg_gadget_strs g_strs = {0}; int ret = USBG_ERROR_INVALID_TYPE; node = config_setting_get_member(root, USBG_LANG_TAG); if (!node) { ret = USBG_ERROR_MISSING_TAG; goto out; } if (!usbg_config_is_int(node)) goto out; lang = config_setting_get_int(node); /* Auto truncate the string to max length */ #define GET_OPTIONAL_GADGET_STR(NAME, FIELD) \ do { \ node = config_setting_get_member(root, #NAME); \ if (node) { \ if (!usbg_config_is_string(node)) \ goto out; \ g_strs.FIELD = (char *)config_setting_get_string(node); \ } \ } while (0) GET_OPTIONAL_GADGET_STR(manufacturer, manufacturer); GET_OPTIONAL_GADGET_STR(product, product); GET_OPTIONAL_GADGET_STR(serialnumber, serial); #undef GET_OPTIONAL_GADGET_STR ret = usbg_set_gadget_strs(g, lang, &g_strs); out: return ret; } static int usbg_import_gadget_strings(config_setting_t *root, usbg_gadget *g) { config_setting_t *node; int ret = USBG_SUCCESS; int count, i; count = config_setting_length(root); for (i = 0; i < count; ++i) { node = config_setting_get_elem(root, i); if (!config_setting_is_group(node)) { ret = USBG_ERROR_INVALID_TYPE; break; } ret = usbg_import_gadget_strs_lang(node, g); if (ret != USBG_SUCCESS) break; } return ret; } static int usbg_import_gadget_attrs(config_setting_t *root, usbg_gadget *g) { config_setting_t *node; int usbg_ret; int val; int ret = USBG_ERROR_INVALID_TYPE; #define GET_OPTIONAL_GADGET_ATTR(NAME, FUNC_END, TYPE) \ do { \ node = config_setting_get_member(root, #NAME); \ if (node) { \ if (!usbg_config_is_int(node)) \ goto out; \ val = config_setting_get_int(node); \ if (val < 0 || val > ((1L << (sizeof(TYPE)*8)) - 1)) { \ ret = USBG_ERROR_INVALID_VALUE; \ goto out; \ } \ usbg_ret = usbg_set_gadget_##FUNC_END(g, (TYPE)val); \ if (usbg_ret != USBG_SUCCESS) { \ ret = usbg_ret; \ goto out; \ } \ } \ } while (0) GET_OPTIONAL_GADGET_ATTR(bcdUSB, device_bcd_usb, uint16_t); GET_OPTIONAL_GADGET_ATTR(bDeviceClass, device_class, uint8_t); GET_OPTIONAL_GADGET_ATTR(bDeviceSubClass, device_subclass, uint8_t); GET_OPTIONAL_GADGET_ATTR(bDeviceProtocol, device_protocol, uint8_t); GET_OPTIONAL_GADGET_ATTR(bMaxPacketSize0, device_max_packet, uint8_t); GET_OPTIONAL_GADGET_ATTR(idVendor, vendor_id, uint16_t); GET_OPTIONAL_GADGET_ATTR(idProduct, product_id, uint16_t); GET_OPTIONAL_GADGET_ATTR(bcdDevice, device_bcd_device, uint16_t); #undef GET_OPTIONAL_GADGET_ATTR /* Empty attrs section is also considered to be valid */ ret = USBG_SUCCESS; out: return ret; } static int usbg_import_gadget_os_descs(config_setting_t *root, usbg_gadget *g) { config_setting_t *node; int usbg_ret; int val; int ret = USBG_ERROR_INVALID_TYPE; struct usbg_gadget_os_descs g_os_descs = {0}; #define GET_OPTIONAL_GADGET_ATTR(NAME, FIELD, TYPE) \ do { \ node = config_setting_get_member(root, #NAME); \ if (node) { \ if (!usbg_config_is_int(node)) \ goto out; \ val = config_setting_get_int(node); \ if (val < 0 || val > ((1L << (sizeof(TYPE)*8)) - 1)) { \ ret = USBG_ERROR_INVALID_VALUE; \ goto out; \ } \ g_os_descs.FIELD = (TYPE)val; \ } \ } while (0) GET_OPTIONAL_GADGET_ATTR(use, use, bool); GET_OPTIONAL_GADGET_ATTR(b_vendor_code, b_vendor_code, uint8_t); #undef GET_OPTIONAL_GADGET_ATTR node = config_setting_get_member(root, "qw_sign"); if (node) { if (!usbg_config_is_string(node)) goto out; /* * No need to strdup() the string * as memory is owned by libconfig */ g_os_descs.qw_sign = (char *)config_setting_get_string(node); } ret = usbg_set_gadget_os_descs(g, &g_os_descs); /* * Configs are optional, because some config may not be * fully configured and not contain any config yet */ node = config_setting_get_member(root, USBG_CONFIG_ID_TAG); if (node) { usbg_config *target; if (!usbg_config_is_int(node)) goto out; val = config_setting_get_int(node); target = usbg_get_config(g, val, NULL); if (!target) { ret = USBG_ERROR_NOT_FOUND; goto out; } usbg_ret = usbg_set_os_desc_config(g, target); if (usbg_ret != USBG_SUCCESS) goto out; } out: return ret; } static int usbg_import_gadget_run(usbg_state *s, config_setting_t *root, const char *name, usbg_gadget **g) { config_setting_t *node; usbg_gadget *newg; int usbg_ret; int ret = USBG_ERROR_MISSING_TAG; /* There is no mandatory data in gadget so let's start with * creating a new gadget */ usbg_ret = usbg_create_gadget(s, name, NULL, NULL, &newg); if (usbg_ret != USBG_SUCCESS) { ret = usbg_ret; goto out; } /* Attrs are optional */ node = config_setting_get_member(root, USBG_ATTRS_TAG); if (node) { if (!config_setting_is_group(node)) { ret = USBG_ERROR_INVALID_TYPE; goto error2; } usbg_ret = usbg_import_gadget_attrs(node, newg); if (usbg_ret != USBG_SUCCESS) goto error; } /* Strings are also optional */ node = config_setting_get_member(root, USBG_STRINGS_TAG); if (node) { if (!config_setting_is_list(node)) { ret = USBG_ERROR_INVALID_TYPE; goto error2; } usbg_ret = usbg_import_gadget_strings(node, newg); if (usbg_ret != USBG_SUCCESS) goto error; } /* Functions too, because some gadgets may not be fully * configured and don't have any function or have all functions * defined inline in configurations */ node = config_setting_get_member(root, USBG_FUNCTIONS_TAG); if (node) { if (!config_setting_is_group(node)) { ret = USBG_ERROR_INVALID_TYPE; goto error2; } usbg_ret = usbg_import_gadget_functions(node, newg); if (usbg_ret != USBG_SUCCESS) goto error; } /* Some gadget may not be fully configured * so configs are also optional */ node = config_setting_get_member(root, USBG_CONFIGS_TAG); if (node) { if (!config_setting_is_list(node)) { ret = USBG_ERROR_INVALID_TYPE; goto error2; } usbg_ret = usbg_import_gadget_configs(node, newg); if (usbg_ret != USBG_SUCCESS) goto error; } /* OS Descriptors are optional too, read after configs */ node = config_setting_get_member(root, USBG_OS_DESCS_TAG); if (node) { if (!config_setting_is_group(node)) { ret = USBG_ERROR_INVALID_TYPE; goto error2; } usbg_ret = usbg_import_gadget_os_descs(node, newg); if (usbg_ret != USBG_SUCCESS) goto error; } *g = newg; ret = USBG_SUCCESS; out: return ret; error: ret = usbg_ret; error2: /* We ignore returned value, if function fails * there is no way to handle it */ usbg_rm_gadget(newg, USBG_RM_RECURSE); return ret; } int usbg_import_function(usbg_gadget *g, FILE *stream, const char *instance, usbg_function **f) { config_t *cfg; config_setting_t *root; usbg_function *newf; int ret, cfg_ret; if (!g || !stream || !instance) return USBG_ERROR_INVALID_PARAM; cfg = malloc(sizeof(*cfg)); if (!cfg) return USBG_ERROR_NO_MEM; config_init(cfg); cfg_ret = config_read(cfg, stream); if (cfg_ret != CONFIG_TRUE) { usbg_set_failed_import(&g->last_failed_import, cfg); ret = USBG_ERROR_INVALID_FORMAT; goto out; } /* Always successful */ root = config_root_setting(cfg); ret = usbg_import_function_run(g, root, instance, &newf); if (ret != USBG_SUCCESS) { usbg_set_failed_import(&g->last_failed_import, cfg); goto out; } if (f) *f = newf; config_destroy(cfg); free(cfg); /* Clean last error */ usbg_set_failed_import(&g->last_failed_import, NULL); out: return ret; } int usbg_import_config(usbg_gadget *g, FILE *stream, int id, usbg_config **c) { config_t *cfg; config_setting_t *root; usbg_config *newc; int ret, cfg_ret; if (!g || !stream || id < 0) return USBG_ERROR_INVALID_PARAM; cfg = malloc(sizeof(*cfg)); if (!cfg) return USBG_ERROR_NO_MEM; config_init(cfg); cfg_ret = config_read(cfg, stream); if (cfg_ret != CONFIG_TRUE) { usbg_set_failed_import(&g->last_failed_import, cfg); ret = USBG_ERROR_INVALID_FORMAT; goto out; } /* Always successful */ root = config_root_setting(cfg); ret = usbg_import_config_run(g, root, id, &newc); if (ret != USBG_SUCCESS) { usbg_set_failed_import(&g->last_failed_import, cfg); goto out; } if (c) *c = newc; config_destroy(cfg); free(cfg); /* Clean last error */ usbg_set_failed_import(&g->last_failed_import, NULL); out: return ret; } int usbg_import_gadget(usbg_state *s, FILE *stream, const char *name, usbg_gadget **g) { config_t *cfg; config_setting_t *root; usbg_gadget *newg; int ret, cfg_ret; if (!s || !stream || !name) return USBG_ERROR_INVALID_PARAM; cfg = malloc(sizeof(*cfg)); if (!cfg) return USBG_ERROR_NO_MEM; config_init(cfg); cfg_ret = config_read(cfg, stream); if (cfg_ret != CONFIG_TRUE) { usbg_set_failed_import(&s->last_failed_import, cfg); ret = USBG_ERROR_INVALID_FORMAT; goto out; } /* Always successful */ root = config_root_setting(cfg); ret = usbg_import_gadget_run(s, root, name, &newg); if (ret != USBG_SUCCESS) { usbg_set_failed_import(&s->last_failed_import, cfg); goto out; } if (g) *g = newg; config_destroy(cfg); free(cfg); /* Clean last error */ usbg_set_failed_import(&s->last_failed_import, NULL); out: return ret; } const char *usbg_get_func_import_error_text(usbg_gadget *g) { if (!g || !g->last_failed_import) return NULL; return config_error_text(g->last_failed_import); } int usbg_get_func_import_error_line(usbg_gadget *g) { if (!g || !g->last_failed_import) return -1; return config_error_line(g->last_failed_import); } const char *usbg_get_config_import_error_text(usbg_gadget *g) { if (!g || !g->last_failed_import) return NULL; return config_error_text(g->last_failed_import); } int usbg_get_config_import_error_line(usbg_gadget *g) { if (!g || !g->last_failed_import) return -1; return config_error_line(g->last_failed_import); } const char *usbg_get_gadget_import_error_text(usbg_state *s) { if (!s || !s->last_failed_import) return NULL; return config_error_text(s->last_failed_import); } int usbg_get_gadget_import_error_line(usbg_state *s) { if (!s || !s->last_failed_import) return -1; return config_error_line(s->last_failed_import); } libusbgx-libusbgx-v0.3.0/src/usbg_schemes_none.c000066400000000000000000000047351467553526200220050ustar00rootroot00000000000000/* * This library is free software; you can redistribute it 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. */ #include #include "usbg/usbg_internal.h" int usbg_export_function(__attribute__ ((unused)) usbg_function *f, __attribute__ ((unused)) FILE *stream) { return USBG_ERROR_NOT_SUPPORTED; } int usbg_export_config(__attribute__ ((unused)) usbg_config *c, __attribute__ ((unused)) FILE *stream) { return USBG_ERROR_NOT_SUPPORTED; } int usbg_export_gadget(__attribute__ ((unused)) usbg_gadget *g, __attribute__ ((unused)) FILE *stream) { return USBG_ERROR_NOT_SUPPORTED; } int usbg_import_function(__attribute__ ((unused)) usbg_gadget *g, __attribute__ ((unused)) FILE *stream, __attribute__ ((unused)) const char *instance, __attribute__ ((unused)) usbg_function **f) { return USBG_ERROR_NOT_SUPPORTED; } int usbg_import_config(__attribute__ ((unused)) usbg_gadget *g, __attribute__ ((unused)) FILE *stream, __attribute__ ((unused)) int id, __attribute__ ((unused)) usbg_config **c) { return USBG_ERROR_NOT_SUPPORTED; } int usbg_import_gadget(__attribute__ ((unused)) usbg_state *s, __attribute__ ((unused)) FILE *stream, __attribute__ ((unused)) const char *name, __attribute__ ((unused)) usbg_gadget **g) { return USBG_ERROR_NOT_SUPPORTED; } const char *usbg_get_func_import_error_text( __attribute__ ((unused)) usbg_gadget *g) { return NULL; } int usbg_get_func_import_error_line(__attribute__ ((unused)) usbg_gadget *g) { return USBG_ERROR_NOT_SUPPORTED; } const char *usbg_get_config_import_error_text( __attribute__ ((unused)) usbg_gadget *g) { return NULL; } int usbg_get_config_import_error_line(__attribute__ ((unused)) usbg_gadget *g) { return USBG_ERROR_NOT_SUPPORTED; } const char *usbg_get_gadget_import_error_text( __attribute__ ((unused)) usbg_state *s) { return NULL; } int usbg_get_gadget_import_error_line(__attribute__ ((unused)) usbg_state *s) { return USBG_ERROR_NOT_SUPPORTED; } void config_destroy(__attribute__ ((unused)) config_t *config) { return; } libusbgx-libusbgx-v0.3.0/tests/000077500000000000000000000000001467553526200165155ustar00rootroot00000000000000libusbgx-libusbgx-v0.3.0/tests/Makefile.am000066400000000000000000000012071467553526200205510ustar00rootroot00000000000000check_PROGRAMS = test header_checker test_SOURCES = test.c usbg-test.c usbg-io-wrappers.c test_LDFLAGS = -ldl test_LDFLAGS += $(CMOCKA_LIBS) test_LDFLAGS += $(LIBCONFIG_LIBS) test_LDADD = ./libusbgx.so test_CPPFLAGS = -I$(top_srcdir)/include/ ./libusbgx.so: -ln -s $(top_srcdir)/src/.libs/libusbgx.so* . CLEANFILES = libusbgx.so* header_checker_SOURCES = header_checker.cpp header_checker_LDFLAGS = -ldl header_checker_LDFLAGS += $(CMOCKA_LIBS) header_checker_LDFLAGS += $(LIBCONFIG_LIBS) header_checker_LDADD = ./libusbgx.so header_checker_CPPFLAGS = -I$(top_srcdir)/include/ check_SCRIPTS = ./test.sh TESTS = $(check_SCRIPTS) header_checker libusbgx-libusbgx-v0.3.0/tests/header_checker.cpp000066400000000000000000000007321467553526200221370ustar00rootroot00000000000000/* * This is just a dummy test which checks if all our headers * compiles correctly with a C++ compiler. */ #include #include #include #include #include #include #include #include #include #include int main(int argc, char **argv) { return 0; } libusbgx-libusbgx-v0.3.0/tests/meson.build000066400000000000000000000006121467553526200206560ustar00rootroot00000000000000test_exe = executable('test_exe', [ 'test.c', 'usbg-test.c', 'usbg-io-wrappers.c', ], dependencies: [ libusbgx_dep, cmocka, ], ) header_checker = executable('header_checker', [ 'header_checker.cpp', ], dependencies: [ libusbgx_dep, cmocka, ], ) # TODO: also run with --generate-config or --use-config test('test_exe', test_exe) test('header_checker', header_checker) libusbgx-libusbgx-v0.3.0/tests/test.c000066400000000000000000002064011467553526200176430ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include #include #include #ifdef HAS_LIBCONFIG #include #endif #include "usbg-test.h" /** * @file tests/test.c */ #define USBG_TEST(name, test, setup, teardown) \ {name, test, setup, teardown} #define FILLED_STR(len, c) \ { [0 ... len - 2] = c, [len - 1] = '\0' } /* two levels of macros allow to strigify result of macro expansion */ #define STR(s) #s #define XSTR(s) STR(s) /* unique string */ #define UNIQUE XSTR(__COUNTER__) #define FUNC_FROM_TYPE(t) { \ .type = t, \ .instance = "instance"UNIQUE \ } #define CONF_FROM_BOUND(b) { \ .label = "c", \ .id = __COUNTER__, \ .bound_funcs = b \ } static struct usbg_gadget_attrs min_gadget_attrs = { .bcdUSB = 0x0000, .bDeviceClass = 0x0, .bDeviceSubClass = 0x0, .bDeviceProtocol = 0x0, .bMaxPacketSize0 = 0x0, .idVendor = 0x0000, .idProduct = 0x0000, .bcdDevice = 0x0000 }; static struct usbg_gadget_attrs max_gadget_attrs = { .bcdUSB = 0xffff, .bDeviceClass = 0xff, .bDeviceSubClass = 0xff, .bDeviceProtocol = 0xff, .bMaxPacketSize0 = 0xff, .idVendor = 0xffff, .idProduct = 0xffff, .bcdDevice = 0xffff }; /* PATH_MAX is limit for path length */ #define LONG_PATH_LEN PATH_MAX/2 static char long_path_str[] = FILLED_STR(LONG_PATH_LEN, 'x'); /* NAME_MAX is limit for filename length */ static char long_usbg_string[] = FILLED_STR(NAME_MAX, 'x'); static struct usbg_config_strs simple_config_strs= { .configuration = "configuration string" }; static struct usbg_config_attrs max_config_attrs = { .bmAttributes = 0xff, .bMaxPower = 0xff }; static struct usbg_config_attrs min_config_attrs = { .bmAttributes = 0x00, .bMaxPower = 0x00 }; /** * @brief Simplest udcs names * @details Used to go through init when testing other things */ static char *simple_udcs[] = { "UDC1", "UDC2", NULL }; static char *long_udcs[] = { long_usbg_string, "UDC1", NULL }; /** * @brief Simplest functions names * @details Used to go through init when testing other things */ static struct test_function simple_funcs[] = { FUNC_FROM_TYPE(USBG_F_ECM), FUNC_FROM_TYPE(USBG_F_ACM), TEST_FUNCTION_LIST_END }; /** * @brief All functions types * @details When testing with this in state, check if all func types are * processed correctly */ static struct test_function all_funcs[] = { FUNC_FROM_TYPE(USBG_F_SERIAL), FUNC_FROM_TYPE(USBG_F_ACM), FUNC_FROM_TYPE(USBG_F_OBEX), FUNC_FROM_TYPE(USBG_F_ECM), FUNC_FROM_TYPE(USBG_F_SUBSET), FUNC_FROM_TYPE(USBG_F_NCM), FUNC_FROM_TYPE(USBG_F_EEM), FUNC_FROM_TYPE(USBG_F_RNDIS), FUNC_FROM_TYPE(USBG_F_PHONET), FUNC_FROM_TYPE(USBG_F_FFS), TEST_FUNCTION_LIST_END }; static struct test_function same_type_funcs[] = { FUNC_FROM_TYPE(USBG_F_SERIAL), FUNC_FROM_TYPE(USBG_F_SERIAL), FUNC_FROM_TYPE(USBG_F_SERIAL), TEST_FUNCTION_LIST_END }; /** * @brief No functions at all * @details Check if gadget with no functions (or config with no bindings) * is processed correctly. */ static struct test_function no_funcs[] = { TEST_FUNCTION_LIST_END }; /** * @brief Simple configs * @details Used to pass through init when testing other things */ static struct test_config simple_confs[] = { CONF_FROM_BOUND(simple_funcs), TEST_CONFIG_LIST_END }; /** * @brief Configs bound to all avaible function types */ static struct test_config all_bindings_confs[] = { CONF_FROM_BOUND(no_funcs), CONF_FROM_BOUND(all_funcs), TEST_CONFIG_LIST_END }; #define GADGET(n, u, c, f) \ { \ .name = n, \ .udc = u, \ .configs = c, \ .functions = f \ } /** * @brief Simplest gadget */ static struct test_gadget simple_gadgets[] = { GADGET("g1", "UDC1", simple_confs, simple_funcs), TEST_GADGET_LIST_END }; /** * @brief Gadgets with all avaible functions */ static struct test_gadget all_funcs_gadgets[] = { GADGET("all_funcs_gadget1", "UDC1", all_bindings_confs, all_funcs), TEST_GADGET_LIST_END }; static struct test_gadget long_udc_gadgets[] = { GADGET("long_udc_gadgets", long_usbg_string, simple_confs, simple_funcs), TEST_GADGET_LIST_END }; struct test_function_attrs_data { struct test_state *state; void *attrs; }; struct test_data { struct test_state *state; struct usbg_state *usbg_state; }; static int simple_serial_attrs = 42; static struct usbg_f_net_attrs simple_net_attrs = { .dev_addr = {}, .host_addr = {}, .ifname = "if", .qmult = 1, }; static char *simple_phonet_attrs = "if"; static char *simple_ffs_attrs = "0"; static int writable_serial_attrs = 0; static struct usbg_f_net_attrs writable_net_attrs = { .dev_addr = {}, .host_addr = {}, .ifname = "", .qmult = 1, }; static char *writable_phonet_attrs = ""; static char *writable_ffs_attrs = ""; struct test_gadget_strs_data { struct test_state *state; struct usbg_gadget_strs *strs; }; #define STATE(p, g, u) { \ .configfs_path = p, \ .gadgets = g, \ .udcs = u \ } /** * @brief Simple state */ static struct test_state simple_state = STATE("config", simple_gadgets, simple_udcs); /** * @brief State with all functions avaible */ static struct test_state all_funcs_state = STATE("all_funcs_configfs", all_funcs_gadgets, simple_udcs); static struct test_state long_path_state = STATE(long_path_str, simple_gadgets, simple_udcs); static struct test_state long_udc_state = STATE("simple_path", long_udc_gadgets, long_udcs); static struct usbg_config_attrs *get_random_config_attrs() { struct usbg_config_attrs *ret; ret = safe_malloc(sizeof(*ret)); srand(time(NULL)); ret->bmAttributes = rand() % max_config_attrs.bmAttributes; ret->bMaxPower = rand() % max_config_attrs.bMaxPower; return ret; } static struct usbg_gadget_attrs *get_random_gadget_attrs() { struct usbg_gadget_attrs *ret; ret = safe_malloc(sizeof(*ret)); srand(time(NULL)); ret->bcdUSB = rand() % max_gadget_attrs.bcdUSB; ret->bDeviceClass = rand() % max_gadget_attrs.bDeviceClass; ret->bDeviceSubClass = rand() % max_gadget_attrs.bDeviceSubClass; ret->bDeviceProtocol = rand() % max_gadget_attrs.bDeviceProtocol; ret->bMaxPacketSize0 = rand() % max_gadget_attrs.bMaxPacketSize0; ret->idVendor = rand() % max_gadget_attrs.idVendor; ret->idProduct = rand() % max_gadget_attrs.idProduct; ret->bcdDevice = rand() % max_gadget_attrs.bcdDevice; return ret; } /** * @brief Add given attributes to all configs in state * @return Prepared state where configs has given attributes */ static void *prepare_state_with_config_attrs(struct test_state *state, struct usbg_config_attrs *attrs) { struct test_gadget *tg; struct test_config *tc; for (tg = state->gadgets; tg->name; ++tg) for (tc = tg->configs; tc->label; ++tc) tc->attrs = attrs; state = prepare_state(state); return state; } static int setup_max_config_attrs_state(void **state) { *state = prepare_state_with_config_attrs(&simple_state, &max_config_attrs); return 0; } static int setup_min_config_attrs_state(void **state) { *state = prepare_state_with_config_attrs(&simple_state, &min_config_attrs); return 0; } static int setup_random_config_attrs_state(void **state) { *state = prepare_state_with_config_attrs(&simple_state, get_random_config_attrs()); return 0; } static int setup_simple_config_strs_state(void **state) { struct test_gadget *tg; struct test_config *tc; for (tg = simple_state.gadgets; tg->name; ++tg) for (tc = tg->configs; tc->label; ++tc) tc->strs = &simple_config_strs; *state = prepare_state(&simple_state); return 0; } /** * @brief Prepare test_state with one gadget containing given function list * @details For testing only functions. We put them in a gadget as simply * as possible. * @param[in] func Pointer to list of functions * @return Pointer to test state with given functions */ static struct test_state *put_func_in_state(struct test_function *func) { struct test_state *st; struct test_gadget *g; struct test_config *c; char **udcs; st = safe_calloc(1, sizeof(*st)); /* Do not need config */ c = safe_calloc(1, sizeof(*c)); g = safe_calloc(2, sizeof(*g)); udcs = safe_calloc(2, sizeof(*udcs)); g[0].name = "g1"; g[0].udc = "UDC1"; g[0].configs = c; g[0].functions = func; g[0].writable = 1; udcs[0] = "UDC1"; g[0].writable = 1; st->configfs_path = "config"; st->gadgets = g; st->udcs = udcs; st->writable = 1; st = prepare_state(st); return st; } /** * @brief Setup simple state with some gadgets, configs and functions */ static int setup_simple_state(void **state) { *state = prepare_state(&simple_state); return 0; } /** * @brief Setup state with all avaible functions */ static int setup_all_funcs_state(void **state) { *state = prepare_state(&all_funcs_state); return 0; } /** * @brief Setup state with few functions of the same type */ static int setup_same_type_funcs_state(void **state) { *state = put_func_in_state(same_type_funcs); return 0; } /** * @brief Setup state with very long path name */ static int setup_long_path_state(void **state) { *state = prepare_state(&long_path_state); return 0; } /** * @brief Setup state with long udc name */ static int setup_long_udc_state(void **state) { *state = prepare_state(&long_udc_state); return 0; } static void alloc_random_len_str(char **str) { int len; len = rand() % USBG_MAX_FILE_SIZE; *str = safe_malloc(len); memset(*str, 'x', len - 1); (*str)[len - 1] = '\0'; } /** * @brief Setup state with gadget strings of random length * @param[out] state Pointer to pointer to test_gadget_strs_data structure * with initialized state and strings */ static int setup_random_len_gadget_strs_data(void **state) { struct usbg_gadget_strs *strs; struct test_gadget_strs_data *data; /* will fill memory with zeros */ strs = safe_calloc(1, sizeof(*strs)); data = safe_malloc(sizeof(*data)); srand(time(NULL)); alloc_random_len_str(&strs->manufacturer); alloc_random_len_str(&strs->product); alloc_random_len_str(&strs->serial); data->strs = strs; data->state = prepare_state(&simple_state); *state = data; return 0; } static void *setup_f_attrs(int f_type, void *attrs) { struct test_function_attrs_data *data; struct test_function *func; data = safe_malloc(sizeof(*data)); func = safe_calloc(2, sizeof(*func)); func[0].type = f_type; func[0].instance = "0"; func[0].writable = 1; data->state = put_func_in_state(func); data->attrs = attrs; return data; } static int setup_f_serial_attrs(void **state) { *state = setup_f_attrs(USBG_F_SERIAL, &simple_serial_attrs); return 0; } static int setup_f_serial_writable_attrs(void **state) { *state = setup_f_attrs(USBG_F_SERIAL, &writable_serial_attrs); return 0; } static int setup_f_acm_attrs(void **state) { *state = setup_f_attrs(USBG_F_ACM, &simple_serial_attrs); return 0; } static int setup_f_acm_writable_attrs(void **state) { *state = setup_f_attrs(USBG_F_ACM, &writable_serial_attrs); return 0; } static int setup_f_obex_attrs(void **state) { *state = setup_f_attrs(USBG_F_OBEX, &simple_serial_attrs); return 0; } static int setup_f_obex_writable_attrs(void **state) { *state = setup_f_attrs(USBG_F_OBEX, &writable_serial_attrs); return 0; } static int setup_f_ecm_attrs(void **state) { *state = setup_f_attrs(USBG_F_ECM, &simple_net_attrs); return 0; } static int setup_f_ecm_writable_attrs(void **state) { *state = setup_f_attrs(USBG_F_ECM, &writable_net_attrs); return 0; } static int setup_f_subset_attrs(void **state) { *state = setup_f_attrs(USBG_F_SUBSET, &simple_net_attrs); return 0; } static int setup_f_subset_writable_attrs(void **state) { *state = setup_f_attrs(USBG_F_SUBSET, &writable_net_attrs); return 0; } static int setup_f_ncm_attrs(void **state) { *state = setup_f_attrs(USBG_F_NCM, &simple_net_attrs); return 0; } static int setup_f_ncm_writable_attrs(void **state) { *state = setup_f_attrs(USBG_F_NCM, &writable_net_attrs); return 0; } static int setup_f_eem_attrs(void **state) { *state = setup_f_attrs(USBG_F_EEM, &simple_net_attrs); return 0; } static int setup_f_eem_writable_attrs(void **state) { *state = setup_f_attrs(USBG_F_EEM, &writable_net_attrs); return 0; } static int setup_f_rndis_attrs(void **state) { *state = setup_f_attrs(USBG_F_RNDIS, &simple_net_attrs); return 0; } static int setup_f_rndis_writable_attrs(void **state) { *state = setup_f_attrs(USBG_F_RNDIS, &writable_net_attrs); return 0; } static int setup_f_phonet_attrs(void **state) { *state = setup_f_attrs(USBG_F_PHONET, &simple_phonet_attrs); return 0; } static int setup_f_phonet_writable_attrs(void **state) { *state = setup_f_attrs(USBG_F_PHONET, &writable_phonet_attrs); return 0; } static int setup_f_ffs_attrs(void **state) { *state = setup_f_attrs(USBG_F_FFS, &simple_ffs_attrs); return 0; } static int setup_f_ffs_writable_attrs(void **state) { *state = setup_f_attrs(USBG_F_FFS, &writable_ffs_attrs); return 0; } /** * @brief Tests usbg_get_gadget function with given state * @details Check if gadgets are returned correctly */ static void test_get_gadget(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_gadget(ts, s, assert_gadget_equal); } /** * @brief Tests usbg_get_gadget with non-existing gadget name * @details Check if get_gadget will not find non-existing gadgets and * will not cause crash. */ static void test_get_gadget_fail(void **state) { usbg_gadget *g = NULL; usbg_state *s = NULL; struct test_state *st; safe_init_with_state(state, &st, &s); g = usbg_get_gadget(s, "non-existing-gadget"); assert_null(g); } /** * @brief Tests usbg_get_first_gadget function * @details Check if gadget returned by get_first_gadget is actually first one */ static void test_get_first_gadget(void **state) { usbg_gadget *g = NULL; usbg_state *s = NULL; struct test_state *st; safe_init_with_state(state, &st, &s); g = usbg_get_first_gadget(s); assert_non_null(g); assert_gadget_equal(g, &st->gadgets[0]); } /** * @brief Tests get_first_gadget with invalid arguments */ static void test_get_first_gadget_fail(void **state) { usbg_gadget *g; g = usbg_get_first_gadget(NULL); assert_null(g); } static void try_get_gadget_name(usbg_gadget *g, struct test_gadget *tg) { const char *name; name = usbg_get_gadget_name(g); assert_string_equal(name, tg->name); } /** * @brief Tests getting name of gadget * @details Check if gadget name is returned correctly */ static void test_get_gadget_name(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_gadget(ts, s, try_get_gadget_name); } static void try_get_gadget_name_len(usbg_gadget *g, struct test_gadget *tg) { int len; char buf; int expected; expected = strlen(tg->name); len = usbg_get_gadget_name_s(g, &buf, 0); assert_int_equal(len, expected); } /** * @brief Tests getting name length of gadget * @details Check if returned name length is equal original */ static void test_get_gadget_name_len(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_gadget(ts, s, try_get_gadget_name_len); } /** * @brief Tests getting name of gadget with invalid arguments * @details Check if trying to get name of wrong (non-existing) gadget * will not cause crash, but return NULL as expected. */ static void test_get_gadget_name_fail(void **state) { const char *name; name = usbg_get_gadget_name(NULL); assert_null(name); } static void try_get_gadget_name_s(usbg_gadget *g, struct test_gadget *tg) { char name[USBG_MAX_NAME_LENGTH]; int ret; ret = usbg_get_gadget_name_s(g, name, USBG_MAX_NAME_LENGTH); assert_int_equal(ret, strlen(tg->name)); assert_string_equal(name, tg->name); } /** * @brief Tests copying gadget's name * @details Check if copying gadget name copy actual name correctly */ static void test_get_gadget_name_s(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_gadget(ts, s, try_get_gadget_name_s); } /** * @brief Test copying gadet name with invalid arguments * @details Check if trying to copy gadget name into non-existing buffer, * or give invalid buffer length, or invalid gadget will be handled by library * and return correct error codes */ static void test_get_gadget_name_s_fail(void **state) { usbg_gadget *g = NULL; usbg_state *s = NULL; struct test_state *st; int i = 0; char name[USBG_MAX_NAME_LENGTH]; int ret; safe_init_with_state(state, &st, &s); for (i = 0; st->gadgets[i].name; i++) { g = usbg_get_gadget(s, st->gadgets[i].name); assert_non_null(g); ret = usbg_get_gadget_name_s(g, NULL, USBG_MAX_NAME_LENGTH); assert_int_equal(ret, USBG_ERROR_INVALID_PARAM); } ret = usbg_get_gadget_name_s(NULL, name, USBG_MAX_NAME_LENGTH); assert_int_equal(ret, USBG_ERROR_INVALID_PARAM); } /** * @brief Tests init by comparing test state and usbg state * @details Check if usbg state after init match given state and * if init returned success code */ static void test_init(void **state) { usbg_state *s = NULL; struct test_state *st; safe_init_with_state(state, &st, &s); assert_state_equal(s, st); } /** * @brief Test getting function by name * @param[in] state Pointer to pointer to correctly initialized * test_state structure */ static void test_get_function(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_function(ts, s, assert_func_equal); } /** * @brief Tests usbg_get_function with some non-existing functions * @details Check if get function will return NULL, when invalid * functions names and types are passed as arguments and will not cause crash. * @param[in] state Pointer to pointer to correctly initialized * test_state structure */ static void test_get_function_fail(void **state) { usbg_state *s = NULL; usbg_gadget *g = NULL; usbg_function *f = NULL; struct test_state *st; safe_init_with_state(state, &st, &s); g = usbg_get_first_gadget(s); assert_non_null(g); f = usbg_get_function(g, USBG_F_ACM, "non-existing-instance"); assert_null(f); f = usbg_get_function(g, 9001, "0"); assert_null(f); } /** * @brief Tests function type translation to string * @param[in] state Pointer to pointer to correctly initialized * test_state structure * @details Check if get_function_type_str returns proper strings for all types. */ static void test_get_function_type_str(void **state) { struct { usbg_function_type type; const char *str; } types[] = { {USBG_F_SERIAL, "gser"}, {USBG_F_ACM, "acm"}, {USBG_F_OBEX, "obex"}, {USBG_F_ECM, "ecm"}, {USBG_F_SUBSET, "geth"}, {USBG_F_NCM, "ncm"}, {USBG_F_EEM, "eem"}, {USBG_F_RNDIS, "rndis"}, {USBG_F_PHONET, "phonet"}, {USBG_F_FFS, "ffs"}, }; const char *str; int i; for (i = 0; i < ARRAY_SIZE(types); i++) { str = usbg_get_function_type_str(types[i].type); assert_non_null(str); assert_string_equal(str, types[i].str); } } static struct { usbg_gadget_str code; const char *name; } gadget_str_names[] = { {USBG_STR_PRODUCT, "product"}, {USBG_STR_MANUFACTURER, "manufacturer"}, {USBG_STR_SERIAL_NUMBER, "serialnumber"}, }; /** * @brief Tests gadget codeing name getting * @param[in] state Pointer to pointer to correctly initialized * test_state structure * @details Check if usbg_get_gadget_code_name returns proper * codeings for all types. */ static void test_get_gadget_str_name(void **state) { const char *name; int i; for (i = 0; i < ARRAY_SIZE(gadget_str_names); i++) { name = usbg_get_gadget_str_name(gadget_str_names[i].code); assert_non_null(name); assert_string_equal(name, gadget_str_names[i].name); } } /** * @brief Tests gadget codeing code getting by its name * @param[in] state Pointer to pointer to correctly initialized * test_state structure * @details Check if usbg_lookup_gadget_code returns values matching codeings */ static void test_lookup_gadget_str(void **state) { int i, code; for (i = 0; i < ARRAY_SIZE(gadget_str_names); i++) { code = usbg_lookup_gadget_str(gadget_str_names[i].name); assert_return_code(code, 0); assert_int_equal(code, gadget_str_names[i].code); } } /** * @brief Tests function type translation to string with unknown funcs * @param[in] state Not used parameter * @details Check if get_function_type_str returns NULL, when given * function type is unknown. */ static void test_get_function_type_str_fail(void **state) { const char *str; str = usbg_get_function_type_str(-1); assert_null(str); } /** * @brief Get instance of given function and check it * @param[in] f Usbg function * @param[in] tf Test function which should match f */ static void try_get_function_instance(usbg_function *f, struct test_function *tf) { const char *str; str = usbg_get_function_instance(f); assert_string_equal(str, tf->instance); } /** * @brief Tests getting function instance from usbg_function structure * @param[in] state Pointer to pointer to correctly initialized * test_state structure * @details Check if returned instance name is correct. */ static void test_get_function_instance(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_function(ts, s, try_get_function_instance); } /** * @brief Cpy instance of given usbg function and check it * @param[in] f Usbg function * @param[in] tf Test function which should match f */ static void try_get_function_instance_s(usbg_function *f, struct test_function *tf) { char str[USBG_MAX_NAME_LENGTH]; int ret; int small_len = 2; ret = usbg_get_function_instance_s(f, str, USBG_MAX_NAME_LENGTH); assert_int_equal(ret, strlen(tf->instance)); assert_string_equal(str, tf->instance); ret = usbg_get_function_instance_s(f, str, small_len); assert_int_equal(ret, strlen(tf->instance)); assert_memory_equal(str, tf->instance, small_len - 1); assert_int_equal(str[small_len - 1], '\0'); } /** * @brief Tests copying function instance from usbg_function structure * into buffer * @param[in] state Pointer to pointer to correctly initialized state * @details Check if buffer contains expected string */ static void test_get_function_instance_s(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_function(ts, s, try_get_function_instance_s); } /** * @brief Get function type and check it * @param[in] f Usbg function * @param[in] tf Test function which should match f by type */ static void try_get_function_type(usbg_function *f, struct test_function *tf) { usbg_function_type type; type = usbg_get_function_type(f); assert_int_equal(type, tf->type); } /** * @brief Tests getting function type * @details Check if getting function type returns what was expected. * State must be proper (init must end with success). * @param[in] state Pointer to pointer to correctly initialized state */ static void test_get_function_type(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_function(ts, s, try_get_function_type); } /** * @brief Check if function instance length is correct * @param[in] f Usbg function * @param[in] tf Test function which should match f */ static void try_get_function_instance_len(usbg_function *f, struct test_function *tf) { size_t len; char buf; len = usbg_get_function_instance_s(f, &buf, 0); assert_int_equal(len, strlen(tf->instance)); } /** * @brief Tests getting length of function instance name * @details Check if returned instance name length matches * actual length of instance name * @param[in] state Pointer to pointer to correctly initialized state */ static void test_get_function_instance_len(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_function(ts, s, try_get_function_instance_len); } /** * @brief Tests getting configfs path from usbg state * @param[in,out] state Pointer to pointer to correctly initialized test state. * When finished, it contains pointer to usbg_state which should be cleaned. */ static void test_get_configfs_path(void **state) { usbg_state *s = NULL; struct test_state *st; const char *path; safe_init_with_state(state, &st, &s); path = usbg_get_configfs_path(s); assert_path_equal(path, st->configfs_path); } /** * @brief Tests getting configfs path length from usbg state * @param[in,out] state Pointer to pointer to correctly initialized test state. * When finished, it contains pointer to usbg_state which should be cleaned. */ static void test_get_configfs_path_len(void **state) { usbg_state *s = NULL; struct test_state *st; char buf; int ret, len; safe_init_with_state(state, &st, &s); ret = usbg_get_configfs_path_s(s, &buf, 0); len = strlen(st->configfs_path); assert_int_equal(ret, len); } /** * @brief Tests copying configfs path into buffer * @param[in,out] state Pointer to pointer to correctly initialized test state. * When finished, it contains pointer to usbg_state which should be cleaned. */ static void test_get_configfs_path_s(void **state) { usbg_state *s = NULL; struct test_state *st; char path[PATH_MAX]; int ret; safe_init_with_state(state, &st, &s); ret = usbg_get_configfs_path_s(s, path, PATH_MAX); assert_int_equal(ret, strlen(st->configfs_path)); assert_path_equal(path, st->configfs_path); } /** * @brief Tests getting config by name * @param[in,out] state Pointer to pointer to correctly initialized test state. * When finished, it contains pointer to usbg_state which should be cleaned. */ static void test_get_config(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_config(ts, s, assert_config_equal); } static void test_get_config_without_label(void **state) { usbg_state *s = NULL; usbg_gadget *g = NULL; usbg_config *c = NULL; struct test_state *ts; struct test_gadget *tg; struct test_config *tc; safe_init_with_state(state, &ts, &s); for (tg = ts->gadgets; tg->name; tg++) { g = usbg_get_gadget(s, tg->name); assert_non_null(g); for (tc = tg->configs; tc->label; tc++) { c = usbg_get_config(g, tc->id, NULL); assert_non_null(c); assert_config_equal(c, tc); } } } /** * @bried Tests getting non-existing config * @param[in,out] state Pointer to pointer to correctly initialized test state. * When finished, it contains pointer to usbg_state which should be cleaned. */ static void test_get_config_fail(void **state) { usbg_state *s = NULL; usbg_gadget *g = NULL; usbg_config *c = NULL; struct test_state *ts; struct test_gadget *tg; safe_init_with_state(state, &ts, &s); for (tg = ts->gadgets; tg->name; tg++) { g = usbg_get_gadget(s, tg->name); assert_non_null(g); c = usbg_get_config(g, 0, "non-existing-config"); assert_null(c); c = usbg_get_config(g, -9001, "c"); assert_null(c); c = usbg_get_config(g, -9001, NULL); assert_null(c); } } /** * @brief Get config label and check it * @param[in] c Usbg config * @param[in] tc Test config which should match c */ static void try_get_config_label(usbg_config *c, struct test_config *tc) { const char *label; label = usbg_get_config_label(c); assert_string_equal(label, tc->label); } /** * @brief Tests getting config label * @param[in,out] state Pointer to pointer to correctly initialized test state. * When finished, it contains pointer to usbg_state which should be cleaned. */ static void test_get_config_label(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_config(ts, s, try_get_config_label); } /** * @brief Check config id with test structure * @param[in] c Usbg config * @param[in] tc Test config which should match c */ static void try_get_config_id(usbg_config *c, struct test_config *tc) { int id; id = usbg_get_config_id(c); assert_int_equal(id, tc->id); } /** * @brief Tests getting config id * @param[in,out] state Pointer to pointer to correctly initialized test state. * When finished, it contains pointer to usbg_state which should be cleaned. */ static void test_get_config_id(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_config(ts, s, try_get_config_id); } /** * @brief Test getting given attributes from gadgets present in state * @param[in] s Pointer to usbg state * @param[in] ts Pointer to test state matching given usbg state * @param[in] attrs Pointer to gadget attributes which should be put in * virtual filesystem for writting by usbg */ static void try_get_gadget_attrs(usbg_state *s, struct test_state *ts, struct usbg_gadget_attrs *attrs) { usbg_gadget *g = NULL; struct usbg_gadget_attrs actual; struct test_gadget *tg; int ret; for (tg = ts->gadgets; tg->name; tg++) { g = usbg_get_gadget(s, tg->name); assert_non_null(g); push_gadget_attrs(tg, attrs); ret = usbg_get_gadget_attrs(g, &actual); assert_int_equal(ret, 0); assert_gadget_attrs_equal(&actual, attrs); } } /** * @brief Tests getting gadget attributes * @param[in] state Pointer to correctly initialized test_state structure **/ static void test_get_gadget_attrs(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); try_get_gadget_attrs(s, ts, &min_gadget_attrs); try_get_gadget_attrs(s, ts, &max_gadget_attrs); try_get_gadget_attrs(s, ts, get_random_gadget_attrs()); } /** * @brief Test setting given attributes on gadgets present in state * @param[in] s Pointer to usbg state * @param[in] ts Pointer to test state matching given usbg state * @param[in] attrs Pointer to gadget attributes to be set */ static void try_set_gadget_attrs(usbg_state *s, struct test_state *ts, struct usbg_gadget_attrs *attrs) { usbg_gadget *g = NULL; struct test_gadget *tg; int ret; for (tg = ts->gadgets; tg->name; tg++) { g = usbg_get_gadget(s, tg->name); assert_non_null(g); pull_gadget_attrs(tg, attrs); ret = usbg_set_gadget_attrs(g, attrs); assert_int_equal(ret, 0); } } /** * @brief Tests setting gadget attributes * @param[in] state Pointer to correctly initialized test_state structure **/ static void test_set_gadget_attrs(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); try_set_gadget_attrs(s, ts, &min_gadget_attrs); try_set_gadget_attrs(s, ts, &max_gadget_attrs); try_set_gadget_attrs(s, ts, get_random_gadget_attrs()); } /** * @brief Test setting given attributes on gadgets present in state one by one, * using functions specific for each attribute * @param[in] s Pointer to usbg state * @param[in] ts Pointer to test state matching given usbg state * @param[in] attrs Pointer to gadget attributes to be set */ static void try_set_specific_gadget_attr(usbg_state *s, struct test_state *ts, struct usbg_gadget_attrs *attrs) { usbg_gadget *g = NULL; struct test_gadget *tg; int ret; int i; int attr; for (tg = ts->gadgets; tg->name; tg++) { g = usbg_get_gadget(s, tg->name); assert_non_null(g); for (i = USBG_GADGET_ATTR_MIN; i < USBG_GADGET_ATTR_MAX; i++) { attr = get_gadget_attr(attrs, i); pull_gadget_attribute(tg, i, attr); usbg_set_gadget_attr(g, i, attr); assert_int_equal(ret, 0); } } } /** * @brief Tests setting gadget attributes one by one * @param[in] state Pointer to correctly initialized test_state structure **/ static void test_set_specific_gadget_attr(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); try_set_specific_gadget_attr(s, ts, &min_gadget_attrs); try_set_specific_gadget_attr(s, ts, &max_gadget_attrs); try_set_specific_gadget_attr(s, ts, get_random_gadget_attrs()); } /** * @brief Tests getting udc from state * @param[in] state Pointer to correctly initialized test_state structure **/ void test_get_udc(void **state) { struct test_state *ts; char **tu; struct test_gadget *tg; usbg_state *s = NULL; usbg_udc *u = NULL; usbg_gadget *g = NULL; safe_init_with_state(state, &ts, &s); for (tu = ts->udcs; *tu; tu++) { u = usbg_get_udc(s, *tu); assert_non_null(u); assert_string_equal(*tu, u->name); assert_int_equal(s, u->parent); } for (tg = ts->gadgets; tg->name; tg++) { u = usbg_get_udc(s, tg->udc); g = usbg_get_gadget(s, tg->name); assert_int_equal(u->gadget, g); } } static void test_get_gadget_attr_str(void **state) { struct { usbg_gadget_attr attr; const char *str; } attrs[] = { {USBG_BCD_USB, "bcdUSB"}, {USBG_B_DEVICE_CLASS, "bDeviceClass"}, {USBG_B_DEVICE_SUB_CLASS, "bDeviceSubClass"}, {USBG_B_DEVICE_PROTOCOL, "bDeviceProtocol"}, {USBG_B_MAX_PACKET_SIZE_0, "bMaxPacketSize0"}, {USBG_ID_VENDOR, "idVendor"}, {USBG_ID_PRODUCT, "idProduct"}, {USBG_BCD_DEVICE, "bcdDevice"}, }; const char *str; int i, j; for (i = 0; i < ARRAY_SIZE(attrs); i++) { str = usbg_get_gadget_attr_str(attrs[i].attr); assert_non_null(str); assert_string_equal(str, attrs[i].str); } /* Check if iteration over values works */ for (i = USBG_GADGET_ATTR_MIN; i < USBG_GADGET_ATTR_MAX; ++i) { str = usbg_get_gadget_attr_str(i); assert_non_null(str); for (j = 0; j < ARRAY_SIZE(attrs); ++j) if (attrs[j].attr == i) { assert_string_equal(str, attrs[j].str); break; } assert_int_not_equal(j, ARRAY_SIZE(attrs)); } } static void test_get_gadget_attr_str_fail(void **state) { const char *str; str = usbg_get_gadget_attr_str(USBG_GADGET_ATTR_MIN - 1); assert_null(str); str = usbg_get_gadget_attr_str(USBG_GADGET_ATTR_MAX); assert_null(str); } /** * @brief set gadget strings * @details Also do it one by one * @param[in] data Pointer to correctly initialized * test_gadget_strs_data structure */ static void test_set_gadget_strs(void **data) { struct test_gadget_strs_data *ts; struct test_gadget *tg; usbg_state *s = NULL; usbg_gadget *g = NULL; int i; int ret; ts = (struct test_gadget_strs_data *)(*data); *data = NULL; init_with_state(ts->state, &s); *data = s; for (tg = ts->state->gadgets; tg->name; tg++) { g = usbg_get_gadget(s, tg->name); pull_gadget_strs(tg, LANG_US_ENG, ts->strs); ret = usbg_set_gadget_strs(g, LANG_US_ENG, ts->strs); assert_int_equal(ret, 0); for (i = 0; i < GADGET_STR_MAX; i++) pull_gadget_string(tg, LANG_US_ENG, i, get_gadget_str(ts->strs, i)); ret = usbg_set_gadget_manufacturer(g, LANG_US_ENG, ts->strs->manufacturer); assert_int_equal(ret, 0); ret = usbg_set_gadget_product(g, LANG_US_ENG, ts->strs->product); assert_int_equal(ret, 0); ret = usbg_set_gadget_serial_number(g, LANG_US_ENG, ts->strs->serial); assert_int_equal(ret, 0); for (i = 0; i < GADGET_STR_MAX; i++) pull_gadget_string(tg, LANG_US_ENG, i, get_gadget_str(ts->strs, i)); ret = usbg_set_gadget_str(g, USBG_STR_MANUFACTURER, LANG_US_ENG, ts->strs->manufacturer); assert_int_equal(ret, 0); ret = usbg_set_gadget_str(g, USBG_STR_PRODUCT, LANG_US_ENG, ts->strs->product); assert_int_equal(ret, 0); ret = usbg_set_gadget_str(g, USBG_STR_SERIAL_NUMBER, LANG_US_ENG, ts->strs->serial); assert_int_equal(ret, 0); } } /** * @brief get gadget strings * @param[in] data Pointer to correctly initialized * test_gadget_strs_data structure */ static void test_get_gadget_strs(void **data) { struct test_gadget_strs_data *ts; struct test_gadget *tg; usbg_state *s = NULL; usbg_gadget *g = NULL; struct usbg_gadget_strs strs; ts = (struct test_gadget_strs_data *)(*data); *data = NULL; init_with_state(ts->state, &s); *data = s; for (tg = ts->state->gadgets; tg->name; tg++) { g = usbg_get_gadget(s, tg->name); push_gadget_strs(tg, LANG_US_ENG, ts->strs); usbg_get_gadget_strs(g, LANG_US_ENG, &strs); assert_gadget_strs_equal(&strs, ts->strs); usbg_free_gadget_strs(&strs); } } /** * @brief Get binding target * @details Check if given function is target of given binding * @param[in] tb Test function * @param[in] b Binding */ static void try_get_binding_target(struct test_binding *tb, usbg_binding *b) { usbg_function *f; f = usbg_get_binding_target(b); assert_non_null(f); assert_func_equal(f, tb->target); } /** * @brief Test get binding target * @details Test all bindings present in given state * @param[in, out] state Pointer to pointer to correctly initialized test state, * will point to usbg state when finished. */ static void test_get_binding_target(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_binding(ts, s, try_get_binding_target); } /** * @brief Get binding name * @details Check if name of given binding is equal name of given function * @param[in] tb Test function * @param[in] b Binding */ static void try_get_binding_name(struct test_binding *tb, usbg_binding *b) { const char *s; s = usbg_get_binding_name(b); assert_non_null(s); assert_string_equal(s, tb->name); } /** * @brief Test get bindig name from all binding present in state * @param[in, out] state Pointer to pointer to correctly initialized test state, * will point to usbg state when finished. */ static void test_get_binding_name(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_binding(ts, s, try_get_binding_name); } /** * @brief Get binding name length * @param[in] tb Test function * @param[in] b Binding */ static void try_get_binding_name_len(struct test_binding *tb, usbg_binding *b) { int n; char buf; n = usbg_get_binding_name_s(b, &buf, 0); assert_int_equal(n, strlen(tb->name)); } /** * @brief Test get binding name length from all bindings present in state * @param[in, out] state Pointer to pointer to correctly initialized test state, * will point to usbg state when finished. */ static void test_get_binding_name_len(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_binding(ts, s, try_get_binding_name_len); } /** * @brief Set config strings * @param[in] c Config on which string should be set * @param[in] tc Test config containing strings to be set */ static void try_set_config_strs(usbg_config *c, struct test_config *tc) { pull_config_strs(tc, LANG_US_ENG, tc->strs); usbg_set_config_strs(c, LANG_US_ENG, tc->strs); } /** * @brief Test setting strings * @details Set strings in all configs present in state * @param[in, out] state Pointer to pointer to correctly initialized test state, * will point to usbg state when finished. */ static void test_set_config_strs(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_config(ts, s, try_set_config_strs); } /** * @brief Set strings one by one on config * @param[in] c Config on which string should be set * @param[in] tc Test config containing strings to be set */ static void try_set_config_string(usbg_config *c, struct test_config *tc) { pull_config_string(tc, LANG_US_ENG, tc->strs->configuration); usbg_set_config_string(c, LANG_US_ENG, tc->strs->configuration); } /** * @brief Test setting strings one by one * @details Set strings on all configs present in given state * @param[in, out] state Pointer to pointer to correctly initialized test state, * will point to usbg state when finished. */ static void test_set_config_string(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_config(ts, s, try_set_config_string); } /** * @brief Get config strings * @details Assume that given configs have the same strings * @param[in] c Config from which strings should be get * @param[in] tc Test config expected to have the same string as c */ static void try_get_config_strs(usbg_config *c, struct test_config *tc) { struct usbg_config_strs strs; push_config_strs(tc, LANG_US_ENG, tc->strs); usbg_get_config_strs(c, LANG_US_ENG, &strs); assert_string_equal(tc->strs->configuration, strs.configuration); usbg_free_config_strs(&strs); } /** * @brief Test getting congig strings * @details Get config strings on all configs present in given state * @param[in, out] state Pointer to pointer to correctly initialized test state, * will point to usbg state when finished. */ static void test_get_config_strs(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_config(ts, s, try_get_config_strs); } /** * @brief Get config attributes * @details Assume that attributes which will be returned are the same as * given test state contains. * @param[in] c Usbg config * @param[in] tc Test config with set attributes */ static void try_get_config_attrs(usbg_config *c, struct test_config *tc) { struct usbg_config_attrs attrs; push_config_attrs(tc, tc->attrs); usbg_get_config_attrs(c, &attrs); assert_config_attrs_equal(tc->attrs, &attrs); } /** * @brief Test getting config attributes * @details Get config attributes on all configfs in state * @param[in, out] state Pointer to pointer to correctly initialized test state, * will point to usbg state when finished. */ static void test_get_config_attrs(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_config(ts, s, try_get_config_attrs); } /** * @brief Set config attributes in given config * @param[in] c Usbg config * @param[in] tc Test config with attributes which will be set */ static void try_set_config_attrs(usbg_config *c, struct test_config *tc) { pull_config_attrs(tc, tc->attrs); usbg_set_config_attrs(c, tc->attrs); } /** * @brief Test setting config attributes * @details Set config attributes on all configs in state * @param[in, out] state Pointer to pointer to correctly initialized test state, * will point to usbg state when finished. */ static void test_set_config_attrs(void **state) { usbg_state *s = NULL; struct test_state *ts; safe_init_with_state(state, &ts, &s); for_each_test_config(ts, s, try_set_config_attrs); } /** * @brieg Test creating config * @details Start with empty gadgets, add all functions from given state * @param[in, out] state Pointer to pointer to correctly initialized test state, * will point to usbg state when finished. */ static void test_create_config(void **state) { usbg_state *s = NULL; usbg_gadget *g = NULL; usbg_config *c = NULL; struct test_state *ts; struct test_state *empty; struct test_gadget *tg; struct test_config *tc; ts = (struct test_state *)(*state); *state = NULL; empty = build_empty_gadget_state(ts); init_with_state(empty, &s); *state = s; for (tg = ts->gadgets; tg->name; tg++) { g = usbg_get_gadget(s, tg->name); assert_non_null(g); for (tc = tg->configs; tc->label; tc++) { pull_create_config(tc); usbg_create_config(g, tc->id, tc->label, tc->attrs, tc->strs, &c); assert_config_equal(c, tc); } } } /** * @brief Start with empty gadget, add all functions from given one */ static void test_create_function(void **state) { usbg_state *s = NULL; usbg_gadget *g = NULL; usbg_function *f = NULL; struct test_state *ts; struct test_state *empty; struct test_gadget *tg; struct test_function *tf; ts = (struct test_state *)(*state); *state = NULL; empty = build_empty_gadget_state(ts); init_with_state(empty, &s); *state = s; for (tg = ts->gadgets; tg->name; tg++) { g = usbg_get_gadget(s, tg->name); assert_non_null(g); for (tf = tg->functions; tf->instance; tf++) { pull_create_function(tf); usbg_create_function(g, tf->type, tf->instance, tf->attrs, &f); assert_func_equal(f, tf); } } } /** * @brief Test only one given function for attribute getting * @param[in] state Pointer to pointer to correctly initialized state */ static void test_get_function_attrs(void **state) { struct test_function_attrs_data *data; usbg_state *s; usbg_function *f; usbg_gadget *g; union { struct usbg_f_net_attrs net; char *ffs_dev_name; struct usbg_f_ms_attrs ms; struct usbg_f_midi_attrs midi; int serial_port_num; char *phonet_ifname; } actual; int ret; data = (struct test_function_attrs_data *)(*state); *state = NULL; init_with_state(data->state, &s); *state = s; g = usbg_get_first_gadget(s); assert_non_null(g); f = usbg_get_first_function(g); assert_non_null(f); push_function_attrs(&data->state->gadgets[0].functions[0], data->attrs); ret = usbg_get_function_attrs(f, &actual); assert_int_equal(ret, 0); assert_function_attrs_equal(&actual, data->attrs, f->type); usbg_cleanup_function_attrs(f, &actual); } /** * @brief Test setting attributes in only one given function * @param[in] state Pointer to pointer to correctly initialized state */ static void test_set_function_attrs(void **state) { struct test_function_attrs_data *data; usbg_state *s; usbg_function *f; usbg_gadget *g; int ret; data = (struct test_function_attrs_data *)(*state); *state = NULL; init_with_state(data->state, &s); *state = s; g = usbg_get_first_gadget(s); assert_non_null(g); f = usbg_get_first_function(g); assert_non_null(f); pull_function_attrs(&data->state->gadgets[0].functions[0], data->attrs); ret = usbg_set_function_attrs(f, data->attrs); assert_int_equal(ret, 0); } /** * * @brief cleanup usbg state */ static int teardown_state(void **state) { usbg_state *s = NULL; s = (usbg_state *)(*state); if (s != NULL) usbg_cleanup(s); cleanup_stack(); return 0; } /* Custom macro for defining test with given name and fixed teardown function */ #define USBG_TEST_TS(name, test, setup) \ USBG_TEST(name, test, setup, teardown_state) /** * @page usbg_tests Tests * @brief This is list of test cases * @tests_start */ #ifndef DOXYGEN static struct CMUnitTest tests[] = { #endif /** * @usbg_test * @test_desc{test_init_simple, * Check if init was successfull on simple configfs state, * usbg_init} */ USBG_TEST_TS("test_init_simple", test_init, setup_simple_state), /** * @usbg_test * @test_desc{test_init_all_funcs, * Check if init was successfull when all avaible functions * are present in configfs, * usbg_init} */ USBG_TEST_TS("test_init_all_funcs", test_init, setup_all_funcs_state), /** * @usbg_test * @test_desc{test_init_long_path, * Try to initialize libusbg with long configfs path, * usbg_init} */ USBG_TEST_TS("test_init_long_path", test_init, setup_long_path_state), /** * @usbg_test * @test_desc{test_init_long_udc, * Try to initialize libusbg with long udc name, * usbg_init} */ USBG_TEST_TS("test_init_long_udc", test_init, setup_long_udc_state), /** * @usbg_test * @test_desc{test_get_gadget_simple, * Check if simple gadget will be correcty returned, * usbg_get_gadget} */ USBG_TEST_TS("test_get_gadget_simple", test_get_gadget, setup_simple_state), /** * @usbg_test * @test_desc{test_get_gadget_fail_simple, * Check if getting non-existing and wrong gadgets cause * expected failure and error codes are correct, * usbg_get_gadget} */ USBG_TEST_TS("test_get_gadget_fail_simple", test_get_gadget_fail, setup_simple_state), /** * @usbg_test * @test_desc{test_get_first_gadget_simple, * Check if gadget returned by get_first_gadget * is actually first one, * usbg_get_first_gadget} */ USBG_TEST_TS("test_get_first_gadget_simple", test_get_first_gadget, setup_simple_state), /** * @usbg_test * @test_desc{test_get_first_gadget_fail, * Check if getting first gadget from state returns NULL when * invalid parameters are passed, * usbg_get_first_gadget} */ unit_test(test_get_first_gadget_fail), /** * @usbg_test * @test_desc{test_get_gadget_name_simple, * Check if returned gadget name matches expected value, * usbg_get_gadget_name} */ USBG_TEST_TS("test_get_gadget_name_simple", test_get_gadget_name, setup_simple_state), /** * @usbg_test * @test_desc{test_get_gadget_name_len, * Check if returned simple gadget name length matches expected value, * usbg_get_gadget_name} */ USBG_TEST_TS("test_get_gadget_name_len_simple", test_get_gadget_name_len, setup_simple_state), /** * @usbg_test * @test_desc{test_get_gadget_name_fail, * Check if trying to get name of invalid gadget * cause expected failure (name is null), * usbg_get_gadget_name} */ unit_test(test_get_gadget_name_fail), /** * @usbg_test * @test_desc{test_get_gadget_name_s_simple, * Check if getting simple gadget name into buffer work as expected, * usbg_get_gadget_name_s} */ USBG_TEST_TS("test_get_gadget_name_s_simple", test_get_gadget_name_s, setup_simple_state), /** * @usbg_test * @test_desc{test_get_gadget_name_s_fail_simple, * Check if writting gadget name into buffer fail when * invalid parameters are passed, * usbg_get_gadget_name_s} */ USBG_TEST_TS("test_get_gadget_name_s_fail_simple", test_get_gadget_name_s_fail, setup_simple_state), /** * @usbg_test * @test_desc{test_get_function_simple, * Check if function can be correctly get from simple state, * usbg_get_function} */ USBG_TEST_TS("test_get_function_simple", test_get_function, setup_simple_state), /** * @usbg_test * @test_desc{test_get_function_all_funcs, * Check if getting function work on all function types, * usbg_get_function} */ USBG_TEST_TS("test_get_function_all_funcs", test_get_function, setup_all_funcs_state), /** * @usbg_test * @test_desc{test_get_function_same_type_funcs, * Check if having multiple functions with the same type does not * cause failure * usbg_get_function} */ USBG_TEST_TS("test_get_function_same_type_funcs", test_get_function, setup_same_type_funcs_state), /** * @usbg_test * @test_desc{test_get_function_fail_simple, * Check if trying to get invalid function's name ends * with expected error, * usbg_get_function} */ USBG_TEST_TS("test_get_function_fail_simple", test_get_function_fail, setup_simple_state), /** * @usbg_test * @test_desc{test_get_function_instance_simple, * Check if getting simple instance returns what expected, * usbg_get_function_instance} */ USBG_TEST_TS("test_get_function_instance_simple", test_get_function_instance, setup_simple_state), /** * @usbg_test * @test_desc{test_get_function_instance_s_simple, * Check if copying simple instance into buffer returns what expected, * usbg_get_function_instance_s} */ USBG_TEST_TS("test_get_function_instance_s_simple", test_get_function_instance_s, setup_all_funcs_state), /** * @usbg_test * @test_desc{test_get_function_type_simple, * Check if function type is returned correctly, * usbg_get_function_type} */ USBG_TEST_TS("test_get_function_type_simple", test_get_function_type, setup_simple_state), /** * @usbg_test * @test_desc{test_get_function_type_all_funcs, * Check if all function types are returned correctly, * usbg_get_function_type} */ USBG_TEST_TS("test_get_function_type_all_funcs", test_get_function_type, setup_all_funcs_state), /** * @usbg_test * @test_desc{test_get_function_instance_len_simple, * Check if function instance length is returned correctly, * usbg_get_function_instance_len} */ USBG_TEST_TS("test_get_function_instance_len_simple", test_get_function_instance_len, setup_simple_state), /** * @usbg_test * @test_desc{test_get_function_type_str, * Compare returned function types strings with expected values, * usbg_get_function_type_str} */ unit_test(test_get_function_type_str), /** * @usbg_test * @test_desc{test_get_function_type_str_fail, * Try to get type string of unknown type, * usbg_get_function_type_str} */ unit_test(test_get_function_type_str_fail), /** * @usbg_test * @test_desc{test_get_configfs_path_simple, * heck if simple configfs path was returned correctly, * usbg_get_configfs_path} */ USBG_TEST_TS("test_get_configfs_path_simple", test_get_configfs_path, setup_simple_state), /** * @usbg_test * @test_desc{test_get_configfs_path_len, * Check if configfs path length is correctly calculated, * usbg_get_configfs_path_len} */ USBG_TEST_TS("test_get_configfs_path_len_simple", test_get_configfs_path_len, setup_simple_state), /** * @usbg_test * @test_desc{test_get_configfs_path_s_simple, * Copy simple configfs path into buffer and compare with original, * usbg_get_configfs_path_s} */ USBG_TEST_TS("test_get_configfs_path_s_simple", test_get_configfs_path_s, setup_simple_state), /** * @usbg_test * @test_desc{test_get_config_simple, * Check if returned simple config matches original one, * usbg_get_config} */ USBG_TEST_TS("test_get_config_simple", test_get_config, setup_simple_state), /** * @usbg_test * @test_desc{test_get_config_without_label_simple, * Check if returned simple config matches original one, * usbg_get_config} */ USBG_TEST_TS("test_get_config_without_label_simple", test_get_config_without_label, setup_simple_state), /** * @usbg_test * @test_desc{test_get_config_fail, * Check if trying to get non-existing or invalid config * fails as expected, * usbg_get_config}*/ USBG_TEST_TS("test_get_config_fail", test_get_config_fail, setup_simple_state), /** * @usbg_test * @test_desc{test_get_config_label_simple, * Check if returned simple config label matches original one, * usbg_get_config_label} */ USBG_TEST_TS("test_get_config_label_simple", test_get_config_label, setup_simple_state), /** * @usbg_test * @test_desc{test_get_config_id_simple, * Check if returned simple config id matches original one, * usbg_get_config_id} */ USBG_TEST_TS("test_get_config_id_simple", test_get_config_id, setup_simple_state), /** * @usbg_test * @test_desc{test_get_gadget_attrs_simple, * Get gadget attributes list and compare them with original, * usbg_get_gadget_attrs} */ USBG_TEST_TS("test_get_gadget_attrs_simple", test_get_gadget_attrs, setup_simple_state), /** * @usbg_tets * @test_desc{test_set_gadget_attrs_simple, * Set gadget attributes list\, check if everything is wrote * as expected, * usbg_set_gadget_attrs} */ USBG_TEST_TS("test_set_gadget_attrs_simple", test_set_gadget_attrs, setup_simple_state), /** * @usbg_test * @test_desc{test_set_specific_gadget_attr_simple, * Set gadget attributes one by one, * usbg_set_gadget_attrs} */ USBG_TEST_TS("test_set_specific_gadget_attr_simple", test_set_specific_gadget_attr, setup_simple_state), /** * @usbg_test * @test_desc{test_get_udc_simple, * Get udc name from state, * usbg_get_udc} */ USBG_TEST_TS("test_get_udc_simple", test_get_udc, setup_simple_state), /** * @usbg_test * @test_desc{test_get_udc_long, * Get udc name witch very long name, * usbg_get_udc} */ USBG_TEST_TS("test_get_udc_long", test_get_udc, setup_long_udc_state), /** * @usbg_test * @test_desc{test_get_gadget_attr_str, * Compare returned gadget attribute strings witch expected values * usbg_get_gadget_attr_str} */ unit_test(test_get_gadget_attr_str), /** * @usbg_test * @test_desc{test_get_gadget_attr_str_fail, * Check returned gadget attribute strings for invalid arguments * usbg_get_gadget_attr_str} */ unit_test(test_get_gadget_attr_str_fail), /** * @usbg_test * @test_desc{test_set_gadget_strs_random, * Set gadget strings of random length, * usbg_set_gadget_strs} */ USBG_TEST_TS("test_set_gadget_strs_random", test_set_gadget_strs, setup_random_len_gadget_strs_data), /** * @usbg_test * @test_desc{test_get_gadget_strs_random, * Get gadget strings, * usbg_get_gadget_strs} */ USBG_TEST_TS("test_get_gadget_strs_random", test_get_gadget_strs, setup_random_len_gadget_strs_data), /** * @usbg_test * @test_desc{test_get_binding_target_simple, * Get binding target, * usbg_get_binding_target} */ USBG_TEST_TS("test_get_binding_target_simple", test_get_binding_target, setup_simple_state), /** * @usbg_test * @test_desc{test_get_binding_name_simple, * Get binding name, * usbg_get_binding_name} */ USBG_TEST_TS("test_get_binding_name_simple", test_get_binding_name, setup_simple_state), /** * @usbg_test * @test_desc{test_get_binding_name_len_simple, * Get binding name length, * usbg_get_binding_name_len} */ USBG_TEST_TS("test_get_binding_name_len_simple", test_get_binding_name_len, setup_simple_state), /** * @usbg_test * @test_desc{test_set_config_strs_simple, * Set simple strings in set of configurations, * usbg_set_config_strs} */ USBG_TEST_TS("test_set_config_strs_simple", test_set_config_strs, setup_simple_config_strs_state), /** * @usbg_test * @test_desc{test_set_config_string_simple, * Set simple string in set of configurations, * usbg_set_config_string} */ USBG_TEST_TS("test_set_config_string_simple", test_set_config_string, setup_simple_config_strs_state), /** * @usbg_test * @test_desc{test_get_config_strs_simple, * Get simple strings from set of configurations, * usbg_get_config_strs} */ USBG_TEST_TS("test_get_config_strs_simple", test_get_config_strs, setup_simple_config_strs_state), /** * @usbg_test * @test_desc{test_get_config_attrs_max, * Get config attributes with max values, * usbg_get_config_attrs} */ USBG_TEST_TS("test_get_config_attrs_max", test_get_config_attrs, setup_max_config_attrs_state), /** * @usbg_test * @test_desc{test_get_config_attrs_min, * Get config attributes with minimum values, * usbg_get_config_attrs} */ USBG_TEST_TS("test_get_config_attrs_min", test_get_config_attrs, setup_min_config_attrs_state), /** * @usbg_test * @test_desc{test_get_config_attrs_random, * Get config attributes with random values, * usbg_get_config_attrs} */ USBG_TEST_TS("test_get_config_attrs_random", test_get_config_attrs, setup_random_config_attrs_state), /** * @usbg_test * @test_desc{test_set_config_attrs_max, * Set config attributes with max values, * usbg_set_config_attrs} */ USBG_TEST_TS("test_set_config_attrs_max", test_set_config_attrs, setup_max_config_attrs_state), /** * @usbg_test * @test_desc{test_set_config_attrs_min, * Set config attributes with minimum values, * usbg_set_config_attrs} */ USBG_TEST_TS("test_set_config_attrs_min", test_set_config_attrs, setup_min_config_attrs_state), /** * @usbg_test * @test_desc{test_set_config_attrs_random, * Set config attributes with random values, * usbg_set_config_attrs} */ USBG_TEST_TS("test_set_config_attrs_random", test_set_config_attrs, setup_random_config_attrs_state), /** * @usbg_test * @test_desc{test_create_config_random, * Create config with random attributes * usbg_create_config} */ USBG_TEST_TS("test_create_config_random", test_create_config, setup_random_config_attrs_state), /** * @usbg_test * @test_desc{test_get_f_serial_attrs, * Get f_serial function attributes, * usbg_get_function_attrs} */ USBG_TEST_TS("test_get_f_serial_attrs", test_get_function_attrs, setup_f_serial_attrs), /** * @usbg_test * @test_desc{test_get_f_obex_attrs, * Get f_obex function attributes, * usbg_get_function_attrs} */ USBG_TEST_TS("test_get_f_obex_attrs", test_get_function_attrs, setup_f_obex_attrs), /** * @usbg_test * @test_desc{test_get_f_acm_attrs, * Get f_acm function attributes, * usbg_get_function_attrs} */ USBG_TEST_TS("test_get_f_acm_attrs", test_get_function_attrs, setup_f_acm_attrs), /** * @usbg_test * @test_desc{test_get_f_ecm_attrs, * Get f_ecm function attributes, * usbg_get_function_attrs} */ USBG_TEST_TS("test_get_f_ecm_attrs", test_get_function_attrs, setup_f_ecm_attrs), /** * @usbg_test * @test_desc{test_get_f_eem_attrs, * Get f_eem function attributes, * usbg_get_function_attrs} */ USBG_TEST_TS("test_get_f_eem_attrs", test_get_function_attrs, setup_f_eem_attrs), /** * @usbg_test * @test_desc{test_get_f_subset_attrs, * Get f_subset function attributes, * usbg_get_function_attrs} */ USBG_TEST_TS("test_get_f_subset_attrs", test_get_function_attrs, setup_f_subset_attrs), /** * @usbg_test * @test_desc{test_get_f_ncm_attrs, * Get f_ncm function attributes, * usbg_get_function_attrs} */ USBG_TEST_TS("test_get_f_ncm_attrs", test_get_function_attrs, setup_f_ncm_attrs), /** * @usbg_test * @test_desc{test_get_f_serial_attrs, * Get f_rndis function attributes, * usbg_get_function_attrs} */ USBG_TEST_TS("test_get_f_rndis_attrs", test_get_function_attrs, setup_f_rndis_attrs), /** * @usbg_test * @test_desc{test_get_f_phonet_attrs, * Get f_phonet function attributes, * usbg_get_function_attrs} */ USBG_TEST_TS("test_get_f_phonet_attrs", test_get_function_attrs, setup_f_phonet_attrs), /** * @usbg_test * @test_desc{test_get_f_serial_attrs, * Get f_ffs function attributes, * usbg_get_function_attrs} */ USBG_TEST_TS("test_get_f_ffs_attrs", test_get_function_attrs, setup_f_ffs_attrs), /** * @usbg_test * @test_desc{test_get_f_serial_attrs, * Set f_serial function attributes, * usbg_set_function_attrs} */ USBG_TEST_TS("test_set_f_serial_attrs", test_set_function_attrs, setup_f_serial_writable_attrs), /** * @usbg_test * @test_desc{test_get_f_acm_attrs, * Set f_acm function attributes, * usbg_set_function_attrs} */ USBG_TEST_TS("test_set_f_acm_attrs", test_set_function_attrs, setup_f_acm_writable_attrs), /** * @usbg_test * @test_desc{test_get_f_serial_obex, * Set f_obex function attributes, * usbg_set_function_attrs} */ USBG_TEST_TS("test_set_f_obex_attrs", test_set_function_attrs, setup_f_obex_writable_attrs), /** * @usbg_test * @test_desc{test_get_f_ecm_attrs, * Set f_ecm function attributes, * usbg_set_function_attrs} */ USBG_TEST_TS("test_set_f_ecm_attrs", test_set_function_attrs, setup_f_ecm_writable_attrs), /** * @usbg_test * @test_desc{test_get_f_eem_attrs, * Set f_eem function attributes, * usbg_set_function_attrs} */ USBG_TEST_TS("test_set_f_eem_attrs", test_set_function_attrs, setup_f_eem_writable_attrs), /** * @usbg_test * @test_desc{test_get_f_subset_attrs, * Set f_subset function attributes, * usbg_set_function_attrs} */ USBG_TEST_TS("test_set_f_subset_attrs", test_set_function_attrs, setup_f_subset_writable_attrs), /** * @usbg_test * @test_desc{test_get_f_ncm_attrs, * Set f_ncm function attributes, * usbg_set_function_attrs} */ USBG_TEST_TS("test_set_f_ncm_attrs", test_set_function_attrs, setup_f_ncm_writable_attrs), /** * @usbg_test * @test_desc{test_get_f_serial_attrs, * Set f_rndis function attributes, * usbg_get_function_attrs} */ USBG_TEST_TS("test_set_f_rndis_attrs", test_set_function_attrs, setup_f_rndis_writable_attrs), /** * @usbg_test * @test_desc{test_get_f_phonet_attrs, * Set f_phonet function attributes, * usbg_set_function_attrs} */ USBG_TEST_TS("test_set_f_phonet_attrs", test_set_function_attrs, setup_f_phonet_writable_attrs), /** * @usbg_test * @test_desc{test_get_f_serial_attrs, * Set f_ffs function attributes, * usbg_set_function_attrs} */ USBG_TEST_TS("test_set_f_ffs_attrs", test_set_function_attrs, setup_f_ffs_writable_attrs), /** * @usbg_test * @test_desc{test_create_all_functions, * Create full set of functions in empty state, * usbg_get_binding_name_len} */ USBG_TEST_TS("test_create_all_functions", test_create_function, setup_all_funcs_state), /** * @usbg_test * @test_desc{test_get_gadget_str_name, * Compare returned gadget string name with expected * usbg_get_gadget_str_name} */ unit_test(test_get_gadget_str_name), /** * @usbg_test * @test_desc{test_lookup_gadget_str, * Compare returned gadget string code with expected * usbg_lookup_gadget_str} */ unit_test(test_lookup_gadget_str), #ifndef DOXYGEN }; #endif /** * @usbg_test * @tests_end */ #define TESTS_TAG "tests" /* for autotools compability */ #define SKIPPED_CODE 77 #ifdef HAS_LIBCONFIG static int gen_test_config(FILE *output) { config_t cfg; config_setting_t *root; config_setting_t *tests_node, *node; int i; int ret = SKIPPED_CODE, cfg_ret = 0; config_init(&cfg); config_set_tab_width(&cfg, 4); root = config_root_setting(&cfg); tests_node = config_setting_add(root, TESTS_TAG, CONFIG_TYPE_LIST); if (!tests_node) { ret = -ENOMEM; goto out; } for (i = 0; i < ARRAY_SIZE(tests); ++i) { node = config_setting_add(tests_node, NULL, CONFIG_TYPE_STRING); if (!node) { ret = -ENOMEM; goto out; } cfg_ret = config_setting_set_string(node, tests[i].name); if (cfg_ret != CONFIG_TRUE) { ret = -EINVAL; goto out; } } config_write(&cfg, output); out: config_destroy(&cfg); return ret; } #else static int gen_test_config(FILE *output) { fprintf(stderr, "Libconfig is not supported\n"); return -ENOTSUP; } #endif /* HAS_LIBCONFIG */ __attribute__((unused)) static int lookup_test(const char *name) { int i; for (i = 0; i < ARRAY_SIZE(tests); ++i) if (!strcmp(name, tests[i].name)) return i; return -1; } __attribute__((unused)) static void test_skipped(void **state) { skip(); } #ifdef HAS_LIBCONFIG static int apply_test_config(FILE *input) { config_t cfg; config_setting_t *root; config_setting_t *tests_node, *node; int i, count, ind; int ret = 0, cfg_ret = 0; const char *test_name; char selected[ARRAY_SIZE(tests)]; for (i = 0; i < ARRAY_SIZE(selected); ++i) selected[i] = 0; config_init(&cfg); cfg_ret = config_read(&cfg, input); if (cfg_ret != CONFIG_TRUE) { fprintf(stderr, "Wrong config format\n"); ret = -EINVAL; goto out; } root = config_root_setting(&cfg); tests_node = config_setting_get_member(root, TESTS_TAG); if (!tests_node || !config_setting_is_list(tests_node)) { fprintf(stderr, "Missing or incorrect tests list\n"); ret = -EINVAL; goto out; } count = config_setting_length(tests_node); for (i = 0; i < count; ++i) { node = config_setting_get_elem(tests_node, i); if (!node) { ret = -EINVAL; goto out; } test_name = config_setting_get_string(node); if (!test_name) { fprintf(stderr, "Incorrect tests list. Element %d\n", i); ret = -EINVAL; goto out; } ind = lookup_test(test_name); if (ind < 0) { fprintf(stderr, "Test %s not found.\n", test_name); ret = -EINVAL; goto out; } selected[ind] = 1; } for (i = 0; i < ARRAY_SIZE(selected); ++i) { if (selected[i]) continue; tests[i].test_func = &test_skipped; tests[i].setup_func = NULL; tests[i].teardown_func = NULL; } out: config_destroy(&cfg); return ret; } #else static int apply_test_config(FILE *input) { fprintf(stderr, "Libconfig is not supported\n"); return -ENOTSUP; } #endif /* HAS_LIBCONFIG */ static void print_help() { fprintf(stderr, "libusbgx test suit:\n" " --generate-config - generates config to stdout and exit\n" " --use-config - runs test suit using config from stdin\n" " -h --help - print this message\n" ); } int main(int argc, char **argv) { enum { GENERATE_CONFIG = 0x01, USE_CONFIG = 0x02, }; int options = 0; int opt; int ret = -EINVAL; static struct option long_options[] = { {"generate-config", no_argument, 0, 1}, {"use-config", no_argument, 0, 2}, {"help", no_argument, 0, 'h'}, {NULL, 0, 0, 0} }; while (1) { opt = getopt_long(argc, argv, "h", long_options, NULL); if (opt < 0) break; switch (opt) { case 1: options |= GENERATE_CONFIG; break; case 2: options |= USE_CONFIG; break; case 'h': default: print_help(); goto out; } } if (optind < argc || ((options & GENERATE_CONFIG) && (options & USE_CONFIG))) { print_help(); goto out; } if (options & GENERATE_CONFIG) { ret = gen_test_config(stdout); goto out; } if (options & USE_CONFIG) { ret = apply_test_config(stdin); if (ret) goto out; } ret = cmocka_run_group_tests(tests, NULL, NULL); out: return ret; } libusbgx-libusbgx-v0.3.0/tests/test.sh000077500000000000000000000024241467553526200200350ustar00rootroot00000000000000#!/bin/bash #USE_CONFIG=0 #GENERATE_CONFIG=0 #HELP=$HELP # for autotools compability (config can be passed by environment variable) if [[ -n $USE_CONFIG ]] then CONFIG_FILE=$USE_CONFIG elif [[ -n $GENERATE_CONFIG ]] then CONFIG_FILE=$GENERATE_CONFIG fi function usage { echo "libusbgx test suit" echo "Usage: ./test.sh [option]" echo "Options:" echo " --generate-config filename - generates config to given file and exit" echo " --use-config filename - runs test suit using config from given file" echo " -h --help - print this message" } # Parse arguments ARGS=$(getopt --long generate-config:,use-config:,help -o h -- "$@" ) if [ $? -ne 0 ] then HELP=1 fi eval set -- $ARGS while true; do case $1 in -h|--help) HELP=1 shift ;; --use-config) USE_CONFIG=1 CONFIG_FILE=$2 shift 2 ;; --generate-config) GENERATE_CONFIG=1 CONFIG_FILE=$2 shift 2 ;; --) shift break ;; *) HELP=1 shift ;; esac done # Run test with io functions ovverride if [[ -n $USE_CONFIG ]] then LD_LIBRARY_PATH=. ./test --use-config < $CONFIG_FILE elif [[ -n $GENERATE_CONFIG ]] then LD_LIBRARY_PATH=. ./test --generate-config > $CONFIG_FILE elif [[ -n $HELP ]] then usage exit 77 # autotools consider it skipped else LD_LIBRARY_PATH=. ./test fi libusbgx-libusbgx-v0.3.0/tests/usbg-io-wrappers.c000066400000000000000000000110431467553526200220660ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include #include typedef int (*fwrite_f_type)(const void *ptr, size_t size, size_t nmemb, FILE *stream); typedef int (*fflush_f_type)(FILE *); typedef fflush_f_type ferror_f_type; /** * @brief Simulates opening file * @details Checks if path is equal expected value and returns given pointer * from cmocka queue */ FILE *fopen(const char *path, const char *mode) { check_expected(path); return mock_ptr_type(FILE *); } /** * @brief Simulates closing file * @details Does absolutely nothing, always acts as successfull close */ int fclose(FILE *fp) { check_expected(fp); return mock_type(int); } /** * @brief Simulates reading file * @details Does not read any file, instead returns value from cmocka queue * @return value specified by caller previously */ size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) { char *data; int len; size_t ret; check_expected(stream); data = mock_ptr_type(char *); len = mock_type(int); ret = size * nmemb < len ? size * nmemb : len; memcpy(ptr, data, ret); return ret; } /** * @brief Simulates opening directory * @details Does not open any dir, instead returns user-specified value * @return value specified by caller previously */ DIR *opendir(const char *name) { int err; check_expected(name); err = mock_type(int); if (err) errno = err; return mock_ptr_type(DIR *); } /** * @brief Simulates closing directory * @details Does nothing and ends successfully. */ int closedir(DIR *dirp) { check_expected(dirp); return mock_type(int); } /** * @brief Simulates scanning directory * @details Checks if dirp has expected value. Then consecutive values from * cmocka queue are proceed. First value must be integer and indicates number * of directory entries which should be returned. Next number of values indicate * names of directory entries. */ int scandir(const char *dirp, struct dirent ***namelist, int (*filter)(const struct dirent *), int (*compar)(const struct dirent **, const struct dirent **)) { int count; int i, j = 0; char *name; struct dirent **entries; struct dirent *entry; int tmp, expected; check_expected(dirp); count = mock_type(int); if (count > 0) entries = calloc(count, sizeof(*entries)); else entries = NULL; for (i = 0; i < count; i++) { name = mock_ptr_type(char *); entry = malloc(sizeof(*entry)); if (strlen(name) >= NAME_MAX) fail(); strcpy(entry->d_name, name); entry->d_type = mock_type(unsigned char); expected = mock_type(int); if (filter) { tmp = filter(entry); assert_int_equal(tmp, expected); if (tmp) entries[j++] = entry; else free(entry); } } if (compar) qsort(entries, count, sizeof(*entries), (int (*)(const void *,const void *))compar); *namelist = entries; return j; } /** * @brief Simultes readlink, with user-specified behavior * @datails Check if path and bufsiz equal expedted values and * write to buf string given by cmocka */ ssize_t readlink(const char *path, char *buf, size_t bufsiz) { char *res; int reslen; check_expected(path); check_expected(bufsiz); res = mock_ptr_type(char *); reslen = strlen(res); if (bufsiz <= reslen) fail(); strcpy(buf, res); return reslen; } /** * @brief Simulates write, with user-specified behavior * @details Check if user is trying to write expected data * @return value received from cmocka queue */ size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) { int ret; /* * Cmocka (or anything else) may want to print some errors. * Especially when running fwrite() itself */ if (stream == stderr || stream == stdout) { fwrite_f_type orig_fwrite; orig_fwrite = (fwrite_f_type)dlsym(RTLD_NEXT, "fwrite"); return orig_fwrite(ptr, size, nmemb, stream); } check_expected(stream); check_expected(ptr); ret = mock_type(int); if (!ret) ret = nmemb; return ret; } int mkdir(const char *pathname, mode_t mode) { check_expected(pathname); check_expected(mode); return mock_type(int); } /** * @brief Does nothing. */ int fflush(FILE *stream) { if (stream == stderr || stream == stdout) { fflush_f_type orig_fflush; orig_fflush = (fflush_f_type)dlsym(RTLD_NEXT, "fflush"); return orig_fflush(stream); } return 0; } int ferror(FILE *stream) { if (stream == stderr || stream == stdout) { ferror_f_type orig_ferror; orig_ferror = (ferror_f_type)dlsym(RTLD_NEXT, "ferror"); return orig_ferror(stream); } return 0; } libusbgx-libusbgx-v0.3.0/tests/usbg-test.c000066400000000000000000001001771467553526200206040ustar00rootroot00000000000000#include #include #include #include #include #include #include #include #include #include #include #include "usbg-test.h" static struct simple_stack{ void *ptr; struct simple_stack *next; } *cleanup_top = NULL; static const char *gadget_str_names[] = { "manufacturer", "product", "serialnumber", }; static const char *config_attr_names[] = { "MaxPower", "bmAttributes" }; static attr_format config_attr_format[] = { [MAX_POWER] = FORMAT_DEC, [BM_ATTRIBUTES] = FORMAT_HEX }; void free_later(void *ptr) { struct simple_stack *t; t = malloc(sizeof(*t)); t->ptr = ptr; t->next = cleanup_top; cleanup_top = t; } void cleanup_stack() { struct simple_stack *t; while (cleanup_top) { free(cleanup_top->ptr); t = cleanup_top->next; free(cleanup_top); cleanup_top = t; } } /* Represent last file/dir opened, next should have bigger numbers.*/ static int file_id = 0; static int dir_id = 0; #define PUSH_FILE(file, content, len) do {\ file_id++;\ expect_path(fopen, path, file);\ will_return(fopen, file_id);\ expect_value(fread, stream, file_id);\ will_return(fread, content);\ will_return(fread, len);\ expect_value(fclose, fp, file_id);\ will_return(fclose, 0);\ } while(0) #define PUSH_FILE_STR(file, content) \ PUSH_FILE(file, content, strlen(content) + 1); #define PUSH_EMPTY_DIR(p) do {\ expect_string(scandir, dirp, p);\ will_return(scandir, 0);\ } while(0) #define EXPECT_OPENDIR(n) do {\ dir_id++;\ expect_path(opendir, name, n);\ will_return(opendir, 0);\ will_return(opendir, dir_id);\ expect_value(closedir, dirp, dir_id);\ will_return(closedir, 0);\ } while(0) #define EXPECT_OPENDIR_ERROR(n, e) do {\ expect_path(opendir, name, n);\ will_return(opendir, e);\ will_return(opendir, NULL);\ } while(0) #define PUSH_DIR(p, c) do {\ expect_path(scandir, dirp, p);\ will_return(scandir, c);\ } while(0) #define PUSH_DIR_ENTRY(name, type) do {\ will_return(scandir, name);\ will_return(scandir, type);\ will_return(scandir, 1);\ } while(0) #define PUSH_LINK(p, c, len) do {\ expect_path(readlink, path, p);\ expect_in_range(readlink, bufsiz, len, INT_MAX);\ will_return(readlink, c);\ } while(0) #define EXPECT_WRITE(file, content, len) do { \ file_id++;\ expect_path(fopen, path, file);\ will_return(fopen, file_id);\ expect_value(fwrite, stream, file_id);\ expect_memory(fwrite, ptr, content, len); \ will_return(fwrite, len);\ expect_value(fclose, fp, file_id);\ will_return(fclose, 0);\ } while(0) #define EXPECT_WRITE_STR(file, content)\ EXPECT_WRITE(file, content, strlen(content) + 1) #define EXPECT_HEX_WRITE(file, content) do {\ file_id++;\ expect_path(fopen, path, file);\ will_return(fopen, file_id);\ expect_value(fwrite, stream, file_id);\ expect_check(fwrite, ptr, hex_str_equal_display_error, content);\ will_return(fwrite, 0);\ expect_value(fclose, fp, file_id);\ will_return(fclose, 0);\ } while(0) #define EXPECT_MKDIR(p) do {\ expect_path(mkdir, pathname, p);\ expect_value(mkdir, mode, 00777);\ will_return(mkdir, 0);\ } while(0) /** * @brief Compare test gadgets' names */ static int test_gadget_cmp(struct test_gadget *a, struct test_gadget *b) { return strcoll(a->name, b->name); } /** * @brief Compare test functions' names */ static int test_function_cmp(struct test_function *a, struct test_function *b) { return strcoll(a->name, b->name); } /** * @brief Compare test bindings' names */ static int test_binding_cmp(struct test_binding *a, struct test_binding *b) { return strcoll(a->name, b->name); } /** * @brief Compare test configs' names */ static int test_config_cmp(struct test_config *a, struct test_config *b) { return strcoll(a->name, b->name); } void prepare_binding(struct test_binding *b, struct test_function *f, char *fpath) { if (!f->name) prepare_function(f, fpath); if (!b->name) { b->name = strdup(f->name); if (b->name == NULL) fail(); free_later(b->name); } b->target = f; } void prepare_config(struct test_config *c, char *cpath, char *fpath) { int count = 0; struct test_function *f; struct test_binding *b; int i; safe_asprintf(&c->name, "%s.%d", c->label, c->id); c->path = cpath; /* check if bindings has been already filled */ if (!c->bindings) { for (f = c->bound_funcs; f->instance; f++) count++; c->bindings = safe_calloc(count + 1, sizeof(*c->bindings)); } else { for (b = c->bindings; b->name; b++) count++; } for (i = 0; i < count; i++) prepare_binding(&c->bindings[i], &c->bound_funcs[i], fpath); qsort(c->bindings, count, sizeof(*c->bindings), (int (*)(const void *, const void *))test_binding_cmp); } void prepare_function(struct test_function *f, char *path) { const char *func_type; func_type = usbg_get_function_type_str(f->type); if (func_type == NULL) fail(); safe_asprintf(&f->name, "%s.%s", func_type, f->instance); f->path = path; } void prepare_gadget(struct test_state *state, struct test_gadget *g) { struct test_config *c; struct test_function *f; char *fpath; char *cpath; int count; g->path = strdup(state->path); if (!g->path) fail(); free_later(g->path); safe_asprintf(&fpath, "%s/%s/functions", g->path, g->name); count = 0; for (f = g->functions; f->instance; f++) { prepare_function(f, fpath); count++; } /* Path needs to be known somehow when list is empty */ f->path = fpath; qsort(g->functions, count, sizeof(*g->functions), (int (*)(const void *, const void *))test_function_cmp); safe_asprintf(&cpath, "%s/%s/configs", g->path, g->name); count = 0; for (c = g->configs; c->label; c++) { prepare_config(c, cpath, fpath); count++; } /* Path needs to be known somehow when list is empty */ c->path = cpath; qsort(g->configs, count, sizeof(*g->configs), (int (*)(const void *, const void *))test_config_cmp); } static void cpy_test_function(struct test_function *to, struct test_function *from) { /* Reuse instance */ to->instance = from->instance; to->type = from->type; /* path and name is not being copied because it has not been allocated now */ to->writable = 1; } static struct test_function *dup_test_functions(struct test_function *functions) { struct test_function *f, *nf, *new_functions; int count = 0; for (f = functions; f->instance; ++f) ++count; new_functions = safe_calloc(count + 1, sizeof(*f)); for (f = functions, nf = new_functions; f->instance; ++f, ++nf) cpy_test_function(nf, f); return new_functions; } static struct test_function *get_new_binding_target(struct test_function *which, struct test_function *old, int count, struct test_function *new) { struct test_function *ret = NULL; /* Should duplicate function? */ if (which < old || ((which - old) > count)) { /* We may need to do a deep copy */ if (!which->writable) { ret = safe_calloc(1, sizeof(*ret)); cpy_test_function(ret, which); } else { ret = which; } } else if (old != new) { /* Function has been copied in bound_funcs so just set new address */ ret = which - old + new; } else { /* Functions are reused so leave address as is */ ret = which; } return ret; } static void cpy_test_binding(struct test_binding *to, struct test_binding *from, struct test_function *old, int func_count, struct test_function *new) { /* Reuse name */ to->name = from->name; to->target = get_new_binding_target(from->target, old, func_count, new); to->writable = 1; } static struct test_binding *dup_test_bindings(struct test_binding *bindings, struct test_function *old, int func_count, struct test_function *new) { struct test_binding *b, *nb, *new_bindings; int count = 0; for (b = bindings; b->name; ++b) ++count; new_bindings = safe_calloc(count + 1, sizeof(*b)); for (b = bindings, nb = new_bindings; b->name; ++b, ++nb) cpy_test_binding(nb, b, old, func_count, new); return new_bindings; } static void cpy_test_config(struct test_config *to, struct test_config *from) { int func_count = 0; struct test_function *f; struct test_binding *b; /* Reuse label */ to->label = from->label; to->id = from->id; to->strs = from->strs; to->attrs = from->attrs; if (from->bound_funcs) { /* If at least one function is not writable we have to copy all of them */ for (f = from->bound_funcs; f->instance; ++f) { ++func_count; if (!f->writable && !to->bound_funcs) { to->bound_funcs = dup_test_functions(from->bound_funcs); } } if (!f->name && !to->bound_funcs) to->bound_funcs = from->bound_funcs; } /* If bindings are set copy also them */ if (from->bindings) { /* If at least one function is not writable we have to copy all of them */ for (b = from->bindings; b->name; ++b) if (!b->writable) to->bindings = dup_test_bindings(from->bindings, from->bound_funcs, func_count, to->bound_funcs); /* if we are reusing binding we have to translate target address to new one which is writable */ if (!b->name && !to->bindings) { to->bindings = from->bindings; for (b = from->bindings; b->name; ++b) b->target = get_new_binding_target( b->target, from->bound_funcs, func_count, to->bound_funcs); } } to->writable = 1; } static struct test_config *dup_test_configs(struct test_config *configs) { struct test_config *c, *nc, *new_configs; int count = 0; for (c = configs; c->label; ++c) ++count; new_configs = safe_calloc(count + 1, sizeof(*c)); for (c = configs, nc = new_configs; c->label; ++c, ++nc) cpy_test_config(nc, c); return new_configs; } static void cpy_test_gadget(struct test_gadget *to, struct test_gadget *from) { struct test_function *f; struct test_config *c; /* Reuse name and udc */ to->name = from->name; to->udc = from->udc; /* path is not being copied because it has not been allocated */ /* If at least one function is not writable we have to copy all of them */ for (f = from->functions; f->instance; ++f) if (!f->writable) { to->functions = dup_test_functions(from->functions); break; } if (!f->name && !to->functions) to->functions = from->functions; /* If at least one config is not writable we have to copy all of them */ for (c = from->configs; c->label; ++c) if (!c->writable) { to->configs = dup_test_configs(from->configs); break; } if (!c->name && !to->configs) to->configs = from->configs; to->writable = 1; } static struct test_gadget *dup_test_gadgets(struct test_gadget *gadgets) { struct test_gadget *g, *ng, *new_gadgets; int count = 0; for (g = gadgets; g->name; ++g) ++count; new_gadgets = safe_calloc(count + 1, sizeof(*g)); for (g = gadgets, ng = new_gadgets; g->name; ++g, ++ng) cpy_test_gadget(ng, g); return new_gadgets; } static struct test_state *dup_test_state(struct test_state *state) { struct test_state *new_state; struct test_gadget *g; new_state = safe_calloc(1, sizeof(*new_state)); /* We don't copy configfs path because it is never changed if you would like to free it before test end replace this code with strdup */ new_state->configfs_path = state->configfs_path; /* path is not being copied because it has not been allocated */ /* If at least one gadget is not writable we have to copy all of them */ for (g = state->gadgets; g->name; ++g) if (!g->writable) { new_state->gadgets = dup_test_gadgets(state->gadgets); break; } if (!g->name && !new_state->gadgets) new_state->gadgets = state->gadgets; /* udcs are also never changed so leave them as they are */ new_state->udcs = state->udcs; new_state->writable = 1; return new_state; } struct test_state *prepare_state(struct test_state *state) { struct test_gadget *g; struct test_state *new_state; int count = 0; if (!state->writable) new_state = dup_test_state(state); else new_state = state; safe_asprintf(&(new_state->path), "%s/usb_gadget", new_state->configfs_path); for (g = new_state->gadgets; g->name; g++) { prepare_gadget(new_state, g); count++; } qsort(new_state->gadgets, count, sizeof(*new_state->gadgets), (int (*)(const void *, const void *))test_gadget_cmp); return new_state; } struct test_state *build_empty_gadget_state(struct test_state *ts) { struct test_state *ret; struct test_gadget *tg; int count = 0; ret = safe_malloc(sizeof(*ret)); ret->udcs = ts->udcs; ret->configfs_path = ts->configfs_path; for (tg = ts->gadgets; tg->name; ++tg) count++; ret->gadgets = safe_calloc(count+1, sizeof(*ts->gadgets)); memcpy(ret->gadgets, ts->gadgets, count*sizeof(*ts->gadgets)); for (tg = ret->gadgets; tg->name; ++tg) { tg->configs = safe_calloc(1, sizeof(*tg->configs)); tg->functions = safe_calloc(1, sizeof(*tg->functions)); } return prepare_state(ret); } /* Simulation of configfs for init */ static void push_binding(struct test_config *conf, struct test_binding *binding) { char *s_path; char *d_path; safe_asprintf(&s_path, "%s/%s/%s", conf->path, conf->name, binding->name); safe_asprintf(&d_path, "%s/%s", binding->target->path, binding->target->name); PUSH_LINK(s_path, d_path, USBG_MAX_PATH_LENGTH - 1); } static void push_config(struct test_config *c) { struct test_binding *b; int count = 0; char *path; safe_asprintf(&path, "%s/%s", c->path, c->name); for (b = c->bindings; b->name; b++) count++; PUSH_DIR(path, count); for (b = c->bindings; b->name; b++) { PUSH_DIR_ENTRY(b->name, DT_LNK); push_binding(c, b); } } static void push_gadget(struct test_gadget *g) { int count; struct test_config *c; struct test_function *f; char *path, *os_desc_path; safe_asprintf(&path, "%s/%s/UDC", g->path, g->name); PUSH_FILE_STR(path, g->udc); count = 0; for (f = g->functions; f->instance; f++) count++; PUSH_DIR(f->path, count); for (f = g->functions; f->instance; f++) PUSH_DIR_ENTRY(f->name, DT_DIR); count = 0; for (c = g->configs; c->label; c++) count++; PUSH_DIR(c->path, count); for (c = g->configs; c->label; c++) PUSH_DIR_ENTRY(c->name, DT_DIR); for (c = g->configs; c->label; c++) push_config(c); safe_asprintf(&os_desc_path, "%s/%s/os_desc", g->path, g->name); PUSH_DIR(os_desc_path, 0); } void push_init(struct test_state *state) { char **udc; struct test_gadget *g; int count = 0; EXPECT_OPENDIR(state->path); for (udc = state->udcs; *udc; udc++) count++; PUSH_DIR("/sys/class/udc", count); for (udc = state->udcs; *udc; udc++) PUSH_DIR_ENTRY(*udc, DT_REG); count = 0; for (g = state->gadgets; g->name; g++) count++; PUSH_DIR(state->path, count); for (g = state->gadgets; g->name; g++) { PUSH_DIR_ENTRY(g->name, DT_DIR); } for (g = state->gadgets; g->name; g++) push_gadget(g); } int get_gadget_attr(struct usbg_gadget_attrs *attrs, usbg_gadget_attr attr) { int ret = -1; switch (attr) { case USBG_BCD_USB: ret = attrs->bcdUSB; break; case USBG_B_DEVICE_CLASS: ret = attrs->bDeviceClass; break; case USBG_B_DEVICE_SUB_CLASS: ret = attrs->bDeviceSubClass; break; case USBG_B_DEVICE_PROTOCOL: ret = attrs->bDeviceProtocol; break; case USBG_B_MAX_PACKET_SIZE_0: ret = attrs->bMaxPacketSize0; break; case USBG_ID_VENDOR: ret = attrs->idVendor; break; case USBG_ID_PRODUCT: ret = attrs->idProduct; break; case USBG_BCD_DEVICE: ret = attrs->bcdDevice; break; default: ret = -1; break; } return ret; } void pull_gadget_attribute(struct test_gadget *gadget, usbg_gadget_attr attr, int value) { char *path; char *content; safe_asprintf(&path, "%s/%s/%s", gadget->path, gadget->name, usbg_get_gadget_attr_str(attr)); safe_asprintf(&content, "0x%x\n", value); EXPECT_HEX_WRITE(path, content); } void push_gadget_attribute(struct test_gadget *gadget, usbg_gadget_attr attr, int value) { char *path; char *content; safe_asprintf(&path, "%s/%s/%s", gadget->path, gadget->name, usbg_get_gadget_attr_str(attr)); safe_asprintf(&content, "0x%x\n", value); PUSH_FILE_STR(path, content); } void push_gadget_attrs(struct test_gadget *gadget, struct usbg_gadget_attrs *attrs) { int i; for (i = USBG_GADGET_ATTR_MIN; i < USBG_GADGET_ATTR_MAX; i++) push_gadget_attribute(gadget, i, get_gadget_attr(attrs, i)); } void pull_gadget_attrs(struct test_gadget *gadget, struct usbg_gadget_attrs *attrs) { int i; for (i = USBG_GADGET_ATTR_MIN; i < USBG_GADGET_ATTR_MAX; i++) pull_gadget_attribute(gadget, i, get_gadget_attr(attrs, i)); } void init_with_state(struct test_state *in, usbg_state **out) { int usbg_ret; push_init(in); usbg_ret = usbg_init(in->configfs_path, out); assert_int_equal(usbg_ret, USBG_SUCCESS); } void safe_init_with_state(void **state, struct test_state **ts, usbg_state **s) { *ts = (struct test_state *)(*state); *state = NULL; init_with_state(*ts, s); *state = *s; } static int get_config_attr(struct usbg_config_attrs *attrs, config_attr attr) { int ret; switch (attr) { case MAX_POWER: ret = attrs->bMaxPower; break; case BM_ATTRIBUTES: ret = attrs->bmAttributes; break; default: ret = -1; break; } return ret; } void push_config_attribute(struct test_config *config, config_attr attr, int value) { char *path; char *content; safe_asprintf(&path, "%s/%s/%s", config->path, config->name, config_attr_names[attr]); switch (config_attr_format[attr]) { case FORMAT_HEX: safe_asprintf(&content, "0x%x\n", value); break; case FORMAT_DEC: safe_asprintf(&content, "%d\n", value); break; } PUSH_FILE_STR(path, content); } void push_config_attrs(struct test_config *config, struct usbg_config_attrs *attrs) { int i; for (i = 0; i < CONFIG_ATTR_MAX; ++i) push_config_attribute(config, i, get_config_attr(attrs, i)); } void pull_config_attribute(struct test_config *config, config_attr attr, int value) { char *path; char *content; safe_asprintf(&path, "%s/%s/%s", config->path, config->name, config_attr_names[attr]); switch (config_attr_format[attr]) { case FORMAT_HEX: safe_asprintf(&content, "0x%x\n", value); break; case FORMAT_DEC: safe_asprintf(&content, "%d\n", value); break; } switch (config_attr_format[attr]) { case FORMAT_HEX: EXPECT_HEX_WRITE(path, content); break; case FORMAT_DEC: EXPECT_WRITE_STR(path, content); break; } } void pull_config_attrs(struct test_config *config, struct usbg_config_attrs *attrs) { int i; for (i = 0; i < CONFIG_ATTR_MAX; ++i) pull_config_attribute(config, i, get_config_attr(attrs, i)); } const char *get_gadget_str(struct usbg_gadget_strs *strs, gadget_str str) { const char *ret = NULL; switch (str) { case STR_SER: ret = strs->serial; break; case STR_MNF: ret = strs->manufacturer; break; case STR_PRD: ret = strs->product; break; default: ret = NULL; break; } return ret; } static void pull_gadget_str_dir(struct test_gadget *gadget, int lang) { char *dir; int tmp; safe_asprintf(&dir, "%s/%s/strings/0x%x", gadget->path, gadget->name, lang); srand(time(NULL)); tmp = rand() % 2; if (tmp) { EXPECT_OPENDIR(dir); } else { EXPECT_OPENDIR_ERROR(dir, ENOENT); EXPECT_MKDIR(dir); } } static void pull_gadget_str(struct test_gadget *gadget, const char *attr_name, int lang, const char *content) { char *path; safe_asprintf(&path, "%s/%s/strings/0x%x/%s", gadget->path, gadget->name, lang, attr_name); EXPECT_WRITE_STR(path, content); } void pull_gadget_string(struct test_gadget *gadget, int lang, gadget_str str, const char *content) { pull_gadget_str_dir(gadget, lang); pull_gadget_str(gadget, gadget_str_names[str], lang, content); } void pull_gadget_strs(struct test_gadget *gadget, int lang, struct usbg_gadget_strs *strs) { int i; pull_gadget_str_dir(gadget, lang); for (i = 0; i < GADGET_STR_MAX; i++) pull_gadget_str(gadget, gadget_str_names[i], lang, get_gadget_str(strs, i)); } static void push_gadget_str_dir(struct test_gadget *gadget, int lang) { char *dir; safe_asprintf(&dir, "%s/%s/strings/0x%x", gadget->path, gadget->name, lang); EXPECT_OPENDIR(dir); } static void push_gadget_str(struct test_gadget *gadget, const char *attr_name, int lang, const char *content) { char *path; safe_asprintf(&path, "%s/%s/strings/0x%x/%s", gadget->path, gadget->name, lang, attr_name); PUSH_FILE_STR(path, content); } void push_gadget_strs(struct test_gadget *gadget, int lang, struct usbg_gadget_strs *strs) { int i; push_gadget_str_dir(gadget, lang); for (i = 0; i < GADGET_STR_MAX; i++) push_gadget_str(gadget, gadget_str_names[i], lang, get_gadget_str(strs, i)); } void pull_config_string(struct test_config *config, int lang, const char *str) { char *path; int tmp; safe_asprintf(&path, "%s/%s/strings/0x%x", config->path, config->name, lang); srand(time(NULL)); tmp = rand() % 2; if (tmp) { EXPECT_OPENDIR(path); } else { EXPECT_OPENDIR_ERROR(path, ENOENT); EXPECT_MKDIR(path); } safe_asprintf(&path, "%s/configuration", path); EXPECT_WRITE_STR(path, str); } void pull_config_strs(struct test_config *config, int lang, struct usbg_config_strs *strs) { pull_config_string(config, lang, strs->configuration); } void push_config_string(struct test_config *config, int lang, const char *str) { char *path; safe_asprintf(&path, "%s/%s/strings/0x%x", config->path, config->name, lang); EXPECT_OPENDIR(path); safe_asprintf(&path, "%s/configuration", path); PUSH_FILE_STR(path, str); } void push_config_strs(struct test_config *config, int lang, struct usbg_config_strs *strs) { push_config_string(config, lang, strs->configuration); } void assert_config_attrs_equal(struct usbg_config_attrs *actual, struct usbg_config_attrs *expected) { assert_int_equal(actual->bmAttributes, expected->bmAttributes); assert_int_equal(actual->bMaxPower, expected->bMaxPower); } void pull_create_config(struct test_config *tc) { char *path; safe_asprintf(&path, "%s/%s", tc->path, tc->name); EXPECT_MKDIR(path); if (tc->attrs) pull_config_attrs(tc, tc->attrs); if (tc->strs) pull_config_strs(tc, LANG_US_ENG, tc->strs); } #define ETHER_ADDR_STR_LEN 19 static void push_serial_attrs(struct test_function *func, int *port_num) { char *path; char *content; safe_asprintf(&path, "%s/%s/port_num", func->path, func->name); safe_asprintf(&content, "%d\n", *port_num); PUSH_FILE_STR(path, content); } static void push_net_attrs(struct test_function *func, struct usbg_f_net_attrs *attrs) { char *path; char *content; safe_asprintf(&path, "%s/%s/dev_addr", func->path, func->name); content = safe_malloc(ETHER_ADDR_STR_LEN * sizeof(char)); ether_ntoa_r(&attrs->dev_addr, content); PUSH_FILE_STR(path, content); path = safe_malloc(USBG_MAX_PATH_LENGTH * sizeof(char)); sprintf(path, "%s/%s/host_addr", func->path, func->name); content = safe_malloc(ETHER_ADDR_STR_LEN * sizeof(char)); ether_ntoa_r(&attrs->host_addr, content); PUSH_FILE_STR(path, content); safe_asprintf(&path, "%s/%s/ifname", func->path, func->name); safe_asprintf(&content, "%s\n", attrs->ifname); PUSH_FILE_STR(path, content); safe_asprintf(&path, "%s/%s/qmult", func->path, func->name); safe_asprintf(&content, "%d\n", attrs->qmult); PUSH_FILE_STR(path, content); safe_asprintf(&path, "%s/%s/class", func->path, func->name); safe_asprintf(&content, "%d\n", attrs->class_); PUSH_FILE_STR(path, content); safe_asprintf(&path, "%s/%s/subclass", func->path, func->name); safe_asprintf(&content, "%d\n", attrs->subclass); PUSH_FILE_STR(path, content); safe_asprintf(&path, "%s/%s/protocol", func->path, func->name); safe_asprintf(&content, "%d\n", attrs->protocol); PUSH_FILE_STR(path, content); } static void push_phonet_attrs(struct test_function *func, char **ifname) { char *path; char *content; safe_asprintf(&path, "%s/%s/ifname", func->path, func->name); safe_asprintf(&content, "%s\n", *ifname); PUSH_FILE_STR(path, content); } void push_function_attrs(struct test_function *func, void *function_attrs) { switch (func->type) { case USBG_F_ACM: case USBG_F_OBEX: case USBG_F_SERIAL: push_serial_attrs(func, function_attrs); break; case USBG_F_ECM: case USBG_F_SUBSET: case USBG_F_NCM: case USBG_F_EEM: case USBG_F_RNDIS: push_net_attrs(func, function_attrs); break; case USBG_F_PHONET: push_phonet_attrs(func, function_attrs); break; case USBG_F_FFS: // ffs does not exist in filesystem default: break; } } static void pull_function_net_attrs(struct test_function *func, struct usbg_f_net_attrs *attrs) { char *path; char *content; safe_asprintf(&path, "%s/%s/dev_addr", func->path, func->name); content = safe_malloc(ETHER_ADDR_STR_LEN * sizeof(char)); usbg_ether_ntoa_r(&attrs->dev_addr, content); EXPECT_WRITE_STR(path, content); safe_asprintf(&path, "%s/%s/host_addr", func->path, func->name); content = safe_malloc(ETHER_ADDR_STR_LEN * sizeof(char)); usbg_ether_ntoa_r(&attrs->host_addr, content); EXPECT_WRITE_STR(path, content); safe_asprintf(&path, "%s/%s/qmult", func->path, func->name); safe_asprintf(&content, "%d\n", attrs->qmult); EXPECT_WRITE_STR(path, content); safe_asprintf(&path, "%s/%s/class", func->path, func->name); safe_asprintf(&content, "%d\n", attrs->class_); EXPECT_WRITE_STR(path, content); safe_asprintf(&path, "%s/%s/subclass", func->path, func->name); safe_asprintf(&content, "%d\n", attrs->subclass); EXPECT_WRITE_STR(path, content); safe_asprintf(&path, "%s/%s/protocol", func->path, func->name); safe_asprintf(&content, "%d\n", attrs->protocol); EXPECT_WRITE_STR(path, content); } void pull_function_attrs(struct test_function *func, void *attrs) { switch (func->type) { case USBG_F_ECM: case USBG_F_SUBSET: case USBG_F_NCM: case USBG_F_EEM: case USBG_F_RNDIS: pull_function_net_attrs(func, attrs); break; default: break; } } void pull_create_function(struct test_function *tf) { char *path; int tmp; tmp = asprintf(&path, "%s/%s", tf->path, tf->name); if (tmp < 0) fail(); free_later(path); EXPECT_MKDIR(path); if (tf->attrs) pull_function_attrs(tf, tf->attrs); } void assert_func_equal(usbg_function *f, struct test_function *expected) { assert_string_equal(f->instance, expected->instance); assert_int_equal(f->type, expected->type); assert_path_equal(f->path, expected->path); } void assert_binding_equal(usbg_binding *b, struct test_binding *expected) { assert_string_equal(b->name, expected->name); assert_func_equal(b->target, expected->target); } void assert_config_equal(usbg_config *c, struct test_config *expected) { int i = 0; usbg_binding *b; assert_int_equal(c->id, expected->id); assert_string_equal(c->label, expected->label); assert_path_equal(c->path, expected->path); usbg_for_each_binding(b, c) assert_binding_equal(b, &expected->bindings[i++]); } void assert_gadget_equal(usbg_gadget *g, struct test_gadget *expected) { usbg_config *c; usbg_function *f; int i; assert_string_equal(g->name, expected->name); assert_path_equal(g->path, expected->path); i = 0; usbg_for_each_function(f, g) assert_func_equal(f, &expected->functions[i++]); i = 0; usbg_for_each_config(c, g) assert_config_equal(c, &expected->configs[i++]); } void assert_state_equal(usbg_state *s, struct test_state *expected) { usbg_gadget *g; int i = 0; assert_path_equal(s->path, expected->path); assert_path_equal(s->configfs_path, expected->configfs_path); usbg_for_each_gadget(g, s) assert_gadget_equal(g, &expected->gadgets[i++]); } #define SIGNUM(x) (((x) > 0) - ((x) < 0)) int path_cmp(const char *actual, const char *expected) { const char *a = actual; const char *b = expected; while (*a != '\0' && *b != '\0') { if (*a != *b) break; do ++a; while (*a == '/'); do ++b; while (*b == '/'); } return SIGNUM(*a - *b); } int path_equal_display_error(const LargestIntegralType actual, const LargestIntegralType expected) { if (path_cmp((const char *)actual, (const char *)expected) == 0) { return 1; } fprintf(stderr, "%s != %s\n", (const char *)actual, (const char *)expected); return 0; } void assert_path_equal(const char *actual, const char *expected) { if (path_equal_display_error( cast_to_largest_integral_type(actual), cast_to_largest_integral_type(expected)) == 0) fail(); } int hex_str_cmp(const char *actual, const char *expected) { int a, b; sscanf(actual, "%x", &a); sscanf(expected, "%x", &b); return SIGNUM(a - b); } int hex_str_equal_display_error(const LargestIntegralType actual, const LargestIntegralType expected) { if (hex_str_cmp((const char *)actual, (const char *)expected) == 0) { return 1; } fprintf(stderr, "%s != %s\n", (const char *)actual, (const char *)expected); return 0; } void assert_gadget_attrs_equal(struct usbg_gadget_attrs *actual, struct usbg_gadget_attrs *expected) { int i; for (i = USBG_GADGET_ATTR_MIN; i < USBG_GADGET_ATTR_MAX; i++) assert_int_equal(get_gadget_attr(actual, i), get_gadget_attr(expected, i)); } void assert_gadget_strs_equal(struct usbg_gadget_strs *actual, struct usbg_gadget_strs *expected) { int i; for (i = 0; i < GADGET_STR_MAX; i++) assert_string_equal(get_gadget_str(actual, i), get_gadget_str(expected, i)); } void assert_f_serial_attrs_equal(int *actual, int *expected) { assert_int_equal(*actual, *expected); } static void assert_ether_addrs_equal(const struct ether_addr *ea1, const struct ether_addr *ea2) { assert_memory_equal(ea1->ether_addr_octet, ea2->ether_addr_octet, ETHER_ADDR_LEN); } void assert_f_net_attrs_equal(struct usbg_f_net_attrs *actual, struct usbg_f_net_attrs *expected) { assert_ether_addrs_equal(&actual->dev_addr, &expected->dev_addr); assert_ether_addrs_equal(&actual->host_addr, &expected->host_addr); assert_string_equal(actual->ifname, expected->ifname); assert_int_equal(actual->qmult, expected->qmult); assert_int_equal(actual->class_, expected->class_); assert_int_equal(actual->subclass, expected->subclass); assert_int_equal(actual->protocol, expected->protocol); } void assert_f_phonet_attrs_equal(char **actual, char **expected) { assert_string_equal(*actual, *expected); } void assert_f_ffs_attrs_equal(char **actual, char **expected) { assert_string_equal(*actual, *expected); } void assert_function_attrs_equal(void *actual, void *expected, usbg_function_type type) { switch (type) { case USBG_F_ACM: case USBG_F_OBEX: case USBG_F_SERIAL: assert_f_serial_attrs_equal(actual, expected); break; case USBG_F_ECM: case USBG_F_SUBSET: case USBG_F_NCM: case USBG_F_EEM: case USBG_F_RNDIS: assert_f_net_attrs_equal(actual, expected); break; case USBG_F_PHONET: assert_f_phonet_attrs_equal(actual, expected); break; case USBG_F_FFS: assert_f_ffs_attrs_equal(actual, expected); break; default: fail(); } } void for_each_test_function(struct test_state *ts, usbg_state *s, FunctionTest fun) { struct test_gadget *tg; struct test_function *tf; usbg_gadget *g = NULL; usbg_function *f = NULL; for (tg = ts->gadgets; tg->name; ++tg) { g = usbg_get_gadget(s, tg->name); assert_non_null(g); for (tf = tg->functions; tf->instance; ++tf) { f = usbg_get_function(g, tf->type, tf->instance); fun(f, tf); } } } void for_each_test_config(struct test_state *ts, usbg_state *s, ConfigTest fun) { usbg_gadget *g = NULL; usbg_config *c = NULL; struct test_gadget *tg; struct test_config *tc; for (tg = ts->gadgets; tg->name; tg++) { g = usbg_get_gadget(s, tg->name); assert_non_null(g); for (tc = tg->configs; tc->label; tc++) { c = usbg_get_config(g, tc->id, tc->label); fun(c, tc); } } } void for_each_binding(struct test_state *ts, usbg_state *s, BindingTestFunc fun) { struct test_gadget *tg; struct test_config *tc; struct test_binding *tb; usbg_gadget *g = NULL; usbg_config *c = NULL; usbg_binding *b = NULL; for (tg = ts->gadgets; tg->name; tg++) { g = usbg_get_gadget(s, tg->name); assert_non_null(g); for (tc = tg->configs; tc->label; tc++) { c = usbg_get_config(g, tc->id, tc->label); assert_non_null(c); b = usbg_get_first_binding(c); for (tb = tc->bindings; tb->name; ++tb) { assert_non_null(b); fun(tb, b); b = usbg_get_next_binding(b); } } } } void for_each_test_gadget(struct test_state *ts, usbg_state *s, GadgetTestFunc fun) { struct test_gadget *tg; usbg_gadget *g = NULL; for (tg = ts->gadgets; tg->name; ++tg) { g = usbg_get_gadget(s, tg->name); assert_non_null(g); fun(g, tg); } } libusbgx-libusbgx-v0.3.0/tests/usbg-test.h000066400000000000000000000414361467553526200206130ustar00rootroot00000000000000#ifndef USBG_TEST_H #define USBG_TEST_H #include #include #include #include #include #include #include #include "usbg/usbg_internal.h" /* Simple structures for defining gadgets. All arrays should be null-terminated.*/ /** * @file tests/usbg-test.h */ struct test_function { usbg_function_type type; char *instance; char *path; char *name; void *attrs; int writable; }; struct test_binding { struct test_function *target; char *name; int writable; }; struct test_config { char *label; int id; struct test_function *bound_funcs; struct test_binding *bindings; char *path; char *name; int writable; struct usbg_config_strs *strs; struct usbg_config_attrs *attrs; }; struct test_gadget { char *name; char *udc; struct test_config *configs; struct test_function *functions; char *path; int writable; }; struct test_state { char *configfs_path; /* filled by prepare_state() */ char *path; struct test_gadget *gadgets; char **udcs; int writable; }; typedef enum { STR_MNF = 0, STR_PRD, STR_SER, GADGET_STR_MAX } gadget_str; typedef enum { MAX_POWER = 0, BM_ATTRIBUTES, CONFIG_ATTR_MAX } config_attr; typedef enum { FORMAT_HEX, FORMAT_DEC } attr_format; #define TEST_FUNCTION_LIST_END { \ .instance = NULL, \ } #define TEST_CONFIG_LIST_END { \ .label = NULL, \ .bindings = NULL, \ } #define TEST_GADGET_LIST_END { \ .name = NULL, \ .udc = NULL, \ .configs = NULL, \ .functions = NULL, \ } #define expect_path(function, param, data) \ expect_check(function, param, \ (CheckParameterValue)(path_equal_display_error), data) /** * @brief Prepare given state for using in tests * @details Generate full pathes to state elements and sort state's content. * Must be called before pasing state to push_* and pull_* functions. * @param[in] state State schema used to genrate test state * @return Pointer to state which can be used for testing. Returned value is * equal to #state if writable attribute has been set to 1 or pointer * to newly allocated test_state filled with suitable values. All memory * allocated in this function is scheduled to free using free_later(). */ struct test_state *prepare_state(struct test_state *state); /** * @brief Prepare given config for using in tests * @details Generate required pathes for given config and sort content * (i.e. binding list) * @param[in] c Config to be filled out * @param[in] cpath Path to configs directory * @param[in] fpath Path to functions directory */ void prepare_config(struct test_config *c, char *cpath, char *fpath); /** * @brief Prepare given function for using in tests * @details Generate required pathes for given function * @param[in] f Function to be filled out * @param[in] path Path to functions directory */ void prepare_function(struct test_function *f, char *path); /** * @brief Prepare given gadget for using in tests * @details Generate required paths for given gadget and sort it's content * (i.e. functions list and config list) * @param[in] state Pointer to gadget's parent state * @param[in] g Gadget to be filled out */ void prepare_gadget(struct test_state *state, struct test_gadget *g); /** * @brief Fill given binding with required values * @details Make given binding point to a function * @param[in] b Test binding to be prepared * @param[in] f Function to which binding will point * @param[in] fpath Path to functions directory */ void prepare_binding(struct test_binding *b, struct test_function *f, char *fpath); /** * @brief Prepare fake filesystem to init usbg with given test state * @details Use wrapped i/o functions to simulate configfs state for usbg. * Calling usbg_init without preparation and with mocked i/o functions * may fail. * @param[in] state Fake state of configfs defined in test */ void push_init(struct test_state *state); /** * Prepare specific attributes writting/reading **/ /** * @brief Prepare for getting config attributes * @param[in] config Configuration from which attributes will be get * @param[in] attrs Attributes which will be present in virtual filesystem */ void push_config_attrs(struct test_config *config, struct usbg_config_attrs *attrs); /** * @brief Preapre for setting config attributes * @param[in] config Configuration on which attributes will be set * @param[in] attrs Attributes which will be set on given config */ void pull_config_attrs(struct test_config *config, struct usbg_config_attrs *attrs); /** * @brief Get gadget attribute * @param[in] attrs * @param[in] attr */ int get_gadget_attr(struct usbg_gadget_attrs *attrs, usbg_gadget_attr attr); /** * @brief Prepare to write given attribute by libusbg * @param[in] gadget Test gadget related to given attribute * @param[in] attr Attribute * @param[in] value Attributes value **/ void push_gadget_attribute(struct test_gadget *gadget, usbg_gadget_attr attr, int value); /** * @brief Prepare to read given attribute by libusbg * @param[in] gadget Test gadget related to given attribute * @param[in] attr Attribute * @param[in] value Attributes value **/ void pull_gadget_attribute(struct test_gadget *gadget, usbg_gadget_attr attr, int value); /** * @brief Prepare fake filesystem to get given gadget attributes * @details Prepare queue of values passed to wrapped i/o functions, * all values got from given attributes structure. * @param[in] gadget Pointer to gadget * @param[in] attrs Pointer to attributes which gadget should have * @warning Calling usbg_get_gadget_attrs function whithout this * preparation and with wrapped i/o may fail. */ void push_gadget_attrs(struct test_gadget *gadget, struct usbg_gadget_attrs *attrs); /** * @brief Prepare fake filesystem for attributes setting attempt. * @details Prepare queue of values passed to wrapped i/o functions, * corresponding to functions called on attributes setting * @param[in] gadget Pointer to gadget * @param[in] attrs Pointer to expected attributes * @warning Calling usbg_get_gadget_attrs function whithout this * preparation and with wrapped i/o may fail. */ void pull_gadget_attrs(struct test_gadget *gadget, struct usbg_gadget_attrs *attrs); /** * @brief Prepare fake filesystem to get given function attributes * @details Prepare queue of values passed to wrapped i/o functions, * all values got from given attributes structure. * @warning Calling usbg_get_function_attrs function whithout this * preparation and with wrapped i/o may fail. */ void push_function_attrs(struct test_function *func, void *attrs); /** * @brief Prepare fake filesystem to set given function attributes * @details Prepare queue of values passed to wrapped i/o functions, * all values got from given attributes structure. * @warning Calling usbg_set_function_attrs function whithout this * preparation and with wrapped i/o may fail. */ void pull_function_attrs(struct test_function *func, void *attrs); /** * @brief Get gadget string * @param[in] strs Set of gadget strings * @param[in] str Identifier of string which should be returned * @return Selected string from given set of strings */ const char *get_gadget_str(struct usbg_gadget_strs *strs, gadget_str str); /** * @brief Prepare filesystem to set selected gadget string * @param[in] gadget Gadget on which str will be set * @param[in] lang Language of string * @param[in] str String identifier * @param[in] content String expected to be set */ void pull_gadget_string(struct test_gadget *gadget, int lang, gadget_str str, const char *content); /** * @brief Prepare filesystem to set given gadget strings * @param[in] gadget Gadget on which strings will be set * @param[in] lang Language of strings * @param[in] strs Strings expected to be set */ void pull_gadget_strs(struct test_gadget *gadget, int lang, struct usbg_gadget_strs *strs); /** * @brief prepare for reading gadget's strings */ void push_gadget_strs(struct test_gadget *gadget, int lang, struct usbg_gadget_strs *strs); /** * @brief Prepare for /ref usbg_set_config_string calling * @details Expect setting the same string as given one * @param[in] config on which strings will be set * @param[in] lang Language of strings * @param[in] str string to be set as configuration string */ void pull_config_string(struct test_config *config, int lang, const char *str); /** * @brief Prepare for writting given config strings * @param[in] config on which strings will be set * @param[in] lang Language of strings * @param[in] strs Strings expected to be set */ void pull_config_strs(struct test_config *config, int lang, struct usbg_config_strs *strs); /** * @brief Prepare for /ref usbg_get_config_string calling * @details Expect setting the same string as given one * @param[in] config from which strings will be get * @param[in] lang Language of strings * @param[in] str string which should be returned as configuration string */ void push_config_string(struct test_config *config, int lang, const char *str); /** * @brief Prepare for reading config strings * @param[in] config from which strings will be get * @param[in] lang Language of strings * @param[in] strs Strings which should be returned */ void push_config_strs(struct test_config *config, int lang, struct usbg_config_strs *strs); /** * @brief Prepare for creating config * @param[in] tc Test config to be created */ void pull_create_config(struct test_config *tc); /** * @brief Prepare for creating function * @param[in] tf Test function to be created */ void pull_create_function(struct test_function *tf); /** * @brief Copy state without configs and functions * @param[in] ts State to bo copied * @return State with empty gadgets */ struct test_state *build_empty_gadget_state(struct test_state *ts); /** * @brief Store given pointer on cleanup stack * @details All stacked pointers will be freed by calling cleanup_queue. * This can be used to manage memory needed for single test casees. */ void free_later(void *ptr); /** * @brief Cleans up memory no longer needed * @details Frees all pointer stored on cleanup stack by calling free_later * @warning Calling this function before end of single test usually make test state * unusable. Use it only when you no longer need allocated data (at the end of * test case, in most cases) */ void cleanup_stack(); /** * @brief init usbg with given test state */ void init_with_state(struct test_state *in, usbg_state **out); /** * @brief Safely initialize usbg state from pointer given to test * @param[in] state Pointer given to test function * @param[out] ts Pointer to be filled with test state * @param[out] s Pointer to be filled with usbg state */ void safe_init_with_state(void **state, struct test_state **ts, usbg_state **s); /** * @brief Assert that given config attributes are equal */ void assert_config_attrs_equal(struct usbg_config_attrs *actual, struct usbg_config_attrs *expected); /** * @brief Assert that given usbg binding matches given test binding * @param[in] f Pointer to usbg binding struct * @param[in] expected Pointer to test binding struct with expected values */ void assert_binding_equal(usbg_binding *b, struct test_binding *expected); /** * @brief Assert that given usbg function matches given test function * @param[in] f Pointer to usbg function struct * @param[in] expected Pointer to test function struct with expected values */ void assert_func_equal(usbg_function *f, struct test_function *expected); /** * @brief Assert that given usbg config matches given test config * @param[in] c Pointer to usbg config struct * @param[in] expected Pointer to test config struct with expected values */ void assert_config_equal(usbg_config *c, struct test_config *expected); /** * @brief Assert that given usbg gadget matches given test gadget * @param[in] g Pointer to usbg gadget struct * @param[in] expected Pointer to test gadget struct with expected values */ void assert_gadget_equal(usbg_gadget *g, struct test_gadget *expected); /** * @brief Assert that given usbg state matches given test state * @param[in] s Pointer to usbg state struct * @param[in] expected Pointer to test state struct with expected values */ void assert_state_equal(usbg_state *s, struct test_state *expected); /** * @brief Compare path names * @details Given pathes don't need to exist * @return Integer less than, equal to, or greater than zero if a is (respectively) * less than, equal to, or greater than b. */ int path_cmp(const char *a, const char *b); /** * @brief Print error when given paths are not equal * @return 1 if paths are equal, 0 otherwise * @note Argument type is defined by cmocka. This specific function type is defined * as custom comparing function in cmocka framework. */ int path_equal_display_error(const LargestIntegralType actual, const LargestIntegralType expected); /** * @brief Compare attributes (as strings) * @return Integer less than, equal to, or greater than zero if a is (respectively) * less than, equal to, or greater than b. */ int hex_str_cmp(const char *actual, const char *expected); /** * @brief Print error when given attributes are not equal * @return 1 if attributes are equal, 0 otherwise * @note Argument type is defined by cmocka. This specific function type is defined * as custom comparing function in cmocka framework. */ int hex_str_equal_display_error(const LargestIntegralType actual, const LargestIntegralType expected); /** * @brief Assert that given path strings are equal * @details Given pathes don't need to exist */ void assert_path_equal(const char *actual, const char *expected); /** * @brief Assert that given usbg gadget attributes sets are equal * @param[in] actual Pointer to actual gadget attributes structure * @param[in] expected Pointer to expeced gadget attributes structure */ void assert_gadget_attrs_equal(struct usbg_gadget_attrs *actual, struct usbg_gadget_attrs *expected); /** * @brief Assert that given function attributes are the same. * @param[in] actual Pointer to actual attributes object * @param[in] expected Pointer to expected attributes obejct * @param[in] type Type of function, which attributes are checked */ void assert_function_attrs_equal(void *actual, void *expected, usbg_function_type type); /** * @brief Assert that given gadget strings are equal */ void assert_gadget_strs_equal(struct usbg_gadget_strs *actual, struct usbg_gadget_strs *expected); /** * @brief Function that performs some test on given usbg function */ typedef void (*FunctionTest)(usbg_function *f, struct test_function *tf); /** * @brief Call given function for all usb functions present in given state * @param[in] ts Test state to be tested * @param[in] s Properly prepared usbg state to be tested * @param[in] fun Function to be called on each usb function in state */ void for_each_test_function(struct test_state *ts, usbg_state *s, FunctionTest fun); /** * @brief Function that performs some test on given usbg config */ typedef void (*ConfigTest)(usbg_config *c, struct test_config *tc); /** * @brief Call given function for all usb configs present in given state * @param[in] ts Test state to be tested * @param[in] s Properly prepared usbg state to be tested * @param[in] fun Function to be called on each usb function in state */ void for_each_test_config(struct test_state *ts, usbg_state *s, ConfigTest fun); /** * @brief Function that performs test on given usbg binding */ typedef void (*BindingTestFunc)(struct test_binding *tb, usbg_binding *b); /** * @brief Call given function for all usb bindings present in given state * @param[in] ts Test state to be tested * @param[in] s Properly prepared usbg state to be tested * @param[in] fun Function to be called on each usb binding in state */ void for_each_binding(struct test_state *ts, usbg_state *s, BindingTestFunc fun); /** * @brief Function that performs test on given usbg gadget */ typedef void (*GadgetTestFunc)(usbg_gadget *g, struct test_gadget *tg); /** * @brief Call given function for all usb gadgets present in given state * @param[in] ts Test state to be tested * @param[in] s Properly prepared usbg state to be tested * @param[in] fun Function to be called on each usb gadget in state */ void for_each_test_gadget(struct test_state *ts, usbg_state *s, GadgetTestFunc fun); static inline void *safe_calloc(int count, size_t size) { void *ptr; ptr = calloc(count, size); if (ptr == NULL) fail(); free_later(ptr); return ptr; } static inline void *safe_malloc(size_t size) { void *ptr; ptr = malloc(size); if (ptr == NULL) fail(); free_later(ptr); return ptr; } static inline int safe_asprintf(char **ptr, const char *fmt, ...) { va_list args; int ret; va_start(args, fmt); ret = vasprintf(ptr, fmt, args); va_end(args); if (ret < 0) fail(); free_later(*ptr); return ret; } #endif /* USBG_TEST_H */