dlang-app added

Change-Id: I9d287c78e73442edd55752ab1dfc43d9bc5b4984
This commit is contained in:
Matheus Catarino
2024-06-05 14:15:15 -03:00
committed by openvela-robot
parent 2194949f4a
commit bbd7759e31
1040 changed files with 33693 additions and 97018 deletions

View File

@@ -118,7 +118,7 @@ jobs:
strategy:
matrix:
boards: [arm-01, arm-02, arm-03, arm-04, arm-05, arm-06, arm-07, arm-08, arm-09, arm-10, arm-11, arm-12, arm-13, other, risc-v, sim-01, sim-02, xtensa, codechecker]
boards: [arm-01, arm-02, arm-03, arm-04, arm-05, arm-06, arm-07, arm-08, arm-09, arm-10, arm-11, arm-12, arm-13, other, risc-v, sim-01, sim-02, xtensa]
steps:
- name: Download Source Artifact
@@ -187,19 +187,19 @@ jobs:
- name: Restore Tools Cache
id: cache-tools
uses: actions/cache@v3
uses: actions/cache@v4
env:
cache-name: ${{ runner.os }}-cache-tools
with:
path: ./sources/tools
key: ${{ runner.os }}-tools-${{ hashFiles('./sources/nuttx/tools/ci/cibuild.sh') }}
key: ${{ runner.os }}-tools-${{ hashFiles('./sources/nuttx/tools/ci/platforms/darwin.sh') }}
- name: Export NuttX Repo SHA
run: echo "nuttx_sha=`git -C sources/nuttx rev-parse HEAD`" >> $GITHUB_ENV
# Released version of Cython has issues with Python 11. Set runner to use Python 3.10
# https://github.com/cython/cython/issues/4500
- uses: actions/setup-python@v4
- uses: actions/setup-python@v5
with:
python-version: '3.10'
- name: Run Builds
@@ -214,3 +214,71 @@ jobs:
name: macos-builds
path: buildartifacts/
continue-on-error: true
msys2:
needs: Fetch-Source
runs-on: windows-latest
strategy:
fail-fast: false
matrix:
boards: [msys2]
defaults:
run:
shell: msys2 {0}
steps:
- uses: actions/checkout@v4
- uses: msys2/setup-msys2@v2
with:
msystem: MSYS
update: false
install: >-
base-devel
gcc
gperf
automake
autoconf
git
python3
ncurses-devel
unzip
zip
tio
zlib-devel
cmake
ninja
python-pip
vim
- name: pip3 install
run: |
pip3 install --root-user-action=ignore --no-cache-dir pyelftools cxxfilt kconfiglib
- run: git config --global core.autocrlf false
- name: Download Source Artifact
uses: actions/download-artifact@v3
with:
name: source-bundle
path: .
- name: Extract sources
run: tar zxf sources.tar.gz
- name: Export NuttX Repo SHA
run: echo "nuttx_sha=`git -C sources/nuttx rev-parse HEAD`" >> $GITHUB_ENV
- name: Run Builds
run: |
echo "::add-matcher::sources/nuttx/.github/gcc.json"
export ARTIFACTDIR=`pwd`/buildartifacts
git config --global --add safe.directory /github/workspace/sources/nuttx
git config --global --add safe.directory /github/workspace/sources/apps
cd sources/nuttx/tools/ci
./cibuild.sh -g -i -A -C -R testlist/${{matrix.boards}}.dat
- uses: actions/upload-artifact@v3
with:
name: msys2-builds
path: buildartifacts/
continue-on-error: true

View File

@@ -22,7 +22,7 @@ jobs:
fetch-depth: 0
- run: mkdir super-linter.report
- name: Lint
uses: github/super-linter@v5
uses: github/super-linter@v6
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VALIDATE_ALL_CODEBASE: false

8
.gitignore vendored
View File

