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 <noreply@anthropic.com>
This commit is contained in:
2026-06-03 10:27:13 +02:00
parent c78ff82923
commit 6b56ab5c42
16 changed files with 2764 additions and 0 deletions

26
.gitignore vendored Normal file
View File

@@ -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

109
CMakeLists.txt Normal file
View File

@@ -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
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
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
)

502
LICENSE Normal file
View File

@@ -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.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it 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.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View File

@@ -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/bsdl.h>
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 (© 20082024 Viveris Technologies,
Jean-François DEL NERO), also LGPL-2.1.

View File

@@ -0,0 +1,5 @@
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/bsdlTargets.cmake")
check_required_components(bsdl)

18
data/README.md Normal file
View File

@@ -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.

199
include/bsdl/bsdl.h Normal file
View File

@@ -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 <stddef.h>
/* -------- 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 */

52
src/bsdl.c Normal file
View File

@@ -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 <stdlib.h>
#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);
}

248
src/bsdl_json.c Normal file
View File

@@ -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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#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);
}

1112
src/bsdl_parse.c Normal file

File diff suppressed because it is too large Load Diff

65
src/bsdl_strings.c Normal file
View File

@@ -0,0 +1,65 @@
/*
* libbsdl - internal keyword lookup tables.
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#include <string.h>
#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 */
}

26
src/bsdl_strings.h Normal file
View File

@@ -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 */

7
tests/CMakeLists.txt Normal file
View File

@@ -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)

90
tests/test_api.c Normal file
View File

@@ -0,0 +1,90 @@
/*
* libbsdl - API test: exercises the lifecycle + JSON layer.
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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;
}

154
tests/test_parse.c Normal file
View File

@@ -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 <stdio.h>
#include <string.h>
#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;
}

77
tools/bsdl2json.c Normal file
View File

@@ -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 <stdio.h>
#include <string.h>
#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] <file.bsd>\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;
}