From 6b56ab5c42ddde751d2e622a942a215e09444a7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois?= Date: Wed, 3 Jun 2026 10:27:13 +0200 Subject: [PATCH] libbsdl: scaffold + working BSDL parser (struct + JSON, C ABI) Standalone LGPL-2.1 parser for BSDL (IEEE 1149.1), shared by essim and bs_explorer. The parser is ported from the Viveris JTAG Core loader, decoupled from jtag_core, and extended with two extractions the original lacks: - PIN_MAP_STRING -> per-port physical package pin, scalar and vector; - TAP_SCAN_* -> TAP signal roles (TDI/TDO/TMS/TCK/TRST). Exposes a stable C ABI (bsdl_parse_file/buffer -> bsdl_t, bsdl_to_json) with a dependency-free JSON serializer and a bsdl2json CLI. CMake builds a versioned shared library with install/export rules for find_package(bsdl). Verified against m2gl010t, xcku040 and xcku15p (100% pin mapping, correct IDCODEs and TAP roles); api and parse regression tests pass, clean build. Co-Authored-By: Claude Opus 4.8 --- .gitignore | 26 + CMakeLists.txt | 109 ++++ LICENSE | 502 +++++++++++++++++ README.md | 74 +++ cmake/bsdlConfig.cmake.in | 5 + data/README.md | 18 + include/bsdl/bsdl.h | 199 +++++++ src/bsdl.c | 52 ++ src/bsdl_json.c | 248 +++++++++ src/bsdl_parse.c | 1112 +++++++++++++++++++++++++++++++++++++ src/bsdl_strings.c | 65 +++ src/bsdl_strings.h | 26 + tests/CMakeLists.txt | 7 + tests/test_api.c | 90 +++ tests/test_parse.c | 154 +++++ tools/bsdl2json.c | 77 +++ 16 files changed, 2764 insertions(+) create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 LICENSE create mode 100644 cmake/bsdlConfig.cmake.in create mode 100644 data/README.md create mode 100644 include/bsdl/bsdl.h create mode 100644 src/bsdl.c create mode 100644 src/bsdl_json.c create mode 100644 src/bsdl_parse.c create mode 100644 src/bsdl_strings.c create mode 100644 src/bsdl_strings.h create mode 100644 tests/CMakeLists.txt create mode 100644 tests/test_api.c create mode 100644 tests/test_parse.c create mode 100644 tools/bsdl2json.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..53b8ce1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +# build trees +/build/ +/build-*/ +/out/ +cmake-build-*/ + +# CMake debris (if ever configured in-source) +CMakeCache.txt +CMakeFiles/ +cmake_install.cmake +CTestTestfile.cmake +install_manifest.txt +*.cmake.user + +# editors +.vscode/ +.idea/ +*.swp + +# artifacts +*.o +*.a +*.so +*.so.* +*.dll +*.dylib diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..c050c14 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,109 @@ +cmake_minimum_required(VERSION 3.14) + +project(bsdl + LANGUAGES C + VERSION 0.1.0 + DESCRIPTION "Standalone BSDL (IEEE 1149.1) parser — struct + JSON, stable C ABI" +) + +# --- top-level detection (PROJECT_IS_TOP_LEVEL needs CMake >= 3.21) --- +if(NOT DEFINED PROJECT_IS_TOP_LEVEL) + if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) + set(PROJECT_IS_TOP_LEVEL ON) + else() + set(PROJECT_IS_TOP_LEVEL OFF) + endif() +endif() + +# This is a dynamic library by nature; build shared unless told otherwise. +if(NOT DEFINED BUILD_SHARED_LIBS) + set(BUILD_SHARED_LIBS ON) +endif() + +option(BSDL_BUILD_CLI "Build the bsdl2json command-line tool" ON) +option(BSDL_BUILD_TESTS "Build the test suite" ${PROJECT_IS_TOP_LEVEL}) + +# ---------------------------------------------------------------- library ---- +add_library(bsdl + src/bsdl.c + src/bsdl_parse.c + src/bsdl_strings.c + src/bsdl_json.c +) +add_library(bsdl::bsdl ALIAS bsdl) + +target_include_directories(bsdl + PUBLIC + $ + $ + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src +) + +set_target_properties(bsdl PROPERTIES + C_STANDARD 11 + C_STANDARD_REQUIRED ON + C_VISIBILITY_PRESET hidden + VISIBILITY_INLINES_HIDDEN ON + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} + PUBLIC_HEADER ${CMAKE_CURRENT_SOURCE_DIR}/include/bsdl/bsdl.h +) + +# Mark exported symbols (dllexport on Windows; default-visibility on ELF). +if(BUILD_SHARED_LIBS) + target_compile_definitions(bsdl PRIVATE BSDL_BUILD_SHARED) +endif() + +if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(bsdl PRIVATE -Wall -Wextra -Wpedantic) +endif() + +# -------------------------------------------------------------------- CLI ---- +if(BSDL_BUILD_CLI) + add_executable(bsdl2json tools/bsdl2json.c) + target_link_libraries(bsdl2json PRIVATE bsdl) +endif() + +# ------------------------------------------------------------------ tests ---- +if(BSDL_BUILD_TESTS) + enable_testing() + add_subdirectory(tests) +endif() + +# --------------------------------------------------- install / export ------- +include(GNUInstallDirs) +include(CMakePackageConfigHelpers) + +install(TARGETS bsdl + EXPORT bsdlTargets + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/bsdl +) +if(BSDL_BUILD_CLI) + install(TARGETS bsdl2json RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) +endif() + +install(EXPORT bsdlTargets + FILE bsdlTargets.cmake + NAMESPACE bsdl:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/bsdl +) + +configure_package_config_file( + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/bsdlConfig.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/bsdlConfig.cmake + INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/bsdl +) +write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/bsdlConfigVersion.cmake + VERSION ${PROJECT_VERSION} + COMPATIBILITY SameMajorVersion +) +install(FILES + ${CMAKE_CURRENT_BINARY_DIR}/bsdlConfig.cmake + ${CMAKE_CURRENT_BINARY_DIR}/bsdlConfigVersion.cmake + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/bsdl +) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4362b49 --- /dev/null +++ b/LICENSE @@ -0,0 +1,502 @@ + 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! diff --git a/README.md b/README.md index e69de29..c5811ed 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,74 @@ +# libbsdl + +A small, standalone parser for **BSDL** (IEEE 1149.1 Boundary-Scan Description +Language) files, exposing a **stable C ABI** plus an optional **JSON** output. + +It is designed to be shared by two consumers: + +- **bs_explorer** (C) — links the library and reads the `bsdl_t` struct directly + (boundary chain, instructions) to drive JTAG hardware. +- **essim** (C++) — consumes it either out-of-process via the `bsdl2json` CLI, + or in-process through the `extern "C"` API, for connectivity verification. + +The parser core is seeded from the Viveris JTAG Core BSDL loader and extended +with the two attributes that loader omits but a netlist cross-check needs: + +- **`PIN_MAP_STRING`** → each port's physical package ball/pin (`physical_pin`); +- **`TAP_SCAN_*`** → each TAP signal's role (TDI/TDO/TMS/TCK/TRST, `tap_role`). + +## Status + +Working. The parser extracts entity, IDCODE (+ mask), port directions, the +scalar **and** vector `PIN_MAP_STRING` (physical pins), `TAP_SCAN_*` roles, the +boundary register (with pin↔cell links) and the instruction opcodes. Verified +against real devices — `m2gl010t` (484 pins), `xcku040` (1156), `xcku15p` +(1517) — with 100% pin mapping and correct IDCODEs/TAP roles. `api` and `parse` +regression tests pass. + +## Build + +```sh +cmake -S . -B build +cmake --build build +ctest --test-dir build --output-on-failure +``` + +Produces `libbsdl.so` (+ `.so.0` / `.so.0.1.0`), the `bsdl2json` tool, and runs +the test suite. Options: `-DBSDL_BUILD_CLI=OFF`, `-DBSDL_BUILD_TESTS=OFF`, +`-DBUILD_SHARED_LIBS=OFF` (static). + +## Use from CMake + +```cmake +find_package(bsdl REQUIRED) +target_link_libraries(my_app PRIVATE bsdl::bsdl) +``` + +## API + +```c +#include + +bsdl_opts_t opts; +bsdl_opts_default(&opts); + +bsdl_t* m = bsdl_parse_file("device.bsd", &opts); +if (m) { + char* json = bsdl_to_json(m); /* compact JSON; free with bsdl_string_free */ + /* ... or walk m->pins / m->chain / m->instructions directly ... */ + bsdl_string_free(json); + bsdl_free(m); +} +``` + +See `include/bsdl/bsdl.h` for the full contract. The `bsdl_t` model is a +superset: extend it **additively** so the shared ABI stays stable for both +consumers. + +## License + +LGPL-2.1-or-later — see [LICENSE](LICENSE). The same license as its two +consumers (essim and bs_explorer are both LGPL-2.1), so code and the parser +can be shared freely; dynamic linking keeps the library replaceable. Derived +from the Viveris JTAG Core BSDL loader (© 2008–2024 Viveris Technologies, +Jean-François DEL NERO), also LGPL-2.1. diff --git a/cmake/bsdlConfig.cmake.in b/cmake/bsdlConfig.cmake.in new file mode 100644 index 0000000..c1be89f --- /dev/null +++ b/cmake/bsdlConfig.cmake.in @@ -0,0 +1,5 @@ +@PACKAGE_INIT@ + +include("${CMAKE_CURRENT_LIST_DIR}/bsdlTargets.cmake") + +check_required_components(bsdl) diff --git a/data/README.md b/data/README.md new file mode 100644 index 0000000..227c4a4 --- /dev/null +++ b/data/README.md @@ -0,0 +1,18 @@ +# Sample BSDL files + +This directory is intentionally **not** populated with a BSDL database. + +BSDL files are mandated to be freely available by IEEE 1149.1, but their +redistribution terms vary per vendor, so they are not vendored here. Point the +tests and tools at a local directory instead. + +Sources: + +- Vendor sites (authoritative): TI, AMD/Xilinx, Intel/Altera, Lattice, NXP, ST… +- [bsdl.info](https://bsdl.info/) — community aggregate (~14k files). +- Quartus / Vivado installs bundle BSDL for their FPGAs. +- For quick local testing, the sibling `bs_explorer` repo ships a few under + `bs_explorer/data/bsdl_files/` (xcku15p, xcku040, m2gl010t). + +> Note: a *configured* FPGA's BSDL differs from the blank device — use the +> blank-device BSDL for connectivity checks. diff --git a/include/bsdl/bsdl.h b/include/bsdl/bsdl.h new file mode 100644 index 0000000..749acfb --- /dev/null +++ b/include/bsdl/bsdl.h @@ -0,0 +1,199 @@ +/* + * libbsdl - Standalone BSDL (IEEE 1149.1) parser with a stable C ABI. + * + * Copyright (c) 2026 François + * Seeded from the Viveris JTAG Core BSDL loader (Jean-François DEL NERO). + * + * This library is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License version 2.1 as + * published by the Free Software Foundation. See the LICENSE file. + */ + +/** + * @file bsdl.h + * @brief Public C API for libbsdl: parse a .bsd file into a struct, or to JSON. + * + * Design notes + * ------------ + * - Pure C ABI: callable as-is from C (bs_explorer) and, via `extern "C"`, + * from C++ (essim). Keep this header free of C++/struct-layout churn. + * - `bsdl_t` is a SUPERSET model; consumers read only the fields they need. + * Extend it additively (append fields/enum values) — never reorder/remove — + * so the shared .so stays ABI-stable for both projects. + * - Ownership: every pointer reachable from a `bsdl_t*` is owned by the model + * and released by bsdl_free(). Do not free individual members. + */ + +#ifndef LIBBSDL_BSDL_H +#define LIBBSDL_BSDL_H + +#include + +/* -------- version -------- */ +#define BSDL_VERSION_MAJOR 0 +#define BSDL_VERSION_MINOR 1 +#define BSDL_VERSION_PATCH 0 +#define BSDL_VERSION_STRING "0.1.0" + +/* -------- symbol visibility / export -------- */ +#if defined(_WIN32) +# if defined(BSDL_BUILD_SHARED) +# define BSDL_API __declspec(dllexport) +# elif !defined(BSDL_STATIC) +# define BSDL_API __declspec(dllimport) +# else +# define BSDL_API +# endif +#else +# if defined(BSDL_BUILD_SHARED) +# define BSDL_API __attribute__((visibility("default"))) +# else +# define BSDL_API +# endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* -------- enumerations (stable values; append-only) -------- */ + +/** Logical port direction (from the VHDL port clause). */ +typedef enum bsdl_dir { + BSDL_DIR_UNKNOWN = 0, + BSDL_DIR_IN, + BSDL_DIR_OUT, + BSDL_DIR_INOUT, + BSDL_DIR_BUFFER, + BSDL_DIR_LINKAGE /**< power / ground / NC — Viveris folds these to UNKNOWN. */ +} bsdl_dir_t; + +/** TAP signal role, derived from the TAP_SCAN_* attributes. */ +typedef enum bsdl_tap_role { + BSDL_TAP_NONE = 0, + BSDL_TAP_TDI, /**< TAP_SCAN_IN */ + BSDL_TAP_TDO, /**< TAP_SCAN_OUT */ + BSDL_TAP_TMS, /**< TAP_SCAN_MODE */ + BSDL_TAP_TCK, /**< TAP_SCAN_CLOCK */ + BSDL_TAP_TRST /**< TAP_SCAN_RESET */ +} bsdl_tap_role_t; + +/** Boundary-register cell type (BC_1 .. BC_7). */ +typedef enum bsdl_cell { + BSDL_CELL_UNKNOWN = 0, + BSDL_CELL_BC1, BSDL_CELL_BC2, BSDL_CELL_BC3, BSDL_CELL_BC4, + BSDL_CELL_BC5, BSDL_CELL_BC6, BSDL_CELL_BC7 +} bsdl_cell_t; + +/** Boundary-register cell function. */ +typedef enum bsdl_bittype { + BSDL_BIT_UNKNOWN = 0, + BSDL_BIT_INPUT, + BSDL_BIT_OUTPUT, + BSDL_BIT_TRISTATE, + BSDL_BIT_INOUT, + BSDL_BIT_CONTROL, + BSDL_BIT_INTERNAL +} bsdl_bittype_t; + +/** Safe / disable logic state. */ +typedef enum bsdl_state { + BSDL_STATE_UNKNOWN = 0, + BSDL_STATE_UNDEF, /**< 'X' */ + BSDL_STATE_HIGH, /**< '1' */ + BSDL_STATE_LOW, /**< '0' */ + BSDL_STATE_HIGHZ /**< 'Z' */ +} bsdl_state_t; + +/* -------- model structures -------- */ + +/** A logical port plus its physical mapping and boundary-cell links. */ +typedef struct bsdl_pin { + const char* name; /**< logical port name, e.g. "TCK", "IO_A2". */ + bsdl_dir_t dir; + const char* physical_pin; /**< package ball/pin from PIN_MAP_STRING, e.g. "W20"; NULL if unmapped. */ + bsdl_tap_role_t tap_role; /**< non-NONE if this port is a TAP signal. */ + int in_bit; /**< boundary-register input bit index, or -1. */ + int out_bit; /**< boundary-register output bit index, or -1. */ + int ctrl_bit; /**< controlling bit index, or -1. */ +} bsdl_pin_t; + +/** One entry of the BOUNDARY_REGISTER. */ +typedef struct bsdl_cell_entry { + int index; + bsdl_cell_t cell; + const char* port; /**< associated port name, or "*" when unnamed. */ + bsdl_bittype_t type; + bsdl_state_t safe; + int ctrl_index; /**< controlling cell index, or -1. */ + bsdl_state_t disable_state; + bsdl_state_t disable_result; +} bsdl_cell_entry_t; + +/** One INSTRUCTION_OPCODE entry. */ +typedef struct bsdl_instr { + const char* name; /**< e.g. "IDCODE", "EXTEST", "BYPASS", "SAMPLE". */ + const char* opcode; /**< bit string, e.g. "001000". */ +} bsdl_instr_t; + +/** The parsed device model. All pointers owned by the model (see bsdl_free). */ +typedef struct bsdl { + const char* entity; /**< entity name (device identifier). */ + const char* src_filename; /**< basename of the source file. */ + unsigned long idcode; /**< IDCODE value (X bits read as 0). */ + unsigned long idcode_mask; /**< 1 where the IDCODE bit is fixed, 0 where 'X'. */ + int instruction_length; + + bsdl_pin_t* pins; size_t pin_count; + bsdl_cell_entry_t* chain; size_t chain_count; + bsdl_instr_t* instructions; size_t instruction_count; +} bsdl_t; + +/* -------- options & diagnostics -------- */ + +typedef enum bsdl_log_level { + BSDL_LOG_ERROR = 0, + BSDL_LOG_WARN, + BSDL_LOG_INFO, + BSDL_LOG_DEBUG +} bsdl_log_level_t; + +/** Optional diagnostic sink. Replaces Viveris' jtag_core logging dependency. */ +typedef void (*bsdl_log_fn)(bsdl_log_level_t level, const char* msg, void* user); + +typedef struct bsdl_opts { + int sort_pins_by_name; /**< replaces the BSDL_LOADER_SORT_PINS_NAME env var. */ + bsdl_log_fn log; /**< may be NULL. */ + void* log_user; /**< passed back to `log`. */ +} bsdl_opts_t; + +/** Fill `opts` with defaults (no sorting, no logging). */ +BSDL_API void bsdl_opts_default(bsdl_opts_t* opts); + +/* -------- API -------- */ + +/** Parse a BSDL file. Returns NULL on error. Free with bsdl_free(). */ +BSDL_API bsdl_t* bsdl_parse_file(const char* path, const bsdl_opts_t* opts); + +/** Parse a BSDL document held in memory. `name` is recorded as src_filename. */ +BSDL_API bsdl_t* bsdl_parse_buffer(const char* text, size_t len, + const char* name, const bsdl_opts_t* opts); + +/** Release a model returned by a bsdl_parse_* function. NULL-safe. */ +BSDL_API void bsdl_free(bsdl_t* model); + +/** Serialize a model to a freshly allocated JSON string (compact, UTF-8). + * Returns NULL on allocation failure or NULL input. Free with bsdl_string_free(). */ +BSDL_API char* bsdl_to_json(const bsdl_t* model); + +/** Free a string returned by bsdl_to_json(). NULL-safe. */ +BSDL_API void bsdl_string_free(char* s); + +/** Library version, e.g. "0.1.0". */ +BSDL_API const char* bsdl_version(void); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* LIBBSDL_BSDL_H */ diff --git a/src/bsdl.c b/src/bsdl.c new file mode 100644 index 0000000..75e69c4 --- /dev/null +++ b/src/bsdl.c @@ -0,0 +1,52 @@ +/* + * libbsdl - core: lifecycle helpers (version, options, teardown). + * SPDX-License-Identifier: LGPL-2.1-or-later + * + * The parser itself lives in bsdl_parse.c; serialization in bsdl_json.c. + */ +#include + +#include "bsdl/bsdl.h" + +const char* bsdl_version(void) +{ + return BSDL_VERSION_STRING; +} + +void bsdl_opts_default(bsdl_opts_t* opts) +{ + if (!opts) + return; + opts->sort_pins_by_name = 0; + opts->log = NULL; + opts->log_user = NULL; +} + +void bsdl_free(bsdl_t* model) +{ + size_t i; + + if (!model) + return; + + free((void*)model->entity); + free((void*)model->src_filename); + + for (i = 0; i < model->pin_count; i++) { + free((void*)model->pins[i].name); + free((void*)model->pins[i].physical_pin); + } + free(model->pins); + + for (i = 0; i < model->chain_count; i++) + free((void*)model->chain[i].port); + free(model->chain); + + for (i = 0; i < model->instruction_count; i++) { + free((void*)model->instructions[i].name); + free((void*)model->instructions[i].opcode); + } + free(model->instructions); + + free(model); +} diff --git a/src/bsdl_json.c b/src/bsdl_json.c new file mode 100644 index 0000000..7de334e --- /dev/null +++ b/src/bsdl_json.c @@ -0,0 +1,248 @@ +/* + * libbsdl - JSON serialization (the optional output layer essim consumes). + * SPDX-License-Identifier: LGPL-2.1-or-later + * + * Self-contained: a tiny growable string buffer, no external JSON dependency. + */ +#include +#include +#include + +#include "bsdl/bsdl.h" + +/* ---- growable string buffer ---- */ +typedef struct { + char* buf; + size_t len; + size_t cap; + int oom; /* sticky out-of-memory flag */ +} sb_t; + +static void sb_reserve(sb_t* sb, size_t extra) +{ + size_t need; + char* p; + if (sb->oom) + return; + need = sb->len + extra + 1; + if (need <= sb->cap) + return; + while (sb->cap < need) + sb->cap = sb->cap ? sb->cap * 2 : 256; + p = (char*)realloc(sb->buf, sb->cap); + if (!p) { sb->oom = 1; return; } + sb->buf = p; +} + +static void sb_putc(sb_t* sb, char c) +{ + sb_reserve(sb, 1); + if (sb->oom) return; + sb->buf[sb->len++] = c; +} + +static void sb_puts(sb_t* sb, const char* s) +{ + size_t n; + if (!s) s = ""; + n = strlen(s); + sb_reserve(sb, n); + if (sb->oom) return; + memcpy(sb->buf + sb->len, s, n); + sb->len += n; +} + +/* Append a JSON string literal (with quotes) for `s`, or `null` if s == NULL. */ +static void sb_json_str(sb_t* sb, const char* s) +{ + if (!s) { sb_puts(sb, "null"); return; } + sb_putc(sb, '"'); + for (; *s; s++) { + unsigned char c = (unsigned char)*s; + switch (c) { + case '"': sb_puts(sb, "\\\""); break; + case '\\': sb_puts(sb, "\\\\"); break; + case '\b': sb_puts(sb, "\\b"); break; + case '\f': sb_puts(sb, "\\f"); break; + case '\n': sb_puts(sb, "\\n"); break; + case '\r': sb_puts(sb, "\\r"); break; + case '\t': sb_puts(sb, "\\t"); break; + default: + if (c < 0x20) { + char esc[7]; + snprintf(esc, sizeof(esc), "\\u%04x", c); + sb_puts(sb, esc); + } else { + sb_putc(sb, (char)c); + } + } + } + sb_putc(sb, '"'); +} + +static void sb_json_int(sb_t* sb, long v) +{ + char tmp[32]; + snprintf(tmp, sizeof(tmp), "%ld", v); + sb_puts(sb, tmp); +} + +static void sb_json_hex32(sb_t* sb, unsigned long v) +{ + char tmp[16]; + snprintf(tmp, sizeof(tmp), "\"0x%08lX\"", v & 0xFFFFFFFFUL); + sb_puts(sb, tmp); +} + +/* Append `"key":` (object member key). */ +static void sb_key(sb_t* sb, const char* k) +{ + sb_json_str(sb, k); + sb_putc(sb, ':'); +} + +/* ---- enum -> token ---- */ +static const char* dir_str(bsdl_dir_t d) +{ + switch (d) { + case BSDL_DIR_IN: return "in"; + case BSDL_DIR_OUT: return "out"; + case BSDL_DIR_INOUT: return "inout"; + case BSDL_DIR_BUFFER: return "buffer"; + case BSDL_DIR_LINKAGE: return "linkage"; + default: return "unknown"; + } +} + +static const char* tap_str(bsdl_tap_role_t t) +{ + switch (t) { + case BSDL_TAP_TDI: return "tdi"; + case BSDL_TAP_TDO: return "tdo"; + case BSDL_TAP_TMS: return "tms"; + case BSDL_TAP_TCK: return "tck"; + case BSDL_TAP_TRST: return "trst"; + default: return "none"; + } +} + +static const char* cell_str(bsdl_cell_t c) +{ + switch (c) { + case BSDL_CELL_BC1: return "BC_1"; + case BSDL_CELL_BC2: return "BC_2"; + case BSDL_CELL_BC3: return "BC_3"; + case BSDL_CELL_BC4: return "BC_4"; + case BSDL_CELL_BC5: return "BC_5"; + case BSDL_CELL_BC6: return "BC_6"; + case BSDL_CELL_BC7: return "BC_7"; + default: return "unknown"; + } +} + +static const char* bittype_str(bsdl_bittype_t b) +{ + switch (b) { + case BSDL_BIT_INPUT: return "input"; + case BSDL_BIT_OUTPUT: return "output"; + case BSDL_BIT_TRISTATE: return "tristate"; + case BSDL_BIT_INOUT: return "inout"; + case BSDL_BIT_CONTROL: return "control"; + case BSDL_BIT_INTERNAL: return "internal"; + default: return "unknown"; + } +} + +static const char* state_str(bsdl_state_t s) +{ + switch (s) { + case BSDL_STATE_UNDEF: return "X"; + case BSDL_STATE_HIGH: return "1"; + case BSDL_STATE_LOW: return "0"; + case BSDL_STATE_HIGHZ: return "Z"; + default: return "unknown"; + } +} + +char* bsdl_to_json(const bsdl_t* m) +{ + sb_t sb = { NULL, 0, 0, 0 }; + size_t i; + + if (!m) + return NULL; + + sb_putc(&sb, '{'); + + sb_key(&sb, "entity"); sb_json_str(&sb, m->entity); sb_putc(&sb, ','); + sb_key(&sb, "src_filename"); sb_json_str(&sb, m->src_filename); sb_putc(&sb, ','); + sb_key(&sb, "idcode"); sb_json_hex32(&sb, m->idcode); sb_putc(&sb, ','); + sb_key(&sb, "idcode_mask"); sb_json_hex32(&sb, m->idcode_mask); sb_putc(&sb, ','); + sb_key(&sb, "instruction_length"); sb_json_int(&sb, m->instruction_length); sb_putc(&sb, ','); + + /* pins */ + sb_key(&sb, "pins"); + sb_putc(&sb, '['); + for (i = 0; i < m->pin_count; i++) { + const bsdl_pin_t* p = &m->pins[i]; + if (i) sb_putc(&sb, ','); + sb_putc(&sb, '{'); + sb_key(&sb, "name"); sb_json_str(&sb, p->name); sb_putc(&sb, ','); + sb_key(&sb, "dir"); sb_json_str(&sb, dir_str(p->dir)); sb_putc(&sb, ','); + sb_key(&sb, "physical_pin"); sb_json_str(&sb, p->physical_pin); sb_putc(&sb, ','); + sb_key(&sb, "tap_role"); sb_json_str(&sb, tap_str(p->tap_role)); sb_putc(&sb, ','); + sb_key(&sb, "in_bit"); sb_json_int(&sb, p->in_bit); sb_putc(&sb, ','); + sb_key(&sb, "out_bit"); sb_json_int(&sb, p->out_bit); sb_putc(&sb, ','); + sb_key(&sb, "ctrl_bit"); sb_json_int(&sb, p->ctrl_bit); + sb_putc(&sb, '}'); + } + sb_putc(&sb, ']'); + sb_putc(&sb, ','); + + /* boundary chain */ + sb_key(&sb, "chain"); + sb_putc(&sb, '['); + for (i = 0; i < m->chain_count; i++) { + const bsdl_cell_entry_t* c = &m->chain[i]; + if (i) sb_putc(&sb, ','); + sb_putc(&sb, '{'); + sb_key(&sb, "index"); sb_json_int(&sb, c->index); sb_putc(&sb, ','); + sb_key(&sb, "cell"); sb_json_str(&sb, cell_str(c->cell)); sb_putc(&sb, ','); + sb_key(&sb, "port"); sb_json_str(&sb, c->port); sb_putc(&sb, ','); + sb_key(&sb, "type"); sb_json_str(&sb, bittype_str(c->type)); sb_putc(&sb, ','); + sb_key(&sb, "safe"); sb_json_str(&sb, state_str(c->safe)); sb_putc(&sb, ','); + sb_key(&sb, "ctrl_index"); sb_json_int(&sb, c->ctrl_index); sb_putc(&sb, ','); + sb_key(&sb, "disable_state"); sb_json_str(&sb, state_str(c->disable_state)); sb_putc(&sb, ','); + sb_key(&sb, "disable_result"); sb_json_str(&sb, state_str(c->disable_result)); + sb_putc(&sb, '}'); + } + sb_putc(&sb, ']'); + sb_putc(&sb, ','); + + /* instructions */ + sb_key(&sb, "instructions"); + sb_putc(&sb, '['); + for (i = 0; i < m->instruction_count; i++) { + const bsdl_instr_t* in = &m->instructions[i]; + if (i) sb_putc(&sb, ','); + sb_putc(&sb, '{'); + sb_key(&sb, "name"); sb_json_str(&sb, in->name); sb_putc(&sb, ','); + sb_key(&sb, "opcode"); sb_json_str(&sb, in->opcode); + sb_putc(&sb, '}'); + } + sb_putc(&sb, ']'); + + sb_putc(&sb, '}'); + + if (sb.oom) { + free(sb.buf); + return NULL; + } + sb.buf[sb.len] = '\0'; + return sb.buf; +} + +void bsdl_string_free(char* s) +{ + free(s); +} diff --git a/src/bsdl_parse.c b/src/bsdl_parse.c new file mode 100644 index 0000000..c76e181 --- /dev/null +++ b/src/bsdl_parse.c @@ -0,0 +1,1112 @@ +/* + * libbsdl - BSDL parser. + * SPDX-License-Identifier: LGPL-2.1-or-later + * + * Ported and adapted from the Viveris JTAG Core BSDL loader + * (bsdl_loader.c, (c) 2008-2024 Viveris Technologies, J.-F. DEL NERO; LGPL-2.1), + * decoupled from jtag_core and extended with two extractions the original omits: + * - PIN_MAP_STRING -> bsdl_pin_t.physical_pin (logical port -> package ball); + * - TAP_SCAN_* -> bsdl_pin_t.tap_role (TDI/TDO/TMS/TCK/TRST). + */ +#define _POSIX_C_SOURCE 200809L /* strdup under -std=c11 */ + +#include +#include +#include +#include + +#include "bsdl/bsdl.h" +#include "bsdl_strings.h" + +#define BSDL_MAX_ELEMENT (64 + 1) +#define BSDL_MAX_FILE_SIZE (8 * 1024 * 1024) +#define BSDL_MAX_LINES (128 * 1024) +#define BSDL_MAX_PINS (128 * 1024) +#define BSDL_MAX_CHAINBITS (512 * 1024) + +/* ------------------------------------------------------------ diagnostics -- */ + +static void plog(const bsdl_opts_t *opts, bsdl_log_level_t lvl, const char *msg) +{ + if (opts && opts->log) + opts->log(lvl, msg, opts->log_user); +} + +/* --------------------------------------------------- working structures ---- */ + +typedef struct { + char name[BSDL_MAX_ELEMENT]; + int dir; /* bsdl_dir_t */ + char phys[BSDL_MAX_ELEMENT]; /* package ball, "" if unmapped */ + int tap; /* bsdl_tap_role_t */ + int in_bit, out_bit, ctrl_bit; +} wpin_t; + +typedef struct { + int index; + int cell; /* bsdl_cell_t */ + char name[BSDL_MAX_ELEMENT]; + int type; /* bsdl_bittype_t */ + int safe; /* bsdl_state_t */ + int ctrl_index; + int disable_state; /* bsdl_state_t */ + int disable_result; /* bsdl_state_t */ +} wchain_t; + +/* -------------------------------------------------- low-level text utils --- */ + +static void str_upper(char *s) +{ + for (; *s; s++) + *s = (char)toupper((unsigned char)*s); +} + +static int str_eq_nocase(const char *a, const char *b) +{ + for (;; a++, b++) { + int d = tolower((unsigned char)*a) - tolower((unsigned char)*b); + if (d != 0 || !*a) + return d == 0; + } +} + +/* Skip blank/comment-only lines; leave *offset at the next meaningful char. */ +static int next_valid_line(char *buf, int size, int *offset) +{ + int o = *offset, line = *offset; + + do { + while (o < size && (buf[o] == ' ' || buf[o] == '\t')) + o++; + + if (o == size) { *offset = o; return 1; } + + if (buf[o] != '\r' && buf[o] != '\n' && + (buf[o] != '-' || buf[o + 1] != '-')) { + *offset = line; + return 0; + } + + if (buf[o] == '-' && buf[o + 1] == '-') { + while (buf[o] && buf[o] != '\r' && buf[o] != '\n') + o++; + } + + if (buf[o] == '\r' || buf[o] == '\n') { + o++; + if (o < size && buf[o] == '\n') + o++; + line = o; + } + } while (o < size && buf[o]); + + *offset = o; + return 1; +} + +/* Read one logical character: strips "--" comments, folds CR/LF/TAB to space. */ +static char next_char(char *buf, int size, int *offset) +{ + char c; + + if (*offset >= size) + return 0; + + c = buf[*offset]; + switch (c) { + case 0: + return 0; + case '\r': + *offset += 1; + if (*offset < size) { + if (buf[*offset] == '\n') + *offset += 1; + next_valid_line(buf, size, offset); + } + return ' '; + case '\t': + *offset += 1; + return ' '; + case '\n': + *offset += 1; + next_valid_line(buf, size, offset); + return ' '; + case '-': + if (buf[*offset + 1] == '-') { + while (*offset < size && buf[*offset] && + buf[*offset] != '\r' && buf[*offset] != '\n') + *offset += 1; + if (*offset < size) { + if (buf[*offset] == '\r') { + *offset += 1; + if (buf[*offset] == '\n') + *offset += 1; + next_valid_line(buf, size, offset); + return ' '; + } + if (buf[*offset] == '\n') { + *offset += 1; + next_valid_line(buf, size, offset); + return ' '; + } + } else { + return 0; + } + return ' '; + } + *offset += 1; + return '-'; + default: + *offset += 1; + return c; + } +} + +/* Split a cleaned BSDL body into statements on ';' (honouring () and ""). */ +static int extract_lines(char *txt, char **lines) +{ + int offset = 0, count = 0; + + do { + int start, end, depth = 0, quote = 0, done = 0; + + while (txt[offset] == ' ' && txt[offset]) + offset++; + start = offset; + + while (!done) { + switch (txt[offset]) { + case 0: + done = 1; + break; + case '(': + if (!quote) depth++; + offset++; + break; + case ')': + if (depth && !quote) depth--; + offset++; + break; + case '"': + quote = !quote; + offset++; + break; + case ';': + if (!depth && !quote) { + end = offset; + if (end - start > 0) { + if (lines) { + lines[count] = malloc((size_t)(end - start) + 2); + if (lines[count]) { + memset(lines[count], 0, (size_t)(end - start) + 2); + memcpy(lines[count], &txt[start], (size_t)(end - start)); + } + } + count++; + } + done = 1; + } + offset++; + break; + default: + offset++; + break; + } + } + } while (txt[offset] && count < BSDL_MAX_LINES); + + return count; +} + +/* Collapse runs of spaces (outside quotes) and concatenate VHDL '&' strings. */ +static void preprocess_line(char *line) +{ + int quote = 0, r = 0, w = 0, spaces = 0, is_str = 0; + + if (!line) + return; + + /* pass 1: squeeze blanks */ + while (line[r]) { + if (line[r] == ' ') { + if (!spaces || quote) line[w++] = line[r]; + r++; spaces++; + } else if (line[r] == '"') { + quote = !quote; + line[w++] = line[r++]; + spaces = 0; + } else { + line[w++] = line[r++]; + spaces = 0; + } + } + line[w] = 0; + + /* pass 2: join "..." & "..." fragments into a single string */ + quote = 0; r = 0; w = 0; + while (line[r]) { + switch (line[r]) { + case '&': + if (quote || !is_str) line[w++] = line[r]; + r++; + break; + case ' ': + if (quote || !is_str) line[w++] = line[r]; + r++; + break; + case '"': + if (!quote) { + quote = 1; + if (!is_str) line[w++] = line[r]; + is_str = 1; + } else { + quote = 0; + } + r++; + break; + default: + if (!quote) { + if (is_str) line[w++] = '"'; + is_str = 0; + } + line[w++] = line[r++]; + break; + } + } + if (is_str) + line[w++] = '"'; + line[w] = 0; +} + +/* -------------------------------------------------------- token scanners --- */ + +static char *check_next_keyword(char *buf, const char *kw, char sep) +{ + char seps[16]; + int i; + + if (!buf) + return NULL; + + seps[0] = sep; + seps[1] = 0; + strcat(seps, "\"() "); + + i = 0; + while (buf[i] && !strchr(seps, buf[i])) i++; + while (buf[i] && strchr(seps, buf[i])) i++; + + if (!strncmp(&buf[i], kw, strlen(kw))) + return &buf[i + strlen(kw)]; + return NULL; +} + +static int get_next_keyword(char *buf, char *out) +{ + int i = 0, j = 0; + if (!buf) { out[0] = 0; return 0; } + while (buf[i] && !strchr("\"():, ", buf[i])) i++; + while (buf[i] && strchr("\"():, ", buf[i])) i++; + while (buf[i] && !strchr("\"():;, ", buf[i])) { + if (j < BSDL_MAX_ELEMENT - 1) out[j++] = buf[i]; + i++; + } + out[j] = 0; + return i; +} + +static int get_next_parameter(char *buf, char *out) +{ + int i = 0, j = 0; + if (!buf) { out[0] = 0; return 0; } + while (buf[i] && !strchr("\":, ", buf[i])) i++; + while (buf[i] && strchr("\":, ", buf[i])) i++; + while (buf[i] && !strchr("\":, ;", buf[i])) { + if (j < BSDL_MAX_ELEMENT - 1) out[j++] = buf[i]; + i++; + } + out[j] = 0; + return i; +} + +static int check_next_symbol(char *buf, char c) +{ + int i = 0; + if (!buf) + return -1; + while (buf[i] && !strchr("\"(): ", buf[i]) && buf[i] != c) i++; + while (buf[i] && buf[i] == ' ') i++; + return (buf[i] == c) ? i : -1; +} + +/* ------------------------------------------------------ attribute lookup --- */ + +static char *get_attribut(char **lines, const char *name, const char *entity) +{ + int i = 0; + while (lines[i]) { + if (!strncmp(lines[i], "attribute ", 10) && + !strncmp(&lines[i][10], name, strlen(name))) { + char *p = check_next_keyword(&lines[i][10], "of", '\0'); + p = check_next_keyword(p, entity, ':'); + if (p) { + int j = 0; + while (p[j] && p[j] != ':' && p[j] == ' ') j++; + if (p[j] == ':') { + p = check_next_keyword(&p[j], "entity", ':'); + p = check_next_keyword(p, "is", '\0'); + return p; + } + } + return NULL; + } + i++; + } + return NULL; +} + +static char *get_attribut_txt(char **lines, const char *name, const char *entity) +{ + char *d = get_attribut(lines, name, entity); + int i = 0; + if (!d) + return NULL; + while (d[i] && d[i] != '"') i++; + return (d[i] == '"') ? &d[i] : NULL; +} + +static int get_attribut_int(char **lines, const char *name, const char *entity) +{ + char *d = get_attribut(lines, name, entity); + int i = 0; + if (!d) + return 0; + while (d[i] && !(d[i] >= '0' && d[i] <= '9')) i++; + return (d[i] >= '0' && d[i] <= '9') ? atoi(&d[i]) : 0; +} + +/* ----------------------------------------------------------- port clause --- */ + +static int get_next_pin(char *name, int *type, char *line, + int *start_index, int *end_index) +{ + int i, io_list_offset = 0, parsed, depth; + char tmp[256]; + + i = get_next_keyword(line, name); + while (line[i] == ' ') i++; + + if (line[i] == ':' || line[i] == ',') { + *start_index = 0; + *end_index = 0; + + if (line[i] == ',') { + io_list_offset = i + 1; + while (line[i] != ':' && line[i] != ';' && line[i]) i++; + if (line[i] != ':') + return 0; + } + + i += get_next_keyword(&line[i], tmp); + str_upper(tmp); + *type = bsdl_kw_lookup(bsdl_dir_kw, tmp); + + i += get_next_keyword(&line[i], tmp); + + if (str_eq_nocase("bit_vector", tmp)) { + while (line[i] != '(' && line[i] != ')' && line[i] != ';') i++; + parsed = 0; depth = 0; + do { + switch (line[i]) { + case '(': + depth++; + if (!parsed) { + i += get_next_keyword(&line[i], tmp); + *start_index = atoi(tmp); + i += get_next_keyword(&line[i], tmp); /* to / downto */ + i += get_next_keyword(&line[i], tmp); + *end_index = atoi(tmp); + parsed = 1; + } + break; + case ')': + if (!depth) return 0; + depth--; + break; + case ';': + return io_list_offset ? io_list_offset : i; + case 0: + break; + } + i++; + } while (line[i]); + return 0; + } + + if (str_eq_nocase("bit", tmp)) { + do { + if (line[i] == ';') + return io_list_offset ? io_list_offset : i; + i++; + } while (line[i]); + } + } + return 0; +} + +static int count_or_fill_pins(char **lines, wpin_t *pins) +{ + int i = 0, total = 0; + + while (lines[i]) { + if (!strncmp(lines[i], "port ", 5) || !strncmp(lines[i], "port(", 5)) { + int j = 0, offset; + char name[256]; + int type, a, b; + + while (lines[i][j] != '(' && lines[i][j]) j++; + + do { + offset = get_next_pin(name, &type, &lines[i][j], &a, &b); + int n = (a <= b) ? (b - a + 1) : (a - b + 1); + int inc = (a <= b) ? 1 : -1; + int k; + + for (k = 0; k < n; k++) { + if (pins && total < BSDL_MAX_PINS) { + snprintf(pins[total].name, BSDL_MAX_ELEMENT, "%.*s", + BSDL_MAX_ELEMENT - 1, name); + if (n > 1) { + char idx[32]; + size_t l = strlen(pins[total].name); + snprintf(idx, sizeof(idx), "(%d)", a + k * inc); + snprintf(pins[total].name + l, BSDL_MAX_ELEMENT - l, "%s", idx); + } + pins[total].dir = type; + pins[total].in_bit = pins[total].out_bit = pins[total].ctrl_bit = -1; + } + total++; + } + j += offset; + } while (offset && total < BSDL_MAX_PINS); + + return total; + } + i++; + } + return 0; +} + +/* ------------------------------------------------------ boundary register -- */ + +static int get_chain(char **lines, const char *entity, + wchain_t **out_chain, int *out_n) +{ + int n = get_attribut_int(lines, "BOUNDARY_LENGTH", entity); + char *s; + wchain_t *chain; + int i, j, count = 0, done = 0, bit; + char tmp[BSDL_MAX_ELEMENT]; + + *out_chain = NULL; + *out_n = 0; + + if (n <= 0 || n >= BSDL_MAX_CHAINBITS) + return 0; + + chain = calloc((size_t)n, sizeof(*chain)); + if (!chain) + return -1; + + s = get_attribut_txt(lines, "BOUNDARY_REGISTER", entity); + if (s && s[0] == '"') { + i = 0; + while (s[i] && !done) { + i += get_next_keyword(&s[i], tmp); + bit = atoi(tmp); + if (bit < 0 || bit >= n) { + free(chain); + return -1; + } + chain[bit].index = bit; + + while (s[i] != '(' && s[i]) i++; + + i += get_next_keyword(&s[i], tmp); + str_upper(tmp); + chain[bit].cell = bsdl_kw_lookup(bsdl_cell_kw, tmp); + + j = check_next_symbol(&s[i], ','); if (j < 0) { free(chain); return -1; } i += j; + i += get_next_parameter(&s[i], chain[bit].name); + + j = check_next_symbol(&s[i], ','); if (j < 0) { free(chain); return -1; } i += j; + i += get_next_keyword(&s[i], tmp); + str_upper(tmp); + chain[bit].type = bsdl_kw_lookup(bsdl_bittype_kw, tmp); + + j = check_next_symbol(&s[i], ','); if (j < 0) { free(chain); return -1; } i += j; + i += get_next_keyword(&s[i], tmp); + str_upper(tmp); + chain[bit].safe = bsdl_kw_lookup(bsdl_state_kw, tmp); + + chain[bit].ctrl_index = -1; + + j = check_next_symbol(&s[i], ')'); + if (s[i] == ',' || j < 0) { + j = check_next_symbol(&s[i], ','); if (j < 0) { free(chain); return -1; } i += j; + i += get_next_keyword(&s[i], tmp); + chain[bit].ctrl_index = atoi(tmp); + + j = check_next_symbol(&s[i], ','); if (j < 0) { free(chain); return -1; } i += j; + i += get_next_keyword(&s[i], tmp); + str_upper(tmp); + chain[bit].disable_state = bsdl_kw_lookup(bsdl_state_kw, tmp); + + j = check_next_symbol(&s[i], ','); if (j < 0) { free(chain); return -1; } i += j; + i += get_next_keyword(&s[i], tmp); + str_upper(tmp); + chain[bit].disable_result = bsdl_kw_lookup(bsdl_state_kw, tmp); + + j = check_next_symbol(&s[i], ')'); if (j < 0) { free(chain); return -1; } + } + i += j; + + i++; + count++; + if (check_next_symbol(&s[i], '"') >= 0) + done = 1; + } + } + + if (count != n) { + free(chain); + return -1; + } + + *out_chain = chain; + *out_n = n; + return n; +} + +/* Link each I/O pin to its boundary-register input/output/control bit. */ +static void link_pins_to_chain(wpin_t *pins, int np, wchain_t *chain, int nc) +{ + int i, j; + for (i = 0; i < np; i++) { + if (pins[i].dir != BSDL_DIR_IN && + pins[i].dir != BSDL_DIR_OUT && + pins[i].dir != BSDL_DIR_INOUT) + continue; + + for (j = 0; j < nc; j++) { + if (strcmp(chain[j].name, pins[i].name)) + continue; + switch (chain[j].type) { + case BSDL_BIT_INPUT: + pins[i].in_bit = chain[j].index; + break; + case BSDL_BIT_OUTPUT: + pins[i].out_bit = chain[j].index; + break; + case BSDL_BIT_TRISTATE: + pins[i].out_bit = chain[j].index; + pins[i].ctrl_bit = chain[j].ctrl_index; + break; + case BSDL_BIT_INOUT: + pins[i].in_bit = chain[j].index; + pins[i].out_bit = chain[j].index; + pins[i].ctrl_bit = chain[j].ctrl_index; + break; + default: + break; + } + } + } +} + +/* ------------------------------------------- NEW: PIN_MAP_STRING + TAP ----- */ + +static wpin_t *find_pin(wpin_t *pins, int n, const char *name) +{ + int i; + for (i = 0; i < n; i++) + if (!strcmp(pins[i].name, name)) + return &pins[i]; + return NULL; +} + +/* Strip every space from a token (PIN_MAP entries carry alignment padding). */ +static void squeeze(char *s) +{ + char *w = s; + for (; *s; s++) + if (*s != ' ') + *w++ = *s; + *w = 0; +} + +/* True if `name` is a subscript of vector port `base` (i.e. "base(k)"). */ +static int is_vector_member(const char *name, const char *base, size_t blen) +{ + const char *paren = strchr(name, '('); + return paren && (size_t)(paren - name) == blen && !strncmp(name, base, blen); +} + +/* Assign a parenthesised ball list positionally: balls[k] -> base(k). + * The vector's subscripts were expanded contiguously, in declared range order, + * which matches the PIN_MAP list order. */ +static void map_vector(wpin_t *pins, int np, const char *base, char *list) +{ + size_t blen = strlen(base); + int j, k = -1; + char *tok = list; + + for (j = 0; j < np; j++) + if (is_vector_member(pins[j].name, base, blen)) { k = j; break; } + if (k < 0) + return; + + for (;;) { + char ball[BSDL_MAX_ELEMENT]; + char *comma = strchr(tok, ','); + size_t len = comma ? (size_t)(comma - tok) : strlen(tok); + + if (len >= sizeof(ball)) + len = sizeof(ball) - 1; + memcpy(ball, tok, len); + ball[len] = 0; + squeeze(ball); + + if (k < np && is_vector_member(pins[k].name, base, blen)) { + if (ball[0]) + snprintf(pins[k].phys, BSDL_MAX_ELEMENT, "%.*s", + BSDL_MAX_ELEMENT - 1, ball); + k++; + } + if (!comma) + break; + tok = comma + 1; + } +} + +/* Parse PIN_MAP_STRING into pins[].phys. Each entry is "PORT:BALL" (scalar) or + * "PORT:(BALL,BALL,...)" (vector, positionally mapped to PORT(0), PORT(1), ...). */ +static void apply_pin_map(char **lines, wpin_t *pins, int np) +{ + int i = 0; + while (lines[i]) { + char *q = strstr(lines[i], "PIN_MAP_STRING"); + char *end; + if (!q) { i++; continue; } + + q = strchr(q, '"'); + if (!q) + return; + q++; + end = strchr(q, '"'); + if (end) + *end = 0; /* bound the scan to the string body */ + + while (*q) { + char port[BSDL_MAX_ELEMENT]; + char *colon, *p; + size_t len; + + while (*q == ',' || *q == ' ') + q++; + colon = strchr(q, ':'); + if (!colon) + break; + + len = (size_t)(colon - q); + if (len >= sizeof(port)) + len = sizeof(port) - 1; + memcpy(port, q, len); + port[len] = 0; + squeeze(port); + + p = colon + 1; + while (*p == ' ') + p++; + + if (*p == '(') { /* vector: (b0, b1, ...) */ + char *close = strchr(p, ')'); + if (!close) + break; + *close = 0; + map_vector(pins, np, port, p + 1); + *close = ')'; + q = close + 1; + } else { /* scalar: single ball */ + char ball[BSDL_MAX_ELEMENT]; + char *comma = strchr(p, ','); + wpin_t *pin; + len = comma ? (size_t)(comma - p) : strlen(p); + if (len >= sizeof(ball)) + len = sizeof(ball) - 1; + memcpy(ball, p, len); + ball[len] = 0; + squeeze(ball); + pin = find_pin(pins, np, port); + if (pin && ball[0]) + snprintf(pin->phys, BSDL_MAX_ELEMENT, "%.*s", + BSDL_MAX_ELEMENT - 1, ball); + q = comma ? comma + 1 : p + strlen(p); + } + } + + if (end) + *end = '"'; /* restore */ + return; + } +} + +/* Map TAP_SCAN_* attributes onto pins[].tap. */ +static void apply_tap_roles(char **lines, wpin_t *pins, int np) +{ + int i = 0; + while (lines[i]) { + if (!strncmp(lines[i], "attribute TAP_SCAN_", 19)) { + char attr[BSDL_MAX_ELEMENT], target[BSDL_MAX_ELEMENT]; + char *of; + int role; + + get_next_keyword(lines[i], attr); /* skip "attribute", read TAP_SCAN_x */ + str_upper(attr); + role = bsdl_kw_lookup(bsdl_tap_kw, attr); + if (role == BSDL_TAP_NONE) { i++; continue; } + + of = check_next_keyword(&lines[i][10], "of", '\0'); + if (of) { + wpin_t *p; + get_next_keyword(of, target); + p = find_pin(pins, np, target); + if (p) + p->tap = role; + } + } + i++; + } +} + +/* --------------------------------------------------------------- IDCODE ---- */ + +static void parse_idcode(char **lines, const char *entity, + unsigned long *id, unsigned long *mask) +{ + char *s = get_attribut_txt(lines, "IDCODE_REGISTER", entity); + int i; + + *id = 0; + *mask = 0xFFFFFFFFUL; + + if (!s || s[0] != '"') + return; + s++; + for (i = 0; s[i] && s[i] != '"' && s[i] != ';' && i < 32; i++) { + switch (s[i]) { + case '0': *id &= ~(0x80000000UL >> i); break; + case '1': *id |= (0x80000000UL >> i); break; + case 'x': + case 'X': *mask &= ~(0x80000000UL >> i); break; + default: break; + } + } +} + +/* ----------------------------------------------------------- instructions -- */ + +static void push_instr(bsdl_instr_t *arr, size_t *n, const char *name, char *opcode) +{ + if (!opcode[0]) + return; + arr[*n].name = strdup(name); + arr[*n].opcode = strdup(opcode); + (*n)++; +} + +static bsdl_instr_t *parse_instructions(char **lines, const char *entity, size_t *count) +{ + static const char *const names[] = { "IDCODE", "EXTEST", "BYPASS", "SAMPLE" }; + bsdl_instr_t *arr; + char *opc; + size_t k; + + *count = 0; + arr = calloc(4, sizeof(*arr)); + if (!arr) + return NULL; + + opc = get_attribut_txt(lines, "INSTRUCTION_OPCODE", entity); + if (!opc) + return arr; + + for (k = 0; k < 4; k++) { + char tmp[BSDL_MAX_ELEMENT] = { 0 }; + char *hit = strstr(opc, names[k]); + if (!hit) { + /* lower-case spelling */ + char lower[16]; + size_t z; + for (z = 0; names[k][z] && z < sizeof(lower) - 1; z++) + lower[z] = (char)tolower((unsigned char)names[k][z]); + lower[z] = 0; + hit = strstr(opc, lower); + } + if (hit) { + get_next_keyword(hit, tmp); + push_instr(arr, count, names[k], tmp); + } + } + return arr; +} + +/* ------------------------------------------------- natural-order pin sort -- */ + +static int nat_cmp(const void *pa, const void *pb) +{ + const char *a = ((const bsdl_pin_t *)pa)->name; + const char *b = ((const bsdl_pin_t *)pb)->name; + + while (*a && *b) { + if (isdigit((unsigned char)*a) && isdigit((unsigned char)*b)) { + long va = strtol(a, (char **)&a, 10); + long vb = strtol(b, (char **)&b, 10); + if (va != vb) + return (va < vb) ? -1 : 1; + } else { + if (*a != *b) + return (unsigned char)*a - (unsigned char)*b; + a++; b++; + } + } + return (unsigned char)*a - (unsigned char)*b; +} + +/* ------------------------------------------------------------- assembly ---- */ + +static bsdl_t *build_model(const char *entity, const char *name, + unsigned long id, unsigned long mask, int ilen, + wpin_t *wp, int np, wchain_t *wc, int nc, + bsdl_instr_t *instr, size_t ninstr, + const bsdl_opts_t *opts) +{ + bsdl_t *m = calloc(1, sizeof(*m)); + int i; + + if (!m) + return NULL; + + m->entity = strdup(entity); + m->src_filename = strdup(name ? name : ""); + m->idcode = id; + m->idcode_mask = mask; + m->instruction_length = ilen; + m->instructions = instr; + m->instruction_count = ninstr; + + if (np > 0) { + m->pins = calloc((size_t)np, sizeof(bsdl_pin_t)); + if (m->pins) { + for (i = 0; i < np; i++) { + m->pins[i].name = strdup(wp[i].name); + m->pins[i].dir = (bsdl_dir_t)wp[i].dir; + m->pins[i].physical_pin = wp[i].phys[0] ? strdup(wp[i].phys) : NULL; + m->pins[i].tap_role = (bsdl_tap_role_t)wp[i].tap; + m->pins[i].in_bit = wp[i].in_bit; + m->pins[i].out_bit = wp[i].out_bit; + m->pins[i].ctrl_bit = wp[i].ctrl_bit; + } + m->pin_count = (size_t)np; + if (opts && opts->sort_pins_by_name) + qsort(m->pins, m->pin_count, sizeof(bsdl_pin_t), nat_cmp); + } + } + + if (nc > 0) { + m->chain = calloc((size_t)nc, sizeof(bsdl_cell_entry_t)); + if (m->chain) { + for (i = 0; i < nc; i++) { + m->chain[i].index = wc[i].index; + m->chain[i].cell = (bsdl_cell_t)wc[i].cell; + m->chain[i].port = strdup(wc[i].name); + m->chain[i].type = (bsdl_bittype_t)wc[i].type; + m->chain[i].safe = (bsdl_state_t)wc[i].safe; + m->chain[i].ctrl_index = wc[i].ctrl_index; + m->chain[i].disable_state = (bsdl_state_t)wc[i].disable_state; + m->chain[i].disable_result = (bsdl_state_t)wc[i].disable_result; + } + m->chain_count = (size_t)nc; + } + } + + return m; +} + +/* ----------------------------------------------------------- public API ---- */ + +bsdl_t *bsdl_parse_buffer(const char *text, size_t len, + const char *name, const bsdl_opts_t *opts) +{ + char *clean = NULL, **lines = NULL, *p; + char entity[256]; + int size, offset, i, nlines, np = 0, nc = 0; + wpin_t *wp = NULL; + wchain_t *wc = NULL; + bsdl_instr_t *instr = NULL; + size_t ninstr = 0; + unsigned long id = 0, mask = 0xFFFFFFFFUL; + int ilen; + bsdl_t *model = NULL; + + if (!text || len == 0 || len > BSDL_MAX_FILE_SIZE) { + plog(opts, BSDL_LOG_ERROR, "bsdl_parse_buffer: empty or oversized input"); + return NULL; + } + size = (int)len; + + /* clean: comment/whitespace-normalised copy */ + clean = malloc((size_t)size + 1); + if (!clean) { + plog(opts, BSDL_LOG_ERROR, "out of memory"); + return NULL; + } + { + char *raw = malloc((size_t)size + 1); + if (!raw) { free(clean); return NULL; } + memcpy(raw, text, (size_t)size); + raw[size] = 0; + offset = 0; i = 0; + while (offset < size && i < size) + clean[i++] = next_char(raw, size, &offset); + clean[i] = 0; + free(raw); + } + + /* entity name */ + p = strstr(clean, "entity"); + if (!p) { + plog(opts, BSDL_LOG_ERROR, "no \"entity\" declaration found"); + goto done; + } + offset = (int)(p - clean); + while (clean[offset] != ' ' && clean[offset]) offset++; + while (clean[offset] == ' ' && clean[offset]) offset++; + i = 0; + memset(entity, 0, sizeof(entity)); + while (clean[offset] != ' ' && clean[offset] && i < (int)sizeof(entity) - 1) + entity[i++] = clean[offset++]; + while (clean[offset] == ' ' && clean[offset]) offset++; + if (strncmp(&clean[offset], "is", 2)) { + plog(opts, BSDL_LOG_ERROR, "malformed entity declaration (\"is\" expected)"); + goto done; + } + offset += 2; + + /* statements */ + nlines = extract_lines(&clean[offset], NULL); + if (nlines <= 0 || nlines > BSDL_MAX_LINES) { + plog(opts, BSDL_LOG_ERROR, "no parsable statements"); + goto done; + } + lines = calloc((size_t)nlines + 1, sizeof(char *)); + if (!lines) + goto done; + extract_lines(&clean[offset], lines); + for (i = 0; i < nlines; i++) + preprocess_line(lines[i]); + + /* fields */ + parse_idcode(lines, entity, &id, &mask); + ilen = get_attribut_int(lines, "INSTRUCTION_LENGTH", entity); + + np = count_or_fill_pins(lines, NULL); + if (np > 0 && np < BSDL_MAX_PINS) { + wp = calloc((size_t)np, sizeof(*wp)); + if (wp) + count_or_fill_pins(lines, wp); + } + + if (get_chain(lines, entity, &wc, &nc) < 0) + plog(opts, BSDL_LOG_WARN, "boundary register parsing failed"); + + if (wp) { + if (wc && nc > 0) + link_pins_to_chain(wp, np, wc, nc); + apply_pin_map(lines, wp, np); /* NEW */ + apply_tap_roles(lines, wp, np); /* NEW */ + } + + instr = parse_instructions(lines, entity, &ninstr); + + model = build_model(entity, name, id, mask, ilen, + wp, wp ? np : 0, wc, nc, instr, ninstr, opts); + if (model) + instr = NULL; /* ownership transferred */ + +done: + if (lines) { + for (i = 0; i < nlines; i++) + free(lines[i]); + free(lines); + } + free(wp); + free(wc); + if (instr) { + size_t z; + for (z = 0; z < ninstr; z++) { + free((void *)instr[z].name); + free((void *)instr[z].opcode); + } + free(instr); + } + free(clean); + return model; +} + +bsdl_t *bsdl_parse_file(const char *path, const bsdl_opts_t *opts) +{ + FILE *f; + long size; + char *buf; + bsdl_t *model; + const char *base; + + if (!path) { + plog(opts, BSDL_LOG_ERROR, "bsdl_parse_file: NULL path"); + return NULL; + } + + f = fopen(path, "rb"); + if (!f) { + plog(opts, BSDL_LOG_ERROR, "cannot open file"); + return NULL; + } + fseek(f, 0, SEEK_END); + size = ftell(f); + fseek(f, 0, SEEK_SET); + if (size <= 0 || size > BSDL_MAX_FILE_SIZE) { + plog(opts, BSDL_LOG_ERROR, "bad file size"); + fclose(f); + return NULL; + } + buf = malloc((size_t)size); + if (!buf) { + fclose(f); + return NULL; + } + if (fread(buf, (size_t)size, 1, f) != 1) { + plog(opts, BSDL_LOG_ERROR, "file read error"); + free(buf); + fclose(f); + return NULL; + } + fclose(f); + + base = strrchr(path, '/'); + base = base ? base + 1 : path; + + model = bsdl_parse_buffer(buf, (size_t)size, base, opts); + free(buf); + return model; +} diff --git a/src/bsdl_strings.c b/src/bsdl_strings.c new file mode 100644 index 0000000..d21bceb --- /dev/null +++ b/src/bsdl_strings.c @@ -0,0 +1,65 @@ +/* + * libbsdl - internal keyword lookup tables. + * SPDX-License-Identifier: LGPL-2.1-or-later + */ +#include + +#include "bsdl/bsdl.h" +#include "bsdl_strings.h" + +const bsdl_kw_t bsdl_dir_kw[] = { + { "IN", BSDL_DIR_IN }, + { "OUT", BSDL_DIR_OUT }, + { "INOUT", BSDL_DIR_INOUT }, + { "BUFFER", BSDL_DIR_BUFFER }, + { "LINKAGE", BSDL_DIR_LINKAGE }, /* power / gnd / NC — kept, unlike Viveris. */ + { 0, BSDL_DIR_UNKNOWN } +}; + +const bsdl_kw_t bsdl_cell_kw[] = { + { "BC_1", BSDL_CELL_BC1 }, { "BC_2", BSDL_CELL_BC2 }, + { "BC_3", BSDL_CELL_BC3 }, { "BC_4", BSDL_CELL_BC4 }, + { "BC_5", BSDL_CELL_BC5 }, { "BC_6", BSDL_CELL_BC6 }, + { "BC_7", BSDL_CELL_BC7 }, + { 0, BSDL_CELL_UNKNOWN } +}; + +const bsdl_kw_t bsdl_bittype_kw[] = { + { "INPUT", BSDL_BIT_INPUT }, + { "OBSERVE_ONLY", BSDL_BIT_INPUT }, + { "OUTPUT", BSDL_BIT_OUTPUT }, + { "OUTPUT2", BSDL_BIT_OUTPUT }, + { "OUTPUT3", BSDL_BIT_TRISTATE }, + { "BIDIR", BSDL_BIT_INOUT }, + { "CONTROL", BSDL_BIT_CONTROL }, + { "CONTROLR", BSDL_BIT_CONTROL }, + { "INTERNAL", BSDL_BIT_INTERNAL }, + { 0, BSDL_BIT_UNKNOWN } +}; + +const bsdl_kw_t bsdl_state_kw[] = { + { "X", BSDL_STATE_UNDEF }, { "1", BSDL_STATE_HIGH }, + { "0", BSDL_STATE_LOW }, { "Z", BSDL_STATE_HIGHZ }, + { 0, BSDL_STATE_UNKNOWN } +}; + +const bsdl_kw_t bsdl_tap_kw[] = { + { "TAP_SCAN_IN", BSDL_TAP_TDI }, + { "TAP_SCAN_OUT", BSDL_TAP_TDO }, + { "TAP_SCAN_MODE", BSDL_TAP_TMS }, + { "TAP_SCAN_CLOCK", BSDL_TAP_TCK }, + { "TAP_SCAN_RESET", BSDL_TAP_TRST }, + { 0, BSDL_TAP_NONE } +}; + +int bsdl_kw_lookup(const bsdl_kw_t* table, const char* name) +{ + int i; + if (!table || !name) + return 0; + for (i = 0; table[i].name; i++) { + if (!strcmp(table[i].name, name)) + return table[i].code; + } + return table[i].code; /* terminator code = UNKNOWN/NONE */ +} diff --git a/src/bsdl_strings.h b/src/bsdl_strings.h new file mode 100644 index 0000000..d7c3aaa --- /dev/null +++ b/src/bsdl_strings.h @@ -0,0 +1,26 @@ +/* + * libbsdl - internal keyword lookup tables. + * SPDX-License-Identifier: LGPL-2.1-or-later + * + * These map BSDL tokens onto the public enums. They are the seed for the + * parser port from Viveris, and already extend it with the two attributes + * Viveris omits: LINKAGE ports and the TAP_SCAN_* roles. + */ +#ifndef LIBBSDL_BSDL_STRINGS_H +#define LIBBSDL_BSDL_STRINGS_H + +typedef struct bsdl_kw { + const char* name; /* BSDL token, upper-cased before lookup. */ + int code; /* corresponding bsdl_* enum value. */ +} bsdl_kw_t; + +extern const bsdl_kw_t bsdl_dir_kw[]; /* -> bsdl_dir_t */ +extern const bsdl_kw_t bsdl_cell_kw[]; /* -> bsdl_cell_t */ +extern const bsdl_kw_t bsdl_bittype_kw[]; /* -> bsdl_bittype_t */ +extern const bsdl_kw_t bsdl_state_kw[]; /* -> bsdl_state_t */ +extern const bsdl_kw_t bsdl_tap_kw[]; /* -> bsdl_tap_role_t */ + +/* Linear lookup; returns the first table entry's code (UNKNOWN/NONE) if absent. */ +int bsdl_kw_lookup(const bsdl_kw_t* table, const char* name); + +#endif /* LIBBSDL_BSDL_STRINGS_H */ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..7e55a13 --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,7 @@ +add_executable(test_api test_api.c) +target_link_libraries(test_api PRIVATE bsdl) +add_test(NAME api COMMAND test_api) + +add_executable(test_parse test_parse.c) +target_link_libraries(test_parse PRIVATE bsdl) +add_test(NAME parse COMMAND test_parse) diff --git a/tests/test_api.c b/tests/test_api.c new file mode 100644 index 0000000..2444bab --- /dev/null +++ b/tests/test_api.c @@ -0,0 +1,90 @@ +/* + * libbsdl - API test: exercises the lifecycle + JSON layer. + * SPDX-License-Identifier: LGPL-2.1-or-later + */ +#include +#include +#include + +#include "bsdl/bsdl.h" + +static int failures = 0; + +#define CHECK(cond) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +int main(void) +{ + bsdl_opts_t opts; + bsdl_t model; + char* json; + + /* version is reported and matches the compiled-in macro */ + CHECK(bsdl_version() != NULL); + CHECK(strcmp(bsdl_version(), BSDL_VERSION_STRING) == 0); + + /* defaults are sane */ + bsdl_opts_default(&opts); + CHECK(opts.sort_pins_by_name == 0); + CHECK(opts.log == NULL); + CHECK(opts.log_user == NULL); + + /* defined behaviour on bad input */ + CHECK(bsdl_parse_file(NULL, &opts) == NULL); + CHECK(bsdl_parse_file("/nonexistent/does-not-exist.bsd", NULL) == NULL); + CHECK(bsdl_to_json(NULL) == NULL); + bsdl_free(NULL); /* must be NULL-safe */ + bsdl_string_free(NULL); /* must be NULL-safe */ + + /* JSON layer over a hand-built model (independent of the parser) */ + { + static bsdl_pin_t pins[1]; + static bsdl_instr_t instrs[1]; + memset(&model, 0, sizeof(model)); + memset(pins, 0, sizeof(pins)); + memset(instrs, 0, sizeof(instrs)); + + pins[0].name = "TCK"; + pins[0].dir = BSDL_DIR_IN; + pins[0].physical_pin = "W20"; + pins[0].tap_role = BSDL_TAP_TCK; + pins[0].in_bit = -1; + pins[0].out_bit = -1; + pins[0].ctrl_bit = -1; + + instrs[0].name = "IDCODE"; + instrs[0].opcode = "001001"; + + model.entity = "DEMO"; + model.src_filename = "demo.bsd"; + model.idcode = 0x12345678UL; + model.idcode_mask = 0xFFFFFFFFUL; + model.instruction_length = 6; + model.pins = pins; + model.pin_count = 1; + model.instructions = instrs; + model.instruction_count = 1; + + json = bsdl_to_json(&model); + CHECK(json != NULL); + if (json) { + CHECK(strstr(json, "\"entity\":\"DEMO\"") != NULL); + CHECK(strstr(json, "\"physical_pin\":\"W20\"") != NULL); + CHECK(strstr(json, "\"tap_role\":\"tck\"") != NULL); + CHECK(strstr(json, "\"idcode\":\"0x12345678\"") != NULL); + CHECK(strstr(json, "\"name\":\"IDCODE\"") != NULL); + bsdl_string_free(json); + } + } + + if (failures) { + fprintf(stderr, "%d check(s) failed\n", failures); + return 1; + } + printf("all API checks passed\n"); + return 0; +} diff --git a/tests/test_parse.c b/tests/test_parse.c new file mode 100644 index 0000000..fc84855 --- /dev/null +++ b/tests/test_parse.c @@ -0,0 +1,154 @@ +/* + * libbsdl - parser regression test over a synthetic in-memory BSDL. + * SPDX-License-Identifier: LGPL-2.1-or-later + * + * Exercises: entity, IDCODE, port directions, scalar + vector PIN_MAP, + * TAP_SCAN roles, boundary register, instruction opcodes. + */ +#include +#include + +#include "bsdl/bsdl.h" + +static int failures = 0; + +#define CHECK(cond) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +static const char DEMO[] = + "entity DEMO is\n" + " generic (PHYSICAL_PIN_MAP : string := \"PKG\");\n" + " port (\n" + " TCK:in bit;\n" + " TDI:in bit;\n" + " TDO:out bit;\n" + " TMS:in bit;\n" + " Q:out bit_vector(0 to 1);\n" + " VCC:linkage bit;\n" + " GND:linkage bit_vector(0 to 1)\n" + " );\n" + " use STD_1149_1_2001.all;\n" + " attribute PIN_MAP of DEMO : entity is PHYSICAL_PIN_MAP;\n" + " constant PKG : PIN_MAP_STRING :=\n" + " \"TCK:1,\" &\n" + " \"TDI:2,\" &\n" + " \"TDO:3,\" &\n" + " \"TMS:4,\" &\n" + " \"Q:(5,6),\" &\n" + " \"VCC:7,\" &\n" + " \"GND:(8,9)\";\n" + " attribute TAP_SCAN_IN of TDI : signal is true;\n" + " attribute TAP_SCAN_MODE of TMS : signal is true;\n" + " attribute TAP_SCAN_OUT of TDO : signal is true;\n" + " attribute TAP_SCAN_CLOCK of TCK : signal is (10.0e6, BOTH);\n" + " attribute INSTRUCTION_LENGTH of DEMO : entity is 4;\n" + " attribute INSTRUCTION_OPCODE of DEMO : entity is\n" + " \"BYPASS (1111),\" &\n" + " \"EXTEST (0000),\" &\n" + " \"SAMPLE (0001),\" &\n" + " \"IDCODE (1110)\";\n" + " attribute IDCODE_REGISTER of DEMO : entity is\n" + " \"0001\" &\n" + " \"0010001101000101\" &\n" + " \"00000000111\" &\n" + " \"1\";\n" + " attribute BOUNDARY_LENGTH of DEMO : entity is 3;\n" + " attribute BOUNDARY_REGISTER of DEMO : entity is\n" + " \"0 (BC_1, Q(0), output3, X, 2, 1, Z),\" &\n" + " \"1 (BC_1, Q(1), output3, X, 2, 1, Z),\" &\n" + " \"2 (BC_1, *, control, 1)\";\n" + "end DEMO;\n"; + +static const bsdl_pin_t *pin(const bsdl_t *m, const char *name) +{ + size_t i; + for (i = 0; i < m->pin_count; i++) + if (!strcmp(m->pins[i].name, name)) + return &m->pins[i]; + return NULL; +} + +static int has_instr(const bsdl_t *m, const char *name, const char *opcode) +{ + size_t i; + for (i = 0; i < m->instruction_count; i++) + if (!strcmp(m->instructions[i].name, name) && + !strcmp(m->instructions[i].opcode, opcode)) + return 1; + return 0; +} + +int main(void) +{ + bsdl_opts_t opts; + bsdl_t *m; + const bsdl_pin_t *p; + + bsdl_opts_default(&opts); + m = bsdl_parse_buffer(DEMO, sizeof(DEMO) - 1, "demo.bsd", &opts); + CHECK(m != NULL); + if (!m) { + fprintf(stderr, "parse returned NULL\n"); + return 1; + } + + /* header */ + CHECK(strcmp(m->entity, "DEMO") == 0); + CHECK(m->idcode == 0x1234500FUL); + CHECK(m->idcode_mask == 0xFFFFFFFFUL); + CHECK(m->instruction_length == 4); + + /* 4 scalars + Q(0..1) + VCC + GND(0..1) = 9 */ + CHECK(m->pin_count == 9); + + /* scalar pin + TAP role + physical pin */ + p = pin(m, "TCK"); + CHECK(p && p->dir == BSDL_DIR_IN && p->tap_role == BSDL_TAP_TCK && + p->physical_pin && !strcmp(p->physical_pin, "1")); + p = pin(m, "TDI"); + CHECK(p && p->tap_role == BSDL_TAP_TDI && !strcmp(p->physical_pin, "2")); + p = pin(m, "TDO"); + CHECK(p && p->dir == BSDL_DIR_OUT && p->tap_role == BSDL_TAP_TDO); + p = pin(m, "TMS"); + CHECK(p && p->tap_role == BSDL_TAP_TMS); + + /* vector PIN_MAP, positional: Q(0)->5, Q(1)->6 */ + p = pin(m, "Q(0)"); + CHECK(p && p->dir == BSDL_DIR_OUT && p->physical_pin && !strcmp(p->physical_pin, "5")); + p = pin(m, "Q(1)"); + CHECK(p && p->physical_pin && !strcmp(p->physical_pin, "6")); + + /* linkage scalar + vector */ + p = pin(m, "VCC"); + CHECK(p && p->dir == BSDL_DIR_LINKAGE && !strcmp(p->physical_pin, "7")); + p = pin(m, "GND(0)"); + CHECK(p && p->dir == BSDL_DIR_LINKAGE && !strcmp(p->physical_pin, "8")); + p = pin(m, "GND(1)"); + CHECK(p && !strcmp(p->physical_pin, "9")); + + /* boundary register linkage to pins (tristate output cell) */ + CHECK(m->chain_count == 3); + p = pin(m, "Q(0)"); + CHECK(p && p->out_bit == 0 && p->ctrl_bit == 2); + p = pin(m, "Q(1)"); + CHECK(p && p->out_bit == 1 && p->ctrl_bit == 2); + + /* instructions */ + CHECK(has_instr(m, "IDCODE", "1110")); + CHECK(has_instr(m, "EXTEST", "0000")); + CHECK(has_instr(m, "BYPASS", "1111")); + CHECK(has_instr(m, "SAMPLE", "0001")); + + bsdl_free(m); + + if (failures) { + fprintf(stderr, "%d check(s) failed\n", failures); + return 1; + } + printf("all parse checks passed\n"); + return 0; +} diff --git a/tools/bsdl2json.c b/tools/bsdl2json.c new file mode 100644 index 0000000..fccbfea --- /dev/null +++ b/tools/bsdl2json.c @@ -0,0 +1,77 @@ +/* + * bsdl2json - parse a BSDL file and print the model as JSON on stdout. + * SPDX-License-Identifier: LGPL-2.1-or-later + * + * Thin frontend over libbsdl. essim invokes this out-of-process; bs_explorer + * links the library directly and uses the struct instead. + */ +#include +#include + +#include "bsdl/bsdl.h" + +static void log_cb(bsdl_log_level_t level, const char* msg, void* user) +{ + static const char* const names[] = { "ERROR", "WARN", "INFO", "DEBUG" }; + (void)user; + fprintf(stderr, "[bsdl:%s] %s\n", names[level], msg); +} + +static void usage(const char* argv0) +{ + fprintf(stderr, + "libbsdl %s\n" + "usage: %s [--quiet] \n" + " prints the parsed BSDL model as JSON on stdout\n", + bsdl_version(), argv0); +} + +int main(int argc, char** argv) +{ + bsdl_opts_t opts; + const char* path = NULL; + int quiet = 0; + int i; + bsdl_t* model; + char* json; + + for (i = 1; i < argc; i++) { + if (!strcmp(argv[i], "--quiet") || !strcmp(argv[i], "-q")) { + quiet = 1; + } else if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) { + usage(argv[0]); + return 0; + } else if (argv[i][0] == '-') { + fprintf(stderr, "unknown option: %s\n", argv[i]); + usage(argv[0]); + return 2; + } else { + path = argv[i]; + } + } + + if (!path) { + usage(argv[0]); + return 2; + } + + bsdl_opts_default(&opts); + if (!quiet) + opts.log = log_cb; + + model = bsdl_parse_file(path, &opts); + if (!model) { + fprintf(stderr, "error: failed to parse %s\n", path); + return 1; + } + + json = bsdl_to_json(model); + if (json) { + fputs(json, stdout); + fputc('\n', stdout); + bsdl_string_free(json); + } + + bsdl_free(model); + return 0; +}