@@ -1,9 +1,6 @@
*.a
*.dbo
*.dba
*.adb
*.asm
*.d
*.dSYM
*.exe
*.gcno
@@ -25,7 +22,7 @@
.context
.depend
.kconfig
/*.lock
*.lock
/bin
/boot_romfsimg.h
/external
@@ -41,3 +38,6 @@ Make.dep
.dirlinks
.vscode
.DS_Store
build
.ccls-cache
compile_commands.json

View File

@@ -23,18 +23,12 @@
# has the value "m"
ifneq ($(MAINSRC),)
ifeq ($(DYNLIB),y)
ifeq ($(MODULE),m)
BUILD_MODULE = y
endif
ifeq ($(CONFIG_BUILD_KERNEL),y)
BUILD_MODULE = y
MODAELFFLAGS = $(CMODULELFFLAGS)
MODCFLAGS = $(CMODULEFLAGS)
MODCXXFLAGS = $(CXXMODULEFLAGS)
MODLDFLAGS = $(LDMODULEFLAGS)
else ifneq ($(or $(filter y,$(CONFIG_BUILD_KERNEL)), $(filter m,$(MODULE))),)
BUILD_MODULE = y
MODAELFFLAGS = $(AELFFLAGS)
MODCFLAGS = $(CELFFLAGS)
MODCXXFLAGS = $(CXXELFFLAGS)
MODLDFLAGS = $(LDELFFLAGS)
endif
endif
@@ -48,10 +42,6 @@ else
CWD = $(CURDIR)
endif
SUFFIX ?= $(subst $(DELIM),.,$(CWD))
PROGNAME := $(subst ",,$(PROGNAME))
# Add the static application library to the linked libraries.
LDLIBS += $(call CONVERT_PATH,$(BIN))
@@ -71,6 +61,10 @@ ifeq ($(BUILD_MODULE),y)
LDLIBS += $(COMPILER_RT_LIB)
endif
SUFFIX ?= $(subst $(DELIM),.,$(CWD))
PROGNAME := $(subst ",,$(PROGNAME))
# Object files
RASRCS = $(filter %.s,$(ASRCS))
@@ -82,26 +76,28 @@ COBJS = $(CSRCS:=$(SUFFIX)$(OBJEXT))
CXXOBJS = $(CXXSRCS:=$(SUFFIX)$(OBJEXT))
RUSTOBJS = $(RUSTSRCS:=$(SUFFIX)$(OBJEXT))
ZIGOBJS = $(ZIGSRCS:=$(SUFFIX)$(OBJEXT))
AIDLOBJS = $(patsubst %$(AIDLEXT),%$(CXXEXT),$(AIDLSRCS))
DOBJS = $(DSRCS:=$(SUFFIX)$(OBJEXT))
MAINCXXSRCS = $(filter %$(CXXEXT),$(MAINSRC))
MAINCSRCS = $(filter %.c,$(MAINSRC))
MAINRUSTSRCS = $(filter %$(RUSTEXT),$(MAINSRC))
MAINZIGSRCS = $(filter %$(ZIGEXT),$(MAINSRC))
MAINDSRCS = $(filter %$(DEXT),$(MAINSRC))
MAINCXXOBJ = $(MAINCXXSRCS:=$(SUFFIX)$(OBJEXT))
MAINCOBJ = $(MAINCSRCS:=$(SUFFIX)$(OBJEXT))
MAINRUSTOBJ = $(MAINRUSTSRCS:=$(SUFFIX)$(OBJEXT))
MAINZIGOBJ = $(MAINZIGSRCS:=$(SUFFIX)$(OBJEXT))
MAINDOBJ = $(MAINDSRCS:=$(SUFFIX)$(OBJEXT))
SRCS = $(ASRCS) $(CSRCS) $(CXXSRCS) $(MAINSRC)
OBJS = $(RAOBJS) $(CAOBJS) $(COBJS) $(CXXOBJS) $(RUSTOBJS) $(ZIGOBJS) $(EXTOBJS)
OBJS = $(RAOBJS) $(CAOBJS) $(COBJS) $(CXXOBJS) $(RUSTOBJS) $(ZIGOBJS) $(DOBJS) $(EXTOBJS)
ifneq ($(BUILD_MODULE),y)
OBJS += $(MAINCOBJ) $(MAINCXXOBJ) $(MAINRUSTOBJ) $(MAINZIGOBJ)
OBJS += $(MAINCOBJ) $(MAINCXXOBJ) $(MAINRUSTOBJ) $(MAINZIGOBJ) $(MAINDOBJ)
endif
ifneq ($(strip $(PROGNAME)),)
PROGOBJ := $(MAINCOBJ) $(MAINCXXOBJ) $(MAINRUSTOBJ)
PROGOBJ := $(MAINCOBJ) $(MAINCXXOBJ) $(MAINRUSTOBJ) $(MAINZIGOBJ) $(MAINDOBJ)
PROGLIST := $(addprefix $(BINDIR)$(DELIM),$(PROGNAME))
REGLIST := $(addprefix $(BUILTIN_REGISTRY)$(DELIM),$(addsuffix .bdat,$(PROGNAME)))
@@ -134,14 +130,14 @@ ifeq ($(WASM_BUILD),y)
DO_REGISTRATION = n
endif
ifeq ($(DYNLIB),y)
DO_REGISTRATION = n
endif
# Compile flags, notice the default flags only suitable for flat build
ZIGELFFLAGS ?= $(ZIGFLAGS)
RUSTELFFLAGS ?= $(RUSTFLAGS)
DELFFLAGS ?= $(DFLAGS)
DEPPATH += --dep-path .
DEPPATH += --obj-path .
VPATH += :.
@@ -154,19 +150,19 @@ all:: .built
define ELFASSEMBLE
$(ECHO_BEGIN)"AS: $1 "
$(Q) $(CC) -c $(MODAELFFLAGS) $($(strip $1)_AELFFLAGS) $1 -o $2
$(Q) $(CC) -c $(AELFFLAGS) $($(strip $1)_AELFFLAGS) $1 -o $2
$(ECHO_END)
endef
define ELFCOMPILE
$(ECHO_BEGIN)"CC: $1 "
$(Q) $(CC) -c $(MODCFLAGS) $($(strip $1)_CELFFLAGS) $1 -o $2
$(Q) $(CC) -c $(CELFFLAGS) $($(strip $1)_CELFFLAGS) $1 -o $2
$(ECHO_END)
endef
define ELFCOMPILEXX
$(ECHO_BEGIN)"CXX: $1 "
$(Q) $(CXX) -c $(MODCXXFLAGS) $($(strip $1)_CXXELFFLAGS) $1 -o $2
$(Q) $(CXX) -c $(CXXELFFLAGS) $($(strip $1)_CXXELFFLAGS) $1 -o $2
$(ECHO_END)
endef
@@ -176,57 +172,59 @@ define ELFCOMPILERUST
$(ECHO_END)
endef
# Remove target suffix here since zig compiler add .o automatically
define ELFCOMPILEZIG
$(ECHO_BEGIN)"ZIG: $1 "
# Remove target suffix here since zig compiler add .o automatically
$(Q) $(ZIG) build-obj $(ZIGELFFLAGS) $($(strip $1)_ZIGELFFLAGS) --name $(basename $2) $1
$(ECHO_END)
endef
define ELFCOMPILED
$(ECHO_BEGIN)"DC: $1 "
$(Q) $(DC) -c $(DELFFLAGS) $($(strip $1)_DELFFLAGS) $1 -of $2
$(ECHO_END)
endef
define ELFLD
$(ECHO_BEGIN)"LD: $2 "
$(Q) $(LD) $(MODLDFLAGS) $(LDMAP) $(LDLIBPATH) $(ARCHCRT0OBJ) $1 $(LDSTARTGROUP) $(LDLIBS) $(LDENDGROUP) -o $2
$(Q) $(LD) $(LDELFFLAGS) $(LDLIBPATH) $(ARCHCRT0OBJ) $1 $(LDSTARTGROUP) $(LDLIBS) $(LDENDGROUP) -o $2
$(ECHO_END)
endef
define COMPILEAIDL
$(ECHO_BEGIN)"AIDL: $1 "
$(Q) $(AIDL) $(AIDLFLAGS) $($(strip $1)_AIDLFLAGS) $1
$(ECHO_END)
endef
define DELAIDLOUT
$(ECHO_BEGIN)"DELAIDLOUT: $1 "
$(Q) $(AIDL) $(AIDLFLAGS) $($(strip $1)_AIDLFLAGS) $1 --delete
# rename "main()" in $1 to "xxx_main()" and save to $2
define RENAMEMAIN
$(ECHO_BEGIN)"Rename main() in $1 and save to $2"
$(Q) ${shell cat $1 | sed -e "s/fn[ ]\+main/fn $(addsuffix _main,$(PROGNAME_$@))/" > $2}
$(ECHO_END)
endef
$(RAOBJS): %.s$(SUFFIX)$(OBJEXT): %.s
$(if $(and $(CONFIG_MODULES),$(MODAELFFLAGS)), \
$(if $(and $(CONFIG_BUILD_LOADABLE),$(AELFFLAGS)), \
$(call ELFASSEMBLE, $<, $@), $(call ASSEMBLE, $<, $@))
$(CAOBJS): %.S$(SUFFIX)$(OBJEXT): %.S
$(if $(and $(CONFIG_MODULES),$(MODAELFFLAGS)), \
$(if $(and $(CONFIG_BUILD_LOADABLE),$(AELFFLAGS)), \
$(call ELFASSEMBLE, $<, $@), $(call ASSEMBLE, $<, $@))
$(COBJS): %.c$(SUFFIX)$(OBJEXT): %.c
$(if $(and $(CONFIG_MODULES),$(MODCFLAGS)), \
$(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \
$(call ELFCOMPILE, $<, $@), $(call COMPILE, $<, $@))
$(CXXOBJS): %$(CXXEXT)$(SUFFIX)$(OBJEXT): %$(CXXEXT)
$(if $(and $(CONFIG_MODULES),$(MODCXXFLAGS)), \
$(if $(and $(CONFIG_BUILD_LOADABLE),$(CXXELFFLAGS)), \
$(call ELFCOMPILEXX, $<, $@), $(call COMPILEXX, $<, $@))
$(RUSTOBJS): %$(RUSTEXT)$(SUFFIX)$(OBJEXT): %$(RUSTEXT)
$(if $(and $(CONFIG_MODULES),$(CELFFLAGS)), \
$(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \
$(call ELFCOMPILERUST, $<, $@), $(call COMPILERUST, $<, $@))
$(ZIGOBJS): %$(ZIGEXT)$(SUFFIX)$(OBJEXT): %$(ZIGEXT)
$(if $(and $(CONFIG_MODULES), $(CELFFLAGS)), \
$(if $(and $(CONFIG_BUILD_LOADABLE), $(CELFFLAGS)), \
$(call ELFCOMPILEZIG, $<, $@), $(call COMPILEZIG, $<, $@))
$(AIDLOBJS): %$(CXXEXT): %$(AIDLEXT)
$(call COMPILEAIDL, $<)
$(DOBJS): %$(DEXT)$(SUFFIX)$(OBJEXT): %$(DEXT)
$(if $(and $(CONFIG_BUILD_LOADABLE), $(CELFFLAGS)), \
$(call ELFCOMPILED, $<, $@), $(call COMPILED, $<, $@))
AROBJS :=
ifneq ($(OBJS),)
@@ -251,20 +249,24 @@ endif
ifeq ($(BUILD_MODULE),y)
$(MAINCXXOBJ): %$(CXXEXT)$(SUFFIX)$(OBJEXT): %$(CXXEXT)
$(if $(and $(CONFIG_MODULES),$(MODCXXFLAGS)), \
$(if $(and $(CONFIG_BUILD_LOADABLE),$(CXXELFFLAGS)), \
$(call ELFCOMPILEXX, $<, $@), $(call COMPILEXX, $<, $@))
$(MAINCOBJ): %.c$(SUFFIX)$(OBJEXT): %.c
$(if $(and $(CONFIG_MODULES),$(MODCFLAGS)), \
$(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \
$(call ELFCOMPILE, $<, $@), $(call COMPILE, $<, $@))
$(PROGLIST): $(MAINCOBJ) $(MAINCXXOBJ) $(MAINRUSTOBJ)
$(MAINZIGOBJ): %$(ZIGEXT)$(SUFFIX)$(OBJEXT): %$(ZIGEXT)
$(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \
$(call ELFCOMPILEZIG, $<, $@), $(call COMPILEZIG, $<, $@))
$(MAINDOBJ): %$(DEXT)$(SUFFIX)$(OBJEXT): %$(DEXT)
$(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \
$(call ELFCOMPILED, $<, $@), $(call COMPILED, $<, $@))
$(PROGLIST): $(MAINCOBJ) $(MAINCXXOBJ) $(MAINRUSTOBJ) $(MAINZIGOBJ) $(MAINDOBJ)
$(Q) mkdir -p $(BINDIR)
ifneq ($(CONFIG_DEBUG_LINK_MAP),)
$(eval PROGNAME_$@ := $(basename $(notdir $@)))
$(eval LDMAP := --cref -Map $(PROGNAME_$@).map)
endif
$(call ELFLD,$(PROGOBJ_$@),$(call CONVERT_PATH,$@))
$(call ELFLD, $(PROGOBJ_$@), $(call CONVERT_PATH,$@))
$(Q) chmod +x $@
ifneq ($(CONFIG_DEBUG_SYMBOLS),y)
$(Q) $(STRIP) $@
@@ -278,32 +280,35 @@ else
$(MAINCXXOBJ): %$(CXXEXT)$(SUFFIX)$(OBJEXT): %$(CXXEXT)
$(eval $<_CXXFLAGS += ${shell $(DEFINE) "$(CXX)" main=$(addsuffix _main,$(PROGNAME_$@))})
$(eval $<_CXXELFFLAGS += ${shell $(DEFINE) "$(CXX)" main=$(addsuffix _main,$(PROGNAME_$@))})
$(if $(and $(CONFIG_MODULES),$(MODCXXFLAGS)), \
$(if $(and $(CONFIG_BUILD_LOADABLE),$(CXXELFFLAGS)), \
$(call ELFCOMPILEXX, $<, $@), $(call COMPILEXX, $<, $@))
$(MAINCOBJ): %.c$(SUFFIX)$(OBJEXT): %.c
$(eval $<_CFLAGS += ${DEFINE_PREFIX}main=$(addsuffix _main,$(PROGNAME_$@)))
$(eval $<_CELFFLAGS += ${DEFINE_PREFIX}main=$(addsuffix _main,$(PROGNAME_$@)))
$(if $(and $(CONFIG_MODULES),$(MODCFLAGS)), \
$(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \
$(call ELFCOMPILE, $<, $@), $(call COMPILE, $<, $@))
$(MAINRUSTOBJ): %$(RUSTEXT)$(SUFFIX)$(OBJEXT): %$(RUSTEXT)
$(if $(and $(CONFIG_MODULES),$(CELFFLAGS)), \
$(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \
$(call ELFCOMPILERUST, $<, $@), $(call COMPILERUST, $<, $@))
$(MAINZIGOBJ): %$(ZIGEXT)$(SUFFIX)$(OBJEXT): %$(ZIGEXT)
$(if $(and $(CONFIG_MODULES),$(CELFFLAGS)), \
$(call ELFCOMPILEZIG, $<, $@), $(call COMPILEZIG, $<, $@))
$(Q) $(call RENAMEMAIN, $<, $(basename $<)_tmp.zig)
$(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \
$(call ELFCOMPILEZIG, $(basename $<)_tmp.zig, $@), $(call COMPILEZIG, $(basename $<)_tmp.zig, $@))
$(Q) rm -f $(basename $<)_tmp.zig
$(MAINDOBJ): %$(DEXT)$(SUFFIX)$(OBJEXT): %$(DEXT)
$(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \
$(call ELFCOMPILED, $<, $@), $(call COMPILED, $<, $@))
install::
@:
endif # BUILD_MODULE
postinstall::
@:
context:: $(AIDLOBJS)
context::
@:
ifeq ($(DO_REGISTRATION),y)
@@ -326,7 +331,7 @@ endif
.depend: Makefile $(wildcard $(foreach SRC, $(SRCS), $(addsuffix /$(SRC), $(subst :, ,$(VPATH))))) $(DEPCONFIG)
$(call SPLITVARIABLE,ALL_DEP_OBJS,$^,100)
$(foreach BATCH, $(ALL_DEP_OBJS_TOTAL), \
$(shell $(MKDEP) $(DEPPATH) --obj-suffix .c$(SUFFIX)$(OBJEXT) "$(CC)" -- $(CFLAGS) -- $(filter %.c,$(ALL_DEP_OBJS_$(BATCH))) >>Make.dep) \
$(shell $(MKDEP) $(DEPPATH) --obj-suffix .c$(SUFFIX)$(OBJEXT) "$(CC)" -- $(CFLAGS) -- $(filter %.c,$(ALL_DEP_OBJS_$(BATCH))) >Make.dep) \
$(shell $(MKDEP) $(DEPPATH) --obj-suffix .S$(SUFFIX)$(OBJEXT) "$(CC)" -- $(CFLAGS) -- $(filter %.S,$(ALL_DEP_OBJS_$(BATCH))) >>Make.dep) \
$(shell $(MKDEP) $(DEPPATH) --obj-suffix $(CXXEXT)$(SUFFIX)$(OBJEXT) "$(CXX)" -- $(CXXFLAGS) -- $(filter %$(CXXEXT),$(ALL_DEP_OBJS_$(BATCH))) >>Make.dep) \
)
@@ -342,7 +347,6 @@ clean::
distclean:: clean
$(call DELFILE, Make.dep)
$(call DELFILE, .depend)
$(foreach AIDLSRC,$(AIDLSRCS),$(call DELAIDLOUT,$(AIDLSRC)))
-include Make.dep

View File

@@ -27,7 +27,6 @@
# ~~~
if(CONFIG_APPS_DIR)
include(nuttx_add_aidl)
nuttx_add_library(apps)
if(NOT EXISTS {NUTTX_APPS_BINDIR}/dummy.c)
file(TOUCH ${NUTTX_APPS_BINDIR}/dummy.c)
@@ -60,22 +59,15 @@ add_subdirectory(platform)
add_subdirectory(sdr)
add_subdirectory(system)
add_subdirectory(testing)
add_subdirectory(tools)
add_subdirectory(wireless)
# add examples and external at the end to allow library dependencies
add_subdirectory(examples)
if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/external/CMakeLists.txt)
if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/external)
add_subdirectory(external)
endif()
if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/frameworks/CMakeLists.txt)
add_subdirectory(frameworks)
endif()
if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/vendor/CMakeLists.txt)
add_subdirectory(vendor)
endif()
add_subdirectory(builtin) # must be last
nuttx_generate_kconfig()

375
LICENSE
View File

@@ -1873,3 +1873,378 @@ apps/crypto/libsodium
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
apps/crypto/wolfssl
===================
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
apps/testing/sd_stress
apps/testing/sd_bench
===================
Copyright (c) 2016-2021 PX4 Development Team. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. Neither the name PX4 nor the names of its contributors may be
used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

View File

@@ -54,11 +54,7 @@ $(foreach BDIR, $(BUILDIRS), $(eval $(call Add_Application,$(BDIR))))
CXXEXT ?= .cxx
RUSTEXT ?= .rs
ZIGEXT ?= .zig
AIDLEXT ?= .aidl
# Tools
AIDL ?= aidl
DEXT ?= .d
# Library path
@@ -166,7 +162,7 @@ endef
define AROBJSRULES
$(1) : $(2)
@ cp $(2) $(1)
cp $(2) $(1)
endef
# CLEANAROBJS - del AR target files exclusively
@@ -174,9 +170,17 @@ endef
ifeq ($(CONFIG_WINDOWS_NATIVE),y)
define CLEANAROBJS
$(call DELFILE,$(subst /,\,$(AROBJS)))
$(call DELFILE,$(subst /,\,$(OBJS)))
$(eval OBJS :=)
endef
else
define CLEANAROBJS
$(foreach AROBJ, $(AROBJS), $(shell rm -f $(AROBJ)))
$(call SPLITVARIABLE,CLEAN_AROBJS,${AROBJS},100)
$(foreach BATCH, $(CLEAN_AROBJS_TOTAL), \
$(shell rm -rf $(CLEAN_AROBJS_$(BATCH))))
$(call SPLITVARIABLE,CLEAN_OBJS,${OBJS},100)
$(foreach BATCH, $(CLEAN_OBJS_TOTAL), \
$(shell rm -rf $(CLEAN_OBJS_$(BATCH))))
$(eval OBJS :=)
endef
endif

View File

@@ -45,12 +45,11 @@ SYMTABOBJ = $(SYMTABSRC:.c=$(OBJEXT))
all: $(BIN)
.PHONY: import install dirlinks export .depdirs preconfig depend clean distclean
.PHONY: context postinstall clean_context context_all postinstall_all register register_all
.PHONY: context clean_context context_all register register_all
.PRECIOUS: $(BIN)
$(foreach SDIR, $(CONFIGURED_APPS), $(eval $(call SDIR_template,$(SDIR),all)))
$(foreach SDIR, $(CONFIGURED_APPS), $(eval $(call SDIR_template,$(SDIR),install)))
$(foreach SDIR, $(CONFIGURED_APPS), $(eval $(call SDIR_template,$(SDIR),postinstall)))
$(foreach SDIR, $(CONFIGURED_APPS), $(eval $(call SDIR_template,$(SDIR),context)))
$(foreach SDIR, $(CONFIGURED_APPS), $(eval $(call SDIR_template,$(SDIR),register)))
$(foreach SDIR, $(CONFIGURED_APPS), $(eval $(call SDIR_template,$(SDIR),depend)))
@@ -65,6 +64,25 @@ $(INCDIR): $(TOPDIR)/tools/incdir.c
IMPORT_TOOLS = $(MKDEP) $(INCDIR)
ifeq ($(CONFIG_TOOLS_WASM_BUILD),y)
configure_wasm:
$(Q) cmake -B$(APPDIR)$(DELIM)tools$(DELIM)Wasm$(DELIM)build \
$(APPDIR)$(DELIM)tools$(DELIM)Wasm \
-DAPPDIR=$(APPDIR) -DTOPDIR=$(TOPDIR) \
-DWASI_SDK_PATH=$(WASI_SDK_PATH) \
-DKCONFIG_FILE_PATH=$(TOPDIR)$(DELIM).config
context_wasm: configure_wasm
$(Q) cmake --build $(APPDIR)$(DELIM)tools$(DELIM)Wasm$(DELIM)build
else
context_wasm:
endif
# In the KERNEL build, we must build and install all of the modules. No
# symbol table is needed
@@ -77,7 +95,6 @@ $(BIN): $(foreach SDIR, $(CONFIGURED_APPS), $(SDIR)_all)
.import: $(BIN)
$(Q) install libapps.a $(APPDIR)$(DELIM)import$(DELIM)libs
$(Q) $(MAKE) install
$(Q) $(MAKE) postinstall
import: $(IMPORT_TOOLS)
$(Q) $(MAKE) context TOPDIR="$(APPDIR)$(DELIM)import"
@@ -90,7 +107,7 @@ else
# In FLAT and protected modes, the modules have already been created. A
# symbol table is required.
ifeq ($(CONFIG_MODULES),)
ifeq ($(CONFIG_BUILD_LOADABLE),)
ifeq ($(CONFIG_WINDOWS_NATIVE),y)
$(BIN): $(foreach SDIR, $(CONFIGURED_APPS), $(SDIR)_all)
else
@@ -112,10 +129,9 @@ $(BIN): $(SYMTABOBJ)
$(call ARLOCK, $(call CONVERT_PATH,$(BIN)), $^)
$(call LINK_WASM)
endif # !CONFIG_MODULES
endif # !CONFIG_BUILD_LOADABLE
install: $(foreach SDIR, $(CONFIGURED_APPS), $(SDIR)_install)
$(Q) $(MAKE) postinstall_all
# Link nuttx
@@ -151,7 +167,6 @@ dirlinks:
context_all: $(foreach SDIR, $(CONFIGURED_APPS), $(SDIR)_context)
register_all: $(foreach SDIR, $(CONFIGURED_APPS), $(SDIR)_register)
postinstall_all: $(foreach SDIR, $(CONFIGURED_APPS), $(SDIR)_postinstall)
staging:
$(Q) mkdir -p $@
@@ -159,6 +174,7 @@ staging:
context: | staging
$(Q) $(MAKE) context_all
$(Q) $(MAKE) register_all
$(Q) $(MAKE) context_wasm
Kconfig:
$(foreach SDIR, $(CONFIGDIRS), $(call MAKE_template,$(SDIR),preconfig))
@@ -209,4 +225,5 @@ distclean: $(foreach SDIR, $(CLEANDIRS), $(SDIR)_distclean)
$(call DELDIR, $(BINDIR))
$(call DELDIR, staging)
$(call DELDIR, wasm)
$(call DELDIR, $(APPDIR)$(DELIM)tools$(DELIM)Wasm$(DELIM)build)
$(call CLEAN)

View File

@@ -1,3 +1,23 @@
############################################################################
# apps/audioutils/fmsynth/test/Makefile
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership. The
# ASF licenses this file to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
############################################################################
SRCS = ../fmsynth_eg.c ../fmsynth_op.c ../fmsynth.c
CFLAGS = -DFAR= -DCODE= -DOK=0 -DERROR=-1 -I .. -I ../../../include -g

View File

@@ -1,211 +0,0 @@
# Music Macro Language (MML) Parser library
MML has often been used as a language for describing music in strings, for example,
in the BASIC language. The mml_parser is a minimalistic Music Macro Language parser
library written in pure C intended for resource-constrained platforms, especially
microcontrollers and other embedded systems.
## Supported Syntax on this library
### Notes
* **C** (Do)
* **D** (Re)
* **E** (Mi)
* **F** (Fa)
* **G** (Sol)
* **A** (La)
* **B** (Ti)
### Sharp and Flat
Add "#" or "+" after the note indicates Sharp. ex: ``"C#"`` ``"C+."``
Add "-" after the note indicates Flat. ex: ``"C-"``
### Length
Length of the tone can be specified in two ways.
One is to specify a length for each note. Add a number after the note in 1, 2, 4, 8, 16, 32 or 64.
ex: ``"C8 C16 C#4."``
The other is to use ``L`` . The ``L`` sets default length. If the note without length, the number which is
indicated by the "L" is used. The number followed after the "L" can be in 1, 2, 4, 8, 16, 32 or 64.
ex: ``"L4 A"`` means "A" with length 4.
In addition, dot is supported. For example, length of "C4." is 4 + 8. Length of "C16.." is 4 + 8 + 16.
### Rest
Rest is represented by "R".
Length of the rest is following after the "R" as the same as the note length. If no length is
specified, the length specified by the ”L" is used.
### Chord
Chord is supported. If some notes are enclosed in parentheses by ``[`` and ``]``, they are interpreted as
a chord. ex: ``"[CEG]"`` is a chord of Do, Mi and Sol.
Chord's length can be put after ``]`` . ex: ``"[CEG]4"`` is a chord with 4 length.
Note: Max notes in a chord is defined as MAX_CHORD_NOTES in ``mml_parser.h``.
### Tuplet
Tuplet is supported. If some notes and Chord are enclosed in parentheses by ``{`` and ``}``, they are
interpreted as a tuplet. ex: ``"{C E G [CEG]}"`` is a tuplet with C, E, G and chord of CEG.
Tuplet's length can be put after "}", and the length is divided equally among each note.
ex: in ``"{C E G [CEG]}4"`` case, C, E, G and chord CEG has each a quarter of the L4 length.
### Octave
Octarve is controlled by "O", ">" or "<".
When "O" is used, the O is followed by a number indicating the octave.
When ">" is used, the value of the new octave is the current octave plus one.
When "<" is used, the value of the new octave is the current octave minus one.
ex: ``"CDEFGAB > C R C < BAGFEDC"``, ``"O4 CDEFGAB O5 C R C O4 BAGFEDC"``
### Tempo
Tempo is indicated as "T" and numter following after the "T".
Tempo number decide a speed of the score. This value is used for culculating sample number for
the note (or rest).
ex: ``"T120"``
### Volume
Volume can be controlled by "V". And numter following after the "V".
ex: ``"V4"``
## Example of a score
### The beginning of the Do Re Mi Song.
Tempo 120, Voulume 10, Octave 4, Default length is 4.
``"T120 V10 O4 L4 C. D8 E. C8 E C E2 D. E8 {FF} {ED} F2"``
## Provided C Functions
mml_parser is providing just 2 functions.
### init_mml()
Initialize an instance of mml parser.
#### Synopsis
```c
#include <audioutils/mml_parser.h>
int init_mml(FAR struct music_macro_lang_s *mml,
int fs, int tempo, int octave, int length);
```
#### Description
The function initializes `struct music_macro_lang_s` instance provided as 1st argument.
The argument `fs` is a sampling frequency of target audio output system, and this value is used for
calculating sample number in case of a tempo and length of note.
`tempo`, `octave` and `length` specify initial values for tempo, octave, and length, respectively.
#### Return value
On success, init_mml() returns 0. On error, it returns an negative value.
#### Errors
Currently no error is happened.
### parse_mml()
Parse MML from given string.
#### Synopsis
```c
#include <audioutils/mml_parser.h>
int parse_mml(FAR struct music_macro_lang_s *mml,
FAR char **score, FAR struct mml_result_s *result);
```
#### Description
parse_mml() parses the first MML of the string given by the argument ``score`` and gives
the result in the return value and the argument ``result``.
The ``result`` is an instance of mml_result_s, which contains note_idx, length, and
chord_notes as members. The meaning of the value of each member depends on the return value.
#### Return value
On error, a nevative value is returned.
On success, following values can be returned. And those values are defined in ``mml_parser.h``.
| Return values | Description |
| -------------------- | ----------- |
| MML_TYPE_EOF | This means that it have reached the end of the string. The content of the ``result`` has no meaning. |
| MML_TYPE_NOTE | This indicates that some note has been parsed. The scale of the note is stored in ``note_idx[0]``. The length of the note is given by the ``length`` member as the number of samples. In the case of tuplet, this return value is returned at the time each note is parsed. In other words, a tuplet is parsed as a single note. |
| MML_TYPE_REST | This indicates the ``rest`` has been parsed. The length of it is given by the ``length`` member as the number of samples. |
| MML_TYPE_TEMPO | This indicates ``"T"`` is parsed. ``length`` member in ``result`` has the value of the tempo. But tempo value is kept in mml instance for calculating sample number for each notes. So basically, no need to handle this return value in your code. |
| MML_TYPE_LENGTH | This indicates ``"L"`` is parsed. ``length`` member in ``result`` has the value of the parsed length. But current length value is kept in mml instance. So basically, no need to handle this return value in your code. |
| MML_TYPE_OCTAVE | This indicates ``"O"``, ``">"``, or ``"<"`` is parsed. ``length`` member in ``result`` has the value of the octave. But the octave is encoded in ``note_idx`` in ``MML_TYPE_NOTE`` case. So basically, no need to handle this return value in your code. |
| MML_TYPE_TUPLETSTART | This indicates tuplet is just started. And total length of the tuplet is stored in ``length`` of ``result`` members. |
| MML_TYPE_TUPLETDONE | This indicates the tuplet is just finished. |
| MML_TYPE_VOLUME | This indicates ``"V"`` is parsed. ``length`` member in ``result`` has the value of the parsed volume. |
| MML_TYPE_TONE | T.B.D. |
| MML_TYPE_CHORD | This indicates a chord is parsed. Chord has some notes, and how many notes is stored in ``chord_notes`` member of ``result``. And each notes are stored in ``note_idx[]``. Length of the chord is stored in ``length`` member of ``result``. |
The value of ``note_idx[]`` is encoding octave, like
| Octave | Note | node_idx value |
| ------ | ---- |:--------------:|
| O0 | C | 0 |
| O0 | C# | 1 |
| O0 | D | 2 |
| O0 | D# | 3 |
| O0 | E | 4 |
| O0 | F | 5 |
| O0 | F# | 6 |
| O0 | G | 7 |
| O0 | G# | 8 |
| O0 | A | 9 |
| O0 | A# | 10 |
| O0 | B | 11 |
| O1 | C | 12 |
And so on.
So for example, G# at Octave 4 is encoded as 56.
#### Errors
Following error code can be received as return value.
| Error code | Description |
| ------------------------------ | -------------- |
| MML_TYPE_NOTE_ERROR | |
| MML_TYPE_REST_ERROR | |
| MML_TYPE_TEMPO_ERROR | |
| MML_TYPE_LENGTH_ERROR | |
| MML_TYPE_OCTAVE_ERROR | |
| MML_TYPE_VOLUME_ERROR | |
| MML_TYPE_TUPLET_ERROR | |
| MML_TYPE_TONE_ERROR | |
| MML_TYPE_CHORD_ERROR | |
| MML_TYPE_ILLIGAL_COMPOSITION | |
| MML_TYPE_ILLIGAL_TOOMANY_NOTES | |
| MML_TYPE_ILLIGAL_TOOFEW_NOTES | |
| MML_TYPE_ILLIGAL_DOUBLE_TUPLET | |
## Running unit tests
Please see examples/mml_parser
## Bugs
There are plenty. Report them on GitHub, or - even better - open a pull request.
Please write unit tests for any new functions you add - it's fun!
## Author
mml_parser was written by Takayoshi Koizumi &lt;takayoshi.koizumi@gmail.com&gt;

View File

@@ -68,7 +68,7 @@ static int configure_audio(int fd, int ch, int fs, int bps, int chmap)
* name: create_audiomq
****************************************************************************/
static mqd_t create_audiomq(int fd, int buf_num)
static mqd_t create_audiomq(const char *mqname, int fd, int buf_num)
{
mqd_t ret;
struct mq_attr attr;
@@ -78,8 +78,7 @@ static mqd_t create_audiomq(int fd, int buf_num)
attr.mq_curmsgs = 0;
attr.mq_flags = 0;
ret = mq_open(CONFIG_AUDIOUTILS_NXAUDIO_MSGQNAME,
O_RDWR | O_CREAT, 0644, &attr);
ret = mq_open(mqname, O_RDWR | O_CREAT, 0644, &attr);
if (ret >= (mqd_t)0)
{
int rr;
@@ -147,14 +146,13 @@ static void free_audio_buffers(FAR struct nxaudio_s *nxaudio)
void fin_nxaudio(FAR struct nxaudio_s *nxaudio)
{
free_audio_buffers(nxaudio);
ioctl(nxaudio->fd, AUDIOIOC_STOP, 0);
ioctl(nxaudio->fd, AUDIOIOC_SHUTDOWN, 0);
ioctl(nxaudio->fd, AUDIOIOC_UNREGISTERMQ, (unsigned long)nxaudio->mq);
ioctl(nxaudio->fd, AUDIOIOC_RELEASE, 0);
ioctl(nxaudio->fd, AUDIOIOC_SHUTDOWN, 0);
free_audio_buffers(nxaudio);
close(nxaudio->fd);
mq_close(nxaudio->mq);
mq_unlink(CONFIG_AUDIOUTILS_NXAUDIO_MSGQNAME);
close(nxaudio->fd);
}
/****************************************************************************
@@ -163,10 +161,23 @@ void fin_nxaudio(FAR struct nxaudio_s *nxaudio)
int init_nxaudio(FAR struct nxaudio_s *nxaudio,
int fs, int bps, int chnum)
{
return init_nxaudio_devname(nxaudio, fs, bps, chnum,
CONFIG_AUDIOUTILS_NXAUDIO_DEVPATH,
CONFIG_AUDIOUTILS_NXAUDIO_MSGQNAME);
}
/****************************************************************************
* name: init_nxaudio_devname
****************************************************************************/
int init_nxaudio_devname(FAR struct nxaudio_s *nxaudio,
int fs, int bps, int chnum,
const char *devname, const char *mqname)
{
struct ap_buffer_info_s buf_info;
nxaudio->fd = open(CONFIG_AUDIOUTILS_NXAUDIO_DEVPATH, O_RDWR | O_CLOEXEC);
nxaudio->fd = open(devname, O_RDWR | O_CLOEXEC);
if (nxaudio->fd >= 0)
{
if (ioctl(nxaudio->fd, AUDIOIOC_RESERVE, 0) < 0)
@@ -186,7 +197,8 @@ int init_nxaudio(FAR struct nxaudio_s *nxaudio,
/* Create message queue to communicate with audio driver */
nxaudio->mq = create_audiomq(nxaudio->fd, buf_info.nbuffers + 8);
nxaudio->mq = create_audiomq(mqname, nxaudio->fd,
buf_info.nbuffers + 8);
/* Create audio buffers to inject audio sample */
@@ -218,6 +230,24 @@ int nxaudio_enqbuffer(FAR struct nxaudio_s *nxaudio,
(unsigned long)(uintptr_t)&desc);
}
/****************************************************************************
* name: nxaudio_pause
****************************************************************************/
int nxaudio_pause(FAR struct nxaudio_s *nxaudio)
{
return ioctl(nxaudio->fd, AUDIOIOC_PAUSE, 0);
}
/****************************************************************************
* name: nxaudio_resume
****************************************************************************/
int nxaudio_resume(FAR struct nxaudio_s *nxaudio)
{
return ioctl(nxaudio->fd, AUDIOIOC_RESUME, 0);
}
/****************************************************************************
* name: nxaudio_setvolume
****************************************************************************/
@@ -252,6 +282,8 @@ int nxaudio_stop(FAR struct nxaudio_s *nxaudio)
{
struct audio_msg_s term_msg;
ioctl(nxaudio->fd, AUDIOIOC_STOP, 0);
term_msg.msg_id = AUDIO_MSG_STOP;
term_msg.u.data = 0;
mq_send(nxaudio->mq, (FAR const char *)&term_msg, sizeof(term_msg), 0);

View File

@@ -1,5 +1,5 @@
# ##############################################################################
# apps/testing/events/CMakeLists.txt
# apps/benchmarks/cachespeed/CMakeLists.txt
#
# Licensed to the Apache Software Foundation (ASF) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
@@ -18,16 +18,14 @@
#
# ##############################################################################
if(CONFIG_TESTING_PERF)
if(CONFIG_BENCHMARK_CACHESPEED)
nuttx_add_application(
NAME
perf_test
PRIORITY
${CONFIG_TESTING_PERF_PRIORITY}
STACKSIZE
${CONFIG_TESTING_PERF_STACKSIZE}
MODULE
${CONFIG_TESTING_PERF}
${CONFIG_BENCHMARK_CACHESPEED_PROGNAME}
SRCS
perf_test.c)
cachespeed_main.c
STACKSIZE
${CONFIG_BENCHMARK_CACHESPEED_STACKSIZE}
PRIORITY
${CONFIG_BENCHMARK_CACHESPEED_PRIORITY})
endif()

View File

@@ -141,7 +141,7 @@ static void report_line(size_t bytes, TIME cost)
if (cost == 0)
{
printf(CACHESPEED_PREFIX "%zu bytes cost time too small!\n", bytes);
printf(CACHESPEED_PREFIX "%d bytes cost time too small!\n", bytes);
return;
}
@@ -149,7 +149,7 @@ static void report_line(size_t bytes, TIME cost)
rate = 1.00 * bytes * REPEAT_NUM / cost;
printf("%zu Bytes: %4lf, %4" PRIu64", %4" PRIu64"\n\r",
printf("%d Bytes: %4lf, %4llu, %4llu\n\r",
bytes, rate, cost / REPEAT_NUM, cost);
}

View File

@@ -1 +0,0 @@
/coremark-pro

View File

@@ -1,314 +0,0 @@
# ##############################################################################
# apps/benchmarks/coremark-pro/CMakeLists.txt
#
# Licensed to the Apache Software Foundation (ASF) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. The ASF licenses this
# file to you under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#
# ##############################################################################
if(CONFIG_BENCHMARK_COREMARK_PRO)
nuttx_add_library(coremark_pro STATIC)
set(CSRCS
coremark-pro/mith/src/md5.c
coremark-pro/mith/src/mith_lib.c
coremark-pro/mith/src/mith_workload.c
coremark-pro/mith/src/th_bignum.c
coremark-pro/mith/src/th_encode.c
coremark-pro/mith/src/th_lib.c
coremark-pro/mith/src/th_math.c
coremark-pro/mith/src/th_rand.c)
file(GLOB MITH_AL_SRCS coremark-pro/mith/al/src/*.c)
list(APPEND CSRCS ${MITH_AL_SRCS})
set(CFLAGS
-Wno-undef
-Wno-strict-prototypes
-Wno-unused-variable
-Wno-pointer-sign
-Wno-unused-but-set-variable
-Wno-shadow
-DNDEBUG
-DHOST_EXAMPLE_CODE=1
-DHAVE_SYS_STAT_H=1
-DGCC_INLINE_MACRO=1
-DMAX_CONTEXTS=100
-DEE_SIZEOF_INT=4
-DUSE_FP128=0)
set(INCDIR ${CMAKE_CURRENT_LIST_DIR}/coremark-pro/mith/include
${CMAKE_CURRENT_LIST_DIR}/coremark-pro/mith/al/include)
if(CONFIG_BENCHMARK_COREMARK_PRO_USE_SINGLE_CONTEXT)
list(APPEND CFLAGS -DUSE_SINGLE_CONTEXT=1 -DHAVE_PTHREAD=0
-DUSE_NATIVE_PTHREAD=0)
else()
list(APPEND CFLAGS -DUSE_SINGLE_CONTEXT=0 -DHAVE_PTHREAD=1
-DUSE_NATIVE_PTHREAD=1)
endif()
if(CONFIG_BENCHMARK_COREMARK_PRO_SMP)
list(APPEND CFLAGS -DHAVE_PTHREAD_SETAFFINITY_NP=1 -DHAVE_PTHREAD_SELF=1)
endif()
if(CONFIG_BENCHMARK_COREMARK_PRO_64BIT)
list(APPEND CFLAGS -DEE_SIZEOF_PTR=8 -DEE_PTR_ALIGN=8 -DEE_SIZEOF_LONG=8)
endif()
if(CONFIG_BENCHMARK_COREMARK_PRO_USE_FP64)
list(APPEND CFLAGS -DUSE_FP64=1 -DUSE_FP32=0)
list(APPEND CSRCS coremark-pro/benchmarks/fp/linpack/ref/inputs_f64.c)
else()
list(APPEND CFLAGS -DUSE_FP32=1 -DUSE_FP64=0)
list(APPEND CSRCS coremark-pro/benchmarks/fp/linpack/ref/inputs_f32.c)
endif()
if(CONFIG_BENCHMARK_COREMARK_PRO_CORE_TEST)
file(GLOB CORE_TEST_SRCS coremark-pro/benchmarks/core/*.c)
set(CORE_TEST_CSRCS coremark-pro/workloads/core/core.c ${CORE_TEST_SRCS})
nuttx_add_application(
NAME
core
PRIORITY
${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE}
MODULE
${CONFIG_BENCHMARK_COREMARK_PRO}
COMPILE_FLAGS
${CFLAGS}
SRCS
${CORE_TEST_CSRCS}
INCLUDE_DIRECTORIES
${INCDIR}
DEPENDS
coremark_pro)
endif()
if(CONFIG_BENCHMARK_COREMARK_PRO_CJPEG_TEST)
file(GLOB CJPEG_SRCS coremark-pro/benchmarks/consumer_v2/cjpeg/*.c)
set(CJPEG_CSRCS
coremark-pro/workloads/cjpeg-rose7-preset/cjpeg-rose7-preset.c
coremark-pro/benchmarks/consumer_v2/cjpeg/data/Rose256_bmp.c
${CJPEG_SRCS})
nuttx_add_application(
NAME
cjpeg_rose7_preset
PRIORITY
${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE}
MODULE
${CONFIG_BENCHMARK_COREMARK_PRO}
COMPILE_FLAGS
${CFLAGS}
SRCS
${CJPEG_CSRCS}
INCLUDE_DIRECTORIES
${INCDIR}
DEPENDS
coremark_pro)
endif()
if(CONFIG_BENCHMARK_COREMARK_PRO_SHA_TEST)
file(GLOB SHA_TEST_SRCS coremark-pro/benchmarks/darkmark/sha/*.c)
set(SHA_TEST_CSRCS coremark-pro/workloads/sha-test/sha-test.c
${SHA_TEST_SRCS})
nuttx_add_application(
NAME
sha_test
PRIORITY
${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE}
MODULE
${CONFIG_BENCHMARK_COREMARK_PRO}
COMPILE_FLAGS
${CFLAGS}
SRCS
${SHA_TEST_CSRCS}
INCLUDE_DIRECTORIES
${INCDIR}
DEPENDS
coremark_pro)
endif()
if(CONFIG_BENCHMARK_COREMARK_PRO_ZIP_TEST)
set(ZIP_TEST_CSRCS coremark-pro/workloads/zip-test/zip-test.c
coremark-pro/benchmarks/darkmark/zip/zip_darkmark.c)
set(ZIP_TEST_FLAGS ${CFLAGS} -Dgzclose_r=coremark_zip_gzclose_r
-Dgzclose_w=coremark_zip_gzclose_w)
set(ZIP_TEST_INCDIR ${INCDIR} ${NUTTX_APPS_DIR}/system/zlib/zlib)
nuttx_add_application(
NAME
zip_test
PRIORITY
${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE}
MODULE
${CONFIG_BENCHMARK_COREMARK_PRO}
COMPILE_FLAGS
${ZIP_TEST_FLAGS}
SRCS
${ZIP_TEST_CSRCS}
INCLUDE_DIRECTORIES
${ZIP_TEST_INCDIR}
DEPENDS
coremark_pro)
endif()
if(CONFIG_BENCHMARK_COREMARK_PRO_LINEAR_ALG_MID_TEST)
set(ALG_MID_CSRCS
coremark-pro/workloads/linear_alg-mid-100x100-sp/linear_alg-mid-100x100-sp.c
coremark-pro/benchmarks/fp/linpack/linpack.c)
nuttx_add_application(
NAME
linear_alg_mid_100x100_sp
PRIORITY
${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE}
MODULE
${CONFIG_BENCHMARK_COREMARK_PRO}
COMPILE_FLAGS
${CFLAGS}
SRCS
${ALG_MID_CSRCS}
INCLUDE_DIRECTORIES
${INCDIR}
DEPENDS
coremark_pro)
endif()
if(CONFIG_BENCHMARK_COREMARK_PRO_RADIX_TEST)
if(CONFIG_BENCHMARK_COREMARK_PRO_USE_FP64)
file(GLOB RADIX_SRCS coremark-pro/benchmarks/fp/fft_radix2/ref/*.c)
else()
file(GLOB RADIX_SRCS coremark-pro/benchmarks/fp/fft_radix2/ref-sp/*.c)
endif()
set(RADIX_CSRCS
coremark-pro/workloads/radix2-big-64k/radix2-big-64k.c
coremark-pro/benchmarks/fp/fft_radix2/fft_radix2.c ${RADIX_SRCS})
nuttx_add_application(
NAME
radix2_big_64k
PRIORITY
${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE}
MODULE
${CONFIG_BENCHMARK_COREMARK_PRO}
COMPILE_FLAGS
${CFLAGS}
SRCS
${RADIX_CSRCS}
INCLUDE_DIRECTORIES
${INCDIR}
DEPENDS
coremark_pro)
endif()
if(CONFIG_BENCHMARK_COREMARK_PRO_LOOPS_ALL_MID_TEST)
if(CONFIG_BENCHMARK_COREMARK_PRO_USE_FP64)
file(GLOB MID_SRCS coremark-pro/benchmarks/fp/loops/ref/*.c)
else()
file(GLOB MID_SRCS coremark-pro/benchmarks/fp/loops/ref-sp/*.c)
endif()
set(MID_CSRCS
coremark-pro/workloads/loops-all-mid-10k-sp/loops-all-mid-10k-sp.c
coremark-pro/benchmarks/fp/loops/loops.c ${MID_SRCS})
nuttx_add_application(
NAME
loops_all_mid_10k_sp
PRIORITY
${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE}
MODULE
${CONFIG_BENCHMARK_COREMARK_PRO}
COMPILE_FLAGS
${CFLAGS}
SRCS
${MID_CSRCS}
INCLUDE_DIRECTORIES
${INCDIR}
DEPENDS
coremark_pro)
endif()
if(CONFIG_BENCHMARK_COREMARK_PRO_NNET_TEST)
if(CONFIG_BENCHMARK_COREMARK_PRO_USE_FP64)
file(GLOB NNET_SRCS coremark-pro/benchmarks/fp/nnet/ref/*.c)
else()
file(GLOB NNET_SRCS coremark-pro/benchmarks/fp/nnet/ref-sp/*.c)
endif()
file(GLOB FP_NNET_SRCS coremark-pro/benchmarks/fp/nnet/*.c)
set(NNET_CSRCS coremark-pro/workloads/nnet_test/nnet_test.c ${FP_NNET_SRCS}
${NNET_SRCS})
nuttx_add_application(
NAME
nnet_test
PRIORITY
${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE}
MODULE
${CONFIG_BENCHMARK_COREMARK_PRO}
COMPILE_FLAGS
${CFLAGS}
SRCS
${NNET_CSRCS}
INCLUDE_DIRECTORIES
${INCDIR}
DEPENDS
coremark_pro)
endif()
if(CONFIG_BENCHMARK_COREMARK_PRO_PARSER_125K)
file(GLOB PARSER_SRCS coremark-pro/benchmarks/darkmark/parser/*.c)
set(PARSER_CSRCS coremark-pro/workloads/parser-125k/parser-125k.c
${PARSER_SRCS})
nuttx_add_application(
NAME
parser_125k
PRIORITY
${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE}
MODULE
${CONFIG_BENCHMARK_COREMARK_PRO}
COMPILE_FLAGS
${CFLAGS}
SRCS
${PARSER_CSRCS}
INCLUDE_DIRECTORIES
${INCDIR}
DEPENDS
coremark_pro)
endif()
target_sources(coremark_pro PRIVATE ${CSRCS})
target_include_directories(coremark_pro PRIVATE ${INCDIR})
target_compile_options(coremark_pro PRIVATE ${CFLAGS})
endif()

View File

@@ -24,13 +24,10 @@ PRIORITY = $(CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY)
STACKSIZE = $(CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE)
MODULE = $(CONFIG_BENCHMARK_COREMARK_PRO)
CFLAGS += -Wno-undef -Wno-strict-prototypes -Wno-unused-variable \
-Wno-pointer-sign -Wno-unused-but-set-variable -Wno-shadow
CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/benchmarks/coremark-pro/coremark-pro/mith/include
CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/benchmarks/coremark-pro/coremark-pro/mith/al/include
CFLAGS += -DNDEBUG -DHOST_EXAMPLE_CODE=1 -DHAVE_SYS_STAT_H=1 \
-DGCC_INLINE_MACRO=1 -DMAX_CONTEXTS=100 -DEE_SIZEOF_INT=4 \
-DUSE_FP128=0
ifneq ($(CONFIG_BENCHMARK_COREMARK_PRO_USE_SINGLE_CONTEXT),)
CFLAGS += -DUSE_SINGLE_CONTEXT=1 -DHAVE_PTHREAD=0 -DUSE_NATIVE_PTHREAD=0
@@ -47,10 +44,10 @@ ifneq ($(CONFIG_BENCHMARK_COREMARK_PRO_64BIT),)
endif
ifneq ($(CONFIG_BENCHMARK_COREMARK_PRO_USE_FP64),)
CFLAGS += -DUSE_FP64=1 -DUSE_FP32=0
CFLAGS += -DUSE_FP64=1
CSRCS += coremark-pro/benchmarks/fp/linpack/ref/inputs_f64.c
else
CFLAGS += -DUSE_FP32=1 -DUSE_FP64=0
CFLAGS += -DUSE_FP32=1
CSRCS += coremark-pro/benchmarks/fp/linpack/ref/inputs_f32.c
endif

View File

@@ -61,56 +61,15 @@ if(CONFIG_BENCHMARK_COREMARK)
# Flags
# ############################################################################
if(CONFIG_COREMARK_MULTITHREAD_OVERRIDE)
set(COREMARK_NTHREADS ${CONFIG_COREMARK_MULTITHREAD_COUNT})
else()
if(CONFIG_SMP_NCPUS)
set(COREMARK_NTHREADS ${CONFIG_SMP_NCPUS})
else()
set(COREMARK_NTHREADS 1)
endif()
endif()
if(CONFIG_COREMARK_PRINT_ARGS)
set(COREMARK_PRINT_ARGS 1)
else()
set(COREMARK_PRINT_ARGS 0)
endif()
get_target_property(FLAGS_STR_LIST nuttx COMPILE_OPTIONS)
list(JOIN FLAGS_STR_LIST " " FLAGS_STR)
set(CFLAGS -Dcrc16=coremark_crc16 -Wno-strict-prototypes -Wno-undef)
if("${CONFIG_COREMARK_MEM_METHOD}" STREQUAL "1")
list(APPEND CFLAGS -DMEM_LOCATION=\"HEAP\")
elseif("${CONFIG_COREMARK_MEM_METHOD}" STREQUAL "2")
list(APPEND CFLAGS -DMEM_LOCATION=\"STACK\")
else()
list(APPEND CFLAGS -DMEM_LOCATION=\"GLOBAL\")
endif()
list(
APPEND
CFLAGS
-DCALLGRIND_RUN=0
-DCOMPILER_REQUIRES_SORT_RETURN=0
-DCORE_DEBUG=${CONFIG_COREMARK_DEBUG}
-DFLAGS_STR="${FLAGS_STR}"
-DMEM_METHOD=${CONFIG_COREMARK_MEM_METHOD}
-DMICA=0
-DMULTITHREAD=${COREMARK_NTHREADS}
-DPERFORMANCE_RUN=1
-DPRINT_ARGS=${COREMARK_PRINT_ARGS}
-DSEED_METHOD=${CONFIG_COREMARK_SEED_METHOD}
-DUSE_CLOCK=1
-DUSE_PTHREAD)
set(CFLAGS
-Wno-undef -DUSE_PTHREAD -DPERFORMANCE_RUN=1
-DMULTITHREAD=${COREMARK_NTHREADS} -DFLAGS_STR="${FLAGS_STR}"
-DMEM_LOCATION="Stack")
if(CONFIG_COREMARK_ITERATIONS_OVERRIDE)
list(APPEND CFLAGS -DITERATIONS=${CONFIG_COREMARK_ITERATIONS_COUNT})
else()
list(APPEND CFLAGS -DITERATIONS=0)
endif()
# ############################################################################
@@ -134,7 +93,7 @@ if(CONFIG_BENCHMARK_COREMARK)
nuttx_add_application(
NAME
${CONFIG_COREMARK_PROGNAME}
coremark
PRIORITY
${CONFIG_COREMARK_PRIORITY}
STACKSIZE

View File

@@ -39,7 +39,6 @@ VPATH += $(COREMARK_UNPACKNAME)$(DELIM)posix
DEPPATH += --dep-path $(COREMARK_UNPACKNAME)
DEPPATH += --dep-path $(COREMARK_UNPACKNAME)$(DELIM)posix
CFLAGS += -Dcrc16=coremark_crc16
CFLAGS += -Wno-strict-prototypes -Wno-undef
ifeq ($(CONFIG_COREMARK_MULTITHREAD_OVERRIDE),y)

View File

@@ -1 +0,0 @@
/dhrystone

View File

@@ -27,11 +27,10 @@ PRIORITY = $(CONFIG_BENCHMARK_DHRYSTONE_PRIORITY)
STACKSIZE = $(CONFIG_BENCHMARK_DHRYSTONE_STACKSIZE)
MODULE = $(CONFIG_BENCHMARK_DHRYSTONE)
CFLAGS += -DMSC_CLOCK -Wno-implicit-int -Wno-strict-prototypes
CFLAGS += -Wno-implicit-function-declaration -Wno-return-type
CFLAGS += -Wno-maybe-uninitialized
CFLAGS += -DMSC_CLOCK
CSRCS += dhrystone/v2.1/dhry_2.c
MAINSRC = dhrystone/v2.2/dry.c
ifeq ($(wildcard dhrystone/.git),)

View File

@@ -1 +0,0 @@
/fio

View File

@@ -1,169 +0,0 @@
# ##############################################################################
# apps/benchmarks/fio/CMakeLists.txt
#
# Licensed to the Apache Software Foundation (ASF) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. The ASF licenses this
# file to you under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#
# ##############################################################################
if(CONFIG_BENCHMARK_FIO)
set(FIOAPP_DIR ${CMAKE_CURRENT_LIST_DIR}/fio)
if(NOT EXISTS ${FIOAPP_DIR})
FetchContent_Declare(
fio_fetch
URL https://github.com/ldorau/fio/archive/refs/heads/master.zip SOURCE_DIR
${CMAKE_CURRENT_LIST_DIR}/fio BINARY_DIR
${CMAKE_BINARY_DIR}/apps/benchmarks/fio/fio
DOWNLOAD_NO_PROGRESS true
TIMEOUT 30
PATCH_COMMAND
patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio <
${CMAKE_CURRENT_LIST_DIR}/0001-external-fio-fix-compile-warning.patch
COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio <
${CMAKE_CURRENT_LIST_DIR}/0002-external-fio-add-os-nuttx-support.patch
COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio <
${CMAKE_CURRENT_LIST_DIR}/0003-external-fio-modify-smaller-size-for-nuttx.patch
COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio <
${CMAKE_CURRENT_LIST_DIR}/0004-external-fio-fix-runtime-error-by-asan.patch
COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio <
${CMAKE_CURRENT_LIST_DIR}/0005-external-fio-fix-compile-warning.patch
COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio <
${CMAKE_CURRENT_LIST_DIR}/0006-external-fio-reinit-global-var-issue-when-run-multip.patch
COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio <
${CMAKE_CURRENT_LIST_DIR}/0007-external-fio-add-engine-init.patch
COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio <
${CMAKE_CURRENT_LIST_DIR}/0008-fio-fix-memory-leak-run-cpuio.fio.patch
COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio <
${CMAKE_CURRENT_LIST_DIR}/0009-fio-fix-memory-leak-ioengine-filecreate.patch
COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio <
${CMAKE_CURRENT_LIST_DIR}/0010-fio-fix-memory-leak-ioengine-exec.patch)
FetchContent_GetProperties(fio_fetch)
if(NOT fio_fetch_POPULATED)
FetchContent_Populate(fio_fetch)
endif()
endif()
file(GLOB LIB_SRCS ${FIOAPP_DIR}/lib/*.c)
file(GLOB CRC_SRCS ${FIOAPP_DIR}/crc/*.c)
set(CSRCS
${LIB_SRCS}
${CRC_SRCS}
${FIOAPP_DIR}/gettime.c
${FIOAPP_DIR}/ioengines.c
${FIOAPP_DIR}/init.c
${FIOAPP_DIR}/stat.c
${FIOAPP_DIR}/log.c
${FIOAPP_DIR}/time.c
${FIOAPP_DIR}/filesetup.c
${FIOAPP_DIR}/eta.c
${FIOAPP_DIR}/verify.c
${FIOAPP_DIR}/memory.c
${FIOAPP_DIR}/io_u.c
${FIOAPP_DIR}/parse.c
${FIOAPP_DIR}/fio_sem.c
${FIOAPP_DIR}/rwlock.c
${FIOAPP_DIR}/pshared.c
${FIOAPP_DIR}/options.c
${FIOAPP_DIR}/smalloc.c
${FIOAPP_DIR}/filehash.c
${FIOAPP_DIR}/profile.c
${FIOAPP_DIR}/debug.c
${FIOAPP_DIR}/server.c
${FIOAPP_DIR}/client.c
${FIOAPP_DIR}/iolog.c
${FIOAPP_DIR}/backend.c
${FIOAPP_DIR}/libfio.c
${FIOAPP_DIR}/flow.c
${FIOAPP_DIR}/cconv.c
${FIOAPP_DIR}/gettime-thread.c
${FIOAPP_DIR}/helpers.c
${FIOAPP_DIR}/json.c
${FIOAPP_DIR}/idletime.c
${FIOAPP_DIR}/td_error.c
${FIOAPP_DIR}/zbd.c
${FIOAPP_DIR}/profiles/tiobench.c
${FIOAPP_DIR}/profiles/act.c
${FIOAPP_DIR}/io_u_queue.c
${FIOAPP_DIR}/filelock.c
${FIOAPP_DIR}/steadystate.c
${FIOAPP_DIR}/workqueue.c
${FIOAPP_DIR}/rate-submit.c
${FIOAPP_DIR}/optgroup.c
${FIOAPP_DIR}/helper_thread.c
${FIOAPP_DIR}/zone-dist.c
${FIOAPP_DIR}/dedupe.c
${FIOAPP_DIR}/engines/exec.c
${FIOAPP_DIR}/engines/cpu.c
${FIOAPP_DIR}/engines/sync.c
${FIOAPP_DIR}/engines/ftruncate.c
${FIOAPP_DIR}/engines/falloc.c
${FIOAPP_DIR}/engines/fileoperations.c
${FIOAPP_DIR}/engines/mmap.c
${FIOAPP_DIR}/engines/null.c
${FIOAPP_DIR}/engines/net.c)
set(CFLAGS
-DCONFIG_GETTIMEOFDAY
-DCONFIG_CLOCK_GETTIME
-DCONFIG_HAVE_GETTID
-DCONFIG_STATIC_ASSERT
-DCONFIG_LITTLE_ENDIAN
-DCONFIG_POSIX_FALLOCATE
-DCONFIG_HAVE_BOOL
-DFIO_INTERNAL
-DCONFIG_NO_SHM
-DFIO_VERSION=\"1.2.0\"
-DFIO_USE_GENERIC_SWAP
-DFIO_USE_GENERIC_INIT_RANDOM_STATE
-DFIO_USE_GENERIC_BDEV_SIZE
-DBLOOM_SIZE=1024*1024
-DBUF_SIZE=512*1024
-DMAX_POOLS=4
-DINITIAL_POOLS=2
-DINITIAL_SIZE=512*1024
-DCONFIG_SEED_BUCKETS=8
-DBITS_PER_LONG=32
-DXXH32_digest=fio_XXH32_digest
-DXXH32_update=fio_XXH32_update
-DXXH32=fio_XXH32
-Dparse_options=fio_parse_options
-Dparse_option=fio_parse_option)
set(INCDIR ${FIOAPP_DIR} ${FIOAPP_DIR}/arch ${FIOAPP_DIR}/crc
${FIOAPP_DIR}/os)
include_directories(${INCDIR})
if(CONFIG_ARCH_ARM)
list(APPEND CFLAGS -D__ARM_ARCH_6__)
endif()
set(SRCS ${FIOAPP_DIR}/fio.c ${CSRCS})
nuttx_add_application(
NAME
fio
PRIORITY
${CONFIG_BENCHMARK_FIO_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_FIO_STACKSIZE}
COMPILE_FLAGS
${CFLAGS}
SRCS
${SRCS})
endif()

View File

@@ -1,87 +0,0 @@
# ##############################################################################
# apps/benchmarks/iozone/CMakeLists.txt
#
# Licensed to the Apache Software Foundation (ASF) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. The ASF licenses this
# file to you under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#
# ##############################################################################
if(CONFIG_BENCHMARK_IOZONE)
# Define the directory and file paths
set(IOZONE_VERSION "${CONFIG_BENCHMARK_IOZONE_VERSION}") # Adjust this as
# needed
set(IOZONE_DIR ${CMAKE_CURRENT_LIST_DIR}/iozone)
set(IOZONE_ZIP ${IOZONE_DIR}.tgz)
set(IOZONE_URL
"https://www.iozone.org/src/current/iozone${IOZONE_VERSION}.tgz")
# Download and unpack iozone if not already present
if(NOT EXISTS ${IOZONE_DIR})
FetchContent_Declare(
iozone_fetch
URL ${IOZONE_URL} SOURCE_DIR ${IOZONE_DIR}
DOWNLOAD_NO_PROGRESS true
TIMEOUT 30
PATCH_COMMAND patch -p1 -d ${IOZONE_DIR} <
${CMAKE_CURRENT_LIST_DIR}/iozone.patch)
FetchContent_GetProperties(iozone_fetch)
if(NOT iozone_fetch_POPULATED)
FetchContent_Populate(iozone_fetch)
endif()
endif()
# Define source files
set(CSRCS ${IOZONE_DIR}/src/current/libbif.c)
set(MAINSRC ${IOZONE_DIR}/src/current/iozone.c)
# Define compile flags
set(CFLAGS
-Dunix
-DHAVE_ANSIC_C
-DHAVE_PREAD
-DNAME=\"nuttx\"
-DNO_MADVISE
-DNO_FORK
-D__FreeBSD__
-DNO_THREADS
-Wno-unused-parameter
-Wno-unused-function
-Wno-shadow
-Wno-unused-but-set-variable
-Wno-strict-prototypes
-Wno-misleading-indentation
-Wno-maybe-uninitialized
-DMAXBUFFERSIZE=32*1024
-DMAXSTREAMS=8
-DMAXNAMESIZE=NAME_MAX
-DRECLEN_START=1024)
# Add application to the build
set(SRCS ${IOZONE_DIR}/src/current/iozone.c ${CSRCS})
nuttx_add_application(
NAME
iozone
PRIORITY
${CONFIG_BENCHMARK_IOZONE_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_IOZONE_STACKSIZE}
COMPILE_FLAGS
${CFLAGS}
SRCS
${SRCS})
endif()

View File

@@ -1,5 +1,5 @@
############################################################################
# apps/benchmarks/iozone/Make.defs
# apps/benchmarks/iozone/Makefile
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with

View File

@@ -131,7 +131,7 @@ static size_t performance_gettime(FAR struct performance_time_s *result)
static FAR void *pthread_switch_task(FAR void *arg)
{
FAR struct performance_thread_s *perf = arg;
irqstate_t flags = enter_critical_section();
irq_t flags = enter_critical_section();
sem_wait(&perf->sem);
performance_end(&perf->time);
leave_critical_section(flags);
@@ -281,9 +281,9 @@ static size_t poll_performance(void)
poll(&fds, 1, -1);
performance_end(&result);
pthread_join(ret, NULL);
close(pipefd[0]);
close(pipefd[1]);
pthread_join(ret, NULL);
return performance_gettime(&result);
}
@@ -353,7 +353,7 @@ static void performance_run(const FAR struct performance_entry_s *item,
for (i = 0; i < count; i++)
{
irqstate_t flags = enter_critical_section();
irq_t flags = enter_critical_section();
size_t time = item->entry();
leave_critical_section(flags);

View File

@@ -6,7 +6,6 @@
config BENCHMARK_RAMSPEED
tristate "RAM Speed Test"
default n
depends on LIBC_FLOATINGPOINT
---help---
Enable a simple RAM speed test.

View File

@@ -64,6 +64,17 @@
} \
} while (0)
#define HAS_IRQ_CONTROL !defined(CONFIG_BUILD_KERNEL) && \
!defined(CONFIG_BUILD_PROTECTED)
#if HAS_IRQ_CONTROL
# define ENABLE_IRQ(flags) leave_critical_section(flags);
# define DISABLE_IRQ(flags) flags=enter_critical_section();
#else
# define ENABLE_IRQ(flags) (void)flags;
# define DISABLE_IRQ(flags) (void)flags;
#endif
/****************************************************************************
* Private Types
****************************************************************************/
@@ -76,7 +87,6 @@ struct ramspeed_s
uint8_t value;
uint32_t repeat_num;
bool irq_disable;
bool allocate_rw_address;
};
/****************************************************************************
@@ -105,8 +115,10 @@ static void show_usage(FAR const char *progname, int exitcode)
" [default value: 0x00].\n");
printf(" -n <decimal-repeat num> number of repetitions"
" [default value: 100].\n");
#if HAS_IRQ_CONTROL
printf(" -i turn off interrupts while testing"
" [default value: false].\n");
#endif
exit(exitcode);
}
@@ -118,6 +130,7 @@ static void parse_commandline(int argc, FAR char **argv,
FAR struct ramspeed_s *info)
{
int ch;
bool allocate_rw_address = false;
memset(info, 0, sizeof(struct ramspeed_s));
info->repeat_num = 100;
@@ -133,7 +146,7 @@ static void parse_commandline(int argc, FAR char **argv,
switch (ch)
{
case 'a':
info->allocate_rw_address = true;
allocate_rw_address = true;
break;
case 'r':
OPTARG_TO_VALUE(info->src, const void *, 16);
@@ -162,9 +175,11 @@ static void parse_commandline(int argc, FAR char **argv,
}
break;
#if HAS_IRQ_CONTROL
case 'i':
info->irq_disable = true;
break;
#endif
case '?':
printf(RAMSPEED_PREFIX "Unknown option: %c\n", (char)optopt);
show_usage(argv[0], EXIT_FAILURE);
@@ -172,45 +187,17 @@ static void parse_commandline(int argc, FAR char **argv,
}
}
if ((info->dest == NULL && !info->allocate_rw_address) || info->size == 0)
if (allocate_rw_address)
{
info->dest = malloc(info->size);
info->src = malloc(info->size);
}
if (info->dest == NULL || info->src == NULL || info->size == 0)
{
printf(RAMSPEED_PREFIX "Missing required arguments\n");
goto out;
show_usage(argv[0], EXIT_FAILURE);
}
else
{
/* We need to automatically apply for memory */
printf(RAMSPEED_PREFIX "Allocate RW buffers on heap\n");
info->dest = malloc(info->size);
if (info->dest == NULL)
{
printf(RAMSPEED_PREFIX "Dest Alloc Memory Failed!\n");
goto out;
}
info->src = malloc(info->size);
if (info->src == NULL)
{
printf(RAMSPEED_PREFIX "Src Alloc Memory Failed!\n");
goto out;
}
}
/* Print info */
printf(RAMSPEED_PREFIX "Write address: %p\n", info->dest);
printf(RAMSPEED_PREFIX "Read address: %p\n", info->src);
printf(RAMSPEED_PREFIX "Size: %zu bytes\n", info->size);
printf(RAMSPEED_PREFIX "Value: 0x%02x\n", info->value);
printf(RAMSPEED_PREFIX "Repeat number: %" PRIu32 "\n", info->repeat_num);
printf(RAMSPEED_PREFIX "Interrupts disabled: %s\n",
info->irq_disable ? "true" : "false");
return;
out:
show_usage(argv[0], EXIT_FAILURE);
}
/****************************************************************************
@@ -220,10 +207,10 @@ out:
static uint32_t get_timestamp(void)
{
struct timespec ts;
uint32_t us;
uint32_t ms;
clock_gettime(CLOCK_MONOTONIC, &ts);
us = ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
return us;
ms = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
return ms;
}
/****************************************************************************
@@ -379,7 +366,7 @@ static void internal_memset(FAR void *dst, uint8_t v, size_t len)
static void print_rate(FAR const char *name, uint64_t bytes,
uint32_t cost_time)
{
double rate;
uint32_t rate;
if (cost_time == 0)
{
printf(RAMSPEED_PREFIX
@@ -388,10 +375,10 @@ static void print_rate(FAR const char *name, uint64_t bytes,
return;
}
rate = (double)bytes / 1024 / (cost_time / 1000000.0);
rate = bytes * 1000 / cost_time / 1024;
printf(RAMSPEED_PREFIX
"%s Rate = %.3f KB/s\t[cost: %.3f ms]\n",
name, rate, cost_time / 1000.0f);
"%s Rate = %" PRIu32 " KB/s\t[cost: %" PRIu32 "ms]\n",
name, rate, cost_time);
}
/****************************************************************************
@@ -428,7 +415,7 @@ static void memcpy_speed_test(FAR void *dest, FAR const void *src,
if (irq_disable)
{
flags = enter_critical_section();
DISABLE_IRQ(flags);
}
start_time = get_timestamp();
@@ -451,7 +438,7 @@ static void memcpy_speed_test(FAR void *dest, FAR const void *src,
if (irq_disable)
{
leave_critical_section(flags);
ENABLE_IRQ(flags);
}
print_rate("system memcpy():\t", total_size, cost_time_system);
@@ -493,7 +480,7 @@ static void memset_speed_test(FAR void *dest, uint8_t value,
if (irq_disable)
{
flags = enter_critical_section();
DISABLE_IRQ(flags);
}
start_time = get_timestamp();
@@ -516,7 +503,7 @@ static void memset_speed_test(FAR void *dest, uint8_t value,
if (irq_disable)
{
leave_critical_section(flags);
ENABLE_IRQ(flags);
}
print_rate("system memset():\t", total_size, cost_time_system);
@@ -538,24 +525,13 @@ int main(int argc, FAR char *argv[])
parse_commandline(argc, argv, &ramspeed);
if (ramspeed.src != NULL)
{
memcpy_speed_test(ramspeed.dest, ramspeed.src,
ramspeed.size, ramspeed.repeat_num,
ramspeed.irq_disable);
}
memcpy_speed_test(ramspeed.dest, ramspeed.src,
ramspeed.size, ramspeed.repeat_num,
ramspeed.irq_disable);
memset_speed_test(ramspeed.dest, ramspeed.value,
ramspeed.size, ramspeed.repeat_num,
ramspeed.irq_disable);
/* Check if alloc from heap? */
if (ramspeed.allocate_rw_address)
{
free(ramspeed.dest);
free((void *)ramspeed.src);
}
return EXIT_SUCCESS;
}

View File

@@ -1,2 +0,0 @@
/rt-tests
/*.zip

View File

@@ -1,43 +0,0 @@
#
# Copyright (C) 2024 Xiaomi Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#
if(CONFIG_BENCHMARK_RTTESTS)
list(
APPEND
CFLAGS
-Wno-maybe-uninitialized
-Wno-unused-variable
-Wno-unused-function
-Wno-unused-but-set-variable
-Wno-shadow
-Wno-stringop-truncation
-Wno-strict-prototypes)
nuttx_add_application(
NAME
cyclictest
PRIORITY
${CONFIG_BENCHMARK_RTTESTS_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_RTTESTS_STACKSIZE}
MODULE
${CONFIG_BENCHMARK_RTTESTS}
COMPILE_FLAGS
${CFLAGS}
SRCS
rttests/src/cyclictest/cyclictest.c)
endif()

View File

@@ -1,32 +0,0 @@
#
# Copyright (C) 2024 Xiaomi Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
config BENCHMARK_RTTESTS
tristate "RT-Tests"
default n
---help---
Measure the timer jitter
if BENCHMARK_RTTESTS
config BENCHMARK_RTTESTS_PRIORITY
int "OS profiling task priority"
default 100
config BENCHMARK_RTTESTS_STACKSIZE
int "OS profiling stack size"
default DEFAULT_TASK_STACKSIZE
endif

View File

@@ -1,19 +0,0 @@
#
# Copyright (C) 2024 Xiaomi Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
ifneq ($(CONFIG_BENCHMARK_RTTESTS),)
CONFIGURED_APPS += $(APPDIR)/benchmarks/rttests
endif

View File

@@ -1,35 +0,0 @@
#
# Copyright (C) 2024 Xiaomi Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
############################################################################
# Targets
############################################################################
include $(APPDIR)/Make.defs
PROGNAME = cyclictest
PRIORITY = $(CONFIG_BENCHMARK_RTTESTS_PRIORITY)
STACKSIZE = $(CONFIG_BENCHMARK_RTTESTS_STACKSIZE)
MODULE = $(CONFIG_BENCHMARK_RTTESTS)
MAINSRC = rttests/src/cyclictest/cyclictest.c
CFLAGS += -Wno-maybe-uninitialized -Wno-unused-variable -Wno-unused-function
CFLAGS += -Wno-unused-but-set-variable -Wno-shadow -Wno-stringop-truncation
CFLAGS += -Wno-strict-prototypes
include $(APPDIR)/Application.mk

View File

@@ -1,5 +1,5 @@
# ##############################################################################
# apps/math/ruy/CMakeLists.txt
# apps/benchmarks/spinlock_bench/CMakeLists.txt
#
# Licensed to the Apache Software Foundation (ASF) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
@@ -18,43 +18,38 @@
#
# ##############################################################################
if(CONFIG_MATH_RUY)
if(CONFIG_BENCHMARK_SPINLOCK)
# ############################################################################
# Config and Fetch ruy lib
# Config and Fetch Coremark application
# ############################################################################
set(RUY_DIR ${CMAKE_CURRENT_LIST_DIR}/ruy)
if(NOT EXISTS ${RUY_DIR})
set(RUY_URL
https://github.com/google/ruy/archive/d37128311b445e758136b8602d1bbd2a755e115d.zip
)
FetchContent_Declare(
ruy_fetch
URL ${RUY_URL} SOURCE_DIR ${RUY_DIR} BINARY_DIR
${CMAKE_BINARY_DIR}/apps/math/ruy/ruy
DOWNLOAD_NO_PROGRESS true
TIMEOUT 30)
FetchContent_GetProperties(ruy_fetch)
if(NOT ruy_fetch_POPULATED)
FetchContent_Populate(ruy_fetch)
endif()
endif()
set(SPINLOCKAPP_DIR ${CMAKE_CURRENT_LIST_DIR})
# ############################################################################
# Include Directory
# Sources
# ############################################################################
set(INCDIR ${CMAKE_CURRENT_LIST_DIR}/ruy)
set(CSRCS ${SPINLOCKAPP_DIR}/spinlock_bench.c)
# ############################################################################
# Library Configuration
# Applications Configuration
# ############################################################################
nuttx_add_library(ruy STATIC)
target_include_directories(ruy PUBLIC ${INCDIR})
nuttx_add_application(
NAME
spinlock_bench
PRIORITY
${CONFIG_SPINLOCK_PRIORITY}
STACKSIZE
${CONFIG_SPINLOCK_STACKSIZE}
MODULE
${CONFIG_BENCHMARK_SPINLOCK}
COMPILE_FLAGS
${CFLAGS}
SRCS
${CSRCS}
INCLUDE_DIRECTORIES
${INCDIR})
endif()

View File

@@ -0,0 +1,45 @@
#
# For a description of the syntax of this configuration file,
# see the file kconfig-language.txt in the NuttX tools repository.
#
menuconfig BENCHMARK_SPINLOCK
bool "Spinlock Benchmark"
depends on BUILD_FLAT
default n
---help---
Enable the Spinlock benchmark application.
if BENCHMARK_SPINLOCK
config SPINLOCK_PROGNAME
string "spinlock benchmark"
default "spinlock_bench"
---help---
This is the name of the program that will be used when the NSH ELF
program is installed.
config SPINLOCK_PRIORITY
int "Spinlock task priority"
default 100
config SPINLOCK_STACKSIZE
int "Spinlock task stack size"
default 4096
config SPINLOCK_MULTITHREAD
int "Number of threads"
default 40
---help---
Override the default number of threads to be executed.
The default value is 40.
config SPINLOCK_ITERATIONS
int "Number of iterations"
default 100
---help---
Default number of iterations for the benchmark on each thread.
The default value is 100.
endif # BENCHMARK_SPINLOCK

View File

@@ -1,5 +1,5 @@
############################################################################
# apps/examples/module/main/Make.defs
# apps/benchmarks/spinlock_bench/Make.defs
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
@@ -18,6 +18,6 @@
#
############################################################################
ifneq ($(CONFIG_EXAMPLES_MODULE),)
CONFIGURED_APPS += $(APPDIR)/examples/module/main
ifneq ($(CONFIG_BENCHMARK_SPINLOCK),)
CONFIGURED_APPS += $(APPDIR)/benchmarks/spinlock_bench
endif

View File

@@ -1,5 +1,5 @@
############################################################################
# apps/math/gemmlowp/Makefile
# apps/benchmarks/spinlock_bench/Makefile
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
@@ -20,22 +20,20 @@
include $(APPDIR)/Make.defs
MODULE = $(CONFIG_MATH_GEMMLOWP)
# spinlock_bench application
GEMMLOWP_VER = 719139ce755a0f31cbf1c37f7f98adcc7fc9f425
############################################################################
# Applications Configuration
############################################################################
gemmlowp.zip:
$(Q) curl -L https://github.com/google/gemmlowp/archive/$(GEMMLOWP_VER).zip -o gemmlowp.zip
$(Q) unzip -o gemmlowp.zip
$(Q) mv gemmlowp-$(GEMMLOWP_VER) gemmlowp
MODULE = $(CONFIG_BENCHMARK_SPINLOCK)
# Download and unpack tarball if no git repo found
ifeq ($(wildcard gemmlowp/.git),)
context:: gemmlowp.zip
PROGNAME += $(CONFIG_SPINLOCK_PROGNAME)
PRIORITY += $(CONFIG_SPINLOCK_PRIORITY)
STACKSIZE += $(CONFIG_SPINLOCK_STACKSIZE)
distclean::
$(call DELDIR, gemmlowp)
$(call DELFILE, gemmlowp.zip)
endif
MAINSRC += spinlock_bench.c
# Build with WebAssembly when CONFIG_INTERPRETERS_WAMR is enabled
include $(APPDIR)/Application.mk

View File

@@ -0,0 +1,110 @@
/****************************************************************************
* apps/benchmarks/spinlock_bench/spinlock_bench.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <stdio.h>
#include <assert.h>
#include <errno.h>
#include <nuttx/spinlock.h>
#include <time.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define TEST_NUM CONFIG_SPINLOCK_MULTITHREAD
#define THREAD_NUM CONFIG_SPINLOCK_MULTITHREAD
/****************************************************************************
* Private Types
****************************************************************************/
struct thread_parmeter_s
{
FAR int *result;
FAR spinlock_t *lock;
};
/****************************************************************************
* Private Functions
****************************************************************************/
static FAR void *thread_spinlock(FAR void *parameter)
{
FAR int *result = ((FAR struct thread_parmeter_s *)parameter)->result;
FAR spinlock_t *lock = ((FAR struct thread_parmeter_s *)parameter)->lock;
int i;
for (i = 0; i < TEST_NUM; i++)
{
spin_lock(lock);
(*result)++;
spin_unlock(lock);
}
return NULL;
}
/****************************************************************************
* Public Functions
****************************************************************************/
void main(void)
{
spinlock_t lock = SP_UNLOCKED;
int result = 0;
pthread_t thread[THREAD_NUM];
struct thread_parmeter_s para;
clock_t start;
clock_t end;
int status;
int i;
para.result = &result;
para.lock = &lock;
start = perf_gettime();
for (i = 0; i < THREAD_NUM; ++i)
{
status = pthread_create(&thread[i], NULL,
thread_spinlock, &para);
if (status != 0)
{
printf("spinlock_test: ERROR pthread_create failed, status=%d\n",
status);
ASSERT(false);
}
}
for (i = 0; i < THREAD_NUM; ++i)
{
pthread_join(thread[i], NULL);
}
end = perf_gettime();
assert(result == THREAD_NUM * TEST_NUM);
printf("total_time: %lu\n", end - start);
}

View File

@@ -1,54 +0,0 @@
# ##############################################################################
# apps/benchmarks/superpi/CMakeList.txt
#
# Licensed to the Apache Software Foundation (ASF) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. The ASF licenses this
# file to you under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#
# ##############################################################################
if(CONFIG_BENCHMARK_SUPERPI)
set(SUPERPI_UNPACK ${CMAKE_CURRENT_LIST_DIR}/superpi)
set(SUPERPI_URL https://github.com/Fibonacci43/SuperPI/archive)
set(SUPERPI_ZIP main.zip)
if(NOT EXISTS ${SUPERPI_UNPACK})
FetchContent_Declare(
superpi_fetch
URL ${SUPERPI_URL}/${SUPERPI_ZIP} SOURCE_DIR ${SUPERPI_UNPACK} BINARY_DIR
${CMAKE_BINARY_DIR}/apps/benchmarks/superpi/superpi
DOWNLOAD_NO_PROGRESS true
TIMEOUT 30)
FetchContent_GetProperties(superpi_fetch)
if(NOT superpi_fetch_POPULATED)
FetchContent_Populate(superpi_fetch)
endif()
endif()
nuttx_add_application(
NAME
${CONFIG_BENCHMARK_SUPERPI_PROGNAME}
STACKSIZE
${CONFIG_BENCHMARK_SUPERPI_STACKSIZE}
PRIORITY
${CONFIG_BENCHMARK_SUPERPI_PRIORITY}
SRCS
${SUPERPI_UNPACK}/pi_fftcs.c
${SUPERPI_UNPACK}/fftsg_h.c)
endif()

View File

@@ -1,2 +0,0 @@
/tacle-bench
/*.zip

View File

@@ -1,2 +0,0 @@
/test-tlb
/*.zip

View File

@@ -1,34 +0,0 @@
#
# Copyright (C) 2024 Xiaomi Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#
if(CONFIG_BENCHMARK_TESTTLB)
set(SRCS testtlb/test-tlb.c)
nuttx_add_application(
NAME
testtlb
PRIORITY
${CONFIG_BENCHMARK_TESTTLB_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_TESTTLB_STACKSIZE}
MODULE
${CONFIG_BENCHMARK_TESTTLB}
COMPILE_FLAGS
${CFLAGS}
SRCS
${SRCS})
endif()

View File

@@ -1,33 +0,0 @@
#
# Copyright (C) 2024 Xiaomi Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
config BENCHMARK_TESTTLB
tristate "Memory Latency profiling"
default n
---help---
Measure the memory latency
if BENCHMARK_TESTTLB
config BENCHMARK_TESTTLB_PRIORITY
int "TestTLB task priority"
default 100
config BENCHMARK_TESTTLB_STACKSIZE
int "TestTLB stack size"
default DEFAULT_TASK_STACKSIZE
endif

View File

@@ -1,19 +0,0 @@
#
# Copyright (C) 2024 Xiaomi Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
ifneq ($(CONFIG_BENCHMARK_TESTTLB),)
CONFIGURED_APPS += $(APPDIR)/benchmarks/testtlb
endif

View File

@@ -1,26 +0,0 @@
#
# Copyright (C) 2024 Xiaomi Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include $(APPDIR)/Make.defs
PROGNAME = testtlb
PRIORITY = $(CONFIG_BENCHMARK_TESTTLB_PRIORITY)
STACKSIZE = $(CONFIG_BENCHMARK_TESTTLB_STACKSIZE)
MODULE = $(CONFIG_BENCHMARK_TESTTLB)
MAINSRC = testtlb/test-tlb.c
include $(APPDIR)/Application.mk

View File

@@ -1,2 +0,0 @@
/tinymembench
/*.zip

View File

@@ -1,47 +0,0 @@
#
# Copyright (C) 2024 Xiaomi Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#
if(CONFIG_BENCHMARK_TINY_MEMBENCH)
list(APPEND CFLAGS -Wno-unused-but-set-variable -Wno-unused-variable
-Wno-strict-prototypes)
set(SRCS tinymembench/main.c)
list(
APPEND
SRCS
tinymembench/aarch64-asm.S
tinymembench/arm-neon.S
tinymembench/x86-sse2.S
tinymembench/mips-32.S
tinymembench/asm-opt.c
tinymembench/util.c)
nuttx_add_application(
NAME
tinymembench
PRIORITY
${CONFIG_BENCHMARK_TINY_MEMBENCH_PRIORITY}
STACKSIZE
${CONFIG_BENCHMARK_TINY_MEMBENCH_STACKSIZE}
MODULE
${CONFIG_BENCHMARK_TINY_MEMBENCH}
COMPILE_FLAGS
${CFLAGS}
SRCS
${SRCS})
endif()

View File

@@ -1,33 +0,0 @@
#
# Copyright (C) 2024 Xiaomi Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
config BENCHMARK_TINY_MEMBENCH
tristate "TinyMemBench"
default n
---help---
Measure the memory bandwidth and latency
if BENCHMARK_TINY_MEMBENCH
config BENCHMARK_TINY_MEMBENCH_PRIORITY
int "TinyMemBench task priority"
default 100
config BENCHMARK_TINY_MEMBENCH_STACKSIZE
int "TinyMemBench stack size"
default DEFAULT_TASK_STACKSIZE
endif

View File

@@ -1,19 +0,0 @@
#
# Copyright (C) 2024 Xiaomi Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
ifneq ($(CONFIG_BENCHMARK_TINY_MEMBENCH),)
CONFIGURED_APPS += $(APPDIR)/benchmarks/tinymembench
endif

View File

@@ -1,37 +0,0 @@
#
# Copyright (C) 2024 Xiaomi Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include $(APPDIR)/Make.defs
PROGNAME = tinymembench
PRIORITY = $(CONFIG_BENCHMARK_TINY_MEMBENCH_PRIORITY)
STACKSIZE = $(CONFIG_BENCHMARK_TINY_MEMBENCH_STACKSIZE)
MODULE = $(CONFIG_BENCHMARK_TINY_MEMBENCH)
ASRCS += tinymembench/aarch64-asm.S
ASRCS += tinymembench/arm-neon.S
ASRCS += tinymembench/x86-sse2.S
ASRCS += tinymembench/mips-32.S
CSRCS += tinymembench/asm-opt.c
CSRCS += tinymembench/util.c
MAINSRC = tinymembench/main.c
CFLAGS += -Wno-unused-but-set-variable -Wno-unused-variable
CFLAGS += -Wno-strict-prototypes
include $(APPDIR)/Application.mk

View File

@@ -12,9 +12,21 @@ menuconfig BOOT_MCUBOOT
if BOOT_MCUBOOT
config MCUBOOT_REPOSITORY
string "MCUboot GIT repository"
default "github.com/mcu-tools/mcuboot"
---help---
Specifies the location of MCUboot GIT repository . This
is by default MCUboot main GIT repository, but it can be changed
to user's fork if required.
config MCUBOOT_VERSION
string "MCUboot version"
default "fefc398cc13ebbc527e297fe9df78cd98a359d75"
---help---
Defines MCUboot version to be downloaded. Either release tag
or commit hash should be specified. Using newer MCUboot version
may cause compatability issues.
config MCUBOOT_ENABLE_LOGGING
bool "Enable MCUboot logging"

View File

@@ -20,10 +20,11 @@
include $(APPDIR)/Make.defs
MCUBOOT_VERSION := $(patsubst "%",%,$(CONFIG_MCUBOOT_VERSION))
MCUBOOT_TARBALL = $(MCUBOOT_VERSION).tar.gz
MCUBOOT_UNPACK = mcuboot
MCUBOOT_SRCDIR = $(MCUBOOT_UNPACK)$(DELIM)boot$(DELIM)bootutil$(DELIM)src
MCUBOOT_VERSION := $(patsubst "%",%,$(CONFIG_MCUBOOT_VERSION))
MCUBOOT_REPOSITORY := $(patsubst "%",%,$(CONFIG_MCUBOOT_REPOSITORY))
MCUBOOT_TARBALL = $(MCUBOOT_VERSION).tar.gz
MCUBOOT_UNPACK = mcuboot
MCUBOOT_SRCDIR = $(MCUBOOT_UNPACK)$(DELIM)boot$(DELIM)bootutil$(DELIM)src
DEPPATH += --dep-path $(MCUBOOT_UNPACK)$(DELIM)src
DEPPATH += --dep-path $(MCUBOOT_SRCDIR)
@@ -38,7 +39,7 @@ PRIORITY += SCHED_PRIORITY_DEFAULT
STACKSIZE += $(CONFIG_DEFAULT_TASK_STACKSIZE)
endif
CFLAGS += -Wno-undef
CFLAGS += -Wno-undef -Wno-unused-but-set-variable
CSRCS := $(MCUBOOT_UNPACK)/boot/bootutil/src/boot_record.c \
$(MCUBOOT_UNPACK)/boot/bootutil/src/bootutil_misc.c \
@@ -75,8 +76,8 @@ CXXFLAGS += ${INCDIR_PREFIX}mcuboot/ext/tinycrypt/lib/include
endif
$(MCUBOOT_TARBALL):
$(Q) echo "Downloading MCUboot-$(MCUBOOT_VERSION)"
$(Q) curl -O -L https://github.com/mcu-tools/mcuboot/archive/$(MCUBOOT_TARBALL)
$(Q) echo "Downloading MCUboot-$(MCUBOOT_VERSION) from $(MCUBOOT_REPOSITORY)"
$(Q) curl -O -L --proto-default https $(MCUBOOT_REPOSITORY)/archive/$(MCUBOOT_TARBALL)
$(MCUBOOT_UNPACK): $(MCUBOOT_TARBALL)
$(Q) echo "Unpacking: $(MCUBOOT_TARBALL) -> $(MCUBOOT_UNPACK)"

View File

@@ -1,54 +0,0 @@
# Boot / `mcuboot` MCUboot
## Description
The NuttX port of MCUboot secure boot library expects that the platform provides a Flash storage with the following partitions:
- `CONFIG_MCUBOOT_PRIMARY_SLOT_PATH`: MTD partition for the application firmware image PRIMARY slot;
- `CONFIG_MCUBOOT_SECONDARY_SLOT_PATH`: MTD partition for the application firmware image SECONDARY slot;
- `CONFIG_MCUBOOT_SCRATCH_PATH`: MTD partition for the Scratch area;
Also, these are optional features that may be enabled:
- `CONFIG_MCUBOOT_WATCHDOG`: If `CONFIG_WATCHDOG` is enabled, MCUboot shall reset the watchdog timer indicated by `CONFIG_MCUBOOT_WATCHDOG_DEVPATH` to the current timeout value, preventing any imminent watchdog timeouts.
The porting layer of MCUboot library consists of the following interfaces:
- `<flash_map_backend/flash_map_backend.h>`, for enabling MCUboot to manage the application firmware image slots in the device storage.
- `<mcuboot_config/mcuboot_config.h>`, for configuration of MCUboot's features.
- `<mcuboot_config/mcuboot_logging.h>`, for providing logging capabilities.
- `<os/os_malloc.h>`, for providing MCUboot access to the OS memory management interfaces.
- `<sysflash/sysflash.h>`, for configuration of the system's flash area organization.
The NuttX port of MCUboot is implemented at application-level and requires minimal knowledge about characteristics of the underlying storage device. This is achieved by means of the `BCH` and `FTL` subsystems, which enable MCUboot to manage MTD partitions via character device drivers using standard POSIX filesystem operations (e.g. `open()` / `close()` / `read()` / `write()`).
## Creating MCUboot-compatible application firmware images
One common use case for MCUboot is to integrate it to a firmware update agent, which is an important component of a secure firmware update subsystem. Through MCUboot APIs an application is able to install a newly received application firmware image and, once this application firmware image is assured to be valid, the application may confirm it as a stable image. In case that application firmware image is deemed bogus, MCUboot provides an API for invalidating that update, which will induce a rollback procedure to the most recent stable application firmware image.
The `CONFIG_EXAMPLES_MCUBOOT_UPDATE_AGENT` example demonstrates this workflow by downloading an application firmware image from a webserver, installing it and triggering the firmware update process for the next boot after a system reset. There is also the `CONFIG_EXAMPLES_MCUBOOT_SLOT_CONFIRM`, which is a fairly simple example that just calls an MCUboot API for confirming the executing application firmware image as stable.
For more information about all MCUboot examples, see `examples/mcuboot` directory.
## Using MCUboot on NuttX as a secure boot solution
NuttX port for MCUboot also enables the creation of a secure bootloader application requiring minimal platform-specific implementation. The logical implementation for the secure boot is performed at application-level by the MCUboot library. Once MCUboot validates the application firmware image, it delegates the loading and execution of the application firmware image to a platform-specific routine, which is accessed via `boardctl(BOARDIOC_BOOT_IMAGE)` call. Each platform must then provide an implementation for the `board_boot_image()` for executing the required actions in order to boot a new application firmware image (e.g. deinitialize peripherals, load the Program Counter register with the application firmware image entry point address).
The MCUboot bootloader application may be enabled by selecting the `CONFIG_MCUBOOT_BOOTLOADER` option.
## Assumptions
### IOCTL MTD commands
The implementation of `<flash_map_backend/flash_map_backend.h>` expects that the MTD driver for a given image partition handles the following `ioctl` commands:
- `MTDIOC_GEOMETRY`, for retrieving information about the geometry of the MTD, required for the configuration of the size of each flash area.
- `MTDIOC_ERASESTATE`, for retrieving the byte value of an erased cell of the MTD, required for the implementation of `flash_area_erased_val()` interface.
### Write access alignment
Through `flash_area_align()` interface MCUboot expects that the implementation provides the shortest data length that may be written via `flash_area_write()` interface. The NuttX implementation passes through the `BCH` and `FTL` layers, which appropriately handle the write alignment restrictions of the underlying MTD. So The NuttX implementation of `flash_area_align()` is able to return a fixed value of 1 byte, even if the MTD does not support byte operations.
## Limitations
### `<flash_map_backend/flash_map_backend.h>` functions are not multitasking-safe
MCUboot's documentation imposes no restrictions regarding the usage of its public interfaces, which doesn't mean they are thread-safe.
But, regarding NuttX implementation of the `<flash_map_backend/flash_map_backend.h>`, it is safe to state that they are **not** multitasking-safe. NuttX implementation manages the MTD partitions via character device drivers. As file-descriptors cannot be shared between different tasks, if one task calls `flash_area_open` and another task calls `flash_area_<read/write/close>` passing the same `struct flash_area` instance, it will result in failure.

View File

@@ -24,11 +24,11 @@
#include <nuttx/config.h>
#include <spawn.h>
#include <fcntl.h>
#include <errno.h>
#include <debug.h>
#include "nshlib/nshlib.h"
#include "builtin/builtin.h"
/****************************************************************************
@@ -62,15 +62,20 @@ int exec_builtin(FAR const char *appname, FAR char * const *argv,
FAR const char *redirfile, int oflags)
{
FAR const struct builtin_s *builtin;
posix_spawnattr_t attr;
posix_spawn_file_actions_t file_actions;
struct sched_param param;
pid_t pid;
int index;
int ret;
/* Verify that an application with this name exists */
index = builtin_isavail(appname);
if (index < 0)
{
errno = ENOENT;
return ERROR;
ret = ENOENT;
goto errout_with_errno;
}
/* Get information about the builtin */
@@ -78,10 +83,122 @@ int exec_builtin(FAR const char *appname, FAR char * const *argv,
builtin = builtin_for_index(index);
if (builtin == NULL)
{
errno = ENOENT;
return ERROR;
ret = ENOENT;
goto errout_with_errno;
}
return nsh_spawn(builtin->name, builtin->main, argv, builtin->priority,
builtin->stacksize, redirfile, oflags, false);
/* Initialize attributes for task_spawn(). */
ret = posix_spawnattr_init(&attr);
if (ret != 0)
{
goto errout_with_errno;
}
ret = posix_spawn_file_actions_init(&file_actions);
if (ret != 0)
{
goto errout_with_attrs;
}
/* Set the correct task size and priority */
param.sched_priority = builtin->priority;
ret = posix_spawnattr_setschedparam(&attr, &param);
if (ret != 0)
{
goto errout_with_actions;
}
ret = posix_spawnattr_setstacksize(&attr, builtin->stacksize);
if (ret != 0)
{
goto errout_with_actions;
}
/* If robin robin scheduling is enabled, then set the scheduling policy
* of the new task to SCHED_RR before it has a chance to run.
*/
#if CONFIG_RR_INTERVAL > 0
ret = posix_spawnattr_setschedpolicy(&attr, SCHED_RR);
if (ret != 0)
{
goto errout_with_actions;
}
ret = posix_spawnattr_setflags(&attr,
POSIX_SPAWN_SETSCHEDPARAM |
POSIX_SPAWN_SETSCHEDULER);
if (ret != 0)
{
goto errout_with_actions;
}
#else
ret = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSCHEDPARAM);
if (ret != 0)
{
goto errout_with_actions;
}
#endif
/* Is output being redirected? */
if (redirfile)
{
/* Set up to close open redirfile and set to stdout (1) */
ret = posix_spawn_file_actions_addopen(&file_actions, 1,
redirfile, oflags, 0644);
if (ret != 0)
{
serr("ERROR: posix_spawn_file_actions_addopen failed: %d\n", ret);
goto errout_with_actions;
}
}
#ifdef CONFIG_LIBC_EXECFUNCS
/* Load and execute the application. */
ret = posix_spawn(&pid, builtin->name, &file_actions, &attr, argv, NULL);
if (ret != 0 && builtin->main != NULL)
#endif
{
/* Start the built-in */
pid = task_spawn(builtin->name, builtin->main, &file_actions,
&attr, argv ? &argv[1] : NULL, NULL);
ret = pid < 0 ? -pid : 0;
}
if (ret != 0)
{
serr("ERROR: task_spawn failed: %d\n", ret);
goto errout_with_actions;
}
/* Free attributes and file actions. Ignoring return values in the case
* of an error.
*/
/* Return the task ID of the new task if the task was successfully
* started. Otherwise, ret will be ERROR (and the errno value will
* be set appropriately).
*/
posix_spawn_file_actions_destroy(&file_actions);
posix_spawnattr_destroy(&attr);
return pid;
errout_with_actions:
posix_spawn_file_actions_destroy(&file_actions);
errout_with_attrs:
posix_spawnattr_destroy(&attr);
errout_with_errno:
errno = ret;
return ERROR;
}

View File

@@ -176,6 +176,8 @@ $(LELYCANOPEN_TARBALL):
$(LELYCANOPEN_SRCNAME): $(LELYCANOPEN_TARBALL)
@echo "Unpacking: $(LELYCANOPEN_TARBALL) -> $(LELYCANOPEN_UNPACKNAME)"
$(Q) $(UNPACK) $(LELYCANOPEN_TARBALL)
# Get the name of the directory created by the tar command
$(eval LELYCANOPEN_UNPACKNAME := $(shell ls -d lely-core-master*))
$(Q) mv $(LELYCANOPEN_UNPACKNAME) $(LELYCANOPEN_SRCNAME)
$(Q) cat 0001-NuttX-port.patch | patch -s -N -d $(LELYCANOPEN_SRCNAME) -p1
$(Q) echo "Patching $(LELYCANOPEN_SRCNAME)"

View File

@@ -1,50 +0,0 @@
# ##############################################################################
# apps/canutils/libcanardv0/CMakeLists.txt
#
# Licensed to the Apache Software Foundation (ASF) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. The ASF licenses this
# file to you under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#
# ##############################################################################
if(CONFIG_CANUTILS_LIBCANARDV0)
# ############################################################################
# Config and Fetch libcanardv0 lib
# ############################################################################
set(LIBCANARDV0_DIR ${CMAKE_CURRENT_LIST_DIR}/libcanardv0)
if(NOT EXISTS ${CMAKE_CURRENT_LIST_DIR}/libcanardv0)
FetchContent_Declare(
libcanardv0
URL ${CONFIG_LIBCANARDV0_URL}/${CONFIG_LIBCANARDV0_VERSION}.zip)
FetchContent_MakeAvailable(libcanardv0)
set(LIBCANARDV0_DIR ${libcanardv0_SOURCE_DIR})
endif()
# ############################################################################
# Library Configuration
# ############################################################################
nuttx_add_user_library(libcanardv0)
target_sources(
libcanardv0 PRIVATE ${LIBCANARDV0_DIR}/canard.c
${LIBCANARDV0_DIR}/drivers/nuttx/canard_nuttx.c)
target_compile_options(libcanardv0 PRIVATE -std=c99
-DCANARD_ASSERT=DEBUGASSERT)
target_include_directories(
libcanardv0 PRIVATE ${LIBCANARDV0_DIR} ${LIBCANARDV0_DIR}/drivers/nuttx)
endif()

View File

@@ -23,7 +23,7 @@ config LIBDRONECAN_VERSION
default "21f2a73df86886101e254d02cfc2277cd2a15717"
---help---
libcanard version.
config LIBDRONECAN_CANFD
bool "(Experimental) libcanard CAN FD Support"
default n
@@ -34,4 +34,4 @@ config LIBDRONECAN_CANFD
since libcanard doesn't support runtime switching
between CAN2.0B and CAN FD that well
endif
endif # CANUTILS_LIBDRONECAN

View File

@@ -27,6 +27,7 @@ switch "mm", "orc"
switch "arm.nuttx.gcc.exe", "arm-none-eabi-gcc"
switch "arm64.nuttx.gcc.exe", "aarch64-none-elf-gcc"
switch "riscv32.nuttx.gcc.exe", "riscv64-unknown-elf-gcc"
switch "riscv64.nuttx.gcc.exe", "riscv64-unknown-elf-gcc"
switch "amd64.nuttx.gcc.exe", "x86_64-linux-gnu-gcc"
switch "nimcache", ".nimcache"
@@ -69,14 +70,19 @@ proc read_config(cfg: string): DotConfig =
case arch
of "arm", "arm64":
result.arch = arch
of "riscv":
result.arch = "riscv32"
of "sim":
if defined(amd64):
result.arch = "amd64"
elif defined(aarch64):
result.arch = "arm64"
result.isSim = true
of "ARCH_FAMILY":
let arch = keyval[1].strip(chars = {'"'})
case arch
of "rv32":
result.arch = "riscv32"
of "rv64":
result.arch = "riscv64"
of "DEBUG_NOOPT":
result.opt = oNone
of "DEBUG_FULLOPT":
@@ -121,6 +127,7 @@ proc setup_cfg(cfg: DotConfig) =
switch("define", "nimMemAlignTiny")
let topdir = getEnv("TOPDIR")
const key = "TOPDIR"
let topdir = if existsEnv(key): getEnv(key) else: thisDir() & "/../nuttx"
let cfg = read_config(topdir & "/.config")
cfg.setup_cfg()

View File

@@ -1,5 +1,5 @@
# ##############################################################################
# apps/testing/mm/CMakeLists.txt
# apps/crypto/controlse/CMakeLists.txt
#
# Licensed to the Apache Software Foundation (ASF) under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
@@ -18,18 +18,28 @@
#
# ##############################################################################
if(CONFIG_TESTING_MM)
if(CONFIG_CRYPTO_CONTROLSE)
set(MBEDTLS_DIR ${CMAKE_BINARY_DIR}/apps/include/mbedtls)
nuttx_add_application(
NAME
${CONFIG_TESTING_MM_PROGNAME}
PRIORITY
${CONFIG_TESTING_MM_PRIORITY}
${CONFIG_CRYPTO_CONTROLSE_PROGNAME}
STACKSIZE
${CONFIG_TESTING_MM_STACKSIZE}
${CONFIG_CRYPTO_CONTROLSE_STACKSIZE}
MODULE
${CONFIG_TESTING_MM}
INCLUDE_DIRECTORIES
${NUTTX_DIR}/mm/mm_heap
${CONFIG_CRYPTO_CONTROLSE}
SRCS
mm_main.c)
controlse_main.cxx
chex_util.cxx
csecure_element.cxx
cstring.cxx
ccertificate.cxx
ccsr.cxx
cpublic_key.cxx
cserial_number.cxx
csan_builder.cxx
INCLUDE_DIRECTORIES
${MBEDTLS_DIR})
endif()

View File

@@ -18,8 +18,9 @@ config CRYPTO_CONTROLSE
select MBEDTLS_X509_CSR_WRITE_C
select MBEDTLS_X509_CRT_WRITE_C
---help---
Enable the controlse utility. This program is used control the
secure element device
Enable the controlse library and utility. It provides an
access library to the secure element device. The utility can
control the secure element device from the nuttx shell
if CRYPTO_CONTROLSE

View File

@@ -18,6 +18,8 @@
#
############################################################################
# Copyright 2023, 2024 NXP
include $(APPDIR)/Make.defs
# controlse built-in application info
@@ -28,7 +30,8 @@ STACKSIZE = $(CONFIG_CRYPTO_CONTROLSE_STACKSIZE)
# controlse main source
MAINSRC = controlse_main.c
CSRCS = x509_utils.c mbedtls_extension.c
MAINSRC = controlse_main.cxx
CXXSRCS = chex_util.cxx csecure_element.cxx cstring.cxx ccertificate.cxx\
ccsr.cxx cpublic_key.cxx cserial_number.cxx csan_builder.cxx
include $(APPDIR)/Application.mk

View File

@@ -0,0 +1,532 @@
//***************************************************************************
// apps/crypto/controlse/ccertificate.cxx
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. The
// ASF licenses this file to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//***************************************************************************
// Copyright 2024 NXP
//***************************************************************************
// Included Files
//***************************************************************************
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
#include "crypto/controlse/ccertificate.hxx"
#include "cmbedtls_se05x_extension.hxx"
#include "crypto/controlse/chex_util.hxx"
#include "crypto/controlse/cpublic_key.hxx"
#include "crypto/controlse/cserial_number.hxx"
#include "crypto/controlse/isecure_element.hxx"
#include <mbedtls/oid.h>
#include <mbedtls/pem.h>
#include <mbedtls/sha256.h>
#include <mbedtls/x509_crt.h>
#include <mbedtls/x509_csr.h>
#include <string.h>
namespace Controlse
{
//***************************************************************************
// Private Data
//***************************************************************************
static constexpr int SECONDS_IN_DAY = (60 * 60 * 24);
static constexpr size_t TBS_HASH_BUFFER_SIZE = 32;
static constexpr char certificate_header[] = "-----BEGIN CERTIFICATE-----\n";
static constexpr char certificate_footer[] = "-----END CERTIFICATE-----\n";
static constexpr size_t datetime_size = 15;
//***************************************************************************
// Class Method Implementations
//***************************************************************************
CCertificate::CCertificate(const ISecureElement &se, uint32_t keystore_id)
{
mbedtls_x509_crt_init(&crt);
is_loaded = LoadFromSecureElement(se, keystore_id);
}
CCertificate::CCertificate(const uint8_t *crt_der_or_pem, size_t crt_size)
{
mbedtls_x509_crt_init(&crt);
is_loaded = LoadFromDerOrPem(crt_der_or_pem, crt_size);
}
static void GetCurrentDateTime(char datetime[datetime_size], int seconds)
{
time_t rawtime;
struct tm tm_info;
time(&rawtime);
rawtime += seconds;
strftime(datetime, datetime_size, "%Y%m%d%H%M%S",
gmtime_r(&rawtime, &tm_info));
}
CCertificate::CCertificate(const ISecureElement &se,
const uint8_t *csr_der_or_pem, size_t csr_size,
uint32_t keystore_id)
{
mbedtls_x509_crt_init(&crt);
char from_datetime[datetime_size];
char to_datetime[datetime_size];
GetCurrentDateTime(from_datetime, 0);
GetCurrentDateTime(to_datetime, SECONDS_IN_DAY);
is_loaded = LoadFromCsrDerOrPem(se, csr_der_or_pem, csr_size, keystore_id,
from_datetime, to_datetime);
}
CCertificate::CCertificate(const ISecureElement &se,
const uint8_t *csr_der_or_pem, size_t csr_size,
uint32_t keystore_id, const char *from_datetime,
const char *to_datetime)
{
mbedtls_x509_crt_init(&crt);
is_loaded = LoadFromCsrDerOrPem(se, csr_der_or_pem, csr_size, keystore_id,
from_datetime, to_datetime);
}
CCertificate::~CCertificate() { mbedtls_x509_crt_free(&crt); }
bool CCertificate::IsLoaded() const { return is_loaded; }
bool CCertificate::StoreOnSecureElement(const ISecureElement &se,
uint32_t keystore_id) const
{
struct se05x_key_transmission_s args;
args.entry.id = keystore_id;
args.content.buffer = crt.raw.p;
args.content.buffer_size = crt.raw.len;
args.content.buffer_content_size = crt.raw.len;
return se.SetData(args);
}
bool CCertificate::LoadFromSecureElement(const ISecureElement &se,
uint32_t keystore_id)
{
size_t certificate_der_size = 1000;
uint8_t *certificate_der = new uint8_t[certificate_der_size];
struct se05x_key_transmission_s args
= { .entry = { .id = keystore_id },
.content = { .buffer = certificate_der,
.buffer_size = certificate_der_size } };
bool result = se.GetData(args);
if (result)
{
result = 0
== mbedtls_x509_crt_parse(&crt, certificate_der,
args.content.buffer_content_size);
}
delete[] certificate_der;
return result;
}
bool CCertificate::LoadFromDerOrPem(const uint8_t *crt_der_or_pem,
size_t crt_size)
{
return 0 == mbedtls_x509_crt_parse(&crt, crt_der_or_pem, crt_size);
}
bool CCertificate::LoadFromCsrDerOrPem(const ISecureElement &se,
const uint8_t *csr_der_or_pem,
size_t csr_size, uint32_t keystore_id,
const char *from_datetime,
const char *to_datetime)
{
mbedtls_x509_csr csr;
mbedtls_x509_csr_init(&csr);
auto result = 0 == mbedtls_x509_csr_parse(&csr, csr_der_or_pem, csr_size);
mbedtls_x509write_cert crt_builder;
mbedtls_x509write_crt_init(&crt_builder);
char subject_name[200];
if (result)
{
mbedtls_x509write_crt_set_version(&crt_builder,
MBEDTLS_X509_CRT_VERSION_3);
result = 0 < mbedtls_x509_dn_gets(subject_name, sizeof(subject_name),
&csr.subject);
}
mbedtls_pk_context key;
mbedtls_pk_init(&key);
if (result)
{
result = 0
== MbedtlsSe05xExtension::mbedtls_pk_setup_key_se05x(
key, se, keystore_id);
}
mbedtls_pk_context public_key;
public_key.pk_ctx = csr.pk.pk_ctx;
public_key.pk_info = csr.pk.pk_info;
// Invalidate the public key in CSR
// The public key is transferred to CRT so the CSR may not free the memory
csr.pk.pk_ctx = nullptr;
csr.pk.pk_info = nullptr;
mbedtls_x509_csr_free(&csr);
if (result)
{
mbedtls_x509write_crt_set_subject_key(&crt_builder, &public_key);
mbedtls_x509write_crt_set_issuer_key(&crt_builder, &key);
result = 0
== mbedtls_x509write_crt_set_subject_name(&crt_builder,
subject_name);
}
if (result)
{
result = 0
== mbedtls_x509write_crt_set_issuer_name(&crt_builder,
"CN=CA,O=controlse,C=NL");
}
mbedtls_mpi serial;
mbedtls_mpi_init(&serial);
if (result)
{
mbedtls_x509write_crt_set_md_alg(&crt_builder, MBEDTLS_MD_SHA256);
result = 0 == mbedtls_mpi_read_string(&serial, 10, "1");
}
if (result)
{
result = 0 == mbedtls_x509write_crt_set_serial(&crt_builder, &serial);
}
if (result)
{
result = 0
== mbedtls_x509write_crt_set_validity(
&crt_builder, from_datetime, to_datetime);
}
size_t buf_size = 1000;
uint8_t *buf = nullptr;
if (result)
{
buf = new uint8_t[buf_size];
result = buf != nullptr;
}
size_t buf_content_size;
if (result)
{
auto der_result
= mbedtls_x509write_crt_der(&crt_builder, buf, buf_size, nullptr, 0);
buf_content_size = der_result;
result = 0 < der_result;
}
mbedtls_x509write_crt_free(&crt_builder);
MbedtlsSe05xExtension::mbedtls_pk_free_se05x(key);
mbedtls_pk_free(&key);
mbedtls_pk_free(&public_key);
mbedtls_mpi_free(&serial);
if (result)
{
result = LoadFromDerOrPem(buf + buf_size - buf_content_size,
buf_content_size);
}
if (buf)
{
delete[] buf;
}
return result;
}
bool CCertificate::VerifyAgainst(const ISecureElement &se,
uint32_t verify_against_id) const
{
if (!is_loaded)
{
return false;
}
uint8_t tbs_buffer[TBS_HASH_BUFFER_SIZE];
bool result = 0 == mbedtls_sha256(crt.tbs.p, crt.tbs.len, tbs_buffer, 0);
if (result)
{
struct se05x_signature_s verify_args = {
.key_id = verify_against_id,
.algorithm = SE05X_ALGORITHM_SHA256,
.tbs = { .buffer = tbs_buffer,
.buffer_size = sizeof(tbs_buffer),
.buffer_content_size = sizeof(tbs_buffer) },
.signature = { .buffer = crt.sig.p,
.buffer_size = crt.sig.len,
.buffer_content_size = crt.sig.len },
};
result = se.Verify(verify_args);
}
return result;
}
static bool check_time(const mbedtls_x509_time *before,
const mbedtls_x509_time *after)
{
if (before->year > after->year)
return false;
if (before->year == after->year && before->mon > after->mon)
return false;
if (before->year == after->year && before->mon == after->mon
&& before->day > after->day)
return false;
if (before->year == after->year && before->mon == after->mon
&& before->day == after->day && before->hour > after->hour)
return false;
if (before->year == after->year && before->mon == after->mon
&& before->day == after->day && before->hour == after->hour
&& before->min > after->min)
return false;
if (before->year == after->year && before->mon == after->mon
&& before->day == after->day && before->hour == after->hour
&& before->min == after->min && before->sec > after->sec)
return false;
return true;
}
int CCertificate::TestValidTimerange(time_t now) const
{
auto lt = gmtime(&now);
mbedtls_x509_time mbedtls_now;
mbedtls_now.year = lt->tm_year + 1900;
mbedtls_now.mon = lt->tm_mon + 1;
mbedtls_now.day = lt->tm_mday;
mbedtls_now.hour = lt->tm_hour;
mbedtls_now.min = lt->tm_min;
mbedtls_now.sec = lt->tm_sec;
if (!check_time(&mbedtls_now, &crt.valid_to))
{
return -1;
}
if (!check_time(&crt.valid_from, &mbedtls_now))
{
return 1;
}
return 0;
}
CPublicKey *CCertificate::GetPublicKey() const
{
if (!is_loaded)
{
return nullptr;
}
size_t root_key_buf_size = 100;
uint8_t *root_key_buf = new uint8_t[root_key_buf_size];
bool result = false;
if (root_key_buf)
{
mbedtls_ecp_keypair *keypair
= reinterpret_cast<mbedtls_ecp_keypair *>(crt.pk.pk_ctx);
result = 0
== mbedtls_ecp_point_write_binary(
&keypair->grp, &keypair->Q, MBEDTLS_ECP_PF_UNCOMPRESSED,
&root_key_buf_size, root_key_buf, root_key_buf_size);
}
CPublicKey *public_key
= result ? new CPublicKey(root_key_buf, root_key_buf_size) : nullptr;
if (root_key_buf)
{
delete[] root_key_buf;
}
return public_key;
}
char *CCertificate::GetOid(const char *oid) const
{
if (!is_loaded)
{
return nullptr;
}
auto item = mbedtls_asn1_find_named_data(&crt.subject, oid, 3);
if (item)
{
auto data = new char[item->val.len + 1];
memcpy(data, item->val.p, item->val.len);
data[item->val.len] = 0;
return data;
}
return nullptr;
}
CSerialNumber *CCertificate::GetSerialNumber() const
{
if (!is_loaded)
{
return nullptr;
}
if (crt.serial.len == CSerialNumber::SERIAL_NUMBER_SIZE)
{
auto serial = new CSerialNumber(crt.serial.p);
return serial;
}
return nullptr;
}
size_t CCertificate::GetNumberOfSubjectAlternativeNames() const
{
if (!is_loaded)
{
return 0;
}
size_t size = 0;
auto current = &crt.subject_alt_names;
do
{
if (current->buf.tag
== (MBEDTLS_ASN1_CONTEXT_SPECIFIC
| MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER))
{
size++;
}
current = current->next;
}
while (current);
return size;
}
char *CCertificate::GetSubjectAlternativeName(int item) const
{
if (!is_loaded)
{
return nullptr;
}
auto current = &crt.subject_alt_names;
// go to first uri
while (current->buf.tag
!= (MBEDTLS_ASN1_CONTEXT_SPECIFIC
| MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER))
{
current = current->next;
if (current == nullptr)
{
return nullptr;
}
}
// go the next uri until we get to the correct item
for (int i = 0; i < item; i++)
{
do
{
current = current->next;
if (current == nullptr)
{
return nullptr;
}
}
while (current->buf.tag
!= (MBEDTLS_ASN1_CONTEXT_SPECIFIC
| MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER));
}
auto san = new char[current->buf.len + 1];
if (san)
{
memcpy(san, current->buf.p, current->buf.len);
san[current->buf.len] = 0;
}
return san;
}
size_t CCertificate::GetDer(uint8_t **der) const
{
if (!is_loaded)
{
return 0;
}
*der = new uint8_t[crt.raw.len];
memcpy(*der, crt.raw.p, crt.raw.len);
return crt.raw.len;
}
char *CCertificate::GetPem() const
{
if (!is_loaded)
{
return 0;
}
char pem_buf[1000];
size_t pem_content_size;
auto result = mbedtls_pem_write_buffer(
certificate_header, certificate_footer, crt.raw.p, crt.raw.len,
(uint8_t *)pem_buf, sizeof(pem_buf), &pem_content_size);
if (result != 0)
{
return nullptr;
}
auto pem = new char[pem_content_size + 1];
memcpy(pem, pem_buf, pem_content_size);
pem[pem_content_size] = 0;
return pem;
}
bool CCertificate::ContainsSan(const char *name, size_t size) const
{
auto san_amount = GetNumberOfSubjectAlternativeNames();
for (size_t i = 0; i < san_amount; i++)
{
auto san = GetSubjectAlternativeName(i);
if (!san)
{
return false;
}
auto found = (memcmp(name, san, size) == 0);
delete[] san;
if (found)
{
return true;
}
}
return false;
}
} // namespace Controlse

212
crypto/controlse/ccsr.cxx Normal file
View File

@@ -0,0 +1,212 @@
//***************************************************************************
// apps/crypto/controlse/ccsr.cxx
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. The
// ASF licenses this file to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//**************************************************************************
// Copyright 2024 NXP
//***************************************************************************
// Included Files
//***************************************************************************
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
#include "crypto/controlse/ccsr.hxx"
#include "cmbedtls_se05x_extension.hxx"
#include "crypto/controlse/cpublic_key.hxx"
#include "crypto/controlse/csecure_element.hxx"
#include <cstring>
#include <mbedtls/pem.h>
using Controlse::MbedtlsSe05xExtension;
namespace Controlse
{
//***************************************************************************
// Private Data
//***************************************************************************
static const char certificate_request_header[]
= "-----BEGIN CERTIFICATE REQUEST-----\n";
static const char certificate_request_footer[]
= "-----END CERTIFICATE REQUEST-----\n";
//***************************************************************************
// Class Method Implementations
//***************************************************************************
CCsr::CCsr(const ISecureElement &se, uint32_t keystore_id)
{
mbedtls_x509_csr_init(&csr);
is_loaded = LoadFromSecureElement(se, keystore_id);
}
CCsr::CCsr(const uint8_t *der_or_pem, const size_t size)
{
mbedtls_x509_csr_init(&csr);
is_loaded = 0 == mbedtls_x509_csr_parse(&csr, der_or_pem, size);
}
CCsr::~CCsr() { mbedtls_x509_csr_free(&csr); }
bool CCsr::IsLoaded() const { return is_loaded; }
bool CCsr::StoreOnSecureElement(const ISecureElement &se,
uint32_t keystore_id) const
{
struct se05x_key_transmission_s args;
args.entry.id = keystore_id;
args.content.buffer = csr.raw.p;
args.content.buffer_size = csr.raw.len;
args.content.buffer_content_size = csr.raw.len;
return se.SetData(args);
}
bool CCsr::LoadFromSecureElement(const ISecureElement &se,
uint32_t keystore_id)
{
size_t csr_der_size = 1000;
uint8_t *csr_der = new uint8_t[csr_der_size];
struct se05x_key_transmission_s args
= { .entry = { .id = keystore_id },
.content = { .buffer = csr_der, .buffer_size = csr_der_size } };
bool result = se.GetData(args);
if (result)
{
result = 0
== mbedtls_x509_csr_parse(&csr, csr_der,
args.content.buffer_content_size);
}
delete[] csr_der;
return result;
}
size_t CCsr::GetDer(uint8_t **der) const
{
if (!IsLoaded())
{
return 0;
}
*der = new uint8_t[csr.raw.len];
memcpy(*der, csr.raw.p, csr.raw.len);
return csr.raw.len;
}
char *CCsr::GetPem() const
{
if (!IsLoaded())
{
return nullptr;
}
char pem_buf[1000];
size_t pem_content_size;
auto result = mbedtls_pem_write_buffer(
certificate_request_header, certificate_request_footer, csr.raw.p,
csr.raw.len, (uint8_t *)pem_buf, sizeof(pem_buf), &pem_content_size);
if (result != 0)
{
return nullptr;
}
auto pem = new char[pem_content_size + 1];
memcpy(pem, pem_buf, pem_content_size);
pem[pem_content_size] = 0;
return pem;
}
CCsr::CsrBuilder::CsrBuilder(ISecureElement &se, const char *subject,
uint32_t key_slot_id)
{
mbedtls_x509write_csr_init(&csr_w);
mbedtls_pk_init(&key);
ready = 0
== MbedtlsSe05xExtension::mbedtls_pk_setup_key_se05x(key, se,
key_slot_id);
if (ready)
{
mbedtls_x509write_csr_set_key(&csr_w, &key);
ready = 0 == mbedtls_x509write_csr_set_subject_name(&csr_w, subject);
}
if (ready)
{
mbedtls_x509write_csr_set_md_alg(&csr_w, MBEDTLS_MD_SHA256);
ready = 0
== mbedtls_x509write_csr_set_key_usage(
&csr_w, MBEDTLS_X509_KU_KEY_CERT_SIGN);
}
}
CCsr::CsrBuilder *CCsr::CsrBuilder::AddExtension(const char *oid,
size_t oid_size,
const uint8_t *value,
size_t value_size)
{
if (ready)
{
ready = 0
== mbedtls_x509write_csr_set_extension(&csr_w, oid, oid_size, 0,
value, value_size);
}
return this;
}
CCsr *CCsr::CsrBuilder::Build()
{
size_t buf_size = 1000;
uint8_t *buf = nullptr;
if (ready)
{
buf = new uint8_t[buf_size];
ready = nullptr != buf;
}
int write_result_size = 0;
if (ready)
{
write_result_size
= mbedtls_x509write_csr_der(&csr_w, buf, buf_size, nullptr, 0);
ready = write_result_size > 0;
}
MbedtlsSe05xExtension::mbedtls_pk_free_se05x(key);
mbedtls_x509write_csr_free(&csr_w);
CCsr *result_csr = nullptr;
if (ready)
{
result_csr
= new CCsr(buf + buf_size - write_result_size, write_result_size);
}
if (buf)
{
delete[] buf;
}
return result_csr;
}
} // namespace Controlse

View File

@@ -0,0 +1,100 @@
//***************************************************************************
// apps/crypto/controlse/chex_util.cxx
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. The
// ASF licenses this file to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//**************************************************************************
// Copyright 2024 NXP
//***************************************************************************
// Included Files
//***************************************************************************
#include "crypto/controlse/chex_util.hxx"
#include <cstdint>
#include <cstdio>
#include <cstring>
namespace Controlse
{
//***************************************************************************
// Class Method Implementations
//***************************************************************************
size_t CHexUtil::GetByteArraySizeFromHexString(const char *hex_buffer)
{
auto hex_buffer_size = strcspn(hex_buffer, " \r\n");
return GetByteArraySizeFromHexStringSize(hex_buffer_size);
}
size_t CHexUtil::GetByteArraySizeFromHexStringSize(size_t hex_buffer_size)
{
return hex_buffer_size / AMOUNT_OF_HEXDIGITS_PER_BYTE;
}
size_t CHexUtil::GetHexStringSizeFromByteArraySize(size_t byte_array_size)
{
return byte_array_size * AMOUNT_OF_HEXDIGITS_PER_BYTE;
}
uint8_t *CHexUtil::ConvertHexStringToByteArray(const char *hex_buffer)
{
auto hex_buffer_size = strcspn(hex_buffer, " \r\n");
if (hex_buffer_size & 1)
{
return nullptr;
}
return ConvertHexStringToByteArray(hex_buffer, hex_buffer_size);
}
uint8_t *CHexUtil::ConvertHexStringToByteArray(const char *hex_buffer,
size_t hex_buffer_size)
{
auto bin_buffer
= new uint8_t[GetByteArraySizeFromHexStringSize(hex_buffer_size)];
if (bin_buffer)
{
size_t hex_buffer_pos;
size_t bin_buffer_pos = 0;
for (hex_buffer_pos = 0; (hex_buffer_pos < hex_buffer_size);
hex_buffer_pos += AMOUNT_OF_HEXDIGITS_PER_BYTE)
{
sscanf(&hex_buffer[hex_buffer_pos], "%2hhx",
&bin_buffer[bin_buffer_pos]);
bin_buffer_pos++;
}
}
return bin_buffer;
}
char *CHexUtil::ByteArrayToHexString(const uint8_t bytearray[], size_t size)
{
auto string = new char[GetHexStringSizeFromByteArraySize(size) + 1];
if (string)
{
char *ptr = string;
for (size_t i = 0; i < size; i++)
{
ptr += sprintf(ptr, "%02x", bytearray[i]);
}
}
return string;
}
} // namespace Controlse

View File

@@ -0,0 +1,188 @@
//***************************************************************************
// apps/crypto/controlse/cmbedtls_se05x_extensions.hxx
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. The
// ASF licenses this file to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//**************************************************************************
// Copyright 2024 NXP
#pragma once
//***************************************************************************
// Included Files
//***************************************************************************
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
#include "crypto/controlse/cpublic_key.hxx"
#include "crypto/controlse/isecure_element.hxx"
#include <../crypto/mbedtls/mbedtls/library/pk_wrap.h>
#include <cerrno>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/pk.h>
#include <mbedtls/x509_csr.h>
#include <nuttx/crypto/se05x.h>
using Controlse::ISecureElement;
struct mbedtls_se05x_ctx
{
const ISecureElement *se;
uint32_t private_key_slot_id;
};
namespace Controlse
{
//***************************************************************************
// Class definitions
//***************************************************************************
class MbedtlsSe05xExtension
{
public:
static int mbedtls_pk_parse_se05x_public_key(mbedtls_pk_context &key,
CPublicKey &se05x_key)
{
mbedtls_ecp_keypair *keypair;
uint8_t *key_buffer = nullptr;
size_t key_buffer_size = 0;
if (se05x_key.IsLoaded())
{
key_buffer_size = se05x_key.GetRawSize();
key_buffer = new uint8_t[key_buffer_size];
keypair = (mbedtls_ecp_keypair *)key.pk_ctx;
}
int result = -ENOMEM;
if (key_buffer)
{
se05x_key.GetRaw(key_buffer);
result
= mbedtls_ecp_group_load(&keypair->grp, MBEDTLS_ECP_DP_SECP256R1);
}
if (result == 0)
{
result = mbedtls_ecp_point_read_binary(&keypair->grp, &keypair->Q,
key_buffer, key_buffer_size);
}
if (key_buffer)
{
delete[] key_buffer;
}
return result;
}
static int ecdsa_sign_wrap(void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t sig_size,
size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
{
mbedtls_ecp_keypair *key = reinterpret_cast<mbedtls_ecp_keypair *>(ctx);
auto se05x_ctx = reinterpret_cast<mbedtls_se05x_ctx *>(key->d.p);
struct se05x_signature_s args
= { se05x_ctx->private_key_slot_id,
SE05X_ALGORITHM_SHA256,
{ const_cast<uint8_t *>(hash), hash_len, hash_len },
{ sig, sig_size, sig_size } };
auto result = se05x_ctx->se->CreateSignature(args);
if (result)
{
*sig_len = args.signature.buffer_content_size;
}
return result ? 0 : -EPERM;
}
// return value is allocated ptr to mbedtls_pk_info_t (need to be deleted)
// otherwise nulltpr
static mbedtls_pk_info_t *CreatePkInfoSe05x()
{
auto info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY);
auto se05x_ec_info = new mbedtls_pk_info_t;
if (se05x_ec_info)
{
*se05x_ec_info = *info;
se05x_ec_info->sign_func = ecdsa_sign_wrap;
}
return se05x_ec_info;
}
static int mbedtls_pk_setup_key_se05x(mbedtls_pk_context &key,
const ISecureElement &se,
uint32_t key_slot_id)
{
auto se05x_ec_info = CreatePkInfoSe05x();
if (se05x_ec_info)
{
key.pk_info = se05x_ec_info;
key.pk_ctx = se05x_ec_info->ctx_alloc_func();
}
int result = -ENOMEM;
if (key.pk_ctx)
{
auto se05x_key = CPublicKey(se, key_slot_id);
result = mbedtls_pk_parse_se05x_public_key(key, se05x_key);
}
mbedtls_se05x_ctx *se05x_ctx = nullptr;
if (result == 0)
{
se05x_ctx = new mbedtls_se05x_ctx;
result = se05x_ctx ? 0 : -ENOMEM;
}
if (result == 0)
{
se05x_ctx->private_key_slot_id = key_slot_id;
se05x_ctx->se = &se;
}
((mbedtls_ecp_keypair *)key.pk_ctx)->d.p
= reinterpret_cast<mbedtls_mpi_uint *>(se05x_ctx);
return result;
}
static void mbedtls_pk_free_se05x(mbedtls_pk_context &key)
{
auto key_ctx = reinterpret_cast<mbedtls_ecp_keypair *>(key.pk_ctx);
if (key_ctx)
{
auto se05x_ctx = reinterpret_cast<mbedtls_se05x_ctx *>(key_ctx->d.p);
if (se05x_ctx)
{
delete se05x_ctx;
key_ctx->d.p = nullptr;
}
}
auto pk_info = key.pk_info;
if (pk_info)
{
mbedtls_pk_free(&key);
delete pk_info;
}
}
};
} // namespace Controlse

View File

@@ -1,737 +0,0 @@
/****************************************************************************
* apps/crypto/controlse/controlse_main.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/* Copyright 2023 NXP */
/****************************************************************************
* Included Files
****************************************************************************/
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
#include <mbedtls/sha256.h>
#include <mbedtls/x509_crt.h>
#include <mbedtls/x509_csr.h>
#include <nuttx/config.h>
#include <nuttx/crypto/se05x.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#ifdef CONFIG_STACK_COLORATION
#include <nuttx/arch.h>
#include <nuttx/sched.h>
#endif
#include "x509_utils.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define EOT 0x04
#define DEFAULT_SETTINGS \
{ \
.se05x_dev_filename = default_se05x_device, 0 \
}
#define TBS_HASH_BUFFER_SIZE 32
#define SIGNATURE_BUFFER_SIZE 300
#define SYMM_KEY_BUFFER_SIZE 300
#define RAW_KEY_BUFFER_SIZE 600
#define DEFAULT_BUFFER_SIZE 1000
/****************************************************************************
* Private Types
****************************************************************************/
typedef enum
{
KEYSTORE_NO_ACTION = 0,
KEYSTORE_READ,
KEYSTORE_WRITE,
KEYSTORE_GENERATE,
KEYSTORE_DELETE,
KEYSTORE_DERIVE_SYMM_KEY,
KEYSTORE_CREATE_SIGNATURE,
KEYSTORE_VERIFY_SIGNATURE,
KEYSTORE_SIGN_CSR,
KEYSTORE_VERIFY_CERTIFICATE,
KEYSTORE_GET_INFO,
KEYSTORE_GET_UID,
} keystore_operation;
struct settings_t
{
FAR const char *se05x_dev_filename;
FAR char *input_filename;
FAR char *signature_filename;
bool skip_process;
keystore_operation operation;
bool raw_data_in_device;
bool interface_with_pem;
uint32_t key_id;
uint32_t private_key_id;
bool show_stack_used;
};
/****************************************************************************
* Private Function Prototypes
****************************************************************************/
/****************************************************************************
* Private Data
****************************************************************************/
static const char default_se05x_device[] = "/dev/se05x";
static const char enter_key_hex[] = "enter key(hex)";
static const char enter_data_pem[] = "enter data(pem)";
static const char enter_data_raw[] = "enter data(raw)";
/****************************************************************************
* Public Data
****************************************************************************/
/****************************************************************************
* Private Functions
****************************************************************************/
static void print_usage(FAR FILE *f, FAR char *prg)
{
fprintf(f, "%s - Control SE05x Secure Element\n", prg);
fprintf(f, "\nUsage: %s [options] <secure element device>\n", prg);
fprintf(f, "Options:\n");
fprintf(f, " -r <id> (read item from keystore at <id>)\n");
fprintf(f, " -w <id> (set item in keystore at <id>)\n");
fprintf(f, " -g <id> (generate keypair at <id>)\n");
fprintf(f, " -d <id> (delete key at <id>)\n");
fprintf(f, " -s <id> (create signature for data\n");
fprintf(f, " with key at <id>)\n");
fprintf(f, " -S <id> (Sign CSR with key at <id>)\n");
fprintf(f, " -v <id> (verify signature for data\n");
fprintf(f, " with key at <id>)\n");
fprintf(f, " -V <id> (verify CRT with key at <id>\n");
fprintf(f, " -a <id> (derive symm key\n");
fprintf(f, " from public key <id>\n");
fprintf(f, " and private key)\n");
fprintf(f, " -t (interface using raw data\n");
fprintf(f, " use with -r, -w)\n");
fprintf(f, " -c (interface with PEM format\n");
fprintf(f, " internally using DER\n");
fprintf(f, " use with -r, -w)\n");
fprintf(f, " -p <id> (select private key\n");
fprintf(f, " use with -a)\n");
fprintf(f, " -n <file> (Read input from file)\n");
fprintf(f, " -N <file> (Read signature from file)\n");
fprintf(f, " -i (show generic information)\n");
fprintf(f, " -u (show UID)\n");
fprintf(f, " -m (show used stack memory space)\n");
fprintf(f, " -h (show this help)\n");
fprintf(f, "\n");
}
static int set_operation(FAR struct settings_t *settings,
keystore_operation operation, FAR char *key_id_text)
{
int result = -EPERM;
if (settings->operation == KEYSTORE_NO_ACTION)
{
settings->operation = operation;
settings->key_id = 0;
if (key_id_text != NULL)
{
settings->key_id = (uint32_t)strtoul(key_id_text, NULL, 0);
}
result = 0;
}
return result;
}
static int parse_arguments(int argc, FAR char *argv[],
FAR struct settings_t *settings)
{
int result = 0;
int opt;
FAR char *prg = basename(argv[0]);
while (
((opt = getopt(argc, argv, "iug:w:r:d:s:v:S:V:tca:p:n:N:mh")) != -1) &&
(result == 0))
{
switch (opt)
{
case 'i':
result = set_operation(settings, KEYSTORE_GET_INFO, optarg);
break;
case 'u':
result = set_operation(settings, KEYSTORE_GET_UID, optarg);
break;
case 'g':
result = set_operation(settings, KEYSTORE_GENERATE, optarg);
break;
case 'r':
result = set_operation(settings, KEYSTORE_READ, optarg);
break;
case 'w':
result = set_operation(settings, KEYSTORE_WRITE, optarg);
break;
case 't':
settings->raw_data_in_device = TRUE;
break;
case 'c':
settings->interface_with_pem = TRUE;
settings->raw_data_in_device = TRUE;
break;
case 'd':
result = set_operation(settings, KEYSTORE_DELETE, optarg);
break;
case 's':
result =
set_operation(settings, KEYSTORE_CREATE_SIGNATURE, optarg);
break;
case 'v':
result =
set_operation(settings, KEYSTORE_VERIFY_SIGNATURE, optarg);
break;
case 'S':
result = set_operation(settings, KEYSTORE_SIGN_CSR, optarg);
break;
case 'V':
result =
set_operation(settings, KEYSTORE_VERIFY_CERTIFICATE, optarg);
break;
case 'a':
result = set_operation(settings, KEYSTORE_DERIVE_SYMM_KEY, optarg);
break;
case 'p':
settings->private_key_id = (uint32_t)strtoul(optarg, NULL, 0);
break;
case 'n':
settings->input_filename = optarg;
break;
case 'N':
settings->signature_filename = optarg;
break;
case 'm':
settings->show_stack_used = TRUE;
break;
case 'h':
print_usage(stdout, prg);
settings->skip_process = TRUE;
break;
default:
print_usage(stderr, prg);
result = -EINVAL;
break;
}
}
if ((result == 0) && (!settings->skip_process))
{
if (settings->operation == KEYSTORE_NO_ACTION)
{
print_usage(stderr, prg);
result = -EINVAL;
}
/* if device is specified as positional argument */
if (optind != argc)
{
settings->se05x_dev_filename = argv[optind];
}
}
return result;
}
static int convert_array_hex_to_bin(FAR char *hex_buffer,
size_t hex_buffer_size,
FAR uint8_t *bin_buffer,
size_t bin_buffer_size,
FAR size_t *bin_buffer_content_size)
{
hex_buffer_size = strcspn(hex_buffer, " \r\n");
if (hex_buffer_size & 1)
{
return -1;
}
*bin_buffer_content_size = 0;
size_t hex_buffer_pos;
for (hex_buffer_pos = 0; (hex_buffer_pos < hex_buffer_size) &&
(*bin_buffer_content_size < bin_buffer_size);
hex_buffer_pos += 2)
{
sscanf(&hex_buffer[hex_buffer_pos], "%2hhx",
&bin_buffer[*bin_buffer_content_size]);
(*bin_buffer_content_size)++;
}
return hex_buffer_pos == hex_buffer_size ? 0 : -1;
}
static int read_from_file(FAR const char *prompt, FAR char *filename,
FAR char *buffer, size_t buffer_size)
{
FAR FILE *f = stdin;
if (filename != NULL)
{
f = fopen(filename, "r");
}
else
{
puts(prompt);
}
size_t buffer_content_size = 0;
if (f != NULL)
{
FAR char *c = buffer;
int result = fgetc(f);
while ((result != EOF) && (result != EOT) &&
(buffer_content_size < buffer_size))
{
*c = result & 0xff;
c++;
buffer_content_size++;
result = fgetc(f);
}
}
if (filename != NULL)
{
fclose(f);
}
return buffer_content_size;
}
static int read_from_file_and_convert(FAR const char *prompt,
FAR char *filename,
FAR uint8_t *buffer,
size_t buffer_size,
FAR size_t *buffer_content_size)
{
char file_buffer[DEFAULT_BUFFER_SIZE];
size_t file_buffer_content_size;
int result;
file_buffer_content_size = read_from_file(
prompt, filename, (FAR char *)file_buffer, sizeof(file_buffer));
result = convert_array_hex_to_bin(file_buffer, file_buffer_content_size,
buffer, buffer_size, buffer_content_size
);
return result;
}
static size_t add_zero_termination_character(char *data, size_t content_size,
size_t buf_size)
{
size_t zero_termination_char_position = content_size - 1;
if ((content_size + 1) <= buf_size)
{
zero_termination_char_position = content_size;
content_size++;
}
data[zero_termination_char_position] = 0;
return content_size;
}
static int process(int se05x_fd, FAR struct settings_t *settings)
{
int result = 0;
if (settings->operation == KEYSTORE_GET_INFO)
{
struct se05x_info_s info;
result = ioctl(se05x_fd, SEIOC_GET_INFO, &info);
if (result == 0)
{
printf("OEF ID: %04x\n", info.oef_id);
}
}
else if (settings->operation == KEYSTORE_GET_UID)
{
struct se05x_uid_s uid;
result = ioctl(se05x_fd, SEIOC_GET_UID, &uid);
if (result == 0)
{
printf("UID: ");
for (size_t i = 0; i < SE05X_MODULE_UNIQUE_ID_LEN; i++)
{
printf("%02x", uid.uid[i]);
}
printf("\n");
}
}
else if (settings->operation == KEYSTORE_GENERATE)
{
struct se05x_generate_keypair_s args = {
.id = settings->key_id, .cipher = SE05X_ASYM_CIPHER_EC_NIST_P_256
};
result = ioctl(se05x_fd, SEIOC_GENERATE_KEYPAIR, &args);
if (result == 0)
{
printf("Keypair generated successfully\n");
}
}
else if (settings->operation == KEYSTORE_WRITE)
{
char pem_buf[DEFAULT_BUFFER_SIZE];
FAR const char *prompt = enter_key_hex;
if (settings->raw_data_in_device)
{
prompt =
settings->interface_with_pem ? enter_data_pem : enter_data_raw;
}
size_t pem_content_size = read_from_file(
prompt, settings->input_filename, pem_buf, sizeof(pem_buf));
uint8_t rawkey[RAW_KEY_BUFFER_SIZE];
size_t rawkey_size = sizeof(rawkey);
FAR uint8_t *data = (FAR uint8_t *)pem_buf;
size_t data_size = pem_content_size;
if (!settings->raw_data_in_device)
{
result = convert_public_key_pem_to_raw(rawkey, rawkey_size,
&rawkey_size, pem_buf);
if (result == 0)
{
data = rawkey;
data_size = rawkey_size;
}
}
if (settings->interface_with_pem)
{
pem_content_size = add_zero_termination_character(
pem_buf, pem_content_size, sizeof(pem_buf));
result = convert_pem_certificate_or_csr_to_der(
rawkey, rawkey_size, &rawkey_size, pem_buf, pem_content_size);
if (result == 0)
{
data = rawkey;
data_size = rawkey_size;
}
}
if (result == 0)
{
struct se05x_key_transmission_s args = {
.entry = {.id = settings->key_id,
.cipher = SE05X_ASYM_CIPHER_EC_NIST_P_256},
.content = {.buffer = data,
.buffer_size = data_size,
.buffer_content_size = data_size}
};
result = ioctl(se05x_fd,
settings->raw_data_in_device ? SEIOC_SET_DATA
: SEIOC_SET_KEY,
&args);
}
if (result == 0)
{
printf("Data stored successfully\n");
}
}
else if (settings->operation == KEYSTORE_READ)
{
uint8_t buffer[DEFAULT_BUFFER_SIZE];
struct se05x_key_transmission_s args = {
.entry = {.id = settings->key_id},
.content = {.buffer = buffer, .buffer_size = sizeof(buffer)}
};
result =
ioctl(se05x_fd,
settings->raw_data_in_device ? SEIOC_GET_DATA : SEIOC_GET_KEY,
&args);
FAR char *data = (FAR char *)args.content.buffer;
if ((result == 0)
&& settings->raw_data_in_device
&& !settings->interface_with_pem)
{
args.content.buffer_content_size = add_zero_termination_character(
data, args.content.buffer_content_size,
args.content.buffer_size);
}
char pem_buf[DEFAULT_BUFFER_SIZE];
if ((result == 0) && !settings->raw_data_in_device)
{
result = convert_public_key_raw_to_pem(
pem_buf, sizeof(pem_buf), args.content.buffer,
args.content.buffer_content_size);
data = pem_buf;
}
if ((result == 0) && settings->interface_with_pem)
{
size_t pem_content_size;
result = convert_der_certificate_or_csr_to_pem(
pem_buf, sizeof(pem_buf), &pem_content_size,
args.content.buffer, args.content.buffer_content_size);
data = pem_buf;
}
if (result == 0)
{
puts(data);
}
}
else if (settings->operation == KEYSTORE_DELETE)
{
result = ioctl(se05x_fd, SEIOC_DELETE_KEY, settings->key_id);
if (result == 0)
{
printf("Deleted key successfully\n");
}
}
else if (settings->operation == KEYSTORE_DERIVE_SYMM_KEY)
{
uint8_t buffer[SYMM_KEY_BUFFER_SIZE];
struct se05x_derive_key_s args = {
.private_key_id = settings->private_key_id,
.public_key_id = settings->key_id,
.content = {.buffer = buffer, .buffer_size = sizeof(buffer)},
};
result = ioctl(se05x_fd, SEIOC_DERIVE_SYMM_KEY, &args);
if (result == 0)
{
for (size_t i = 0; i < args.content.buffer_content_size; i++)
{
printf("%02x", args.content.buffer[i]);
}
printf("\n");
}
}
else if (settings->operation == KEYSTORE_CREATE_SIGNATURE)
{
uint8_t tbs_buffer[TBS_HASH_BUFFER_SIZE];
size_t tbs_content_size;
read_from_file_and_convert("Enter tbs(hex):", settings->input_filename,
tbs_buffer, sizeof(tbs_buffer),
&tbs_content_size);
uint8_t signature_buffer[SIGNATURE_BUFFER_SIZE];
size_t signature_content_len = 0;
if (result == 0)
{
struct se05x_signature_s args = {
.key_id = settings->key_id,
.algorithm = SE05X_ALGORITHM_SHA256,
.tbs = {.buffer = tbs_buffer,
.buffer_size = tbs_content_size,
.buffer_content_size = tbs_content_size},
.signature = {.buffer = signature_buffer,
.buffer_size = sizeof(signature_buffer)},
};
result = ioctl(se05x_fd, SEIOC_CREATE_SIGNATURE, &args);
signature_content_len = args.signature.buffer_content_size;
}
if (result == 0)
{
for (size_t i = 0; i < signature_content_len; i++)
{
printf("%02x", signature_buffer[i]);
}
printf("\n");
}
}
else if (settings->operation == KEYSTORE_VERIFY_SIGNATURE)
{
uint8_t tbs_buffer[TBS_HASH_BUFFER_SIZE];
size_t tbs_content_size;
result = read_from_file_and_convert(
"Enter tbs(hex):", settings->input_filename, tbs_buffer,
sizeof(tbs_buffer), &tbs_content_size);
uint8_t signature_buffer[SIGNATURE_BUFFER_SIZE];
size_t signature_content_size;
if (result == 0)
{
result = read_from_file_and_convert(
"Enter signature(hex):", settings->signature_filename,
signature_buffer, sizeof(signature_buffer),
&signature_content_size);
}
if (result == 0)
{
struct se05x_signature_s args = {
.key_id = settings->key_id,
.algorithm = SE05X_ALGORITHM_SHA256,
.tbs = {.buffer = tbs_buffer,
.buffer_size = tbs_content_size,
.buffer_content_size = tbs_content_size},
.signature = {.buffer = signature_buffer,
.buffer_size = signature_content_size,
.buffer_content_size = signature_content_size},
};
result = ioctl(se05x_fd, SEIOC_VERIFY_SIGNATURE, &args);
}
if (result == 0)
{
printf("Signature verified successfully\n");
}
}
else if (settings->operation == KEYSTORE_SIGN_CSR)
{
char csr_pem_buf[DEFAULT_BUFFER_SIZE];
size_t csr_pem_buf_content_size =
read_from_file("enter csr(pem)", settings->input_filename,
csr_pem_buf, sizeof(csr_pem_buf));
csr_pem_buf_content_size = add_zero_termination_character(csr_pem_buf,
csr_pem_buf_content_size, sizeof(csr_pem_buf));
char crt_pem_buf[DEFAULT_BUFFER_SIZE];
result = sign_csr(se05x_fd, settings->key_id, crt_pem_buf,
sizeof(crt_pem_buf), csr_pem_buf,
csr_pem_buf_content_size);
if (result == 0)
{
puts(crt_pem_buf);
}
}
else if (settings->operation == KEYSTORE_VERIFY_CERTIFICATE)
{
char pem_buf[DEFAULT_BUFFER_SIZE];
size_t pem_content_size =
read_from_file("enter crt(pem)", settings->input_filename, pem_buf,
sizeof(pem_buf));
pem_content_size = add_zero_termination_character(pem_buf,
pem_content_size, sizeof(pem_buf));
mbedtls_x509_crt crt;
mbedtls_x509_crt_init(&crt);
result = mbedtls_x509_crt_parse(&crt, (FAR uint8_t *)pem_buf,
pem_content_size);
uint8_t tbs_buffer[TBS_HASH_BUFFER_SIZE];
if (result == 0)
{
result = mbedtls_sha256(crt.tbs.p,
crt.tbs.len, tbs_buffer, 0
);
}
if (result == 0)
{
struct se05x_signature_s args = {
.key_id = settings->key_id,
.algorithm = SE05X_ALGORITHM_SHA256,
.tbs = {.buffer = tbs_buffer,
.buffer_size = sizeof(tbs_buffer),
.buffer_content_size = sizeof(tbs_buffer)},
.signature = {.buffer = crt.sig.p,
.buffer_size = crt.sig.len,
.buffer_content_size =
crt.sig.len},
};
result = ioctl(se05x_fd, SEIOC_VERIFY_SIGNATURE, &args);
}
if (result == 0)
{
printf("Signature verified successfully\n");
}
mbedtls_x509_crt_free(&crt);
}
return result;
}
/****************************************************************************
* Public Functions
****************************************************************************/
int main(int argc, FAR char *argv[])
{
struct settings_t settings = DEFAULT_SETTINGS;
int result = parse_arguments(argc, argv, &settings);
if ((result == 0) && (!settings.skip_process))
{
int fd = open(settings.se05x_dev_filename, O_RDONLY);
if (fd == -1)
{
result = -ENODEV;
}
else
{
result = process(fd, &settings);
close(fd);
}
}
if (result != 0)
{
fprintf(stderr, "err %i: %s\n", -result, strerror(-result));
}
if (settings.show_stack_used)
{
#ifdef CONFIG_STACK_COLORATION
FAR struct tcb_s *tcb;
tcb = nxsched_get_tcb(getpid());
fprintf(stderr, "\nStack used: %zu / %zu\n",
up_check_tcbstack(tcb), tcb->adj_stack_size);
#else
fprintf(stderr, "\nStack used: unknown"
" (STACK_COLORATION must be enabled)\n");
#endif
}
return result == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}

View File

@@ -0,0 +1,711 @@
//***************************************************************************
// apps/crypto/controlse/controlse_main.cxx
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. The
// ASF licenses this file to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//**************************************************************************
// Copyright 2023, 2024 NXP
//***************************************************************************
// Included Files
//***************************************************************************
#include "crypto/controlse/ccertificate.hxx"
#include "crypto/controlse/ccsr.hxx"
#include "crypto/controlse/chex_util.hxx"
#include "crypto/controlse/cpublic_key.hxx"
#include "crypto/controlse/csecure_element.hxx"
#include "crypto/controlse/cstring.hxx"
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <nuttx/config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#ifdef CONFIG_STACK_COLORATION
#include <nuttx/arch.h>
#include <nuttx/sched.h>
#endif
//***************************************************************************
// Pre-processor Definitions
//**************************************************************************
#define EOT 0x04
#define DEFAULT_SETTINGS \
{ \
.se05x_dev_filename = default_se05x_device, 0 \
}
#define TBS_HASH_BUFFER_SIZE 32
#define SIGNATURE_BUFFER_SIZE 300
#define SYMM_KEY_BUFFER_SIZE 300
#define RAW_KEY_BUFFER_SIZE 600
#define DEFAULT_BUFFER_SIZE 1000
//***************************************************************************
// Private Types
//**************************************************************************
typedef enum
{
KEYSTORE_NO_ACTION = 0,
KEYSTORE_READ,
KEYSTORE_WRITE,
KEYSTORE_GENERATE,
KEYSTORE_DELETE,
KEYSTORE_DERIVE_SYMM_KEY,
KEYSTORE_CREATE_SIGNATURE,
KEYSTORE_VERIFY_SIGNATURE,
KEYSTORE_SIGN_CSR,
KEYSTORE_VERIFY_CERTIFICATE,
KEYSTORE_GET_INFO,
KEYSTORE_GET_UID,
} EKeystoreOperation;
typedef enum
{
KEYSTORE_DATA_TYPE_KEY = 0,
KEYSTORE_DATA_TYPE_CERT_OR_CSR,
KEYSTORE_DATA_TYPE_STRING,
} EKeystoreDataType;
struct SSettings
{
FAR const char *se05x_dev_filename;
FAR char *input_filename;
FAR char *signature_filename;
bool skip_process;
EKeystoreOperation operation;
EKeystoreDataType data_type;
uint32_t key_id;
uint32_t private_key_id;
bool show_stack_used;
};
//***************************************************************************
// Private Function Prototypes
//**************************************************************************
extern "C" int main(int argc, FAR char *argv[]);
//***************************************************************************
// Private Data
//**************************************************************************
static const char default_se05x_device[] = "/dev/se05x";
static const char enter_key_hex[] = "enter key(hex)";
static const char enter_data_pem[] = "enter data(pem)";
static const char enter_data_raw[] = "enter data(raw)";
//***************************************************************************
// Public Data
//**************************************************************************
//***************************************************************************
// Private Functions
//**************************************************************************
static void printUsage(FAR FILE *f, FAR char *prg)
{
fprintf(f, "%s - Control SE05x Secure Element\n", prg);
fprintf(f, "\nUsage: %s [options] <secure element device>\n", prg);
fprintf(f, "Options:\n");
fprintf(f, " -r <id> (read item from keystore at <id>)\n");
fprintf(f, " -w <id> (set item in keystore at <id>)\n");
fprintf(f, " -g <id> (generate keypair at <id>)\n");
fprintf(f, " -d <id> (delete key at <id>)\n");
fprintf(f, " -s <id> (create signature for data\n");
fprintf(f, " with key at <id>)\n");
fprintf(f, " -S <id> (Sign CSR with key at <id>)\n");
fprintf(f, " -v <id> (verify signature for data\n");
fprintf(f, " with key at <id>)\n");
fprintf(f, " -V <id> (verify CRT with key at <id>\n");
fprintf(f, " -a <id> (derive symm key\n");
fprintf(f, " from public key <id>\n");
fprintf(f, " and private key)\n");
fprintf(f, " -t (interface using raw data\n");
fprintf(f, " use with -r, -w)\n");
fprintf(f, " -c (interface with PEM format\n");
fprintf(f, " internally using DER\n");
fprintf(f, " use with -r, -w)\n");
fprintf(f, " -p <id> (select private key\n");
fprintf(f, " use with -a)\n");
fprintf(f, " -n <file> (Read input from file)\n");
fprintf(f, " -N <file> (Read signature from file)\n");
fprintf(f, " -i (show generic information)\n");
fprintf(f, " -u (show UID)\n");
fprintf(f, " -m (show used stack memory space)\n");
fprintf(f, " -h (show this help)\n");
fprintf(f, "\n");
}
static int setOperation(FAR struct SSettings *settings,
EKeystoreOperation operation, FAR char *key_id_text)
{
int result = -EPERM;
if (settings->operation == KEYSTORE_NO_ACTION)
{
settings->operation = operation;
settings->key_id = 0;
if (key_id_text != NULL)
{
settings->key_id = (uint32_t)strtoul(key_id_text, NULL, 0);
}
result = 0;
}
return result;
}
static int parseArguments(int argc, FAR char *argv[],
FAR struct SSettings *settings)
{
int result = 0;
int opt;
FAR char *prg = basename(argv[0]);
while (((opt = getopt(argc, argv, "iug:w:r:d:s:v:S:V:tca:p:n:N:mh")) != -1)
&& (result == 0))
{
switch (opt)
{
case 'i':
result = setOperation(settings, KEYSTORE_GET_INFO, optarg);
break;
case 'u':
result = setOperation(settings, KEYSTORE_GET_UID, optarg);
break;
case 'g':
result = setOperation(settings, KEYSTORE_GENERATE, optarg);
break;
case 'r':
result = setOperation(settings, KEYSTORE_READ, optarg);
break;
case 'w':
result = setOperation(settings, KEYSTORE_WRITE, optarg);
break;
case 't':
settings->data_type = KEYSTORE_DATA_TYPE_STRING;
break;
case 'c':
settings->data_type = KEYSTORE_DATA_TYPE_CERT_OR_CSR;
break;
case 'd':
result = setOperation(settings, KEYSTORE_DELETE, optarg);
break;
case 's':
result = setOperation(settings, KEYSTORE_CREATE_SIGNATURE, optarg);
break;
case 'v':
result = setOperation(settings, KEYSTORE_VERIFY_SIGNATURE, optarg);
break;
case 'S':
result = setOperation(settings, KEYSTORE_SIGN_CSR, optarg);
break;
case 'V':
result = setOperation(settings, KEYSTORE_VERIFY_CERTIFICATE, optarg);
break;
case 'a':
result = setOperation(settings, KEYSTORE_DERIVE_SYMM_KEY, optarg);
break;
case 'p':
settings->private_key_id = (uint32_t)strtoul(optarg, NULL, 0);
break;
case 'n':
settings->input_filename = optarg;
break;
case 'N':
settings->signature_filename = optarg;
break;
case 'm':
settings->show_stack_used = TRUE;
break;
case 'h':
printUsage(stdout, prg);
settings->skip_process = TRUE;
break;
default:
printUsage(stderr, prg);
result = -EINVAL;
break;
}
}
if ((result == 0) && (!settings->skip_process))
{
if (settings->operation == KEYSTORE_NO_ACTION)
{
printUsage(stderr, prg);
result = -EINVAL;
}
// if device is specified as positional argument
if (optind != argc)
{
settings->se05x_dev_filename = argv[optind];
}
}
return result;
}
// TODO: use chexutil
static int convert_array_hex_to_bin(FAR char *hex_buffer,
size_t hex_buffer_size,
FAR uint8_t *bin_buffer,
size_t bin_buffer_size,
FAR size_t *bin_buffer_content_size)
{
hex_buffer_size = strcspn(hex_buffer, " \r\n");
if (hex_buffer_size & 1)
{
return -1;
}
*bin_buffer_content_size = 0;
size_t hex_buffer_pos;
for (hex_buffer_pos = 0; (hex_buffer_pos < hex_buffer_size)
&& (*bin_buffer_content_size < bin_buffer_size);
hex_buffer_pos += 2)
{
sscanf(&hex_buffer[hex_buffer_pos], "%2hhx",
&bin_buffer[*bin_buffer_content_size]);
(*bin_buffer_content_size)++;
}
return hex_buffer_pos == hex_buffer_size ? 0 : -1;
}
static int readFromFile(FAR const char *prompt, FAR char *filename,
FAR char *buffer, size_t buffer_size)
{
FAR FILE *f = stdin;
if (filename != NULL)
{
f = fopen(filename, "r");
}
else
{
puts(prompt);
}
size_t buffer_content_size = 0;
if (f != NULL)
{
FAR char *c = buffer;
int result = fgetc(f);
// keep looping until EOF or EOT are received or the buffer has only 1
// space left (needed for the zero termination character)
while ((result != EOF) && (result != EOT)
&& ((buffer_content_size + 1) < buffer_size))
{
*c = result & 0xff;
c++;
buffer_content_size++;
result = fgetc(f);
}
// Add zero termination character
*c = 0;
buffer_content_size++;
}
puts("\n");
if (filename != NULL)
{
fclose(f);
}
return buffer_content_size;
}
static int readFromFileAndConvert(FAR const char *prompt, FAR char *filename,
FAR uint8_t *buffer, size_t buffer_size,
FAR size_t *buffer_content_size)
{
char file_buffer[DEFAULT_BUFFER_SIZE];
size_t file_buffer_content_size;
int result;
file_buffer_content_size = readFromFile(
prompt, filename, (FAR char *)file_buffer, sizeof(file_buffer));
result = convert_array_hex_to_bin(file_buffer, file_buffer_content_size,
buffer, buffer_size, buffer_content_size);
return result;
}
static size_t addZeroTerminationCharacter(char *data, size_t content_size,
size_t buf_size)
{
size_t zero_termination_char_position = content_size - 1;
if ((content_size + 1) <= buf_size)
{
zero_termination_char_position = content_size;
content_size++;
}
data[zero_termination_char_position] = 0;
return content_size;
}
static int process(int se05x_fd, FAR struct SSettings *settings)
{
int result = 0;
Controlse::CSecureElement se(se05x_fd);
if (settings->operation == KEYSTORE_GET_INFO)
{
struct se05x_info_s info;
result = se.GetInfo(info) ? 0 : -EPERM;
if (result == 0)
{
printf("OEF ID: %04x\n", info.oef_id);
}
}
else if (settings->operation == KEYSTORE_GET_UID)
{
struct se05x_uid_s uid;
result = se.GetUid(uid) ? 0 : -EPERM;
if (result == 0)
{
printf("UID: ");
for (size_t i = 0; i < SE05X_MODULE_UNIQUE_ID_LEN; i++)
{
printf("%02x", uid.uid[i]);
}
printf("\n");
}
}
else if (settings->operation == KEYSTORE_GENERATE)
{
struct se05x_generate_keypair_s args
= { .id = settings->key_id,
.cipher = SE05X_ASYM_CIPHER_EC_NIST_P_256 };
result = se.GenerateKey(args) ? 0 : -EPERM;
if (result == 0)
{
printf("Keypair generated successfully\n");
}
}
else if (settings->operation == KEYSTORE_WRITE)
{
char data[DEFAULT_BUFFER_SIZE];
FAR const char *prompt = settings->data_type == KEYSTORE_DATA_TYPE_STRING
? enter_data_raw
: enter_data_pem;
size_t data_size
= readFromFile(prompt, settings->input_filename, data, sizeof(data));
result = -EINVAL;
if (data_size != 0)
{
Controlse::ISecureElementObject *object = nullptr;
if (settings->data_type == KEYSTORE_DATA_TYPE_STRING)
{
object = new Controlse::CString(
data,
data_size - 1); // -1 because no zero termination character
// required
}
else if (settings->data_type == KEYSTORE_DATA_TYPE_KEY)
{
object = new Controlse::CPublicKey(data);
}
else if (settings->data_type == KEYSTORE_DATA_TYPE_CERT_OR_CSR)
{
object = new Controlse::CCertificate(
reinterpret_cast<uint8_t *>(data), data_size);
if (object)
{
if (!object->IsLoaded())
{
delete object;
object = new Controlse::CCsr(
reinterpret_cast<uint8_t *>(data), data_size);
}
}
}
result = -EPERM;
if (object)
{
if (object->IsLoaded())
{
result = object->StoreOnSecureElement(se, settings->key_id)
? 0
: -EPERM;
}
delete object;
}
}
if (result == 0)
{
printf("Data stored successfully\n");
}
}
else if (settings->operation == KEYSTORE_READ)
{
char *data = nullptr;
if (settings->data_type == KEYSTORE_DATA_TYPE_STRING)
{
Controlse::CString string(se, settings->key_id);
if (string.IsLoaded())
{
data = string.c_str();
}
}
else if (settings->data_type == KEYSTORE_DATA_TYPE_KEY)
{
Controlse::CPublicKey key(se, settings->key_id);
if (key.IsLoaded())
{
data = key.GetPem();
}
}
else if (settings->data_type == KEYSTORE_DATA_TYPE_CERT_OR_CSR)
{
Controlse::CCertificate cert(se, settings->key_id);
if (cert.IsLoaded())
{
data = cert.GetPem();
}
else
{
Controlse::CCsr csr(se, settings->key_id);
if (csr.IsLoaded())
{
data = csr.GetPem();
}
}
}
if (data)
{
puts(data);
delete[] data;
}
else
{
result = -EPERM;
}
}
else if (settings->operation == KEYSTORE_DELETE)
{
result = se.DeleteKey(settings->key_id) ? 0 : -EPERM;
if (result == 0)
{
printf("Deleted key successfully\n");
}
}
else if (settings->operation == KEYSTORE_DERIVE_SYMM_KEY)
{
uint8_t buffer[SYMM_KEY_BUFFER_SIZE];
struct se05x_derive_key_s args = {
.private_key_id = settings->private_key_id,
.public_key_id = settings->key_id,
.content = { .buffer = buffer, .buffer_size = sizeof(buffer) },
};
result = se.DeriveSymmetricalKey(args) ? 0 : -EPERM;
if (result == 0)
{
for (size_t i = 0; i < args.content.buffer_content_size; i++)
{
printf("%02x", args.content.buffer[i]);
}
printf("\n");
}
}
else if (settings->operation == KEYSTORE_CREATE_SIGNATURE)
{
uint8_t tbs_buffer[TBS_HASH_BUFFER_SIZE];
size_t tbs_content_size;
readFromFileAndConvert("Enter tbs(hex):", settings->input_filename,
tbs_buffer, sizeof(tbs_buffer),
&tbs_content_size);
uint8_t signature_buffer[SIGNATURE_BUFFER_SIZE];
size_t signature_content_len = 0;
if (result == 0)
{
struct se05x_signature_s args = {
.key_id = settings->key_id,
.algorithm = SE05X_ALGORITHM_SHA256,
.tbs = { .buffer = tbs_buffer,
.buffer_size = tbs_content_size,
.buffer_content_size = tbs_content_size },
.signature = { .buffer = signature_buffer,
.buffer_size = sizeof(signature_buffer) },
};
result = se.CreateSignature(args) ? 0 : -EPERM;
signature_content_len = args.signature.buffer_content_size;
}
if (result == 0)
{
for (size_t i = 0; i < signature_content_len; i++)
{
printf("%02x", signature_buffer[i]);
}
printf("\n");
}
}
else if (settings->operation == KEYSTORE_VERIFY_SIGNATURE)
{
uint8_t tbs_buffer[TBS_HASH_BUFFER_SIZE];
size_t tbs_content_size;
result = readFromFileAndConvert(
"Enter tbs(hex):", settings->input_filename, tbs_buffer,
sizeof(tbs_buffer), &tbs_content_size);
uint8_t signature_buffer[SIGNATURE_BUFFER_SIZE];
size_t signature_content_size;
if (result == 0)
{
result = readFromFileAndConvert(
"Enter signature(hex):", settings->signature_filename,
signature_buffer, sizeof(signature_buffer),
&signature_content_size);
}
if (result == 0)
{
struct se05x_signature_s args = {
.key_id = settings->key_id,
.algorithm = SE05X_ALGORITHM_SHA256,
.tbs = { .buffer = tbs_buffer,
.buffer_size = tbs_content_size,
.buffer_content_size = tbs_content_size },
.signature = { .buffer = signature_buffer,
.buffer_size = signature_content_size,
.buffer_content_size = signature_content_size },
};
result = se.Verify(args) ? 0 : -EPERM;
}
if (result == 0)
{
printf("Signature verified successfully\n");
}
}
else if (settings->operation == KEYSTORE_SIGN_CSR)
{
char csr_pem_buf[DEFAULT_BUFFER_SIZE];
size_t csr_pem_buf_content_size
= readFromFile("enter csr(pem)", settings->input_filename,
csr_pem_buf, sizeof(csr_pem_buf));
csr_pem_buf_content_size = addZeroTerminationCharacter(
csr_pem_buf, csr_pem_buf_content_size, sizeof(csr_pem_buf));
auto certificate = Controlse::CCertificate(
se, reinterpret_cast<uint8_t *>(csr_pem_buf),
csr_pem_buf_content_size, settings->key_id);
auto crt_pem = certificate.GetPem();
if (crt_pem)
{
puts(crt_pem);
delete[] crt_pem;
}
else
{
result = -EPERM;
}
}
else if (settings->operation == KEYSTORE_VERIFY_CERTIFICATE)
{
char pem_buf[DEFAULT_BUFFER_SIZE];
size_t pem_content_size
= readFromFile("enter crt(pem)", settings->input_filename, pem_buf,
sizeof(pem_buf));
pem_content_size = addZeroTerminationCharacter(pem_buf, pem_content_size,
sizeof(pem_buf));
auto certificate = Controlse::CCertificate(
reinterpret_cast<uint8_t *>(pem_buf), pem_content_size);
result = certificate.VerifyAgainst(se, settings->key_id) ? 0 : -EPERM;
if (result == 0)
{
printf("Signature verified successfully\n");
}
}
return result;
}
//***************************************************************************
// Public Functions
//**************************************************************************
int main(int argc, FAR char *argv[])
{
struct SSettings settings = DEFAULT_SETTINGS;
int result = parseArguments(argc, argv, &settings);
if ((result == 0) && (!settings.skip_process))
{
int fd = open(settings.se05x_dev_filename, O_RDONLY);
if (fd == -1)
{
result = -ENODEV;
}
else
{
result = process(fd, &settings);
close(fd);
}
}
if (result != 0)
{
fprintf(stderr, "err %i: %s\n", -result, strerror(-result));
}
if (settings.show_stack_used)
{
#ifdef CONFIG_STACK_COLORATION
FAR struct tcb_s *tcb;
tcb = nxsched_get_tcb(getpid());
fprintf(stderr, "\nStack used: %zu / %zu\n", up_check_tcbstack(tcb),
tcb->adj_stack_size);
#else
fprintf(stderr, "\nStack used: unknown"
" (STACK_COLORATION must be enabled)\n");
#endif
}
return result == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}

View File

@@ -0,0 +1,243 @@
//***************************************************************************
// apps/crypto/controlse/cpublic_key.cxx
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. The
// ASF licenses this file to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//**************************************************************************
// Copyright 2024 NXP
//***************************************************************************
// Included Files
//***************************************************************************
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
#include "crypto/controlse/cpublic_key.hxx"
#include "crypto/controlse/isecure_element.hxx"
#include "crypto/controlse/isecure_element_object.hxx"
#include <errno.h>
#include <mbedtls/pk.h>
#include <string.h>
namespace Controlse
{
//***************************************************************************
// Class Method Implementations
//***************************************************************************
CPublicKey::CPublicKey(const ISecureElement &se, uint32_t keystore_id)
{
(void)LoadFromSecureElement(se, keystore_id);
}
CPublicKey::CPublicKey(const char *pem)
{
uint8_t key_buf[300];
m_key = nullptr;
if (0
== convert_public_key_pem_to_raw(key_buf, sizeof(key_buf), &m_size, pem))
{
m_key = new uint8_t[m_size];
memcpy(m_key, key_buf, m_size);
}
}
CPublicKey::CPublicKey(const uint8_t *buffer, size_t buffer_size)
: m_key(new uint8_t[buffer_size]), m_size(buffer_size)
{
memcpy(m_key, buffer, m_size);
}
CPublicKey::CPublicKey(const CPublicKey &p1) : CPublicKey(p1.m_key, p1.m_size)
{
}
CPublicKey::~CPublicKey() { Unload(); }
CPublicKey &CPublicKey::operator=(const CPublicKey &other)
{
if (this != &other)
{
auto new_key = new uint8_t[other.m_size];
memcpy(new_key, other.m_key, other.m_size);
delete[] m_key;
m_key = new_key;
m_size = other.m_size;
}
return *this;
}
void CPublicKey::Unload()
{
if (IsLoaded())
{
delete[] m_key;
m_key = NULL;
m_size = 0;
}
}
bool CPublicKey::IsLoaded() const { return m_key != NULL; }
bool CPublicKey::StoreOnSecureElement(const ISecureElement &se,
uint32_t keystore_id) const
{
if (!IsLoaded())
{
return false;
}
struct se05x_key_transmission_s args = {
.entry = { .id = keystore_id, .cipher = SE05X_ASYM_CIPHER_EC_NIST_P_256 },
.content
= { .buffer = m_key, .buffer_size = m_size, .buffer_content_size = m_size }
};
return se.SetKey(args);
}
bool CPublicKey::LoadFromSecureElement(const ISecureElement &se,
uint32_t keystore_id)
{
Unload();
m_size = 100;
m_key = new uint8_t[m_size];
struct se05x_key_transmission_s args = {
.entry = { .id = keystore_id, .cipher = SE05X_ASYM_CIPHER_EC_NIST_P_256 },
.content
= { .buffer = m_key, .buffer_size = m_size, .buffer_content_size = m_size }
};
bool result = se.GetKey(args);
m_size = args.content.buffer_content_size;
if (!result)
{
Unload();
}
return result;
}
bool CPublicKey::operator==(const CPublicKey &a) const
{
if (this->m_size != a.m_size)
{
return false;
}
return 0 == memcmp(this->m_key, a.m_key, m_size);
}
bool CPublicKey::operator!=(const CPublicKey &a) const
{
return !operator==(a);
}
size_t CPublicKey::GetRawSize() const { return m_size; }
void CPublicKey::GetRaw(uint8_t *raw_buffer) const
{
memcpy(raw_buffer, m_key, m_size);
}
char *CPublicKey::GetPem() const
{
char pem_buf[500];
auto res
= convert_public_key_raw_to_pem(pem_buf, sizeof(pem_buf), m_key, m_size);
if (res < 0)
{
return nullptr;
}
auto pem_size = strlen(pem_buf);
auto pem = new char[pem_size + 1];
memcpy(pem, pem_buf, pem_size);
pem[pem_size] = 0;
return pem;
}
int CPublicKey::convert_public_key_raw_to_pem(char *pem_buf,
size_t pem_buf_size,
const uint8_t *key_buf,
size_t key_buf_size)
{
mbedtls_pk_context key = { 0 };
mbedtls_pk_init(&key);
const mbedtls_pk_info_t *info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY);
int result = -1;
if (info != NULL)
{
result = mbedtls_pk_setup(&key, info);
}
mbedtls_ecp_keypair *keypair = (mbedtls_ecp_keypair *)key.pk_ctx;
if (result == 0)
{
result = mbedtls_ecp_group_load(&keypair->grp, MBEDTLS_ECP_DP_SECP256R1);
}
if (result == 0)
{
result = mbedtls_ecp_point_read_binary(&keypair->grp, &keypair->Q,
key_buf, key_buf_size);
}
if (result == 0)
{
result = mbedtls_pk_write_pubkey_pem(&key, (uint8_t *)pem_buf,
pem_buf_size);
}
mbedtls_pk_free(&key);
return result < 0 ? -EINVAL : 0;
}
int CPublicKey::convert_public_key_pem_to_raw(uint8_t *key_buf,
size_t key_buf_size,
size_t *key_size,
const char *pem_buf)
{
int result = -1;
mbedtls_pk_context key = { 0 };
mbedtls_pk_init(&key);
result = mbedtls_pk_parse_public_key(&key, (uint8_t *)pem_buf,
strlen(pem_buf) + 1);
if (result == 0)
{
result = mbedtls_pk_can_do(&key, MBEDTLS_PK_ECKEY) == 1 ? 0 : -1;
}
if (result == 0)
{
mbedtls_ecp_keypair *keypair = (mbedtls_ecp_keypair *)key.pk_ctx;
result = mbedtls_ecp_point_write_binary(&keypair->grp, &keypair->Q,
MBEDTLS_ECP_PF_UNCOMPRESSED,
key_size, key_buf, key_buf_size);
}
mbedtls_pk_free(&key);
return result < 0 ? -EINVAL : 0;
}
} // namespace Controlse

View File

@@ -0,0 +1,124 @@
//***************************************************************************
// apps/crypto/controlse/csan_builder.cxx
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. The
// ASF licenses this file to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//**************************************************************************
// Copyright 2024 NXP
//***************************************************************************
// Included Files
//***************************************************************************
#include "crypto/controlse/csan_builder.hxx"
#include "mbedtls/asn1write.h"
#include <cstring>
namespace Controlse
{
//***************************************************************************
// Class Method Implementations
//***************************************************************************
CSanBuilder::~CSanBuilder()
{
while (entry != nullptr)
{
delete[] entry->p;
auto next_entry = entry->next;
delete entry;
entry = next_entry;
}
}
CSanBuilder *CSanBuilder::AddSan(uint8_t type, const char *value,
size_t value_size)
{
auto old_entry = entry;
entry = new List();
if (entry)
{
entry->type = type;
entry->p = new char[value_size];
if (entry->p)
{
memcpy(entry->p, value, value_size);
entry->size = value_size;
entry->next = old_entry;
total_size += value_size;
total_size += 2;
}
else
{
delete entry;
}
}
return this;
}
//*
// result: pointer to dynamically allocated san (to be deleted with delete[])
// or error when size == 0
///
size_t CSanBuilder::Build(uint8_t **san)
{
if (!entry)
{
return 0;
}
const size_t reservation_for_additional_length_bytes = 8;
const size_t buffer_size
= total_size + reservation_for_additional_length_bytes;
auto *buffer = new uint8_t[buffer_size];
auto current = entry;
const unsigned char *start = buffer;
unsigned char *p = buffer + buffer_size;
int ret = 0;
size_t len = 0;
while (current)
{
ret = mbedtls_asn1_write_tagged_string(&p, start, current->type,
current->p, current->size);
current = current->next;
}
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&p, start, total_size));
MBEDTLS_ASN1_CHK_ADD(
len, mbedtls_asn1_write_tag(
&p, start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE));
*san = new uint8_t[total_size + len];
memcpy(*san, p, total_size + len);
delete[] buffer;
return total_size + len;
}
uint32_t CSanBuilder::GetNumberOfSan()
{
auto e = entry;
uint32_t amount = 0;
while (e != nullptr)
{
e = e->next;
amount++;
}
return amount;
}
}

View File

@@ -0,0 +1,189 @@
//***************************************************************************
// apps/crypto/controlse/csecure_element.cxx
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. The
// ASF licenses this file to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//**************************************************************************
// Copyright 2024 NXP
//***************************************************************************
// Included Files
//***************************************************************************
#include "crypto/controlse/csecure_element.hxx"
#include "crypto/controlse/ccertificate.hxx"
#include "crypto/controlse/cpublic_key.hxx"
#include <fcntl.h>
#include <libgen.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
extern "C"
{
#include <nuttx/crypto/se05x.h>
}
namespace Controlse
{
//***************************************************************************
// Class Method Implementations
//***************************************************************************
CSecureElement::CSecureElement(const char *se05x_device)
: se05x_fd(open(se05x_device, O_RDONLY)), close_device_at_destructor(true)
{
}
CSecureElement::CSecureElement(int fd)
: se05x_fd(fd), close_device_at_destructor(false)
{
}
CSecureElement::~CSecureElement()
{
if ((se05x_fd >= 0) && close_device_at_destructor)
{
close(se05x_fd);
}
}
bool CSecureElement::IsReady() const { return se05x_fd >= 0; }
bool CSecureElement::GenerateKey(struct se05x_generate_keypair_s &args) const
{
bool result = false;
if (se05x_fd >= 0)
{
result = 0 == ioctl(se05x_fd, SEIOC_GENERATE_KEYPAIR, &args);
}
return result;
}
bool CSecureElement::SetKey(struct se05x_key_transmission_s &args) const
{
bool result = false;
if (se05x_fd >= 0)
{
result = 0 == ioctl(se05x_fd, SEIOC_SET_KEY, &args);
}
return result;
}
bool CSecureElement::GetKey(struct se05x_key_transmission_s &args) const
{
bool result = false;
if (se05x_fd >= 0)
{
result = 0 == ioctl(se05x_fd, SEIOC_GET_KEY, &args);
}
return result;
}
bool CSecureElement::DeleteKey(uint32_t id) const
{
bool result = false;
if (se05x_fd >= 0)
{
result = 0 == ioctl(se05x_fd, SEIOC_DELETE_KEY, id);
}
return result;
}
bool CSecureElement::SetData(struct se05x_key_transmission_s &args) const
{
bool result = false;
if (se05x_fd >= 0)
{
result = 0 == ioctl(se05x_fd, SEIOC_SET_DATA, &args);
}
return result;
}
bool CSecureElement::GetData(struct se05x_key_transmission_s &args) const
{
bool result = false;
if (se05x_fd >= 0)
{
result = 0 == ioctl(se05x_fd, SEIOC_GET_DATA, &args);
}
return result;
}
bool CSecureElement::CreateSignature(struct se05x_signature_s &args) const
{
bool result = false;
if (se05x_fd >= 0)
{
result = 0 == ioctl(se05x_fd, SEIOC_CREATE_SIGNATURE, &args);
}
return result;
}
bool CSecureElement::Verify(struct se05x_signature_s &args) const
{
bool result = false;
if (se05x_fd >= 0)
{
result = 0 == ioctl(se05x_fd, SEIOC_VERIFY_SIGNATURE, &args);
}
return result;
}
bool CSecureElement::DeriveSymmetricalKey(
struct se05x_derive_key_s &args) const
{
bool result = false;
if (se05x_fd >= 0)
{
result = 0 == ioctl(se05x_fd, SEIOC_DERIVE_SYMM_KEY, &args);
}
return result;
}
bool CSecureElement::GetUid(struct se05x_uid_s &args) const
{
bool result = false;
if (se05x_fd >= 0)
{
result = 0 == ioctl(se05x_fd, SEIOC_GET_UID, &args);
}
return result;
}
bool CSecureElement::GetInfo(struct se05x_info_s &args) const
{
bool result = false;
if (se05x_fd >= 0)
{
result = 0 == ioctl(se05x_fd, SEIOC_GET_INFO, &args);
}
return result;
}
CCertificate *CSecureElement::GetCertificate(uint32_t keystore_id)
{
return new CCertificate(*this, keystore_id);
}
CPublicKey *CSecureElement::GetPublicKey(uint32_t keystore_id)
{
return new CPublicKey(*this, keystore_id);
}
} // namespace Controlse

View File

@@ -0,0 +1,94 @@
//***************************************************************************
// apps/crypto/controlse/cserial_number.cxx
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. The
// ASF licenses this file to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//**************************************************************************
// Copyright 2024 NXP
//***************************************************************************
// Included Files
//***************************************************************************
#include "crypto/controlse/cserial_number.hxx"
#include "crypto/controlse/isecure_element.hxx"
#include <string.h>
namespace Controlse
{
constexpr size_t CSerialNumber::SERIAL_NUMBER_SIZE;
//***************************************************************************
// Class Method Implementations
//***************************************************************************
CSerialNumber::CSerialNumber(const ISecureElement &se, uint32_t keystore_id)
{
is_loaded = LoadFromSecureElement(se, keystore_id);
}
CSerialNumber::CSerialNumber(uint8_t const *serial_number_byte_array)
{
memcpy(serial_number, serial_number_byte_array, SERIAL_NUMBER_SIZE);
is_loaded = true;
}
bool CSerialNumber::operator==(CSerialNumber &a) const
{
return 0 == (memcmp(a.serial_number, serial_number, SERIAL_NUMBER_SIZE));
}
bool CSerialNumber::operator!=(CSerialNumber &a) const
{
return !operator==(a);
}
bool CSerialNumber::operator<(const CSerialNumber &a) const
{
return 0 < (memcmp(a.serial_number, serial_number, SERIAL_NUMBER_SIZE));
}
bool CSerialNumber::IsLoaded() const { return is_loaded; }
bool CSerialNumber::GetSerialNumber(
uint8_t serial_number_destination[SERIAL_NUMBER_SIZE]) const
{
if (!is_loaded)
{
return false;
}
memcpy(serial_number_destination, serial_number, SERIAL_NUMBER_SIZE);
return true;
}
bool CSerialNumber::StoreOnSecureElement(const ISecureElement &se,
uint32_t keystore_id) const
{
return false;
}
bool CSerialNumber::LoadFromSecureElement(const ISecureElement &se,
uint32_t keystore_id)
{
struct se05x_key_transmission_s args
= { .entry = { .id = keystore_id },
.content
= { .buffer = serial_number, .buffer_size = SERIAL_NUMBER_SIZE } };
return se.GetData(args);
}
} // namespace Controlse

View File

@@ -0,0 +1,141 @@
//***************************************************************************
// apps/crypto/controlse/cstring.cxx
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. The
// ASF licenses this file to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//**************************************************************************
// Copyright 2024 NXP
//***************************************************************************
// Included Files
//***************************************************************************
#include "crypto/controlse/cstring.hxx"
#include "crypto/controlse/csecure_element.hxx"
#include <cstring>
namespace Controlse
{
//***************************************************************************
// Class Method Implementations
//***************************************************************************
CString::CString(const ISecureElement &se, uint32_t keystore_id)
{
(void)LoadFromSecureElement(se, keystore_id);
}
CString::CString(char *string, size_t size) : m_size(size)
{
m_string = new char[m_size];
memcpy(m_string, string, m_size);
}
CString::CString(const CString &p1) : CString(p1.m_string, p1.m_size) {}
CString::~CString()
{
if (m_string != nullptr)
{
delete[] m_string;
m_size = 0;
}
}
CString &CString::operator=(const CString &other)
{
if (this != &other)
{
auto new_string = new char[other.m_size];
memcpy(new_string, other.m_string, other.m_size);
delete[] m_string;
m_string = new_string;
m_size = other.m_size;
}
return *this;
}
bool CString::operator==(CString &a) const
{
if (a.m_size != m_size)
{
return false;
}
return 0 == (memcmp(a.m_string, m_string, m_size));
}
bool CString::operator!=(CString &a) const { return !operator==(a); }
char *CString::c_str(void) const
{
char *c_str = nullptr;
if (IsLoaded() && (m_size > 0))
{
bool add_termination_character = false;
if (m_string[m_size - 1] != 0)
{
add_termination_character = true;
}
c_str = new char[m_size + (add_termination_character ? 1 : 0)];
memcpy(c_str, m_string, m_size);
if (add_termination_character)
{
c_str[m_size] = 0;
}
}
return c_str;
}
bool CString::IsLoaded() const { return m_string != nullptr; }
bool CString::StoreOnSecureElement(const ISecureElement &se,
uint32_t keystore_id) const
{
auto result = false;
if (IsLoaded())
{
struct se05x_key_transmission_s args
= { .entry = { .id = keystore_id },
.content = { .buffer = reinterpret_cast<uint8_t *>(m_string),
.buffer_size = m_size } };
result = se.SetData(args);
}
return result;
}
bool CString::LoadFromSecureElement(const ISecureElement &se,
uint32_t keystore_id)
{
uint8_t buffer[1000];
struct se05x_key_transmission_s args
= { .entry = { .id = keystore_id },
.content = { .buffer = buffer, .buffer_size = sizeof(buffer) } };
auto result = se.GetData(args);
if (result)
{
m_size = args.content.buffer_content_size;
m_string = new char[m_size + 1];
memcpy(m_string, buffer, m_size);
m_string[m_size] = 0;
}
return result;
}
} // namespace Controlse

View File

@@ -1,310 +0,0 @@
/****************************************************************************
* apps/crypto/controlse/mbedtls_extension.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* The source code in this file is based on
* mbedtls_x509write_crt_der() method from x509write_crt.c in Mbed TLS
*/
/* Copyright 2023 NXP */
/****************************************************************************
* Included Files
****************************************************************************/
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
#include <mbedtls/asn1write.h>
#include <mbedtls/error.h>
#include <mbedtls/oid.h>
#include <mbedtls/x509_crt.h>
#include <nuttx/crypto/se05x.h>
#include <sys/ioctl.h>
#include <string.h>
/****************************************************************************
* Private Functions
****************************************************************************/
static int x509_write_time(FAR unsigned char **p, FAR unsigned char *start,
FAR const char *t, size_t size)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
/* write MBEDTLS_ASN1_UTC_TIME if year < 2050 (2 bytes shorter) */
if (t[0] == '2' && t[1] == '0' && t[2] < '5')
{
MBEDTLS_ASN1_CHK_ADD(
len, mbedtls_asn1_write_raw_buffer(
p, start, (FAR const unsigned char *)t + 2, size - 2));
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
MBEDTLS_ASN1_CHK_ADD(
len, mbedtls_asn1_write_tag(p, start, MBEDTLS_ASN1_UTC_TIME));
}
else
{
MBEDTLS_ASN1_CHK_ADD(len,
mbedtls_asn1_write_raw_buffer(
p, start, (FAR const unsigned char *)t, size));
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(
p, start, MBEDTLS_ASN1_GENERALIZED_TIME));
}
return ((int)len);
}
/****************************************************************************
* Public Functions
****************************************************************************/
int mbedtls_x509write_crt_der_se05x(FAR mbedtls_x509write_cert *ctx,
FAR unsigned char *buf, size_t size,
int se05x_fd, uint32_t private_key_id)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
FAR const char *sig_oid;
size_t sig_oid_len = 0;
FAR unsigned char *c;
FAR unsigned char *c2;
unsigned char hash[64];
unsigned char sig[MBEDTLS_PK_SIGNATURE_MAX_SIZE];
size_t sub_len = 0;
size_t pub_len = 0;
size_t sig_and_oid_len = 0;
size_t sig_len;
size_t len = 0;
mbedtls_pk_type_t pk_alg;
/* Prepare data to be signed at the end of the target buffer */
c = buf + size;
/* Signature algorithm needed in TBS, and later for actual signature */
/* There's no direct way of extracting a signature algorithm
* (represented as an element of mbedtls_pk_type_t) from a PK instance.
*/
if (mbedtls_pk_can_do(ctx->issuer_key, MBEDTLS_PK_RSA))
{
pk_alg = MBEDTLS_PK_RSA;
}
else if (mbedtls_pk_can_do(ctx->issuer_key, MBEDTLS_PK_ECDSA))
{
pk_alg = MBEDTLS_PK_ECDSA;
}
else
{
return (MBEDTLS_ERR_X509_INVALID_ALG);
}
if ((ret = mbedtls_oid_get_oid_by_sig_alg(pk_alg, ctx->md_alg, &sig_oid,
&sig_oid_len)) != 0)
{
return (ret);
}
/* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension */
/* Only for v3 */
if (ctx->version == MBEDTLS_X509_CRT_VERSION_3)
{
MBEDTLS_ASN1_CHK_ADD(
len, mbedtls_x509_write_extensions(&c, buf, ctx->extensions));
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
MBEDTLS_ASN1_CHK_ADD(len,
mbedtls_asn1_write_tag(&c, buf,
MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE));
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
MBEDTLS_ASN1_CHK_ADD(
len, mbedtls_asn1_write_tag(&c, buf,
MBEDTLS_ASN1_CONTEXT_SPECIFIC |
MBEDTLS_ASN1_CONSTRUCTED | 3));
}
/* SubjectPublicKeyInfo */
MBEDTLS_ASN1_CHK_ADD(
pub_len, mbedtls_pk_write_pubkey_der(ctx->subject_key, buf, c - buf));
c -= pub_len;
len += pub_len;
/* Subject ::= Name */
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_x509_write_names(&c, buf, ctx->subject));
/* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time }
*/
sub_len = 0;
MBEDTLS_ASN1_CHK_ADD(sub_len,
x509_write_time(&c, buf, ctx->not_after,
MBEDTLS_X509_RFC5280_UTC_TIME_LEN));
MBEDTLS_ASN1_CHK_ADD(sub_len,
x509_write_time(&c, buf, ctx->not_before,
MBEDTLS_X509_RFC5280_UTC_TIME_LEN));
len += sub_len;
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, sub_len));
MBEDTLS_ASN1_CHK_ADD(
len, mbedtls_asn1_write_tag(
&c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE));
/* Issuer ::= Name */
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_x509_write_names(&c, buf, ctx->issuer));
/* Signature ::= AlgorithmIdentifier */
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_algorithm_identifier(
&c, buf, sig_oid, strlen(sig_oid), 0));
/* Serial ::= INTEGER
*
* Written data is:
* - "ctx->serial_len" bytes for the raw serial buffer
* - if MSb of "serial" is 1, then prepend an extra 0x00 byte
* - 1 byte for the length
* - 1 byte for the TAG
*/
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_raw_buffer(&c, buf,
ctx->serial, ctx->serial_len));
if (*c & 0x80)
{
if (c - buf < 1)
{
return MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
}
*(--c) = 0x0;
len++;
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf,
ctx->serial_len + 1));
}
else
{
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf,
ctx->serial_len));
}
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(&c, buf,
MBEDTLS_ASN1_INTEGER));
/* Version ::= INTEGER { v1(0), v2(1), v3(2) } */
/* Can be omitted for v1 */
if (ctx->version != MBEDTLS_X509_CRT_VERSION_1)
{
sub_len = 0;
MBEDTLS_ASN1_CHK_ADD(sub_len,
mbedtls_asn1_write_int(&c, buf, ctx->version));
len += sub_len;
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, sub_len));
MBEDTLS_ASN1_CHK_ADD(
len, mbedtls_asn1_write_tag(&c, buf,
MBEDTLS_ASN1_CONTEXT_SPECIFIC |
MBEDTLS_ASN1_CONSTRUCTED | 0));
}
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
MBEDTLS_ASN1_CHK_ADD(
len, mbedtls_asn1_write_tag(
&c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE));
/* Make signature
*/
/* Compute hash of CRT. */
if ((ret = mbedtls_md(mbedtls_md_info_from_type(ctx->md_alg), c, len,
hash)) != 0)
{
return (ret);
}
{
struct se05x_signature_s args = {
.key_id = private_key_id,
.algorithm = SE05X_ALGORITHM_SHA256,
.tbs = {
.buffer = hash,
.buffer_size = 32,
.buffer_content_size = 32
},
.signature = {.buffer = sig, .buffer_size = sizeof(sig)},
};
ret = ioctl(se05x_fd, SEIOC_CREATE_SIGNATURE, &args);
if (ret != 0)
{
return ret;
}
sig_len = args.signature.buffer_content_size;
}
/* Move CRT to the front of the buffer to have space
* for the signature.
*/
memmove(buf, c, len);
c = buf + len;
/* Add signature at the end of the buffer,
* making sure that it doesn't underflow
* into the CRT buffer.
*/
c2 = buf + size;
MBEDTLS_ASN1_CHK_ADD(
sig_and_oid_len,
mbedtls_x509_write_sig(&c2, c, sig_oid, sig_oid_len, sig, sig_len));
/* Memory layout after this step:
*
* buf c=buf+len c2 buf+size
* [CRT0,...,CRTn, UNUSED, ..., UNUSED, SIG0, ..., SIGm]
*/
/* Move raw CRT to just before the signature. */
c = c2 - len;
memmove(c, buf, len);
len += sig_and_oid_len;
MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
MBEDTLS_ASN1_CHK_ADD(
len, mbedtls_asn1_write_tag(
&c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE));
return ((int)len);
}

View File

@@ -1,40 +0,0 @@
/****************************************************************************
* apps/crypto/controlse/mbedtls_extension.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/* Copyright 2023 NXP */
#ifndef __INCLUDE_APPS_CRYPTO_CONTROLSE_MBEDTLS_EXTENSION_H_
#define __INCLUDE_APPS_CRYPTO_CONTROLSE_MBEDTLS_EXTENSION_H_
/****************************************************************************
* Included Files
****************************************************************************/
#include <mbedtls/x509_crt.h>
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
int mbedtls_x509write_crt_der_se05x(mbedtls_x509write_cert *ctx,
unsigned char *buf, size_t size,
int se05x_fd, uint32_t private_key_id);
#endif /* __INCLUDE_APPS_CRYPTO_CONTROLSE_MBEDTLS_EXTENSION_H_ */

View File

@@ -1,350 +0,0 @@
/****************************************************************************
* apps/crypto/controlse/x509_utils.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/* Copyright 2023 NXP */
/****************************************************************************
* Included Files
****************************************************************************/
#include <errno.h>
#include <string.h>
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/ecp.h"
#include "mbedtls/entropy.h"
#include "mbedtls/pem.h"
#include "mbedtls/pk.h"
#include "mbedtls/x509_crt.h"
#include "mbedtls/x509_csr.h"
#include "mbedtls_extension.h"
#include <time.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define SECONDS_IN_DAY (60 * 60 * 24)
/****************************************************************************
* Private Data
****************************************************************************/
static const char certificate_header[] = "-----BEGIN CERTIFICATE-----\n";
static const char certificate_footer[] = "-----END CERTIFICATE-----\n";
static const char certificate_request_header[] =
"-----BEGIN CERTIFICATE REQUEST-----\n";
static const char certificate_request_footer[] =
"-----END CERTIFICATE REQUEST-----\n";
/****************************************************************************
* Private Functions
****************************************************************************/
static int convert_der_certificate_to_pem(FAR char *pem_buf,
size_t pem_buf_size,
FAR size_t *pem_content_size,
FAR uint8_t *der_buf,
size_t der_buf_size)
{
int result;
{
mbedtls_x509_crt crt;
mbedtls_x509_crt_init(&crt);
result = mbedtls_x509_crt_parse(&crt, der_buf, der_buf_size);
mbedtls_x509_crt_free(&crt);
}
if (result == 0)
{
result = mbedtls_pem_write_buffer(
certificate_header, certificate_footer, der_buf, der_buf_size,
(FAR uint8_t *)pem_buf, pem_buf_size, pem_content_size);
}
return result;
}
static int convert_der_csr_to_pem(FAR char *pem_buf, size_t pem_buf_size,
FAR size_t *pem_content_size,
FAR uint8_t *der_buf, size_t der_buf_size)
{
int result;
{
mbedtls_x509_csr csr;
mbedtls_x509_csr_init(&csr);
result =
mbedtls_x509_csr_parse(&csr, (FAR uint8_t *)der_buf, der_buf_size);
mbedtls_x509_csr_free(&csr);
}
if (result == 0)
{
result = mbedtls_pem_write_buffer(certificate_request_header,
certificate_request_footer, der_buf,
der_buf_size, (FAR uint8_t *)pem_buf,
pem_buf_size, pem_content_size);
}
return result;
}
/****************************************************************************
* Public Functions
****************************************************************************/
int convert_public_key_raw_to_pem(FAR char *pem_buf, size_t pem_buf_size,
FAR uint8_t *key_buf, size_t key_buf_size)
{
mbedtls_pk_context key =
{
0
};
mbedtls_pk_init(&key);
FAR const mbedtls_pk_info_t *info =
mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY);
int result = -1;
if (info != NULL)
{
result = mbedtls_pk_setup(&key, info);
}
FAR mbedtls_ecp_keypair *keypair = (mbedtls_ecp_keypair *)key.pk_ctx;
if (result == 0)
{
result =
mbedtls_ecp_group_load(&keypair->grp, MBEDTLS_ECP_DP_SECP256R1);
}
if (result == 0)
{
result = mbedtls_ecp_point_read_binary(&keypair->grp, &keypair->Q,
key_buf, key_buf_size);
}
if (result == 0)
{
result = mbedtls_pk_write_pubkey_pem(&key, (FAR uint8_t *)pem_buf,
pem_buf_size);
}
mbedtls_pk_free(&key);
return result < 0 ? -EINVAL : 0;
}
int convert_public_key_pem_to_raw(FAR uint8_t *key_buf, size_t key_buf_size,
FAR size_t *key_size, FAR char *pem_buf)
{
int result = -1;
mbedtls_pk_context key =
{
0
};
mbedtls_pk_init(&key);
result = mbedtls_pk_parse_public_key(&key, (FAR uint8_t *)pem_buf,
strlen(pem_buf) + 1);
if (result == 0)
{
result = mbedtls_pk_can_do(&key, MBEDTLS_PK_ECKEY) == 1 ? 0 : -1;
}
if (result == 0)
{
FAR mbedtls_ecp_keypair *keypair = (mbedtls_ecp_keypair *)key.pk_ctx;
result = mbedtls_ecp_point_write_binary(
&keypair->grp, &keypair->Q, MBEDTLS_ECP_PF_UNCOMPRESSED, key_size,
key_buf, key_buf_size);
}
mbedtls_pk_free(&key);
return result < 0 ? -EINVAL : 0;
}
int convert_pem_certificate_or_csr_to_der(FAR uint8_t *der_buf,
size_t der_buf_size,
FAR size_t *der_content_size,
FAR char *pem_buf,
size_t pem_buf_size)
{
int result;
{
mbedtls_x509_crt crt;
mbedtls_x509_crt_init(&crt);
result =
mbedtls_x509_crt_parse(&crt, (FAR uint8_t *)pem_buf, pem_buf_size);
if ((result == 0) && (der_buf_size < crt.raw.len))
{
result = -EINVAL;
}
if (result == 0)
{
memcpy(der_buf, crt.raw.p, crt.raw.len);
*der_content_size = crt.raw.len;
}
mbedtls_x509_crt_free(&crt);
}
/* if bad input data then try parsing CSR */
if (result != 0)
{
mbedtls_x509_csr csr;
mbedtls_x509_csr_init(&csr);
result =
mbedtls_x509_csr_parse(&csr, (FAR uint8_t *)pem_buf, pem_buf_size);
if ((result == 0) && (der_buf_size < csr.raw.len))
{
result = -EINVAL;
}
if (result == 0)
{
memcpy(der_buf, csr.raw.p, csr.raw.len);
*der_content_size = csr.raw.len;
}
mbedtls_x509_csr_free(&csr);
}
return result;
}
int convert_der_certificate_or_csr_to_pem(FAR char *pem_buf,
size_t pem_buf_size,
FAR size_t *pem_content_size,
FAR uint8_t *der_buf,
size_t der_buf_size)
{
int result = convert_der_certificate_to_pem(
pem_buf, pem_buf_size, pem_content_size, der_buf, der_buf_size);
if (result != 0)
{
result = convert_der_csr_to_pem(pem_buf, pem_buf_size,
pem_content_size,
der_buf, der_buf_size);
}
return result;
}
int sign_csr(int se05x_fd, uint32_t private_key_id, FAR char *crt_pem_buf,
size_t crt_pem_buf_size, FAR char *csr_pem_buf,
size_t csr_pem_buf_content_size)
{
mbedtls_x509_csr csr;
mbedtls_x509_csr_init(&csr);
int result = mbedtls_x509_csr_parse(&csr, (FAR uint8_t *)csr_pem_buf,
csr_pem_buf_content_size);
mbedtls_x509write_cert crt;
mbedtls_x509write_crt_init(&crt);
char subject_name[200];
if (result == 0)
{
mbedtls_x509write_crt_set_version(&crt, MBEDTLS_X509_CRT_VERSION_3);
result = mbedtls_x509_dn_gets(subject_name, sizeof(subject_name),
&csr.subject);
}
mbedtls_pk_context private_key;
mbedtls_pk_init(&private_key);
if (result >= 0)
{
mbedtls_x509write_crt_set_subject_key(&crt, &csr.pk);
result = mbedtls_pk_setup(
&private_key,
mbedtls_pk_info_from_type((mbedtls_pk_type_t)MBEDTLS_PK_ECDSA));
}
if (result == 0)
{
mbedtls_x509write_crt_set_issuer_key(&crt, &private_key);
result = mbedtls_x509write_crt_set_subject_name(&crt, subject_name);
}
if (result == 0)
{
result =
mbedtls_x509write_crt_set_issuer_name(&crt, "CN=CA,O=NXP,C=NL");
}
mbedtls_mpi serial;
mbedtls_mpi_init(&serial);
if (result == 0)
{
mbedtls_x509write_crt_set_md_alg(&crt, MBEDTLS_MD_SHA256);
result = mbedtls_mpi_read_string(&serial, 10, "1");
}
if (result == 0)
{
result = mbedtls_x509write_crt_set_serial(&crt, &serial);
}
if (result == 0)
{
time_t rawtime;
struct tm tm_info;
char from_datetime[20];
char to_datetime[20];
time(&rawtime);
strftime(from_datetime, sizeof(from_datetime), "%Y%m%d%H%M%S",
gmtime_r(&rawtime, &tm_info));
rawtime += SECONDS_IN_DAY;
strftime(to_datetime, sizeof(to_datetime), "%Y%m%d%H%M%S",
gmtime_r(&rawtime, &tm_info));
result = mbedtls_x509write_crt_set_validity(&crt, from_datetime,
to_datetime);
}
if (result == 0)
{
result = mbedtls_x509write_crt_der_se05x(
&crt, (FAR uint8_t *)crt_pem_buf, crt_pem_buf_size, se05x_fd,
private_key_id);
}
if (result >= 0)
{
size_t olen;
result = mbedtls_pem_write_buffer(
certificate_header, certificate_footer,
(FAR uint8_t *)(crt_pem_buf + crt_pem_buf_size - result), result,
(FAR uint8_t *)crt_pem_buf, crt_pem_buf_size, &olen);
}
mbedtls_mpi_free(&serial);
mbedtls_pk_free(&private_key);
mbedtls_x509write_crt_free(&crt);
mbedtls_x509_csr_free(&csr);
return result;
}

View File

@@ -1,54 +0,0 @@
/****************************************************************************
* apps/crypto/controlse/x509_utils.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/* Copyright 2023 NXP */
#ifndef __INCLUDE_APPS_CRYPTO_CONTROLSE_X509_UTILS_H_
#define __INCLUDE_APPS_CRYPTO_CONTROLSE_X509_UTILS_H_
/****************************************************************************
* Included Files
****************************************************************************/
#include <stdint.h>
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
int convert_public_key_raw_to_pem(FAR char *pem_buf, size_t pem_buf_size,
FAR uint8_t *key_buf, size_t key_buf_size);
int convert_public_key_pem_to_raw(FAR uint8_t *key_buf, size_t key_buf_size,
FAR size_t *key_size, char *pem_buf);
int convert_pem_certificate_or_csr_to_der(FAR uint8_t *der_buf,
size_t der_buf_size,
FAR size_t *der_content_size,
FAR char *pem_buf,
size_t pem_buf_size);
int convert_der_certificate_or_csr_to_pem(FAR char *pem_buf,
size_t pem_buf_size,
FAR size_t *pem_content_size,
FAR uint8_t *der_buf,
size_t der_buf_size);
int sign_csr(int se05x_fd, uint32_t private_key_id, FAR char *crt_pem_buf,
size_t crt_pem_buf_size, FAR char *csr_pem_buf,
size_t csr_pem_buf_content_size);
#endif /* __INCLUDE_APPS_CRYPTO_CONTROLSE_X509_UTILS_H_ */

View File

@@ -33,7 +33,6 @@ LIBSODIUM_UNPACKTESTDIR = $(LIBSODIUM_UNPACKNAME)$(DELIM)test$(DELIM)default
CSRCS += $(shell find $(LIBSODIUM_UNPACKLIBDIR) -name "*.c")
CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/libsodium/libsodium/src/libsodium/include/sodium
CFLAGS += -DDEV_MODE -DCONFIGURED=1
CFLAGS += -Wno-unused-function -Wno-undef -Wno-unused-variable -Wno-deprecated-declarations \
-Wno-shadow

View File

@@ -67,21 +67,17 @@ if(CONFIG_CRYPTO_MBEDTLS)
# Include Directory
# ############################################################################
set(INCDIR ${CMAKE_CURRENT_LIST_DIR}/include ${MBEDTLS_DIR}/include)
set(INCDIR ${MBEDTLS_DIR}/include)
# ############################################################################
# Library Configuration
# ############################################################################
set_property(
TARGET nuttx
APPEND
PROPERTY NUTTX_INCLUDE_DIRECTORIES ${INCDIR})
nuttx_add_library(mbedtls STATIC)
nuttx_export_header(TARGET mbedtls INCLUDE_DIRECTORIES ${MBEDTLS_DIR}/include)
target_sources(mbedtls PRIVATE ${CSRCS})
target_include_directories(mbedtls PRIVATE ${INCDIR})
target_compile_definitions(mbedtls PRIVATE unix)
target_compile_definitions(mbedtls PRIVATE __unix__)
if(CONFIG_ARCH_SIM)
target_compile_options(mbedtls PRIVATE -O0)

View File

@@ -17,7 +17,7 @@ config MBEDTLS_VERSION
config MBEDTLS_DEBUG_C
bool "This module provides debugging functions."
default DEBUG_CRYPTO_INFO
default DEBUG_FEATURES
---help---
This module provides debugging functions.
@@ -72,10 +72,6 @@ config MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE
depends on MBEDTLS_SSL_DTLS_HELLO_VERIFY
default y
config MBEDTLS_BLOWFISH_C
bool "Enable the Blowfish block cipher."
default n
config MBEDTLS_CAMELLIA_C
bool "Enable the Camellia block cipher."
default y
@@ -182,7 +178,6 @@ config MBEDTLS_X509_CSR_PARSE_C
config MBEDTLS_X509_CRT_POOL
bool "Enable the X509 Certificate Pool"
depends on MBEDTLS_THREADING_C
default n
config MBEDTLS_HAVE_ASM
@@ -402,10 +397,6 @@ config MBEDTLS_AESCE_C
depends on MBEDTLS_HAVE_ASM
default y
config MBEDTLS_ARC4_C
bool "Enable the ARCFOUR stream cipher."
default n
config MBEDTLS_ARIA_C
bool "Enable the ARIA block cipher."
default y
@@ -554,7 +545,7 @@ config MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH
int "Size in bytes of a ticket nonce."
default 32
config MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH
config MBEDTLS_SSL_TLS1_3_DEFAULT_NEW_SESSION_TICKETS
int "Default number of NewSessionTicket messages to be sent by a TLS 1.3 server after handshake completion."
default 1
@@ -576,16 +567,6 @@ config MBEDTLS_MD5_ALT
select MBEDTLS_ALT
default n
config MBEDTLS_POLY1305_ALT
bool "Enable Mbedt TLS POLY1305 module alted by nuttx crypto"
select MBEDTLS_ALT
default n
config MBEDTLS_RIPEMD160_ALT
bool "Enable Mbedt TLS RIPEMD160 module alted by nuttx crypto"
select MBEDTLS_ALT
default n
config MBEDTLS_SHA1_ALT
bool "Enable Mbedt TLS SHA1 module alted by nuttx crypto"
select MBEDTLS_ALT
@@ -601,11 +582,6 @@ config MBEDTLS_SHA512_ALT
select MBEDTLS_ALT
default n
config MBEDTLS_BIGNUM_ALT
bool "Enable Mbedt TLS Bignum module alted by nuttx mpi"
select MBEDTLS_ALT
default n
endif # CRYPTO_CRYPTODEV
menuconfig MBEDTLS_APPS

View File

@@ -23,10 +23,12 @@ CONFIGURED_APPS += $(APPDIR)/crypto/mbedtls
# Allows `<mbedtls/<>.h>` import.
MBEDTLS_FLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/mbedtls/include
MBEDTLS_FLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/mbedtls/mbedtls/include
CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/mbedtls/include
CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/mbedtls/mbedtls/include
CFLAGS += ${DEFINE_PREFIX}MBEDTLS_CONFIG_FILE="<mbedtls/mbedtls_config.h>"
CFLAGS += ${MBEDTLS_FLAGS}
CXXFLAGS += ${MBEDTLS_FLAGS}
CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/mbedtls/include
CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/mbedtls/mbedtls/include
CXXFLAGS += ${DEFINE_PREFIX}MBEDTLS_CONFIG_FILE="<mbedtls/mbedtls_config.h>"
endif

View File

@@ -36,7 +36,7 @@ MBEDTLS_UNPACKLIBDIR = $(MBEDTLS_UNPACKNAME)$(DELIM)library
MBEDTLS_UNPACKPROGDIR = $(MBEDTLS_UNPACKNAME)$(DELIM)programs
# This lets Mbed TLS better use some of the POSIX features we have
CFLAGS += ${DEFINE_PREFIX}unix
CFLAGS += ${DEFINE_PREFIX}__unix__
mbedtls/library/bignum.c_CFLAGS += -fno-lto
@@ -48,7 +48,6 @@ mbedtls/library/bignum.c_CFLAGS += -fno-lto
ifeq ($(CONFIG_FRAME_POINTER),y)
ifeq ($(CONFIG_DEBUG_OPTLEVEL),"-O3")
mbedtls/library/sha256.c_CFLAGS += -O2
mbedtls/library/cmac.c_CFLAGS += -O2
endif
endif
@@ -123,14 +122,6 @@ ifeq ($(CONFIG_MBEDTLS_MD5_ALT),y)
CSRCS += $(APPDIR)/crypto/mbedtls/source/md5_alt.c
endif
ifeq ($(CONFIG_MBEDTLS_POLY1305_ALT),y)
CSRCS += $(APPDIR)/crypto/mbedtls/source/poly1305_alt.c
endif
ifeq ($(CONFIG_MBEDTLS_RIPEMD160_ALT),y)
CSRCS += $(APPDIR)/crypto/mbedtls/source/ripemd160_alt.c
endif
ifeq ($(CONFIG_MBEDTLS_SHA1_ALT),y)
CSRCS += $(APPDIR)/crypto/mbedtls/source/sha1_alt.c
endif
@@ -143,10 +134,6 @@ ifeq ($(CONFIG_MBEDTLS_SHA512_ALT),y)
CSRCS += $(APPDIR)/crypto/mbedtls/source/sha512_alt.c
endif
ifeq ($(CONFIG_MBEDTLS_BIGNUM_ALT),y)
CSRCS += $(APPDIR)/crypto/mbedtls/source/bignum_alt.c
endif
endif
include $(APPDIR)/Application.mk

View File

@@ -30,7 +30,7 @@
* Pre-processor Definitions
****************************************************************************/
#define MAX_KEY_SIZE 64
#define MAX_KEY_SIZE 36
typedef struct mbedtls_aes_context
{

View File

@@ -371,13 +371,9 @@
#ifdef CONFIG_MBEDTLS_MD5_ALT
#define MBEDTLS_MD5_ALT
#endif
#ifdef CONFIG_MBEDTLS_POLY1305_ALT
#define MBEDTLS_POLY1305_ALT
#endif
#ifdef CONFIG_MBEDTLS_RIPEMD160_ALT
#define MBEDTLS_RIPEMD160_ALT
#endif
/* #define MBEDTLS_RSA_ALT
/* #define MBEDTLS_POLY1305_ALT
* #define MBEDTLS_RIPEMD160_ALT
* #define MBEDTLS_RSA_ALT
*/
#ifdef CONFIG_MBEDTLS_SHA1_ALT
#define MBEDTLS_SHA1_ALT
@@ -388,9 +384,6 @@
#ifdef CONFIG_MBEDTLS_SHA512_ALT
#define MBEDTLS_SHA512_ALT
#endif
#ifdef CONFIG_MBEDTLS_BIGNUM_ALT
#define MBEDTLS_BIGNUM_ALT
#endif
/* #define MBEDTLS_XTEA_ALT
*/
@@ -987,6 +980,21 @@
#define MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
#endif
/**
* \def MBEDTLS_X509_CRT_POOL
*
* Enable X.509 certificate pool.
*
* Module: library/x509_crt_pool.c
*
* Requires: MBEDTLS_THREADING_C
*
* This module is required for X.509 certificate pool.
*/
#ifdef CONFIG_MBEDTLS_X509_CRT_POOL
#define MBEDTLS_X509_CRT_POOL
#endif
/**
* \def MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
*
@@ -3830,21 +3838,6 @@
*/
#define MBEDTLS_X509_CRT_PARSE_C
/**
* \def MBEDTLS_X509_CRT_POOL
*
* Enable X.509 certificate pool.
*
* Module: library/x509_crt_pool.c
*
* Requires: MBEDTLS_THREADING_C
*
* This module is required for X.509 certificate pool.
*/
#ifdef CONFIG_MBEDTLS_X509_CRT_POOL
#define MBEDTLS_X509_CRT_POOL
#endif
/**
* \def MBEDTLS_X509_CRL_PARSE_C
*

View File

@@ -1,31 +0,0 @@
/****************************************************************************
* apps/crypto/mbedtls/include/poly1305_alt.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
****************************************************************************/
#ifndef __APPS_CRYPTO_MBEDTLS_INCLUDE_POLY1305_ALT_H
#define __APPS_CRYPTO_MBEDTLS_INCLUDE_POLY1305_ALT_H
/****************************************************************************
* Included Files
****************************************************************************/
#include "dev_alt.h"
#define mbedtls_poly1305_context cryptodev_context_t
#endif /* __APPS_CRYPTO_MBEDTLS_INCLUDE_POLY1305_ALT_H */

View File

@@ -1,31 +0,0 @@
/****************************************************************************
* apps/crypto/mbedtls/include/ripemd160_alt.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
****************************************************************************/
#ifndef __APPS_CRYPTO_MBEDTLS_INCLUDE_RIPEMD160_ALT_H
#define __APPS_CRYPTO_MBEDTLS_INCLUDE_RIPEMD160_ALT_H
/****************************************************************************
* Included Files
****************************************************************************/
#include "dev_alt.h"
#define mbedtls_ripemd160_context cryptodev_context_t
#endif /* __APPS_CRYPTO_MBEDTLS_INCLUDE_RIPEMD160_ALT_H */

View File

@@ -51,18 +51,6 @@ int mbedtls_aes_setkey_enc(FAR mbedtls_aes_context *ctx,
FAR const unsigned char *key,
unsigned int keybits)
{
switch (keybits)
{
case 128:
break;
case 192:
break;
case 256:
break;
default:
return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH;
}
memcpy(ctx->key, key, keybits / 8);
ctx->dev.session.key = (caddr_t)ctx->key;
ctx->dev.session.keylen = keybits / 8;
@@ -86,11 +74,6 @@ int mbedtls_aes_crypt_ecb(FAR mbedtls_aes_context *ctx,
int ret;
unsigned char iv[16];
if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT)
{
return MBEDTLS_ERR_AES_BAD_INPUT_DATA;
}
ctx->dev.session.cipher = CRYPTO_AES_CBC;
ret = cryptodev_get_session(&ctx->dev);
if (ret != 0)
@@ -124,16 +107,6 @@ int mbedtls_aes_crypt_cbc(mbedtls_aes_context *ctx,
{
int ret;
if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT)
{
return MBEDTLS_ERR_AES_BAD_INPUT_DATA;
}
if (length % 16)
{
return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH;
}
ctx->dev.session.cipher = CRYPTO_AES_CBC;
ret = cryptodev_get_session(&ctx->dev);
if (ret != 0)
@@ -168,11 +141,6 @@ int mbedtls_aes_crypt_ctr(FAR mbedtls_aes_context *ctx,
{
int ret;
if (*nc_off > 0x0f)
{
return MBEDTLS_ERR_AES_BAD_INPUT_DATA;
}
ctx->dev.session.cipher = CRYPTO_AES_CTR;
memcpy(ctx->key + ctx->dev.session.keylen,
nonce_counter, NONCE_LENGTH);
@@ -215,22 +183,14 @@ int mbedtls_aes_xts_setkey_enc(FAR mbedtls_aes_xts_context *ctx,
FAR const unsigned char *key,
unsigned int keybits)
{
if (keybits != 256 && keybits != 512)
{
return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH;
}
memcpy(ctx->key, key, keybits / 8);
ctx->dev.session.key = (caddr_t)ctx->key;
ctx->dev.session.keylen = keybits / 8;
return 0;
return mbedtls_aes_setkey_enc(ctx, key, keybits);
}
int mbedtls_aes_xts_setkey_dec(FAR mbedtls_aes_xts_context *ctx,
FAR const unsigned char *key,
unsigned int keybits)
{
return mbedtls_aes_xts_setkey_enc(ctx, key, keybits);
return mbedtls_aes_setkey_dec(ctx, key, keybits);
}
int mbedtls_aes_crypt_xts(FAR mbedtls_aes_xts_context *ctx,
@@ -243,25 +203,6 @@ int mbedtls_aes_crypt_xts(FAR mbedtls_aes_xts_context *ctx,
int ret;
unsigned char iv[16];
if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT)
{
return MBEDTLS_ERR_AES_BAD_INPUT_DATA;
}
/* Data units must be at least 16 bytes long. */
if (length < 16)
{
return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH;
}
/* NIST SP 800-38E disallows data units larger than 2**20 blocks. */
if (length > (1 << 20) * 16)
{
return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH;
}
ctx->dev.session.cipher = CRYPTO_AES_XTS;
ret = cryptodev_get_session(&ctx->dev);
if (ret != 0)
@@ -297,16 +238,6 @@ int mbedtls_aes_crypt_cfb128(FAR mbedtls_aes_context *ctx,
{
int ret;
if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT)
{
return MBEDTLS_ERR_AES_BAD_INPUT_DATA;
}
if (*iv_off > 15)
{
return MBEDTLS_ERR_AES_BAD_INPUT_DATA;
}
ctx->dev.session.cipher = CRYPTO_AES_CFB_128;
ret = cryptodev_get_session(&ctx->dev);
if (ret != 0)
@@ -342,11 +273,6 @@ int mbedtls_aes_crypt_cfb8(FAR mbedtls_aes_context *ctx,
{
int ret;
if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT)
{
return MBEDTLS_ERR_AES_BAD_INPUT_DATA;
}
ctx->dev.session.cipher = CRYPTO_AES_CFB_8;
ret = cryptodev_get_session(&ctx->dev);
if (ret != 0)
@@ -380,11 +306,6 @@ int mbedtls_aes_crypt_ofb(FAR mbedtls_aes_context *ctx,
{
int ret;
if (*iv_off > 15)
{
return MBEDTLS_ERR_AES_BAD_INPUT_DATA;
}
ctx->dev.session.cipher = CRYPTO_AES_OFB;
ret = cryptodev_get_session(&ctx->dev);
if (ret != 0)

View File

@@ -1,299 +0,0 @@
/****************************************************************************
* apps/crypto/mbedtls/source/bignum_alt.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/types.h>
#include <mbedtls/bignum.h>
#include <mbedtls/platform.h>
#include <nuttx/math/math_ioctl.h>
#include <nuttx/math/mpi.h>
#define MBEDTLS_ROUNDUP(v, size) (((v) + (size - 1)) & ~(size - 1))
/****************************************************************************
* Private Functions
****************************************************************************/
static inline
void mbedtls_mpi_to_mpiparam(FAR struct mpiparam *a,
FAR const mbedtls_mpi *A)
{
a->n = A->n * sizeof(mbedtls_mpi_uint);
a->s = A->s;
a->p = (uint8_t *)A->p;
}
static inline
void mpiparam_to_mbedtls_mpi(FAR mbedtls_mpi *A,
FAR const struct mpiparam *a)
{
A->n = a->n / sizeof(mbedtls_mpi_uint);
A->s = a->s;
A->p = (mbedtls_mpi_uint *)a->p;
}
/****************************************************************************
* Public Functions
****************************************************************************/
int mbedtls_mpi_add_mpi(FAR mbedtls_mpi *X, FAR const mbedtls_mpi *A,
FAR const mbedtls_mpi *B)
{
int ret = 0;
int fd;
struct mpi_calc_s mpi;
fd = open("/dev/mpi0", O_RDWR);
if (fd < 0)
{
return -errno;
}
mpi.op = MPI_CALC_FUNC_ADD;
mbedtls_mpi_to_mpiparam(&mpi.param[0], A);
mbedtls_mpi_to_mpiparam(&mpi.param[1], B);
mbedtls_mpi_grow(X, MBEDTLS_ROUNDUP(MAX(A->n, B->n) + 1,
sizeof(mbedtls_mpi_uint)));
mbedtls_mpi_to_mpiparam(&mpi.param[2], X);
ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi));
if (ret >= 0)
{
mpiparam_to_mbedtls_mpi(X, &mpi.param[2]);
}
close(fd);
return ret;
}
int mbedtls_mpi_sub_mpi(FAR mbedtls_mpi *X, FAR const mbedtls_mpi *A,
FAR const mbedtls_mpi *B)
{
int ret = 0;
int fd;
struct mpi_calc_s mpi;
fd = open("/dev/mpi0", O_RDWR);
if (fd < 0)
{
return -errno;
}
mpi.op = MPI_CALC_FUNC_SUB;
mbedtls_mpi_to_mpiparam(&mpi.param[0], A);
mbedtls_mpi_to_mpiparam(&mpi.param[1], B);
mbedtls_mpi_grow(X, MBEDTLS_ROUNDUP(MAX(A->n, B->n) + 1,
sizeof(mbedtls_mpi_uint)));
mbedtls_mpi_to_mpiparam(&mpi.param[2], X);
ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi));
if (ret >= 0)
{
mpiparam_to_mbedtls_mpi(X, &mpi.param[2]);
}
close(fd);
return ret;
}
int mbedtls_mpi_mul_mpi(FAR mbedtls_mpi *X, FAR const mbedtls_mpi *A,
FAR const mbedtls_mpi *B)
{
int ret = 0;
int fd;
struct mpi_calc_s mpi;
fd = open("/dev/mpi0", O_RDWR);
if (fd < 0)
{
return -errno;
}
mpi.op = MPI_CALC_FUNC_MUL;
mbedtls_mpi_to_mpiparam(&mpi.param[0], A);
mbedtls_mpi_to_mpiparam(&mpi.param[1], B);
mbedtls_mpi_grow(X, MBEDTLS_ROUNDUP(A->n + B->n,
sizeof(mbedtls_mpi_uint)));
mbedtls_mpi_to_mpiparam(&mpi.param[2], X);
ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi));
if (ret >= 0)
{
mpiparam_to_mbedtls_mpi(X, &mpi.param[2]);
}
close(fd);
return ret;
}
int mbedtls_mpi_div_mpi(FAR mbedtls_mpi *Q, FAR mbedtls_mpi *R,
FAR const mbedtls_mpi *A, FAR const mbedtls_mpi *B)
{
int ret = 0;
int fd;
struct mpi_calc_s mpi;
fd = open("/dev/mpi0", O_RDWR);
if (fd < 0)
{
return -errno;
}
mpi.op = MPI_CALC_FUNC_DIV;
mbedtls_mpi_to_mpiparam(&mpi.param[0], A);
mbedtls_mpi_to_mpiparam(&mpi.param[1], B);
mbedtls_mpi_grow(Q, A->n);
mbedtls_mpi_grow(R, B->n);
mbedtls_mpi_to_mpiparam(&mpi.param[2], Q);
mbedtls_mpi_to_mpiparam(&mpi.param[3], R);
ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi));
if (ret >= 0)
{
mpiparam_to_mbedtls_mpi(Q, &mpi.param[2]);
mpiparam_to_mbedtls_mpi(R, &mpi.param[3]);
}
close(fd);
return ret;
}
int mbedtls_mpi_mod_mpi(FAR mbedtls_mpi *R, FAR const mbedtls_mpi *A,
FAR const mbedtls_mpi *B)
{
int ret = 0;
int fd;
struct mpi_calc_s mpi;
fd = open("/dev/mpi0", O_RDWR);
if (fd < 0)
{
return -errno;
}
mpi.op = MPI_CALC_FUNC_MOD;
mbedtls_mpi_to_mpiparam(&mpi.param[0], A);
mbedtls_mpi_to_mpiparam(&mpi.param[1], B);
mbedtls_mpi_grow(R, B->n);
mbedtls_mpi_to_mpiparam(&mpi.param[2], R);
ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi));
if (ret >= 0)
{
mpiparam_to_mbedtls_mpi(R, &mpi.param[2]);
}
close(fd);
return ret;
}
int mbedtls_mpi_exp_mod(FAR mbedtls_mpi *X, FAR const mbedtls_mpi *A,
FAR const mbedtls_mpi *E, FAR const mbedtls_mpi *N,
FAR mbedtls_mpi *)
{
int ret = 0;
int fd;
struct mpi_calc_s mpi;
fd = open("/dev/mpi0", O_RDWR);
if (fd < 0)
{
return -errno;
}
mpi.op = MPI_CALC_FUNC_EXP_MOD;
mbedtls_mpi_to_mpiparam(&mpi.param[0], A);
mbedtls_mpi_to_mpiparam(&mpi.param[1], E);
mbedtls_mpi_to_mpiparam(&mpi.param[2], N);
mbedtls_mpi_grow(X, N->n);
mbedtls_mpi_to_mpiparam(&mpi.param[3], X);
ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi));
if (ret >= 0)
{
mpiparam_to_mbedtls_mpi(X, &mpi.param[3]);
}
close(fd);
return ret;
}
int mbedtls_mpi_gcd(FAR mbedtls_mpi *G, FAR const mbedtls_mpi *A,
FAR const mbedtls_mpi *B)
{
int ret = 0;
int fd;
struct mpi_calc_s mpi;
fd = open("/dev/mpi0", O_RDWR);
if (fd < 0)
{
return -errno;
}
mpi.op = MPI_CALC_FUNC_GCD;
mbedtls_mpi_to_mpiparam(&mpi.param[0], A);
mbedtls_mpi_to_mpiparam(&mpi.param[1], B);
mbedtls_mpi_grow(G, MIN(A->n, B->n));
mbedtls_mpi_to_mpiparam(&mpi.param[2], G);
ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi));
if (ret >= 0)
{
mpiparam_to_mbedtls_mpi(G, &mpi.param[2]);
}
close(fd);
return ret;
}
int mbedtls_mpi_inv_mod(FAR mbedtls_mpi *X, FAR const mbedtls_mpi *A,
FAR const mbedtls_mpi *N)
{
int ret = 0;
int fd;
struct mpi_calc_s mpi;
fd = open("/dev/mpi0", O_RDWR);
if (fd < 0)
{
return -errno;
}
mpi.op = MPI_CALC_FUNC_INV_MOD;
mbedtls_mpi_to_mpiparam(&mpi.param[0], A);
mbedtls_mpi_to_mpiparam(&mpi.param[1], N);
mbedtls_mpi_grow(X, N->n);
mbedtls_mpi_to_mpiparam(&mpi.param[2], X);
ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi));
if (ret >= 0)
{
mpiparam_to_mbedtls_mpi(X, &mpi.param[2]);
}
close(fd);
return ret;
}

View File

@@ -94,5 +94,5 @@ int cryptodev_clone(FAR cryptodev_context_t *dst,
{
dst->session = src->session;
dst->crypt = src->crypt;
return dup2(src->fd, dst->fd);
return cryptodev_get_session(dst);
}

View File

@@ -1,101 +0,0 @@
/****************************************************************************
* apps/crypto/mbedtls/source/poly1305_alt.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include "mbedtls/error.h"
#include "mbedtls/poly1305.h"
/****************************************************************************
* Public Functions
****************************************************************************/
void mbedtls_poly1305_init(FAR mbedtls_poly1305_context *ctx)
{
cryptodev_init(ctx);
}
void mbedtls_poly1305_free(FAR mbedtls_poly1305_context *ctx)
{
cryptodev_free(ctx);
}
int mbedtls_poly1305_starts(mbedtls_poly1305_context *ctx,
const unsigned char key[32])
{
ctx->session.mac = CRYPTO_POLY1305;
ctx->session.mackey = (caddr_t)key;
ctx->session.mackeylen = 32;
return cryptodev_get_session(ctx);
}
int mbedtls_poly1305_update(FAR mbedtls_poly1305_context *ctx,
FAR const unsigned char *input,
size_t ilen)
{
ctx->crypt.op = COP_ENCRYPT;
ctx->crypt.flags |= COP_FLAG_UPDATE;
ctx->crypt.src = (caddr_t)input;
ctx->crypt.len = ilen;
return cryptodev_crypt(ctx);
}
int mbedtls_poly1305_finish(FAR mbedtls_poly1305_context *ctx,
unsigned char mac[16])
{
int ret;
ctx->crypt.op = COP_ENCRYPT;
ctx->crypt.flags = 0;
ctx->crypt.mac = (caddr_t)mac;
ret = cryptodev_crypt(ctx);
cryptodev_free_session(ctx);
return ret;
}
int mbedtls_poly1305_mac(const unsigned char key[32],
FAR const unsigned char *input,
size_t ilen,
unsigned char mac[16])
{
mbedtls_poly1305_context ctx;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_poly1305_init(&ctx);
ret = mbedtls_poly1305_starts(&ctx, key);
if (ret != 0)
{
goto cleanup;
}
ret = mbedtls_poly1305_update(&ctx, input, ilen);
if (ret != 0)
{
goto cleanup;
}
ret = mbedtls_poly1305_finish(&ctx, mac);
cleanup:
mbedtls_poly1305_free(&ctx);
return ret;
}

View File

@@ -1,74 +0,0 @@
/****************************************************************************
* apps/crypto/mbedtls/source/ripemd160_alt.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include "mbedtls/ripemd160.h"
/****************************************************************************
* Public Functions
****************************************************************************/
void mbedtls_ripemd160_clone(FAR mbedtls_ripemd160_context *dst,
FAR const mbedtls_ripemd160_context *src)
{
cryptodev_clone(dst, src);
}
void mbedtls_ripemd160_init(FAR mbedtls_ripemd160_context *ctx)
{
cryptodev_init(ctx);
}
void mbedtls_ripemd160_free(FAR mbedtls_ripemd160_context *ctx)
{
cryptodev_free(ctx);
}
int mbedtls_ripemd160_starts(FAR mbedtls_ripemd160_context *ctx)
{
ctx->session.mac = CRYPTO_RIPEMD160;
return cryptodev_get_session(ctx);
}
int mbedtls_ripemd160_update(FAR mbedtls_ripemd160_context *ctx,
FAR const unsigned char *input,
size_t ilen)
{
ctx->crypt.op = COP_ENCRYPT;
ctx->crypt.flags |= COP_FLAG_UPDATE;
ctx->crypt.src = (caddr_t)input;
ctx->crypt.len = ilen;
return cryptodev_crypt(ctx);
}
int mbedtls_ripemd160_finish(FAR mbedtls_ripemd160_context *ctx,
unsigned char output[20])
{
int ret;
ctx->crypt.op = COP_ENCRYPT;
ctx->crypt.flags = 0;
ctx->crypt.mac = (caddr_t)output;
ret = cryptodev_crypt(ctx);
cryptodev_free_session(ctx);
return ret;
}

View File

@@ -1,9 +0,0 @@
#
# For a description of the syntax of this configuration file,
# see the file kconfig-language.txt in the NuttX tools repository.
#
config OPENSSL_MBEDTLS_WRAPPER
depends on CRYPTO_MBEDTLS
bool "openssl mbedtls wrapper"
default n

View File

@@ -1,25 +0,0 @@
############################################################################
# apps/crypto/openssl_mbedtls_wrapper/Make.defs
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership. The
# ASF licenses this file to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
############################################################################
ifneq ($(CONFIG_OPENSSL_MBEDTLS_WRAPPER),)
CONFIGURED_APPS += $(APPDIR)/crypto/openssl_mbedtls_wrapper
CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/openssl_mbedtls_wrapper/include
CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/openssl_mbedtls_wrapper/include
endif

View File

@@ -1,23 +0,0 @@
############################################################################
# apps/crypto/openssl_mbedtls_wrapper/Makefile
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership. The
# ASF licenses this file to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
############################################################################
include $(APPDIR)/Make.defs
CSRCS += $(wildcard $(APPDIR)/crypto/openssl_mbedtls_wrapper/mbedtls/*.c)
include $(APPDIR)/Application.mk

View File

@@ -1,80 +0,0 @@
/****************************************************************************
* apps/crypto/openssl_mbedtls_wrapper/include/openssl/aes.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
****************************************************************************/
#ifndef OPENSSL_MBEDTLS_WRAPPER_AES_H
#define OPENSSL_MBEDTLS_WRAPPER_AES_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <openssl/base.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define AES_ENCRYPT 1
#define AES_DECRYPT 0
#define AES_BLOCK_SIZE 16
#define AES_MAXNR 14
#ifdef __cplusplus
extern "C"
{
#endif
/****************************************************************************
* Public Types
****************************************************************************/
struct aes_key_st
{
uint32_t rd_key[4 * (AES_MAXNR + 1)];
unsigned rounds;
};
typedef struct aes_key_st AES_KEY;
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
int AES_set_encrypt_key(const uint8_t *key, unsigned bits,
AES_KEY *aeskey);
void AES_encrypt(const uint8_t *in, uint8_t *out,
const AES_KEY *key);
int AES_set_decrypt_key(const uint8_t *key, unsigned bits,
AES_KEY *aeskey);
void AES_decrypt(const uint8_t *in, uint8_t *out,
const AES_KEY *key);
void AES_cbc_encrypt(const uint8_t *in, uint8_t *out,
size_t len, const AES_KEY *key,
uint8_t *ivec, const int enc);
#ifdef __cplusplus
}
#endif
#endif /* OPENSSL_MBEDTLS_WRAPPER_AES_H */

View File

@@ -1,82 +0,0 @@
/****************************************************************************
* apps/crypto/openssl_mbedtls_wrapper/include/openssl/asn1.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
****************************************************************************/
#ifndef OPENSSL_MBEDTLS_WRAPPER_ASN1_H
#define OPENSSL_MBEDTLS_WRAPPER_ASN1_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <openssl/base.h>
#include <time.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define MBSTRING_FLAG 0x1000
#define MBSTRING_UTF8 (MBSTRING_FLAG)
#define MBSTRING_ASC (MBSTRING_FLAG | 1)
#define V_ASN1_NULL 5
#ifdef __cplusplus
extern "C"
{
#endif
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
void ASN1_BIT_STRING_free(ASN1_BIT_STRING *a);
void ASN1_INTEGER_free(ASN1_INTEGER *a);
void ASN1_OBJECT_free(ASN1_OBJECT *a);
void ASN1_OCTET_STRING_free(ASN1_OCTET_STRING *a);
void ASN1_TIME_free(ASN1_TIME *a);
ASN1_BIT_STRING *ASN1_BIT_STRING_new(void);
int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *str, int n, int value);
ASN1_OCTET_STRING *ASN1_OCTET_STRING_new(void);
int i2d_ASN1_BIT_STRING(const ASN1_BIT_STRING *in, uint8_t **outp);
int ASN1_OCTET_STRING_set(ASN1_OCTET_STRING *str,
const unsigned char *data, int len);
ASN1_INTEGER *ASN1_INTEGER_new(void);
ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai);
ASN1_TIME *ASN1_TIME_new(void);
ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t);
#ifdef __cplusplus
}
#endif
#endif /* OPENSSL_MBEDTLS_WRAPPER_ASN1_H */

View File

@@ -1,81 +0,0 @@
/****************************************************************************
* apps/crypto/openssl_mbedtls_wrapper/include/openssl/base.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
****************************************************************************/
#ifndef OPENSSL_MBEDTLS_WRAPPER_BASE_H
#define OPENSSL_MBEDTLS_WRAPPER_BASE_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define ASN1_BIT_STRING ASN1_STRING
#ifdef __cplusplus
extern "C"
{
#endif
/****************************************************************************
* Public Types
****************************************************************************/
typedef struct EVP_CIPHER EVP_CIPHER;
typedef struct EVP_CIPHER_CTX EVP_CIPHER_CTX;
typedef struct ENGINE ENGINE;
typedef struct EVP_MD EVP_MD;
typedef struct EVP_MD_CTX EVP_MD_CTX;
typedef struct ASN1_BIT_STRING ASN1_BIT_STRING;
typedef struct ASN1_INTEGER ASN1_INTEGER;
typedef struct ASN1_OBJECT ASN1_OBJECT;
typedef struct ASN1_OCTET_STRING ASN1_OCTET_STRING;
typedef struct ASN1_TIME ASN1_TIME;
typedef struct BN_CTX BN_CTX;
typedef struct EC_GROUP EC_GROUP;
typedef struct EC_KEY EC_KEY;
typedef struct EC_POINT EC_POINT;
typedef struct evp_pkey_st EVP_PKEY;
typedef struct EVP_PKEY_CTX EVP_PKEY_CTX;
typedef struct PKCS8_PRIV_KEY_INFO PKCS8_PRIV_KEY_INFO;
typedef struct X509_ALGOR X509_ALGOR;
typedef struct X509_EXTENSION X509_EXTENSION;
typedef struct X509_NAME X509_NAME;
typedef struct BIGNUM BIGNUM;
typedef struct HMAC_CTX HMAC_CTX;
typedef struct rsa_meth_st RSA_METHOD;
typedef struct ecdsa_method_st ECDSA_METHOD;
typedef struct BN_GENCB BN_GENCB;
typedef struct sha256_state_st SHA256_CTX;
typedef struct sha_state_st SHA_CTX;
typedef struct cbb_st CBB;
typedef struct ecdsa_sig_st ECDSA_SIG;
typedef void RSA;
#ifdef __cplusplus
}
#endif
#endif /* OPENSSL_MBEDTLS_WRAPPER_BASE_H */

View File

@@ -1,42 +0,0 @@
/****************************************************************************
* apps/crypto/openssl_mbedtls_wrapper/include/openssl/bio.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
****************************************************************************/
#ifndef OPENSSL_MBEDTLS_WRAPPER_BIO_H
#define OPENSSL_MBEDTLS_WRAPPER_BIO_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <openssl/base.h>
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
#ifdef __cplusplus
extern "C"
{
#endif
#ifdef __cplusplus
}
#endif
#endif /* OPENSSL_MBEDTLS_WRAPPER_BIO_H */

View File

@@ -1,76 +0,0 @@
/****************************************************************************
* apps/crypto/openssl_mbedtls_wrapper/include/openssl/bn.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
****************************************************************************/
#ifndef OPENSSL_MBEDTLS_WRAPPER_BN_H
#define OPENSSL_MBEDTLS_WRAPPER_BN_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <openssl/asn1.h>
#include <openssl/base.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define BN_ULONG uint32_t
#define BN_BITS2 32
#ifdef __cplusplus
extern "C"
{
#endif
/****************************************************************************
* Public Types
****************************************************************************/
typedef uint32_t BN_ULONG;
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
BN_CTX *BN_CTX_new(void);
void BN_CTX_free(BN_CTX *a);
void BN_free(BIGNUM *a);
BN_ULONG BN_get_word(const BIGNUM *bn);
unsigned BN_num_bits(const BIGNUM *bn);
BIGNUM *BN_new(void);
int BN_bn2binpad(const BIGNUM *in, uint8_t *out, int len);
int BN_set_word(BIGNUM *bn, BN_ULONG value);
BIGNUM *BN_dup(const BIGNUM *src);
BIGNUM *BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret);
int BN_one(BIGNUM *bn);
#ifdef __cplusplus
}
#endif
#endif /* OPENSSL_MBEDTLS_WRAPPER_BN_H */

View File

@@ -1,114 +0,0 @@
/****************************************************************************
* apps/crypto/openssl_mbedtls_wrapper/include/openssl/bytestring.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
****************************************************************************/
#ifndef OPENSSL_MBEDTLS_WRAPPER_BYTESTRING_H
#define OPENSSL_MBEDTLS_WRAPPER_BYTESTRING_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <openssl/base.h>
#ifdef __cplusplus
extern "C"
{
#endif
/****************************************************************************
* Public Types
****************************************************************************/
struct cbb_buffer_st
{
uint8_t * buf;
/* len is the number of valid bytes in |buf|. */
size_t len;
/* cap is the size of |buf|. */
size_t cap;
/* can_resize is one iff |buf| is owned by this object. If not then |buf|
* cannot be resized.
*/
unsigned can_resize : 1;
/* error is one if there was an error writing to this CBB. All future
* operations will fail.
*/
unsigned error : 1;
};
struct cbb_child_st
{
/* base is a pointer to the buffer this |CBB| writes to. */
struct cbb_buffer_st * base;
/* offset is the number of bytes from the start of
* |base->buf| to this |CBB|'s
* pending length prefix.
*/
size_t offset;
/* pending_len_len contains the number of bytes in this |CBB|'s pending
* length-prefix, or zero if no length-prefix is pending.
*/
uint8_t pending_len_len;
unsigned pending_is_asn1 : 1;
};
struct cbb_st
{
/* child points to a child CBB if a length-prefix is pending.
* CBB* child;
* is_child is one if this is a child |CBB| and zero if it is a top-level
* |CBB|. This determines which arm of the union is valid.
*/
char is_child;
union
{
struct cbb_buffer_st base;
struct cbb_child_st child;
} u;
};
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
int CBB_init(CBB *cbb, size_t initial_capacity);
int CBB_finish(CBB *cbb, uint8_t **out_data, size_t *out_len);
void CBB_cleanup(CBB *cbb);
#ifdef __cplusplus
}
#endif
#endif /* OPENSSL_MBEDTLS_WRAPPER_BYTESTRING_H */

View File

@@ -1,108 +0,0 @@
/****************************************************************************
* apps/crypto/openssl_mbedtls_wrapper/include/openssl/cipher.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
****************************************************************************/
#ifndef OPENSSL_MBEDTLS_WRAPPER_CIPER_H
#define OPENSSL_MBEDTLS_WRAPPER_CIPER_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <openssl/base.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define CIPHER_R_BAD_DECRYPT 101
#define EVP_CTRL_GCM_GET_TAG 0x10
#define EVP_CTRL_GCM_SET_TAG 0x11
#ifdef __cplusplus
extern "C"
{
#endif
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx);
int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *ctx);
const EVP_CIPHER *EVP_aes_128_ecb(void);
const EVP_CIPHER *EVP_aes_192_ecb(void);
const EVP_CIPHER *EVP_aes_256_ecb(void);
const EVP_CIPHER *EVP_aes_128_cbc(void);
const EVP_CIPHER *EVP_aes_192_cbc(void);
const EVP_CIPHER *EVP_aes_256_cbc(void);
const EVP_CIPHER *EVP_aes_128_ctr(void);
const EVP_CIPHER *EVP_aes_192_ctr(void);
const EVP_CIPHER *EVP_aes_256_ctr(void);
const EVP_CIPHER *EVP_aes_128_gcm(void);
const EVP_CIPHER *EVP_aes_192_gcm(void);
const EVP_CIPHER *EVP_aes_256_gcm(void);
const EVP_CIPHER *EVP_des_ede(void);
const EVP_CIPHER *EVP_des_ede3(void);
const EVP_CIPHER *EVP_des_ede_cbc(void);
const EVP_CIPHER *EVP_des_ede3_cbc(void);
int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr);
int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *c, int pad);
int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
ENGINE *impl, const unsigned char *key,
const unsigned char *iv, int enc);
int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
int *outl, const unsigned char *in,
int inl);
int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm,
int *outl);
int EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx);
EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void);
void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx);
int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
ENGINE *impl, const uint8_t *key,
const uint8_t *iv);
int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
ENGINE *impl, const uint8_t *key,
const uint8_t *iv);
int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out,
int *out_len, const uint8_t *in,
int in_len);
int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len);
int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out,
int *out_len, const uint8_t *in,
int in_len);
int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len);
#ifdef __cplusplus
}
#endif
#endif /* OPENSSL_MBEDTLS_WRAPPER_CIPER_H */

View File

@@ -1,77 +0,0 @@
/****************************************************************************
* apps/crypto/openssl_mbedtls_wrapper/include/openssl/curve25519.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
****************************************************************************/
#ifndef OPENSSL_MBEDTLS_WRAPPER_CURVE25519_H
#define OPENSSL_MBEDTLS_WRAPPER_CURVE25519_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <openssl/base.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define X25519_PRIVATE_KEY_LEN 32
#define X25519_PUBLIC_VALUE_LEN 32
#define X25519_SHARED_KEY_LEN 32
#define ED25519_PRIVATE_KEY_LEN 64
#define ED25519_PUBLIC_KEY_LEN 32
#define ED25519_SIGNATURE_LEN 64
#ifdef __cplusplus
extern "C"
{
#endif
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
/* ED25519_keypair sets |out_public_key| and |out_private_key| to a freshly
* generated, publicprivate key pair.
*/
void ED25519_keypair(uint8_t out_public_key[32],
uint8_t out_private_key[64]);
void X25519_keypair(uint8_t out_public_value[32],
uint8_t out_private_key[32]);
int X25519(uint8_t out_shared_key[32], const uint8_t private_key[32],
const uint8_t peer_public_value[32]);
int ED25519_sign(uint8_t out_sig[64], const uint8_t *message,
size_t message_len, const uint8_t private_key[64]);
int ED25519_verify(const uint8_t *message, size_t message_len,
const uint8_t signature[64],
const uint8_t public_key[32]);
void ED25519_keypair_from_seed(uint8_t out_public_key[32],
uint8_t out_private_key[64],
const uint8_t seed[32]);
#ifdef __cplusplus
}
#endif
#endif /* OPENSSL_MBEDTLS_WRAPPER_CURVE25519_H */

Some files were not shown because too many files have changed in this diff Show More