Update wifi marauder

This commit is contained in:
MX 2023-07-05 20:26:47 +03:00
parent 93acba9ae3
commit a9d4897dfb
No known key found for this signature in database
GPG key ID: 7CCC66B7DBDD1C83
47 changed files with 5416 additions and 9 deletions

View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. 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
them 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 prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey 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;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
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.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
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.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
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
state 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 3 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, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program 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, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU 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. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View file

@ -1,8 +1,41 @@
# WiFi Marauder companion app for Flipper Zero
Requires a connected dev board running Marauder FW. [See install instructions from UberGuidoZ here.](https://github.com/UberGuidoZ/Flipper/tree/main/Wifi_DevBoard#marauder-install-information)
## https://github.com/0xchocolate/flipperzero-wifi-marauder
Requires a connected dev board running Marauder FW. [See install instructions from UberGuidoZ here.](https://github.com/UberGuidoZ/Flipper/tree/main/Wifi_DevBoard#marauder-install-information)
## Get the app
1. Make sure you're logged in with a github account (otherwise the downloads in step 2 won't work)
2. Navigate to the [FAP Build](https://github.com/0xchocolate/flipperzero-wifi-marauder/actions/workflows/build.yml)
GitHub action workflow, and select the most recent run, scroll down to artifacts.
3. The FAP is built for the `dev` and `release` channels of both official and unleashed
firmware. Download the artifact corresponding to your firmware version.
4. (Optional step to avoid confusion) Go to "Apps/GPIO" on the Flipper SD Card, delete any existing Marauder app, on some firmwares there will be a `ESP32CAM_Marauder.fap` or similar.
5. Extract `esp32_wifi_marauder.fap` from the ZIP file downloaded in step 3 to your Flipper Zero SD card, preferably under Apps/GPIO along with the rest of the GPIO apps. (If you're using qFlipper to transfer files you need to extract the content of the ZIP file to your computer before you drag it to qFlipper, as qFlipper does not support direct dragging from a ZIP file (at least on Windows)).
From a local clone of this repo, you can also build the app yourself using ufbt.
## In-app ESP32 flasher (WIP)
Guide by [@francis2054](https://github.com/francis2054)
The app now contains a work-in-progress of an ESP32 flasher (close to the bottom of the marauder menu). Use at your own risk. This hardcodes addresses for non-S3 ESP32 chips.
To use this method:
1. Make sure you follow the instructions for how to get the Marauder app on your Flipper Zero, they can be found on the top of this page. Latest release needs to be downloaded and installed.
2. Go to [Justcallmekoko's firmware page](https://github.com/justcallmekoko/ESP32Marauder/wiki/update-firmware#using-spacehuhn-web-updater) and download all files necessary for the board you are flashing, most boards will want all 4 files but for the Wifi Devboard you want to download these 3 files: `0x1000` (Bootloader), `0x8000` (partitions), `0x10000` (Firmware). The `Boot App` is not needed for the Wifi Devboard with this method. The Firmware one will redirect you to the releases page where you'll need to pick the one relevant to the board you're flashing, if you are using the official Wi-Fi Devboard you want to pick the one ending in `_flipper_sd_serial.bin`.
3. Place all files downloaded in step 2 in a new folder on your desktop, the name does not matter. Rename the `_flipper_sd_serial.bin` file you downloaded in step 2 to `Firmware.bin`.
4. Now for transferring the files to the Flipper Zero, drag all the files from the folder on your desktop to the "Marauder" folder inside "apps_data" folder on the Flipper Zero SD card. Preferred method to transfer these files is plugging the SD card into your computer with an adapter, but qFlipper works as well. Insert the Flipper Zero SD Card back into the Flipper before proceeding to the next step.
5. Plug your Wi-Fi Devboard into the Flipper.
6. Press and keep holding the boot button while you press the reset button once, release the boot button after 2 seconds.
7. Open the Marauder app on your Flipper Zero, it should be named "esp32_wifi_marauder" and be located under Apps->GPIO from the main menu if you followed the instructions for how to install the app further up on this page. (You might get an API mismatch error if the Flipper firmware you are running doesn't match the files you've downloaded, you can try "Continue" anyway, otherwise the app needs to be rebuilt or you might need to update the firmware on your Flipper).
8. Press the up arrow on the Flipper three times to get to "Reflash ESP32 (WIP)" and open it.
9. For "Bootloader" scroll down in the list and select `esp32_marauder.ino.bootloader.bin`, for "Paritition table" select `esp32_marauder.ino.partitions.bin` and for "Firmware" select `Firmware.bin`.
10. Scroll down and click "[>] FLASH" and wait for it to complete. (If you get errors here, press back button once and repeat step 6 then try "[>] FLASH" again).
11. Once it says "Done flashing" on the screen, restart the Flipper and you are done :)
## For future updates, just repeat from step 2 and only download the new "Firmware" bin
This process will improve with future updates! :)
## Support

View file

@ -8,5 +8,22 @@ App(
order=90,
fap_icon="wifi_10px.png",
fap_category="GPIO",
fap_private_libs=[
Lib(
name="esp-serial-flasher",
fap_include_paths=["include"],
sources=[
"src/esp_loader.c",
"src/esp_targets.c",
"src/md5_hash.c",
"src/protocol_common.c",
"src/protocol_uart.c",
"src/slip.c"
],
cincludes=["lib/esp-serial-flasher/private_include"],
cdefines=["SERIAL_FLASHER_INTERFACE_UART=1", "MD5_ENABLED=1"],
),
],
cdefines=["SERIAL_FLASHER_INTERFACE_UART=1"],
fap_icon_assets="assets",
)

View file

@ -0,0 +1,9 @@
## WiFi Marauder companion app for Flipper Zero
Requires a connected dev board running Marauder FW. See install instructions from UberGuidoZ here: https://github.com/UberGuidoZ/Flipper/tree/main/Wifi_DevBoard#marauder-install-information
## Support
For app feedback, bugs, and feature requests, please create an issue here: https://github.com/0xchocolate/flipperzero-wifi-marauder/issues
You can find me (0xchocolate) on discord as @cococode.

View file

@ -0,0 +1,5 @@
## v0.4.0
Added Signal Monitor (thanks @justcallmekoko!) to support new sigmon command in Marauder v0.10.5: https://github.com/justcallmekoko/ESP32Marauder/releases
Added keyboard and +5V support from unleashed (thanks @xMasterX!)

View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View file

@ -0,0 +1,154 @@
# esp-serial-flasher
`esp-serial-flasher` is a portable C library for flashing or loading apps to RAM of Espressif SoCs from other host microcontrollers.
## Using the library
Espressif SoCs are normally programmed via serial interface (UART). The port layer for the given host microcontroller has to be implemented if not available. Details can be found in section below.
Supported **host** microcontrollers:
- STM32
- Raspberry Pi SBC
- ESP32
- Any MCU running Zephyr OS
Supported **target** microcontrollers:
- ESP32
- ESP8266
- ESP32-S2
- ESP32-S3
- ESP32-C3
- ESP32-C2
- ESP32-H2
Supported hardware interfaces:
- UART
- SPI (only for RAM download, experimental)
For example usage check the `examples` directory.
## Supporting a new host target
In order to support a new target, following functions have to be implemented by user:
- `loader_port_read()`
- `loader_port_write()`
- `loader_port_enter_bootloader()`
- `loader_port_delay_ms()`
- `loader_port_start_timer()`
- `loader_port_remaining_time()`
For the SPI interface ports
- `loader_port_spi_set_cs()`
needs to be implemented as well.
The following functions are part of the [io.h](include/io.h) header for convenience, however, the user does not have to strictly follow function signatures, as there are not called directly from library.
- `loader_port_change_transmission_rate()`
- `loader_port_reset_target()`
- `loader_port_debug_print()`
Prototypes of all functions mentioned above can be found in [io.h](include/io.h).
## Configuration
These are the configuration toggles available to the user:
* `SERIAL_FLASHER_INTERFACE_UART/SERIAL_FLASHER_INTERFACE_SPI`
This defines the hardware interface to use. SPI interface only supports RAM download mode and is in experimental stage and can undergo changes.
Default: SERIAL_FLASHER_INTERFACE_UART
* `MD5_ENABLED`
If enabled, `esp-serial-flasher` is capable of verifying flash integrity after writing to flash.
Default: Enabled
> Warning: As ROM bootloader of the ESP8266 does not support MD5_CHECK, this option has to be disabled!
* `SERIAL_FLASHER_RESET_HOLD_TIME_MS`
This is the time for which the reset pin is asserted when doing a hard reset in milliseconds.
Default: 100
* `SERIAL_FLASHER_BOOT_HOLD_TIME_MS`
This is the time for which the boot pin is asserted when doing a hard reset in milliseconds.
Default: 50
Configuration can be passed to `cmake` via command line:
```
cmake -DMD5_ENABLED=1 .. && cmake --build .
```
### STM32 support
The STM32 port makes use of STM32 HAL libraries, and these do not come with CMake support. In order to compile the project, `stm32-cmake` (a `CMake` support package) has to be pulled as submodule.
```
git clone --recursive https://github.com/espressif/esp-serial-flasher.git
```
If you have cloned this repository without the `--recursive` flag, you can initialize the submodule using the following command:
```
git submodule update --init
```
In addition to configuration parameters mentioned above, following definitions has to be set:
- TOOLCHAIN_PREFIX: path to arm toolchain (i.e /home/user/gcc-arm-none-eabi-9-2019-q4-major)
- STM32Cube_DIR: path to STM32 Cube libraries (i.e /home/user/STM32Cube/Repository/STM32Cube_FW_F4_V1.25.0)
- STM32_CHIP: name of STM32 for which project should be compiled (i.e STM32F407VG)
- PORT: STM32
This can be achieved by passing definitions to the command line, such as:
```
cmake -DTOOLCHAIN_PREFIX="/path_to_toolchain" -DSTM32Cube_DIR="path_to_stm32Cube" -DSTM32_CHIP="STM32F407VG" -DPORT="STM32" .. && cmake --build .
```
Alternatively, those variables can be set in the top level `cmake` directory:
```
set(TOOLCHAIN_PREFIX path_to_toolchain)
set(STM32Cube_DIR path_to_stm32_HAL)
set(STM32_CHIP STM32F407VG)
set(PORT STM32)
```
### Zephyr support
The Zephyr port is ready to be integrated into Zephyr apps as a Zephyr module. In the manifest file (west.yml), add:
```
- name: esp-flasher
url: https://github.com/espressif/esp-serial-flasher
revision: master
path: modules/lib/esp_flasher
```
And add
```
CONFIG_ESP_SERIAL_FLASHER=y
CONFIG_CONSOLE_GETCHAR=y
CONFIG_SERIAL_FLASHER_MD5_ENABLED=y
```
to the project configuration `prj.conf`.
For the C/C++ source code, the example code provided in `examples/zephyr_example` can be used as a starting point.
## Licence
Code is distributed under Apache 2.0 license.
## Known limitations
Size of new binary image has to be known before flashing.

View file

@ -0,0 +1,313 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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.
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Used for backwards compatibility with the previous API */
#define esp_loader_change_baudrate esp_loader_change_transmission_rate
/**
* Macro which can be used to check the error code,
* and return in case the code is not ESP_LOADER_SUCCESS.
*/
#define RETURN_ON_ERROR(x) do { \
esp_loader_error_t _err_ = (x); \
if (_err_ != ESP_LOADER_SUCCESS) { \
return _err_; \
} \
} while(0)
/**
* @brief Error codes
*/
typedef enum {
ESP_LOADER_SUCCESS, /*!< Success */
ESP_LOADER_ERROR_FAIL, /*!< Unspecified error */
ESP_LOADER_ERROR_TIMEOUT, /*!< Timeout elapsed */
ESP_LOADER_ERROR_IMAGE_SIZE, /*!< Image size to flash is larger than flash size */
ESP_LOADER_ERROR_INVALID_MD5, /*!< Computed and received MD5 does not match */
ESP_LOADER_ERROR_INVALID_PARAM, /*!< Invalid parameter passed to function */
ESP_LOADER_ERROR_INVALID_TARGET, /*!< Connected target is invalid */
ESP_LOADER_ERROR_UNSUPPORTED_CHIP, /*!< Attached chip is not supported */
ESP_LOADER_ERROR_UNSUPPORTED_FUNC, /*!< Function is not supported on attached target */
ESP_LOADER_ERROR_INVALID_RESPONSE /*!< Internal error */
} esp_loader_error_t;
/**
* @brief Supported targets
*/
typedef enum {
ESP8266_CHIP = 0,
ESP32_CHIP = 1,
ESP32S2_CHIP = 2,
ESP32C3_CHIP = 3,
ESP32S3_CHIP = 4,
ESP32C2_CHIP = 5,
ESP32H4_CHIP = 6,
ESP32H2_CHIP = 7,
ESP_MAX_CHIP = 8,
ESP_UNKNOWN_CHIP = 8
} target_chip_t;
/**
* @brief Application binary header
*/
typedef struct {
uint8_t magic;
uint8_t segments;
uint8_t flash_mode;
uint8_t flash_size_freq;
uint32_t entrypoint;
} esp_loader_bin_header_t;
/**
* @brief Segment binary header
*/
typedef struct {
uint32_t addr;
uint32_t size;
uint8_t *data;
} esp_loader_bin_segment_t;
/**
* @brief SPI pin configuration arguments
*/
typedef union {
struct {
uint32_t pin_clk: 6;
uint32_t pin_q: 6;
uint32_t pin_d: 6;
uint32_t pin_cs: 6;
uint32_t pin_hd: 6;
uint32_t zero: 2;
};
uint32_t val;
} esp_loader_spi_config_t;
/**
* @brief Connection arguments
*/
typedef struct {
uint32_t sync_timeout; /*!< Maximum time to wait for response from serial interface. */
int32_t trials; /*!< Number of trials to connect to target. If greater than 1,
100 millisecond delay is inserted after each try. */
} esp_loader_connect_args_t;
#define ESP_LOADER_CONNECT_DEFAULT() { \
.sync_timeout = 100, \
.trials = 10, \
}
/**
* @brief Connects to the target
*
* @param connect_args[in] Timing parameters to be used for connecting to target.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_connect(esp_loader_connect_args_t *connect_args);
/**
* @brief Returns attached target chip.
*
* @warning This function can only be called after connection with target
* has been successfully established by calling esp_loader_connect().
*
* @return One of target_chip_t
*/
target_chip_t esp_loader_get_target(void);
#ifdef SERIAL_FLASHER_INTERFACE_UART
/**
* @brief Initiates flash operation
*
* @param offset[in] Address from which flash operation will be performed.
* @param image_size[in] Size of the whole binary to be loaded into flash.
* @param block_size[in] Size of buffer used in subsequent calls to esp_loader_flash_write.
*
* @note image_size is size of the whole image, whereas, block_size is chunk of data sent
* to the target, each time esp_loader_flash_write function is called.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_flash_start(uint32_t offset, uint32_t image_size, uint32_t block_size);
/**
* @brief Writes supplied data to target's flash memory.
*
* @param payload[in] Data to be flashed into target's memory.
* @param size[in] Size of payload in bytes.
*
* @note size must not be greater that block_size supplied to previously called
* esp_loader_flash_start function. If size is less than block_size,
* remaining bytes of payload buffer will be padded with 0xff.
* Therefore, size of payload buffer has to be equal or greater than block_size.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_flash_write(void *payload, uint32_t size);
/**
* @brief Ends flash operation.
*
* @param reboot[in] reboot the target if true.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_flash_finish(bool reboot);
#endif /* SERIAL_FLASHER_INTERFACE_UART */
/**
* @brief Initiates mem operation, initiates loading for program into target RAM
*
* @param offset[in] Address from which mem operation will be performed.
* @param size[in] Size of the whole binary to be loaded into mem.
* @param block_size[in] Size of buffer used in subsequent calls to esp_loader_mem_write.
*
* @note image_size is size of the whole image, whereas, block_size is chunk of data sent
* to the target, each time esp_mem_flash_write function is called.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_mem_start(uint32_t offset, uint32_t size, uint32_t block_size);
/**
* @brief Writes supplied data to target's mem memory.
*
* @param payload[in] Data to be loaded into target's memory.
* @param size[in] Size of data in bytes.
*
* @note size must not be greater that block_size supplied to previously called
* esp_loader_mem_start function.
* Therefore, size of data buffer has to be equal or greater than block_size.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_mem_write(const void *payload, uint32_t size);
/**
* @brief Ends mem operation, finish loading for program into target RAM
* and send the entrypoint of ram_loadable app
*
* @param entrypoint[in] entrypoint of ram program.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_mem_finish(uint32_t entrypoint);
/**
* @brief Writes register.
*
* @param address[in] Address of register.
* @param reg_value[in] New register value.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_write_register(uint32_t address, uint32_t reg_value);
/**
* @brief Reads register.
*
* @param address[in] Address of register.
* @param reg_value[out] Register value.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
*/
esp_loader_error_t esp_loader_read_register(uint32_t address, uint32_t *reg_value);
/**
* @brief Change baud rate.
*
* @note Baud rate has to be also adjusted accordingly on host MCU, as
* target's baud rate is changed upon return from this function.
*
* @param transmission_rate[in] new baud rate to be set.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC Unsupported on the target
*/
esp_loader_error_t esp_loader_change_transmission_rate(uint32_t transmission_rate);
/**
* @brief Verify target's flash integrity by checking MD5.
* MD5 checksum is computed from data pushed to target's memory by calling
* esp_loader_flash_write() function and compared against target's MD5.
* Target computes checksum based on offset and image_size passed to
* esp_loader_flash_start() function.
*
* @note This function is only available if MD5_ENABLED is set.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_INVALID_MD5 MD5 does not match
* - ESP_LOADER_ERROR_TIMEOUT Timeout
* - ESP_LOADER_ERROR_INVALID_RESPONSE Internal error
* - ESP_LOADER_ERROR_UNSUPPORTED_FUNC Unsupported on the target
*/
#if MD5_ENABLED
esp_loader_error_t esp_loader_flash_verify(void);
#endif
/**
* @brief Toggles reset pin.
*/
void esp_loader_reset_target(void);
#ifdef __cplusplus
}
#endif

View file

@ -0,0 +1,112 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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.
*/
#pragma once
#include <stdint.h>
#include "esp_loader.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Changes the transmission rate of the used peripheral.
*/
esp_loader_error_t loader_port_change_transmission_rate(uint32_t transmission_rate);
/**
* @brief Writes data over the io interface.
*
* @param data[in] Buffer with data to be written.
* @param size[in] Size of data in bytes.
* @param timeout[in] Timeout in milliseconds.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout elapsed
*/
esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout);
/**
* @brief Reads data from the io interface.
*
* @param data[out] Buffer into which received data will be written.
* @param size[in] Number of bytes to read.
* @param timeout[in] Timeout in milliseconds.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_TIMEOUT Timeout elapsed
*/
esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout);
/**
* @brief Delay in milliseconds.
*
* @param ms[in] Number of milliseconds.
*
*/
void loader_port_delay_ms(uint32_t ms);
/**
* @brief Starts timeout timer.
*
* @param ms[in] Number of milliseconds.
*
*/
void loader_port_start_timer(uint32_t ms);
/**
* @brief Returns remaining time since timer was started by calling esp_loader_start_timer.
* 0 if timer has elapsed.
*
* @return Number of milliseconds.
*
*/
uint32_t loader_port_remaining_time(void);
/**
* @brief Asserts bootstrap pins to enter boot mode and toggles reset pin.
*
* @note Reset pin should stay asserted for at least 20 milliseconds.
*/
void loader_port_enter_bootloader(void);
/**
* @brief Toggles reset pin.
*
* @note Reset pin should stay asserted for at least 20 milliseconds.
*/
void loader_port_reset_target(void);
/**
* @brief Function can be defined by user to print debug message.
*
* @note Empty weak function is used, otherwise.
*
*/
void loader_port_debug_print(const char *str);
#ifdef SERIAL_FLASHER_INTERFACE_SPI
/**
* @brief Sets the chip select to a defined level
*/
void loader_port_spi_set_cs(uint32_t level);
#endif /* SERIAL_FLASHER_INTERFACE_SPI */
#ifdef __cplusplus
}
#endif

View file

@ -0,0 +1,24 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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.
*/
#warning Please replace serial_io.h with esp_loader_io.h and change the function names \
to match the new API
/* Defines used to avoid breaking existing ports */
#define loader_port_change_baudrate loader_port_change_transmission_rate
#define loader_port_serial_write loader_port_write
#define loader_port_serial_read loader_port_read
#include "esp_loader_io.h"

View file

@ -0,0 +1,181 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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 "esp32_port.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "esp_timer.h"
#include "esp_log.h"
#include "esp_idf_version.h"
#include <unistd.h>
#ifdef SERIAL_FLASHER_DEBUG_TRACE
static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write)
{
static bool write_prev = false;
if (write_prev != write) {
write_prev = write;
printf("\n--- %s ---\n", write ? "WRITE" : "READ");
}
for (uint32_t i = 0; i < size; i++) {
printf("%02x ", data[i]);
}
}
#endif
static int64_t s_time_end;
static int32_t s_uart_port;
static int32_t s_reset_trigger_pin;
static int32_t s_gpio0_trigger_pin;
esp_loader_error_t loader_port_esp32_init(const loader_esp32_config_t *config)
{
s_uart_port = config->uart_port;
s_reset_trigger_pin = config->reset_trigger_pin;
s_gpio0_trigger_pin = config->gpio0_trigger_pin;
// Initialize UART
uart_config_t uart_config = {
.baud_rate = config->baud_rate,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
.source_clk = UART_SCLK_DEFAULT,
#endif
};
int rx_buffer_size = config->rx_buffer_size ? config->rx_buffer_size : 400;
int tx_buffer_size = config->tx_buffer_size ? config->tx_buffer_size : 400;
QueueHandle_t *uart_queue = config->uart_queue ? config->uart_queue : NULL;
int queue_size = config->queue_size ? config->queue_size : 0;
if ( uart_param_config(s_uart_port, &uart_config) != ESP_OK ) {
return ESP_LOADER_ERROR_FAIL;
}
if ( uart_set_pin(s_uart_port, config->uart_tx_pin, config->uart_rx_pin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE) != ESP_OK ) {
return ESP_LOADER_ERROR_FAIL;
}
if ( uart_driver_install(s_uart_port, rx_buffer_size, tx_buffer_size, queue_size, uart_queue, 0) != ESP_OK ) {
return ESP_LOADER_ERROR_FAIL;
}
// Initialize boot pin selection pins
gpio_reset_pin(s_reset_trigger_pin);
gpio_set_pull_mode(s_reset_trigger_pin, GPIO_PULLUP_ONLY);
gpio_set_direction(s_reset_trigger_pin, GPIO_MODE_OUTPUT);
gpio_reset_pin(s_gpio0_trigger_pin);
gpio_set_pull_mode(s_gpio0_trigger_pin, GPIO_PULLUP_ONLY);
gpio_set_direction(s_gpio0_trigger_pin, GPIO_MODE_OUTPUT);
return ESP_LOADER_SUCCESS;
}
void loader_port_esp32_deinit(void)
{
uart_driver_delete(s_uart_port);
}
esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout)
{
uart_write_bytes(s_uart_port, (const char *)data, size);
esp_err_t err = uart_wait_tx_done(s_uart_port, pdMS_TO_TICKS(timeout));
if (err == ESP_OK) {
#ifdef SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, size, true);
#endif
return ESP_LOADER_SUCCESS;
} else if (err == ESP_ERR_TIMEOUT) {
return ESP_LOADER_ERROR_TIMEOUT;
} else {
return ESP_LOADER_ERROR_FAIL;
}
}
esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout)
{
int read = uart_read_bytes(s_uart_port, data, size, pdMS_TO_TICKS(timeout));
if (read < 0) {
return ESP_LOADER_ERROR_FAIL;
} else if (read < size) {
#ifdef SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, read, false);
#endif
return ESP_LOADER_ERROR_TIMEOUT;
} else {
#ifdef SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, read, false);
#endif
return ESP_LOADER_SUCCESS;
}
}
// Set GPIO0 LOW, then
// assert reset pin for 50 milliseconds.
void loader_port_enter_bootloader(void)
{
gpio_set_level(s_gpio0_trigger_pin, 0);
loader_port_reset_target();
loader_port_delay_ms(SERIAL_FLASHER_BOOT_HOLD_TIME_MS);
gpio_set_level(s_gpio0_trigger_pin, 1);
}
void loader_port_reset_target(void)
{
gpio_set_level(s_reset_trigger_pin, 0);
loader_port_delay_ms(SERIAL_FLASHER_RESET_HOLD_TIME_MS);
gpio_set_level(s_reset_trigger_pin, 1);
}
void loader_port_delay_ms(uint32_t ms)
{
usleep(ms * 1000);
}
void loader_port_start_timer(uint32_t ms)
{
s_time_end = esp_timer_get_time() + ms * 1000;
}
uint32_t loader_port_remaining_time(void)
{
int64_t remaining = (s_time_end - esp_timer_get_time()) / 1000;
return (remaining > 0) ? (uint32_t)remaining : 0;
}
void loader_port_debug_print(const char *str)
{
printf("DEBUG: %s\n", str);
}
esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate)
{
esp_err_t err = uart_set_baudrate(s_uart_port, baudrate);
return (err == ESP_OK) ? ESP_LOADER_SUCCESS : ESP_LOADER_ERROR_FAIL;
}

View file

@ -0,0 +1,59 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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.
*/
#pragma once
#include "esp_loader_io.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
uint32_t baud_rate; /*!< Initial baud rate, can be changed later */
uint32_t uart_port; /*!< UART port */
uint32_t uart_rx_pin; /*!< This pin will be configured as UART Rx pin */
uint32_t uart_tx_pin; /*!< This pin will be configured as UART Tx pin */
uint32_t reset_trigger_pin; /*!< This pin will be used to reset target chip */
uint32_t gpio0_trigger_pin; /*!< This pin will be used to toggle set IO0 of target chip */
uint32_t rx_buffer_size; /*!< Set to zero for default RX buffer size */
uint32_t tx_buffer_size; /*!< Set to zero for default TX buffer size */
uint32_t queue_size; /*!< Set to zero for default UART queue size */
QueueHandle_t *uart_queue; /*!< Set to NULL, if UART queue handle is not
necessary. Otherwise, it will be assigned here */
} loader_esp32_config_t;
/**
* @brief Initializes serial interface.
*
* @param baud_rate[in] Communication speed.
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_FAIL Initialization failure
*/
esp_loader_error_t loader_port_esp32_init(const loader_esp32_config_t *config);
/**
* @brief Deinitialize serial interface.
*/
void loader_port_esp32_deinit(void);
#ifdef __cplusplus
}
#endif

View file

@ -0,0 +1,298 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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 "esp32_spi_port.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "esp_timer.h"
#include "esp_log.h"
#include "esp_idf_version.h"
#include <unistd.h>
// #define SERIAL_DEBUG_ENABLE
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 3, 0)
#define DMA_CHAN SPI_DMA_CH_AUTO
#else
#define DMA_CHAN 1
#endif
#define WORD_ALIGNED(ptr) ((size_t)ptr % sizeof(size_t) == 0)
#ifdef SERIAL_DEBUG_ENABLE
static void dec_to_hex_str(const uint8_t dec, uint8_t hex_str[3])
{
static const uint8_t dec_to_hex[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
hex_str[0] = dec_to_hex[dec >> 4];
hex_str[1] = dec_to_hex[dec & 0xF];
hex_str[2] = '\0';
}
static void serial_debug_print(const uint8_t *data, uint16_t size, bool write)
{
static bool write_prev = false;
uint8_t hex_str[3];
if(write_prev != write) {
write_prev = write;
printf("\n--- %s ---\n", write ? "WRITE" : "READ");
}
for(uint32_t i = 0; i < size; i++) {
dec_to_hex_str(data[i], hex_str);
printf("%s ", hex_str);
}
}
#else
static void serial_debug_print(const uint8_t *data, uint16_t size, bool write) { }
#endif
static spi_host_device_t s_spi_bus;
static spi_bus_config_t s_spi_config;
static spi_device_handle_t s_device_h;
static spi_device_interface_config_t s_device_config;
static int64_t s_time_end;
static uint32_t s_reset_trigger_pin;
static uint32_t s_strap_bit0_pin;
static uint32_t s_strap_bit1_pin;
static uint32_t s_strap_bit2_pin;
static uint32_t s_strap_bit3_pin;
static uint32_t s_spi_cs_pin;
esp_loader_error_t loader_port_esp32_spi_init(const loader_esp32_spi_config_t *config)
{
/* Initialize the global static variables*/
s_spi_bus = config->spi_bus;
s_reset_trigger_pin = config->reset_trigger_pin;
s_strap_bit0_pin = config->strap_bit0_pin;
s_strap_bit1_pin = config->strap_bit1_pin;
s_strap_bit2_pin = config->strap_bit2_pin;
s_strap_bit3_pin = config->strap_bit3_pin;
s_spi_cs_pin = config->spi_cs_pin;
/* Configure and initialize the SPI bus*/
s_spi_config.mosi_io_num = config->spi_mosi_pin;
s_spi_config.miso_io_num = config->spi_miso_pin;
s_spi_config.sclk_io_num = config->spi_clk_pin;
s_spi_config.quadwp_io_num = config->spi_quadwp_pin;
s_spi_config.quadhd_io_num = config->spi_quadhd_pin;
s_spi_config.max_transfer_sz = 4096 * 4;
if (spi_bus_initialize(s_spi_bus, &s_spi_config, DMA_CHAN) != ESP_OK) {
return ESP_LOADER_ERROR_FAIL;
}
/* Configure and add the device */
s_device_config.clock_speed_hz = config->frequency;
s_device_config.spics_io_num = -1; /* We're using the chip select pin as GPIO as we need to
chain multiple transactions with CS pulled down */
s_device_config.flags = SPI_DEVICE_HALFDUPLEX;
s_device_config.queue_size = 16;
if (spi_bus_add_device(s_spi_bus, &s_device_config, &s_device_h) != ESP_OK) {
return ESP_LOADER_ERROR_FAIL;
}
/* Initialize the pins except for the strapping ones */
gpio_reset_pin(s_reset_trigger_pin);
gpio_set_pull_mode(s_reset_trigger_pin, GPIO_PULLUP_ONLY);
gpio_set_direction(s_reset_trigger_pin, GPIO_MODE_OUTPUT);
gpio_set_level(s_reset_trigger_pin, 1);
gpio_reset_pin(s_spi_cs_pin);
gpio_set_pull_mode(s_spi_cs_pin, GPIO_PULLUP_ONLY);
gpio_set_direction(s_spi_cs_pin, GPIO_MODE_OUTPUT);
gpio_set_level(s_spi_cs_pin, 1);
return ESP_LOADER_SUCCESS;
}
void loader_port_esp32_spi_deinit(void)
{
gpio_reset_pin(s_reset_trigger_pin);
gpio_reset_pin(s_spi_cs_pin);
spi_bus_remove_device(s_device_h);
spi_bus_free(s_spi_bus);
}
void loader_port_spi_set_cs(const uint32_t level) {
gpio_set_level(s_spi_cs_pin, level);
}
esp_loader_error_t loader_port_write(const uint8_t *data, const uint16_t size, const uint32_t timeout)
{
/* Due to the fact that the SPI driver uses DMA for larger transfers,
and the DMA requirements, the buffer must be word aligned */
if (data == NULL || !WORD_ALIGNED(data)) {
return ESP_LOADER_ERROR_INVALID_PARAM;
}
serial_debug_print(data, size, true);
spi_transaction_t transaction = {
.tx_buffer = data,
.rx_buffer = NULL,
.length = size * 8U,
.rxlength = 0,
};
esp_err_t err = spi_device_transmit(s_device_h, &transaction);
if (err == ESP_OK) {
serial_debug_print(data, size, false);
return ESP_LOADER_SUCCESS;
} else if (err == ESP_ERR_TIMEOUT) {
return ESP_LOADER_ERROR_TIMEOUT;
} else {
return ESP_LOADER_ERROR_FAIL;
}
}
esp_loader_error_t loader_port_read(uint8_t *data, const uint16_t size, const uint32_t timeout)
{
/* Due to the fact that the SPI driver uses DMA for larger transfers,
and the DMA requirements, the buffer must be word aligned */
if (data == NULL || !WORD_ALIGNED(data)) {
return ESP_LOADER_ERROR_INVALID_PARAM;
}
serial_debug_print(data, size, true);
spi_transaction_t transaction = {
.tx_buffer = NULL,
.rx_buffer = data,
.rxlength = size * 8,
};
esp_err_t err = spi_device_transmit(s_device_h, &transaction);
if (err == ESP_OK) {
serial_debug_print(data, size, false);
return ESP_LOADER_SUCCESS;
} else if (err == ESP_ERR_TIMEOUT) {
return ESP_LOADER_ERROR_TIMEOUT;
} else {
return ESP_LOADER_ERROR_FAIL;
}
}
void loader_port_enter_bootloader(void)
{
/*
We have to initialize the GPIO pins for the target strapping pins here,
as they may overlap with target SPI pins.
For instance in the case of ESP32C3 MISO and strapping bit 0 pins overlap.
*/
spi_bus_remove_device(s_device_h);
spi_bus_free(s_spi_bus);
gpio_reset_pin(s_strap_bit0_pin);
gpio_set_pull_mode(s_strap_bit0_pin, GPIO_PULLUP_ONLY);
gpio_set_direction(s_strap_bit0_pin, GPIO_MODE_OUTPUT);
gpio_reset_pin(s_strap_bit1_pin);
gpio_set_pull_mode(s_strap_bit1_pin, GPIO_PULLUP_ONLY);
gpio_set_direction(s_strap_bit1_pin, GPIO_MODE_OUTPUT);
gpio_reset_pin(s_strap_bit2_pin);
gpio_set_pull_mode(s_strap_bit2_pin, GPIO_PULLUP_ONLY);
gpio_set_direction(s_strap_bit2_pin, GPIO_MODE_OUTPUT);
gpio_reset_pin(s_strap_bit3_pin);
gpio_set_pull_mode(s_strap_bit3_pin, GPIO_PULLUP_ONLY);
gpio_set_direction(s_strap_bit3_pin, GPIO_MODE_OUTPUT);
/* Set the strapping pins and perform the reset sequence */
gpio_set_level(s_strap_bit0_pin, 1);
gpio_set_level(s_strap_bit1_pin, 0);
gpio_set_level(s_strap_bit2_pin, 0);
gpio_set_level(s_strap_bit3_pin, 0);
loader_port_reset_target();
loader_port_delay_ms(SERIAL_FLASHER_BOOT_HOLD_TIME_MS);
gpio_set_level(s_strap_bit3_pin, 1);
gpio_set_level(s_strap_bit0_pin, 0);
/* Disable the strapping pins so they can be used by the slave later */
gpio_reset_pin(s_strap_bit0_pin);
gpio_reset_pin(s_strap_bit1_pin);
gpio_reset_pin(s_strap_bit2_pin);
gpio_reset_pin(s_strap_bit3_pin);
/* Restore the SPI bus pins */
spi_bus_initialize(s_spi_bus, &s_spi_config, DMA_CHAN);
spi_bus_add_device(s_spi_bus, &s_device_config, &s_device_h);
}
void loader_port_reset_target(void)
{
gpio_set_level(s_reset_trigger_pin, 0);
loader_port_delay_ms(SERIAL_FLASHER_RESET_HOLD_TIME_MS);
gpio_set_level(s_reset_trigger_pin, 1);
}
void loader_port_delay_ms(const uint32_t ms)
{
usleep(ms * 1000);
}
void loader_port_start_timer(const uint32_t ms)
{
s_time_end = esp_timer_get_time() + ms * 1000;
}
uint32_t loader_port_remaining_time(void)
{
int64_t remaining = (s_time_end - esp_timer_get_time()) / 1000;
return (remaining > 0) ? (uint32_t)remaining : 0;
}
void loader_port_debug_print(const char *str)
{
printf("DEBUG: %s\n", str);
}
esp_loader_error_t loader_port_change_transmission_rate(const uint32_t frequency)
{
if (spi_bus_remove_device(s_device_h) != ESP_OK) {
return ESP_LOADER_ERROR_FAIL;
}
uint32_t old_frequency = s_device_config.clock_speed_hz;
s_device_config.clock_speed_hz = frequency;
if (spi_bus_add_device(s_spi_bus, &s_device_config, &s_device_h) != ESP_OK) {
s_device_config.clock_speed_hz = old_frequency;
return ESP_LOADER_ERROR_FAIL;
}
return ESP_LOADER_SUCCESS;
}

View file

@ -0,0 +1,60 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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.
*/
#pragma once
#include "esp_loader_io.h"
#include "driver/spi_master.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
spi_host_device_t spi_bus;
uint32_t frequency;
uint32_t spi_clk_pin;
uint32_t spi_miso_pin;
uint32_t spi_mosi_pin;
uint32_t spi_cs_pin;
uint32_t spi_quadwp_pin;
uint32_t spi_quadhd_pin;
uint32_t reset_trigger_pin;
uint32_t strap_bit0_pin;
uint32_t strap_bit1_pin;
uint32_t strap_bit2_pin;
uint32_t strap_bit3_pin;
} loader_esp32_spi_config_t;
/**
* @brief Initializes the SPI interface.
*
* @param config[in] Configuration structure
*
* @return
* - ESP_LOADER_SUCCESS Success
* - ESP_LOADER_ERROR_FAIL Initialization failure
*/
esp_loader_error_t loader_port_esp32_spi_init(const loader_esp32_spi_config_t *config);
/**
* @brief Deinitializes the SPI interface.
*/
void loader_port_esp32_spi_deinit(void);
#ifdef __cplusplus
}
#endif

View file

@ -0,0 +1,302 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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 "esp_loader_io.h"
#include "protocol.h"
#include <pigpio.h>
#include "raspberry_port.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <time.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#ifdef SERIAL_FLASHER_DEBUG_TRACE
static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write)
{
static bool write_prev = false;
if (write_prev != write) {
write_prev = write;
printf("\n--- %s ---\n", write ? "WRITE" : "READ");
}
for (uint32_t i = 0; i < size; i++) {
printf("%02x ", data[i]);
}
}
#endif
static int serial;
static int64_t s_time_end;
static int32_t s_reset_trigger_pin;
static int32_t s_gpio0_trigger_pin;
static speed_t convert_baudrate(int baud)
{
switch (baud) {
case 50: return B50;
case 75: return B75;
case 110: return B110;
case 134: return B134;
case 150: return B150;
case 200: return B200;
case 300: return B300;
case 600: return B600;
case 1200: return B1200;
case 1800: return B1800;
case 2400: return B2400;
case 4800: return B4800;
case 9600: return B9600;
case 19200: return B19200;
case 38400: return B38400;
case 57600: return B57600;
case 115200: return B115200;
case 230400: return B230400;
case 460800: return B460800;
case 500000: return B500000;
case 576000: return B576000;
case 921600: return B921600;
case 1000000: return B1000000;
case 1152000: return B1152000;
case 1500000: return B1500000;
case 2000000: return B2000000;
case 2500000: return B2500000;
case 3000000: return B3000000;
case 3500000: return B3500000;
case 4000000: return B4000000;
default: return -1;
}
}
static int serialOpen (const char *device, uint32_t baudrate)
{
struct termios options;
int status, fd;
if ((fd = open (device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK)) == -1) {
printf("Error occured while opening serial port !\n");
return -1 ;
}
fcntl (fd, F_SETFL, O_RDWR) ;
// Get and modify current options:
tcgetattr (fd, &options);
speed_t baud = convert_baudrate(baudrate);
if(baud < 0) {
printf("Invalid baudrate!\n");
return -1;
}
cfmakeraw (&options) ;
cfsetispeed (&options, baud) ;
cfsetospeed (&options, baud) ;
options.c_cflag |= (CLOCAL | CREAD) ;
options.c_cflag &= ~(PARENB | CSTOPB | CSIZE) ;
options.c_cflag |= CS8 ;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG) ;
options.c_oflag &= ~OPOST ;
options.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl
options.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL); // Disable any special handling of received bytes
options.c_cc [VMIN] = 0 ;
options.c_cc [VTIME] = 10 ; // 1 Second
tcsetattr (fd, TCSANOW, &options) ;
ioctl (fd, TIOCMGET, &status);
status |= TIOCM_DTR ;
status |= TIOCM_RTS ;
ioctl (fd, TIOCMSET, &status);
usleep (10000) ; // 10mS
return fd ;
}
static esp_loader_error_t change_baudrate(int file_desc, int baudrate)
{
struct termios options;
speed_t baud = convert_baudrate(baudrate);
if(baud < 0) {
return ESP_LOADER_ERROR_INVALID_PARAM;
}
tcgetattr (file_desc, &options);
cfmakeraw (&options) ;
cfsetispeed (&options, baud);
cfsetospeed (&options, baud);
tcsetattr (file_desc, TCSANOW, &options);
return ESP_LOADER_SUCCESS;
}
static void set_timeout(uint32_t timeout)
{
struct termios options;
timeout /= 100;
timeout = MAX(timeout, 1);
tcgetattr(serial, &options);
options.c_cc[VTIME] = timeout;
tcsetattr(serial, TCSANOW, &options);
}
static esp_loader_error_t read_char(char *c, uint32_t timeout)
{
set_timeout(timeout);
int read_bytes = read(serial, c, 1);
if (read_bytes == 1) {
return ESP_LOADER_SUCCESS;
} else if (read_bytes == 0) {
return ESP_LOADER_ERROR_TIMEOUT;
} else {
return ESP_LOADER_ERROR_FAIL;
}
}
static esp_loader_error_t read_data(char *buffer, uint32_t size)
{
for (int i = 0; i < size; i++) {
uint32_t remaining_time = loader_port_remaining_time();
RETURN_ON_ERROR( read_char(&buffer[i], remaining_time) );
}
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t loader_port_raspberry_init(const loader_raspberry_config_t *config)
{
s_reset_trigger_pin = config->reset_trigger_pin;
s_gpio0_trigger_pin = config->gpio0_trigger_pin;
serial = serialOpen(config->device, config->baudrate);
if (serial < 0) {
printf("Serial port could not be opened!\n");
return ESP_LOADER_ERROR_FAIL;
}
if (gpioInitialise() < 0) {
printf("pigpio initialisation failed\n");
return ESP_LOADER_ERROR_FAIL;
}
gpioSetMode(config->reset_trigger_pin, PI_OUTPUT);
gpioSetMode(config->gpio0_trigger_pin, PI_OUTPUT);
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout)
{
int written = write(serial, data, size);
if (written < 0) {
return ESP_LOADER_ERROR_FAIL;
} else if (written < size) {
#ifdef SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, written, true);
#endif
return ESP_LOADER_ERROR_TIMEOUT;
} else {
#ifdef SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, written, true);
#endif
return ESP_LOADER_SUCCESS;
}
}
esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout)
{
RETURN_ON_ERROR( read_data(data, size) );
#ifdef SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, size, false);
#endif
return ESP_LOADER_SUCCESS;
}
// Set GPIO0 LOW, then assert reset pin for 50 milliseconds.
void loader_port_enter_bootloader(void)
{
gpioWrite(s_gpio0_trigger_pin, 0);
loader_port_reset_target();
loader_port_delay_ms(SERIAL_FLASHER_BOOT_HOLD_TIME_MS);
gpioWrite(s_gpio0_trigger_pin, 1);
}
void loader_port_reset_target(void)
{
gpioWrite(s_reset_trigger_pin, 0);
loader_port_delay_ms(SERIAL_FLASHER_RESET_HOLD_TIME_MS);
gpioWrite(s_reset_trigger_pin, 1);
}
void loader_port_delay_ms(uint32_t ms)
{
usleep(ms * 1000);
}
void loader_port_start_timer(uint32_t ms)
{
s_time_end = clock() + (ms * (CLOCKS_PER_SEC / 1000));
}
uint32_t loader_port_remaining_time(void)
{
int64_t remaining = (s_time_end - clock()) / 1000;
return (remaining > 0) ? (uint32_t)remaining : 0;
}
void loader_port_debug_print(const char *str)
{
printf("DEBUG: %s\n", str);
}
esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate)
{
return change_baudrate(serial, baudrate);
}

View file

@ -0,0 +1,36 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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.
*/
#pragma once
#include <stdint.h>
#include "esp_loader_io.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
const char *device;
uint32_t baudrate;
uint32_t reset_trigger_pin;
uint32_t gpio0_trigger_pin;
} loader_raspberry_config_t;
esp_loader_error_t loader_port_raspberry_init(const loader_raspberry_config_t *config);
#ifdef __cplusplus
}
#endif

View file

@ -0,0 +1,140 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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 <string.h>
#include <unistd.h>
#include <stdint.h>
#include <sys/param.h>
#include <stdio.h>
#include "stm32_port.h"
static UART_HandleTypeDef *uart;
static GPIO_TypeDef* gpio_port_io0, *gpio_port_rst;
static uint16_t gpio_num_io0, gpio_num_rst;
#ifdef SERIAL_FLASHER_DEBUG_TRACE
static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write)
{
static bool write_prev = false;
if (write_prev != write) {
write_prev = write;
printf("\n--- %s ---\n", write ? "WRITE" : "READ");
}
for (uint32_t i = 0; i < size; i++) {
printf("%02x ", data[i]);
}
}
#endif
static uint32_t s_time_end;
esp_loader_error_t loader_port_write(const uint8_t *data, uint16_t size, uint32_t timeout)
{
HAL_StatusTypeDef err = HAL_UART_Transmit(uart, (uint8_t *)data, size, timeout);
if (err == HAL_OK) {
#ifdef SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, size, true);
#endif
return ESP_LOADER_SUCCESS;
} else if (err == HAL_TIMEOUT) {
return ESP_LOADER_ERROR_TIMEOUT;
} else {
return ESP_LOADER_ERROR_FAIL;
}
}
esp_loader_error_t loader_port_read(uint8_t *data, uint16_t size, uint32_t timeout)
{
HAL_StatusTypeDef err = HAL_UART_Receive(uart, data, size, timeout);
if (err == HAL_OK) {
#ifdef SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, size, false);
#endif
return ESP_LOADER_SUCCESS;
} else if (err == HAL_TIMEOUT) {
return ESP_LOADER_ERROR_TIMEOUT;
} else {
return ESP_LOADER_ERROR_FAIL;
}
}
void loader_port_stm32_init(loader_stm32_config_t *config)
{
uart = config->huart;
gpio_port_io0 = config->port_io0;
gpio_port_rst = config->port_rst;
gpio_num_io0 = config->pin_num_io0;
gpio_num_rst = config->pin_num_rst;
}
// Set GPIO0 LOW, then
// assert reset pin for 100 milliseconds.
void loader_port_enter_bootloader(void)
{
HAL_GPIO_WritePin(gpio_port_io0, gpio_num_io0, GPIO_PIN_RESET);
loader_port_reset_target();
HAL_Delay(SERIAL_FLASHER_BOOT_HOLD_TIME_MS);
HAL_GPIO_WritePin(gpio_port_io0, gpio_num_io0, GPIO_PIN_SET);
}
void loader_port_reset_target(void)
{
HAL_GPIO_WritePin(gpio_port_rst, gpio_num_rst, GPIO_PIN_RESET);
HAL_Delay(SERIAL_FLASHER_RESET_HOLD_TIME_MS);
HAL_GPIO_WritePin(gpio_port_rst, gpio_num_rst, GPIO_PIN_SET);
}
void loader_port_delay_ms(uint32_t ms)
{
HAL_Delay(ms);
}
void loader_port_start_timer(uint32_t ms)
{
s_time_end = HAL_GetTick() + ms;
}
uint32_t loader_port_remaining_time(void)
{
int32_t remaining = s_time_end - HAL_GetTick();
return (remaining > 0) ? (uint32_t)remaining : 0;
}
void loader_port_debug_print(const char *str)
{
printf("DEBUG: %s", str);
}
esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate)
{
uart->Init.BaudRate = baudrate;
if( HAL_UART_Init(uart) != HAL_OK ) {
return ESP_LOADER_ERROR_FAIL;
}
return ESP_LOADER_SUCCESS;
}

View file

@ -0,0 +1,38 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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.
*/
#pragma once
#include <stdint.h>
#include "esp_loader_io.h"
#include "stm32f4xx_hal.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
UART_HandleTypeDef *huart;
GPIO_TypeDef *port_io0;
uint16_t pin_num_io0;
GPIO_TypeDef *port_rst;
uint16_t pin_num_rst;
} loader_stm32_config_t;
void loader_port_stm32_init(loader_stm32_config_t *config);
#ifdef __cplusplus
}
#endif

View file

@ -0,0 +1,170 @@
/*
* Copyright (c) 2022 KT-Elektronik, Klaucke und Partner GmbH
*
* 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 "zephyr_port.h"
#include <zephyr/drivers/uart.h>
#include <zephyr/console/tty.h>
static const struct device *uart_dev;
static struct gpio_dt_spec enable_spec;
static struct gpio_dt_spec boot_spec;
static struct tty_serial tty;
static char tty_rx_buf[CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE];
static char tty_tx_buf[CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE];
#ifdef SERIAL_FLASHER_DEBUG_TRACE
static void transfer_debug_print(const uint8_t *data, uint16_t size, bool write)
{
static bool write_prev = false;
if (write_prev != write) {
write_prev = write;
printk("\n--- %s ---\n", write ? "WRITE" : "READ");
}
for (uint32_t i = 0; i < size; i++) {
printk("%02x ", data[i]);
}
}
#endif
esp_loader_error_t configure_tty()
{
if (tty_init(&tty, uart_dev) < 0 ||
tty_set_rx_buf(&tty, tty_rx_buf, sizeof(tty_rx_buf)) < 0 ||
tty_set_tx_buf(&tty, tty_tx_buf, sizeof(tty_tx_buf)) < 0) {
return ESP_LOADER_ERROR_FAIL;
}
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t loader_port_read(uint8_t *data, const uint16_t size, const uint32_t timeout)
{
if (!device_is_ready(uart_dev) || data == NULL || size == 0) {
return ESP_LOADER_ERROR_FAIL;
}
ssize_t total_read = 0;
ssize_t remaining = size;
tty_set_rx_timeout(&tty, timeout);
while (remaining > 0) {
const uint16_t chunk_size = remaining < CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE ?
remaining : CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE;
ssize_t read = tty_read(&tty, &data[total_read], chunk_size);
if (read < 0) {
return ESP_LOADER_ERROR_TIMEOUT;
}
#ifdef SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, read, false);
#endif
total_read += read;
remaining -= read;
}
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t loader_port_write(const uint8_t *data, const uint16_t size, const uint32_t timeout)
{
if (!device_is_ready(uart_dev) || data == NULL || size == 0) {
return ESP_LOADER_ERROR_FAIL;
}
ssize_t total_written = 0;
ssize_t remaining = size;
tty_set_tx_timeout(&tty, timeout);
while (remaining > 0) {
const uint16_t chunk_size = remaining < CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE ?
remaining : CONFIG_ESP_SERIAL_FLASHER_UART_BUFSIZE;
ssize_t written = tty_write(&tty, &data[total_written], chunk_size);
if (written < 0) {
return ESP_LOADER_ERROR_TIMEOUT;
}
#ifdef SERIAL_FLASHER_DEBUG_TRACE
transfer_debug_print(data, written, true);
#endif
total_written += written;
remaining -= written;
}
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t loader_port_zephyr_init(const loader_zephyr_config_t *config)
{
uart_dev = config->uart_dev;
enable_spec = config->enable_spec;
boot_spec = config->boot_spec;
return configure_tty();
}
void loader_port_reset_target(void)
{
gpio_pin_set_dt(&enable_spec, false);
loader_port_delay_ms(CONFIG_SERIAL_FLASHER_RESET_HOLD_TIME_MS);
gpio_pin_set_dt(&enable_spec, true);
}
void loader_port_enter_bootloader(void)
{
gpio_pin_set_dt(&boot_spec, false);
loader_port_reset_target();
loader_port_delay_ms(CONFIG_SERIAL_FLASHER_BOOT_HOLD_TIME_MS);
gpio_pin_set_dt(&boot_spec, true);
}
void loader_port_delay_ms(uint32_t ms)
{
k_msleep(ms);
}
static uint64_t s_time_end;
void loader_port_start_timer(uint32_t ms)
{
s_time_end = sys_clock_timeout_end_calc(Z_TIMEOUT_MS(ms));
}
uint32_t loader_port_remaining_time(void)
{
int64_t remaining = k_ticks_to_ms_floor64(s_time_end - k_uptime_ticks());
return (remaining > 0) ? (uint32_t)remaining : 0;
}
esp_loader_error_t loader_port_change_transmission_rate(uint32_t baudrate)
{
struct uart_config uart_config;
if (!device_is_ready(uart_dev)) {
return ESP_LOADER_ERROR_FAIL;
}
if (uart_config_get(uart_dev, &uart_config) != 0) {
return ESP_LOADER_ERROR_FAIL;
}
uart_config.baudrate = baudrate;
if (uart_configure(uart_dev, &uart_config) != 0) {
return ESP_LOADER_ERROR_FAIL;
}
/* bitrate-change can require tty re-configuration */
return configure_tty();
}

View file

@ -0,0 +1,39 @@
/*
* Copyright (c) 2022 KT-Elektronik, Klaucke und Partner GmbH
*
* 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.
*/
#pragma once
#include "esp_loader_io.h"
#include <zephyr/kernel.h>
#include <zephyr/drivers/gpio.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
const struct device *uart_dev;
const struct gpio_dt_spec enable_spec;
const struct gpio_dt_spec boot_spec;
} loader_zephyr_config_t;
esp_loader_error_t loader_port_zephyr_init(const loader_zephyr_config_t *config);
#ifdef __cplusplus
}
#endif

View file

@ -0,0 +1,33 @@
/* Copyright 2020 Espressif Systems (Shanghai) PTE LTD
*
* 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.
*/
#pragma once
#include <stdint.h>
#include "esp_loader.h"
typedef struct {
uint32_t cmd;
uint32_t usr;
uint32_t usr1;
uint32_t usr2;
uint32_t w0;
uint32_t mosi_dlen;
uint32_t miso_dlen;
} target_registers_t;
esp_loader_error_t loader_detect_chip(target_chip_t *target, const target_registers_t **regs);
esp_loader_error_t loader_read_spi_config(target_chip_t target_chip, uint32_t *spi_config);
bool encryption_in_begin_flash_cmd(target_chip_t target);

View file

@ -0,0 +1,28 @@
/*
* MD5 hash implementation and interface functions
* Copyright (c) 2003-2005, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
struct MD5Context {
uint32_t buf[4];
uint32_t bits[2];
uint8_t in[64];
};
void MD5Init(struct MD5Context *context);
void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len);
void MD5Final(unsigned char digest[16], struct MD5Context *context);
#ifdef __cplusplus
}
#endif

View file

@ -0,0 +1,230 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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.
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include "esp_loader.h"
#ifdef __cplusplus
extern "C" {
#endif
#define STATUS_FAILURE 1
#define STATUS_SUCCESS 0
#define READ_DIRECTION 1
#define WRITE_DIRECTION 0
#define MD5_SIZE 32
typedef enum __attribute__((packed))
{
FLASH_BEGIN = 0x02,
FLASH_DATA = 0x03,
FLASH_END = 0x04,
MEM_BEGIN = 0x05,
MEM_END = 0x06,
MEM_DATA = 0x07,
SYNC = 0x08,
WRITE_REG = 0x09,
READ_REG = 0x0a,
SPI_SET_PARAMS = 0x0b,
SPI_ATTACH = 0x0d,
CHANGE_BAUDRATE = 0x0f,
FLASH_DEFL_BEGIN = 0x10,
FLASH_DEFL_DATA = 0x11,
FLASH_DEFL_END = 0x12,
SPI_FLASH_MD5 = 0x13,
} command_t;
typedef enum __attribute__((packed))
{
RESPONSE_OK = 0x00,
INVALID_COMMAND = 0x05, // parameters or length field is invalid
COMMAND_FAILED = 0x06, // Failed to act on received message
INVALID_CRC = 0x07, // Invalid CRC in message
FLASH_WRITE_ERR = 0x08, // After writing a block of data to flash, the ROM loader reads the value back and the 8-bit CRC is compared to the data read from flash. If they don't match, this error is returned.
FLASH_READ_ERR = 0x09, // SPI read failed
READ_LENGTH_ERR = 0x0a, // SPI read request length is too long
DEFLATE_ERROR = 0x0b, // ESP32 compressed uploads only
} error_code_t;
typedef struct __attribute__((packed))
{
uint8_t direction;
uint8_t command; // One of command_t
uint16_t size;
uint32_t checksum;
} command_common_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t erase_size;
uint32_t packet_count;
uint32_t packet_size;
uint32_t offset;
uint32_t encrypted;
} flash_begin_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t data_size;
uint32_t sequence_number;
uint32_t zero_0;
uint32_t zero_1;
} data_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t stay_in_loader;
} flash_end_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t total_size;
uint32_t blocks;
uint32_t block_size;
uint32_t offset;
} mem_begin_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t stay_in_loader;
uint32_t entry_point_address;
} mem_end_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint8_t sync_sequence[36];
} sync_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t address;
uint32_t value;
uint32_t mask;
uint32_t delay_us;
} write_reg_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t address;
} read_reg_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t configuration;
uint32_t zero; // ESP32 ROM only
} spi_attach_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t new_baudrate;
uint32_t old_baudrate;
} change_baudrate_command_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t address;
uint32_t size;
uint32_t reserved_0;
uint32_t reserved_1;
} spi_flash_md5_command_t;
typedef struct __attribute__((packed))
{
uint8_t direction;
uint8_t command; // One of command_t
uint16_t size;
uint32_t value;
} common_response_t;
typedef struct __attribute__((packed))
{
uint8_t failed;
uint8_t error;
} response_status_t;
typedef struct __attribute__((packed))
{
common_response_t common;
response_status_t status;
} response_t;
typedef struct __attribute__((packed))
{
common_response_t common;
uint8_t md5[MD5_SIZE]; // ROM only
response_status_t status;
} rom_md5_response_t;
typedef struct __attribute__((packed))
{
command_common_t common;
uint32_t id;
uint32_t total_size;
uint32_t block_size;
uint32_t sector_size;
uint32_t page_size;
uint32_t status_mask;
} write_spi_command_t;
esp_loader_error_t loader_initialize_conn(esp_loader_connect_args_t *connect_args);
#ifdef SERIAL_FLASHER_INTERFACE_UART
esp_loader_error_t loader_flash_begin_cmd(uint32_t offset, uint32_t erase_size, uint32_t block_size, uint32_t blocks_to_write, bool encryption);
esp_loader_error_t loader_flash_data_cmd(const uint8_t *data, uint32_t size);
esp_loader_error_t loader_flash_end_cmd(bool stay_in_loader);
esp_loader_error_t loader_sync_cmd(void);
esp_loader_error_t loader_spi_attach_cmd(uint32_t config);
esp_loader_error_t loader_md5_cmd(uint32_t address, uint32_t size, uint8_t *md5_out);
esp_loader_error_t loader_spi_parameters(uint32_t total_size);
#endif /* SERIAL_FLASHER_INTERFACE_UART */
esp_loader_error_t loader_mem_begin_cmd(uint32_t offset, uint32_t size, uint32_t blocks_to_write, uint32_t block_size);
esp_loader_error_t loader_mem_data_cmd(const uint8_t *data, uint32_t size);
esp_loader_error_t loader_mem_end_cmd(uint32_t entrypoint);
esp_loader_error_t loader_write_reg_cmd(uint32_t address, uint32_t value, uint32_t mask, uint32_t delay_us);
esp_loader_error_t loader_read_reg_cmd(uint32_t address, uint32_t *reg);
esp_loader_error_t loader_change_baudrate_cmd(uint32_t baudrate);
#ifdef __cplusplus
}
#endif

View file

@ -0,0 +1,31 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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.
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include "esp_loader.h"
#include "protocol.h"
void log_loader_internal_error(error_code_t error);
esp_loader_error_t send_cmd(const void *cmd_data, uint32_t size, uint32_t *reg_value);
esp_loader_error_t send_cmd_with_data(const void *cmd_data, size_t cmd_size,
const void *data, size_t data_size);
esp_loader_error_t send_cmd_md5(const void *cmd_data, size_t cmd_size, uint8_t md5_out[MD5_SIZE]);

View file

@ -0,0 +1,28 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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.
*/
#pragma once
#include "esp_loader.h"
#include <stdint.h>
#include <stdlib.h>
esp_loader_error_t SLIP_receive_data(uint8_t *buff, size_t size);
esp_loader_error_t SLIP_receive_packet(uint8_t *buff, size_t size);
esp_loader_error_t SLIP_send(const uint8_t *data, size_t size);
esp_loader_error_t SLIP_send_delimiter(void);

View file

@ -0,0 +1,415 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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 "protocol.h"
#include "esp_loader_io.h"
#include "esp_loader.h"
#include "esp_targets.h"
#include "md5_hash.h"
#include <string.h>
#include <assert.h>
#ifndef MAX
#define MAX(a, b) ((a) > (b)) ? (a) : (b)
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b)) ? (a) : (b)
#endif
#ifndef ROUNDUP
#define ROUNDUP(a, b) (((int)a + (int)b - 1) / (int)b)
#endif
static const uint32_t DEFAULT_TIMEOUT = 1000;
static const uint32_t DEFAULT_FLASH_TIMEOUT = 3000; // timeout for most flash operations
static const uint32_t LOAD_RAM_TIMEOUT_PER_MB = 2000000; // timeout (per megabyte) for erasing a region
typedef enum {
SPI_FLASH_READ_ID = 0x9F
} spi_flash_cmd_t;
static const target_registers_t *s_reg = NULL;
static target_chip_t s_target = ESP_UNKNOWN_CHIP;
#if MD5_ENABLED
static const uint32_t MD5_TIMEOUT_PER_MB = 800;
static struct MD5Context s_md5_context;
static uint32_t s_start_address;
static uint32_t s_image_size;
static inline void init_md5(uint32_t address, uint32_t size)
{
s_start_address = address;
s_image_size = size;
MD5Init(&s_md5_context);
}
static inline void md5_update(const uint8_t *data, uint32_t size)
{
MD5Update(&s_md5_context, data, size);
}
static inline void md5_final(uint8_t digets[16])
{
MD5Final(digets, &s_md5_context);
}
#else
static inline void init_md5(uint32_t address, uint32_t size) { }
static inline void md5_update(const uint8_t *data, uint32_t size) { }
static inline void md5_final(uint8_t digets[16]) { }
#endif
static uint32_t timeout_per_mb(uint32_t size_bytes, uint32_t time_per_mb)
{
uint32_t timeout = time_per_mb * (size_bytes / 1e6);
return MAX(timeout, DEFAULT_FLASH_TIMEOUT);
}
esp_loader_error_t esp_loader_connect(esp_loader_connect_args_t *connect_args)
{
loader_port_enter_bootloader();
RETURN_ON_ERROR(loader_initialize_conn(connect_args));
RETURN_ON_ERROR(loader_detect_chip(&s_target, &s_reg));
#ifdef SERIAL_FLASHER_INTERFACE_UART
esp_loader_error_t err;
uint32_t spi_config;
if (s_target == ESP8266_CHIP) {
err = loader_flash_begin_cmd(0, 0, 0, 0, s_target);
} else {
RETURN_ON_ERROR( loader_read_spi_config(s_target, &spi_config) );
loader_port_start_timer(DEFAULT_TIMEOUT);
err = loader_spi_attach_cmd(spi_config);
}
return err;
#endif /* SERIAL_FLASHER_INTERFACE_UART */
return ESP_LOADER_SUCCESS;
}
target_chip_t esp_loader_get_target(void)
{
return s_target;
}
#ifdef SERIAL_FLASHER_INTERFACE_UART
static uint32_t s_flash_write_size = 0;
static esp_loader_error_t spi_set_data_lengths(size_t mosi_bits, size_t miso_bits)
{
if (mosi_bits > 0) {
RETURN_ON_ERROR( esp_loader_write_register(s_reg->mosi_dlen, mosi_bits - 1) );
}
if (miso_bits > 0) {
RETURN_ON_ERROR( esp_loader_write_register(s_reg->miso_dlen, miso_bits - 1) );
}
return ESP_LOADER_SUCCESS;
}
static esp_loader_error_t spi_set_data_lengths_8266(size_t mosi_bits, size_t miso_bits)
{
uint32_t mosi_mask = (mosi_bits == 0) ? 0 : mosi_bits - 1;
uint32_t miso_mask = (miso_bits == 0) ? 0 : miso_bits - 1;
return esp_loader_write_register(s_reg->usr1, (miso_mask << 8) | (mosi_mask << 17));
}
static esp_loader_error_t spi_flash_command(spi_flash_cmd_t cmd, void *data_tx, size_t tx_size, void *data_rx, size_t rx_size)
{
assert(rx_size <= 32); // Reading more than 32 bits back from a SPI flash operation is unsupported
assert(tx_size <= 64); // Writing more than 64 bytes of data with one SPI command is unsupported
uint32_t SPI_USR_CMD = (1 << 31);
uint32_t SPI_USR_MISO = (1 << 28);
uint32_t SPI_USR_MOSI = (1 << 27);
uint32_t SPI_CMD_USR = (1 << 18);
uint32_t CMD_LEN_SHIFT = 28;
// Save SPI configuration
uint32_t old_spi_usr;
uint32_t old_spi_usr2;
RETURN_ON_ERROR( esp_loader_read_register(s_reg->usr, &old_spi_usr) );
RETURN_ON_ERROR( esp_loader_read_register(s_reg->usr2, &old_spi_usr2) );
if (s_target == ESP8266_CHIP) {
RETURN_ON_ERROR( spi_set_data_lengths_8266(tx_size, rx_size) );
} else {
RETURN_ON_ERROR( spi_set_data_lengths(tx_size, rx_size) );
}
uint32_t usr_reg_2 = (7 << CMD_LEN_SHIFT) | cmd;
uint32_t usr_reg = SPI_USR_CMD;
if (rx_size > 0) {
usr_reg |= SPI_USR_MISO;
}
if (tx_size > 0) {
usr_reg |= SPI_USR_MOSI;
}
RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr, usr_reg) );
RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr2, usr_reg_2 ) );
if (tx_size == 0) {
// clear data register before we read it
RETURN_ON_ERROR( esp_loader_write_register(s_reg->w0, 0) );
} else {
uint32_t *data = (uint32_t *)data_tx;
uint32_t words_to_write = (tx_size + 31) / (8 * 4);
uint32_t data_reg_addr = s_reg->w0;
while (words_to_write--) {
uint32_t word = *data++;
RETURN_ON_ERROR( esp_loader_write_register(data_reg_addr, word) );
data_reg_addr += 4;
}
}
RETURN_ON_ERROR( esp_loader_write_register(s_reg->cmd, SPI_CMD_USR) );
uint32_t trials = 10;
while (trials--) {
uint32_t cmd_reg;
RETURN_ON_ERROR( esp_loader_read_register(s_reg->cmd, &cmd_reg) );
if ((cmd_reg & SPI_CMD_USR) == 0) {
break;
}
}
if (trials == 0) {
return ESP_LOADER_ERROR_TIMEOUT;
}
RETURN_ON_ERROR( esp_loader_read_register(s_reg->w0, data_rx) );
// Restore SPI configuration
RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr, old_spi_usr) );
RETURN_ON_ERROR( esp_loader_write_register(s_reg->usr2, old_spi_usr2) );
return ESP_LOADER_SUCCESS;
}
static esp_loader_error_t detect_flash_size(size_t *flash_size)
{
uint32_t flash_id = 0;
RETURN_ON_ERROR( spi_flash_command(SPI_FLASH_READ_ID, NULL, 0, &flash_id, 24) );
uint32_t size_id = flash_id >> 16;
if (size_id < 0x12 || size_id > 0x18) {
return ESP_LOADER_ERROR_UNSUPPORTED_CHIP;
}
*flash_size = 1 << size_id;
return ESP_LOADER_SUCCESS;
}
static uint32_t calc_erase_size(const target_chip_t target, const uint32_t offset,
const uint32_t image_size)
{
if (target != ESP8266_CHIP) {
return image_size;
} else {
/* Needed to fix a bug in the ESP8266 ROM */
const uint32_t sectors_per_block = 16U;
const uint32_t sector_size = 4096U;
const uint32_t num_sectors = (image_size + sector_size - 1) / sector_size;
const uint32_t start_sector = offset / sector_size;
uint32_t head_sectors = sectors_per_block - (start_sector % sectors_per_block);
/* The ROM bug deletes extra num_sectors if we don't cross the block boundary
and extra head_sectors if we do */
if (num_sectors <= head_sectors) {
return ((num_sectors + 1) / 2) * sector_size;
} else {
return (num_sectors - head_sectors) * sector_size;
}
}
}
esp_loader_error_t esp_loader_flash_start(uint32_t offset, uint32_t image_size, uint32_t block_size)
{
s_flash_write_size = block_size;
size_t flash_size = 0;
if (detect_flash_size(&flash_size) == ESP_LOADER_SUCCESS) {
if (image_size > flash_size) {
return ESP_LOADER_ERROR_IMAGE_SIZE;
}
loader_port_start_timer(DEFAULT_TIMEOUT);
RETURN_ON_ERROR( loader_spi_parameters(flash_size) );
} else {
loader_port_debug_print("Flash size detection failed, falling back to default");
}
init_md5(offset, image_size);
bool encryption_in_cmd = encryption_in_begin_flash_cmd(s_target);
const uint32_t erase_size = calc_erase_size(esp_loader_get_target(), offset, image_size);
const uint32_t blocks_to_write = (image_size + block_size - 1) / block_size;
const uint32_t erase_region_timeout_per_mb = 10000;
loader_port_start_timer(timeout_per_mb(erase_size, erase_region_timeout_per_mb));
return loader_flash_begin_cmd(offset, erase_size, block_size, blocks_to_write, encryption_in_cmd);
}
esp_loader_error_t esp_loader_flash_write(void *payload, uint32_t size)
{
uint32_t padding_bytes = s_flash_write_size - size;
uint8_t *data = (uint8_t *)payload;
uint32_t padding_index = size;
if (size > s_flash_write_size) {
return ESP_LOADER_ERROR_INVALID_PARAM;
}
const uint8_t padding_pattern = 0xFF;
while (padding_bytes--) {
data[padding_index++] = padding_pattern;
}
md5_update(payload, (size + 3) & ~3);
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_flash_data_cmd(data, s_flash_write_size);
}
esp_loader_error_t esp_loader_flash_finish(bool reboot)
{
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_flash_end_cmd(!reboot);
}
#endif /* SERIAL_FLASHER_INTERFACE_UART */
esp_loader_error_t esp_loader_mem_start(uint32_t offset, uint32_t size, uint32_t block_size)
{
uint32_t blocks_to_write = ROUNDUP(size, block_size);
loader_port_start_timer(timeout_per_mb(size, LOAD_RAM_TIMEOUT_PER_MB));
return loader_mem_begin_cmd(offset, size, blocks_to_write, block_size);
}
esp_loader_error_t esp_loader_mem_write(const void *payload, uint32_t size)
{
const uint8_t *data = (const uint8_t *)payload;
loader_port_start_timer(timeout_per_mb(size, LOAD_RAM_TIMEOUT_PER_MB));
return loader_mem_data_cmd(data, size);
}
esp_loader_error_t esp_loader_mem_finish(uint32_t entrypoint)
{
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_mem_end_cmd(entrypoint);
}
esp_loader_error_t esp_loader_read_register(uint32_t address, uint32_t *reg_value)
{
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_read_reg_cmd(address, reg_value);
}
esp_loader_error_t esp_loader_write_register(uint32_t address, uint32_t reg_value)
{
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_write_reg_cmd(address, reg_value, 0xFFFFFFFF, 0);
}
esp_loader_error_t esp_loader_change_transmission_rate(uint32_t transmission_rate)
{
if (s_target == ESP8266_CHIP) {
return ESP_LOADER_ERROR_UNSUPPORTED_FUNC;
}
loader_port_start_timer(DEFAULT_TIMEOUT);
return loader_change_baudrate_cmd(transmission_rate);
}
#if MD5_ENABLED
static void hexify(const uint8_t raw_md5[16], uint8_t hex_md5_out[32])
{
static const uint8_t dec_to_hex[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
for (int i = 0; i < 16; i++) {
*hex_md5_out++ = dec_to_hex[raw_md5[i] >> 4];
*hex_md5_out++ = dec_to_hex[raw_md5[i] & 0xF];
}
}
esp_loader_error_t esp_loader_flash_verify(void)
{
if (s_target == ESP8266_CHIP) {
return ESP_LOADER_ERROR_UNSUPPORTED_FUNC;
}
uint8_t raw_md5[16] = {0};
/* Zero termination and new line character require 2 bytes */
uint8_t hex_md5[MD5_SIZE + 2] = {0};
uint8_t received_md5[MD5_SIZE + 2] = {0};
md5_final(raw_md5);
hexify(raw_md5, hex_md5);
loader_port_start_timer(timeout_per_mb(s_image_size, MD5_TIMEOUT_PER_MB));
RETURN_ON_ERROR( loader_md5_cmd(s_start_address, s_image_size, received_md5) );
bool md5_match = memcmp(hex_md5, received_md5, MD5_SIZE) == 0;
if (!md5_match) {
hex_md5[MD5_SIZE] = '\n';
received_md5[MD5_SIZE] = '\n';
loader_port_debug_print("Error: MD5 checksum does not match:\n");
loader_port_debug_print("Expected:\n");
loader_port_debug_print((char *)received_md5);
loader_port_debug_print("Actual:\n");
loader_port_debug_print((char *)hex_md5);
return ESP_LOADER_ERROR_INVALID_MD5;
}
return ESP_LOADER_SUCCESS;
}
#endif
void esp_loader_reset_target(void)
{
loader_port_reset_target();
}

View file

@ -0,0 +1,263 @@
/* Copyright 2020 Espressif Systems (Shanghai) PTE LTD
*
* 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 "esp_targets.h"
#include <stddef.h>
#define MAX_MAGIC_VALUES 2
typedef esp_loader_error_t (*read_spi_config_t)(uint32_t efuse_base, uint32_t *spi_config);
typedef struct {
target_registers_t regs;
uint32_t efuse_base;
uint32_t chip_magic_value[MAX_MAGIC_VALUES];
read_spi_config_t read_spi_config;
bool encryption_in_begin_flash_cmd;
} esp_target_t;
// This ROM address has a different value on each chip model
#define CHIP_DETECT_MAGIC_REG_ADDR 0x40001000
#define ESP8266_SPI_REG_BASE 0x60000200
#define ESP32S2_SPI_REG_BASE 0x3f402000
#define ESP32xx_SPI_REG_BASE 0x60002000
#define ESP32_SPI_REG_BASE 0x3ff42000
static esp_loader_error_t spi_config_esp32(uint32_t efuse_base, uint32_t *spi_config);
static esp_loader_error_t spi_config_esp32xx(uint32_t efuse_base, uint32_t *spi_config);
static const esp_target_t esp_target[ESP_MAX_CHIP] = {
// ESP8266
{
.regs = {
.cmd = ESP8266_SPI_REG_BASE + 0x00,
.usr = ESP8266_SPI_REG_BASE + 0x1c,
.usr1 = ESP8266_SPI_REG_BASE + 0x20,
.usr2 = ESP8266_SPI_REG_BASE + 0x24,
.w0 = ESP8266_SPI_REG_BASE + 0x40,
.mosi_dlen = 0,
.miso_dlen = 0,
},
.efuse_base = 0, // Not used
.chip_magic_value = { 0xfff0c101, 0 },
.read_spi_config = NULL, // Not used
},
// ESP32
{
.regs = {
.cmd = ESP32_SPI_REG_BASE + 0x00,
.usr = ESP32_SPI_REG_BASE + 0x1c,
.usr1 = ESP32_SPI_REG_BASE + 0x20,
.usr2 = ESP32_SPI_REG_BASE + 0x24,
.w0 = ESP32_SPI_REG_BASE + 0x80,
.mosi_dlen = ESP32_SPI_REG_BASE + 0x28,
.miso_dlen = ESP32_SPI_REG_BASE + 0x2c,
},
.efuse_base = 0x3ff5A000,
.chip_magic_value = { 0x00f01d83, 0 },
.read_spi_config = spi_config_esp32,
},
// ESP32S2
{
.regs = {
.cmd = ESP32S2_SPI_REG_BASE + 0x00,
.usr = ESP32S2_SPI_REG_BASE + 0x18,
.usr1 = ESP32S2_SPI_REG_BASE + 0x1c,
.usr2 = ESP32S2_SPI_REG_BASE + 0x20,
.w0 = ESP32S2_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32S2_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32S2_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x3f41A000,
.chip_magic_value = { 0x000007c6, 0 },
.read_spi_config = spi_config_esp32xx,
},
// ESP32C3
{
.regs = {
.cmd = ESP32xx_SPI_REG_BASE + 0x00,
.usr = ESP32xx_SPI_REG_BASE + 0x18,
.usr1 = ESP32xx_SPI_REG_BASE + 0x1c,
.usr2 = ESP32xx_SPI_REG_BASE + 0x20,
.w0 = ESP32xx_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32xx_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x60008800,
.chip_magic_value = { 0x6921506f, 0x1b31506f },
.read_spi_config = spi_config_esp32xx,
},
// ESP32S3
{
.regs = {
.cmd = ESP32xx_SPI_REG_BASE + 0x00,
.usr = ESP32xx_SPI_REG_BASE + 0x18,
.usr1 = ESP32xx_SPI_REG_BASE + 0x1c,
.usr2 = ESP32xx_SPI_REG_BASE + 0x20,
.w0 = ESP32xx_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32xx_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x60007000,
.chip_magic_value = { 0x00000009, 0 },
.read_spi_config = spi_config_esp32xx,
},
// ESP32C2
{
.regs = {
.cmd = ESP32xx_SPI_REG_BASE + 0x00,
.usr = ESP32xx_SPI_REG_BASE + 0x18,
.usr1 = ESP32xx_SPI_REG_BASE + 0x1c,
.usr2 = ESP32xx_SPI_REG_BASE + 0x20,
.w0 = ESP32xx_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32xx_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x60008800,
.chip_magic_value = { 0x6f51306f, 0x7c41a06f },
.read_spi_config = spi_config_esp32xx,
},
// ESP32H4
{
.regs = {
.cmd = ESP32xx_SPI_REG_BASE + 0x00,
.usr = ESP32xx_SPI_REG_BASE + 0x18,
.usr1 = ESP32xx_SPI_REG_BASE + 0x1c,
.usr2 = ESP32xx_SPI_REG_BASE + 0x20,
.w0 = ESP32xx_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32xx_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x6001A000,
.chip_magic_value = {0xca26cc22, 0x6881b06f}, // ESP32H4-BETA1, ESP32H4-BETA2
.read_spi_config = spi_config_esp32xx,
},
// ESP32H2
{
.regs = {
.cmd = ESP32xx_SPI_REG_BASE + 0x00,
.usr = ESP32xx_SPI_REG_BASE + 0x18,
.usr1 = ESP32xx_SPI_REG_BASE + 0x1c,
.usr2 = ESP32xx_SPI_REG_BASE + 0x20,
.w0 = ESP32xx_SPI_REG_BASE + 0x58,
.mosi_dlen = ESP32xx_SPI_REG_BASE + 0x24,
.miso_dlen = ESP32xx_SPI_REG_BASE + 0x28,
},
.efuse_base = 0x6001A000,
.chip_magic_value = {0xd7b73e80, 0},
.read_spi_config = spi_config_esp32xx,
},
};
const target_registers_t *get_esp_target_data(target_chip_t chip)
{
return (const target_registers_t *)&esp_target[chip];
}
esp_loader_error_t loader_detect_chip(target_chip_t *target_chip, const target_registers_t **target_data)
{
uint32_t magic_value;
RETURN_ON_ERROR( esp_loader_read_register(CHIP_DETECT_MAGIC_REG_ADDR, &magic_value) );
for (int chip = 0; chip < ESP_MAX_CHIP; chip++) {
for(int index = 0; index < MAX_MAGIC_VALUES; index++) {
if (magic_value == esp_target[chip].chip_magic_value[index]) {
*target_chip = (target_chip_t)chip;
*target_data = (target_registers_t *)&esp_target[chip];
return ESP_LOADER_SUCCESS;
}
}
}
return ESP_LOADER_ERROR_INVALID_TARGET;
}
esp_loader_error_t loader_read_spi_config(target_chip_t target_chip, uint32_t *spi_config)
{
const esp_target_t *target = &esp_target[target_chip];
return target->read_spi_config(target->efuse_base, spi_config);
}
static inline uint32_t efuse_word_addr(uint32_t efuse_base, uint32_t n)
{
return efuse_base + (n * 4);
}
// 30->GPIO32 | 31->GPIO33
static inline uint8_t adjust_pin_number(uint8_t num)
{
return (num >= 30) ? num + 2 : num;
}
static esp_loader_error_t spi_config_esp32(uint32_t efuse_base, uint32_t *spi_config)
{
*spi_config = 0;
uint32_t reg5, reg3;
RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 5), &reg5) );
RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 3), &reg3) );
uint32_t pins = reg5 & 0xfffff;
if (pins == 0 || pins == 0xfffff) {
return ESP_LOADER_SUCCESS;
}
uint8_t clk = adjust_pin_number( (pins >> 0) & 0x1f );
uint8_t q = adjust_pin_number( (pins >> 5) & 0x1f );
uint8_t d = adjust_pin_number( (pins >> 10) & 0x1f );
uint8_t cs = adjust_pin_number( (pins >> 15) & 0x1f );
uint8_t hd = adjust_pin_number( (reg3 >> 4) & 0x1f );
if (clk == cs || clk == d || clk == q || q == cs || q == d || q == d) {
return ESP_LOADER_SUCCESS;
}
*spi_config = (hd << 24) | (cs << 18) | (d << 12) | (q << 6) | clk;
return ESP_LOADER_SUCCESS;
}
// Applies for esp32s2, esp32c3 and esp32c3
static esp_loader_error_t spi_config_esp32xx(uint32_t efuse_base, uint32_t *spi_config)
{
*spi_config = 0;
uint32_t reg1, reg2;
RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 18), &reg1) );
RETURN_ON_ERROR( esp_loader_read_register(efuse_word_addr(efuse_base, 19), &reg2) );
uint32_t pins = ((reg1 >> 16) | ((reg2 & 0xfffff) << 16)) & 0x3fffffff;
if (pins == 0 || pins == 0xffffffff) {
return ESP_LOADER_SUCCESS;
}
*spi_config = pins;
return ESP_LOADER_SUCCESS;
}
bool encryption_in_begin_flash_cmd(target_chip_t target)
{
return target == ESP32_CHIP || target == ESP8266_CHIP;
}

View file

@ -0,0 +1,262 @@
/*
* MD5 hash implementation and interface functions
* Copyright (c) 2003-2005, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#include "md5_hash.h"
#include <stdlib.h>
#include <string.h>
static void MD5Transform(uint32_t buf[4], uint32_t const in[16]);
/* ===== start - public domain MD5 implementation ===== */
/*
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to MD5Init, call MD5Update as
* needed on buffers full of bytes, and then call MD5Final, which
* will fill a supplied 16-byte array with the digest.
*/
#ifndef WORDS_BIGENDIAN
#define byteReverse(buf, len) /* Nothing */
#else
/*
* Note: this code is harmless on little-endian machines.
*/
static void byteReverse(unsigned char *buf, unsigned longs)
{
uint32_t t;
do {
t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
((unsigned) buf[1] << 8 | buf[0]);
*(uint32_t *) buf = t;
buf += 4;
} while (--longs);
}
#endif
/*
* Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
* initialization constants.
*/
void MD5Init(struct MD5Context *ctx)
{
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
ctx->buf[3] = 0x10325476;
ctx->bits[0] = 0;
ctx->bits[1] = 0;
}
/*
* Update context to reflect the concatenation of another buffer full
* of bytes.
*/
void MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len)
{
uint32_t t;
/* Update bitcount */
t = ctx->bits[0];
if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) {
ctx->bits[1]++; /* Carry from low to high */
}
ctx->bits[1] += len >> 29;
t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
/* Handle any leading odd-sized chunks */
if (t) {
unsigned char *p = (unsigned char *) ctx->in + t;
t = 64 - t;
if (len < t) {
memcpy(p, buf, len);
return;
}
memcpy(p, buf, t);
byteReverse(ctx->in, 16);
MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in);
buf += t;
len -= t;
}
/* Process data in 64-byte chunks */
while (len >= 64) {
memcpy(ctx->in, buf, 64);
byteReverse(ctx->in, 16);
MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in);
buf += 64;
len -= 64;
}
/* Handle any remaining bytes of data. */
memcpy(ctx->in, buf, len);
}
/*
* Final wrapup - pad to 64-byte boundary with the bit pattern
* 1 0* (64-bit count of bits processed, MSB-first)
*/
void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
{
unsigned count;
unsigned char *p;
/* Compute number of bytes mod 64 */
count = (ctx->bits[0] >> 3) & 0x3F;
/* Set the first char of padding to 0x80. This is safe since there is
always at least one byte free */
p = ctx->in + count;
*p++ = 0x80;
/* Bytes of padding needed to make 64 bytes */
count = 64 - 1 - count;
/* Pad out to 56 mod 64 */
if (count < 8) {
/* Two lots of padding: Pad the first block to 64 bytes */
memset(p, 0, count);
byteReverse(ctx->in, 16);
MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in);
/* Now fill the next block with 56 bytes */
memset(ctx->in, 0, 56);
} else {
/* Pad block to 56 bytes */
memset(p, 0, count - 8);
}
byteReverse(ctx->in, 14);
/* Append length in bits and transform */
((uint32_t *) ctx->in)[14] = ctx->bits[0];
((uint32_t *) ctx->in)[15] = ctx->bits[1];
MD5Transform((uint32_t *)ctx->buf, (uint32_t *) ctx->in);
byteReverse((unsigned char *) ctx->buf, 4);
memcpy(digest, ctx->buf, 16);
memset(ctx, 0, sizeof(struct MD5Context)); /* In case it's sensitive */
}
/* The four core functions - F1 is optimized somewhat */
/* #define F1(x, y, z) (x & y | ~x & z) */
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))
/* This is the central step in the MD5 algorithm. */
#define MD5STEP(f, w, x, y, z, data, s) \
( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
/*
* The core of the MD5 algorithm, this alters an existing MD5 hash to
* reflect the addition of 16 longwords of new data. MD5Update blocks
* the data and converts bytes into longwords for this routine.
*/
static void MD5Transform(uint32_t buf[4], uint32_t const in[16])
{
register uint32_t a, b, c, d;
a = buf[0];
b = buf[1];
c = buf[2];
d = buf[3];
MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
buf[0] += a;
buf[1] += b;
buf[2] += c;
buf[3] += d;
}
/* ===== end - public domain MD5 implementation ===== */

View file

@ -0,0 +1,301 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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 "protocol.h"
#include "protocol_prv.h"
#include "esp_loader_io.h"
#include <stddef.h>
#include <string.h>
#define CMD_SIZE(cmd) ( sizeof(cmd) - sizeof(command_common_t) )
static uint32_t s_sequence_number = 0;
static uint8_t compute_checksum(const uint8_t *data, uint32_t size)
{
uint8_t checksum = 0xEF;
while (size--) {
checksum ^= *data++;
}
return checksum;
}
void log_loader_internal_error(error_code_t error)
{
loader_port_debug_print("Error: ");
switch (error) {
case INVALID_CRC: loader_port_debug_print("INVALID_CRC"); break;
case INVALID_COMMAND: loader_port_debug_print("INVALID_COMMAND"); break;
case COMMAND_FAILED: loader_port_debug_print("COMMAND_FAILED"); break;
case FLASH_WRITE_ERR: loader_port_debug_print("FLASH_WRITE_ERR"); break;
case FLASH_READ_ERR: loader_port_debug_print("FLASH_READ_ERR"); break;
case READ_LENGTH_ERR: loader_port_debug_print("READ_LENGTH_ERR"); break;
case DEFLATE_ERROR: loader_port_debug_print("DEFLATE_ERROR"); break;
default: loader_port_debug_print("UNKNOWN ERROR"); break;
}
loader_port_debug_print("\n");
}
esp_loader_error_t loader_flash_begin_cmd(uint32_t offset,
uint32_t erase_size,
uint32_t block_size,
uint32_t blocks_to_write,
bool encryption)
{
uint32_t encryption_size = encryption ? sizeof(uint32_t) : 0;
flash_begin_command_t flash_begin_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = FLASH_BEGIN,
.size = CMD_SIZE(flash_begin_cmd) - encryption_size,
.checksum = 0
},
.erase_size = erase_size,
.packet_count = blocks_to_write,
.packet_size = block_size,
.offset = offset,
.encrypted = 0
};
s_sequence_number = 0;
return send_cmd(&flash_begin_cmd, sizeof(flash_begin_cmd) - encryption_size, NULL);
}
esp_loader_error_t loader_flash_data_cmd(const uint8_t *data, uint32_t size)
{
data_command_t data_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = FLASH_DATA,
.size = CMD_SIZE(data_cmd) + size,
.checksum = compute_checksum(data, size)
},
.data_size = size,
.sequence_number = s_sequence_number++,
};
return send_cmd_with_data(&data_cmd, sizeof(data_cmd), data, size);
}
esp_loader_error_t loader_flash_end_cmd(bool stay_in_loader)
{
flash_end_command_t end_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = FLASH_END,
.size = CMD_SIZE(end_cmd),
.checksum = 0
},
.stay_in_loader = stay_in_loader
};
return send_cmd(&end_cmd, sizeof(end_cmd), NULL);
}
esp_loader_error_t loader_mem_begin_cmd(uint32_t offset, uint32_t size, uint32_t blocks_to_write, uint32_t block_size)
{
mem_begin_command_t mem_begin_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = MEM_BEGIN,
.size = CMD_SIZE(mem_begin_cmd),
.checksum = 0
},
.total_size = size,
.blocks = blocks_to_write,
.block_size = block_size,
.offset = offset
};
s_sequence_number = 0;
return send_cmd(&mem_begin_cmd, sizeof(mem_begin_cmd), NULL);
}
esp_loader_error_t loader_mem_data_cmd(const uint8_t *data, uint32_t size)
{
data_command_t data_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = MEM_DATA,
.size = CMD_SIZE(data_cmd) + size,
.checksum = compute_checksum(data, size)
},
.data_size = size,
.sequence_number = s_sequence_number++,
};
return send_cmd_with_data(&data_cmd, sizeof(data_cmd), data, size);
}
esp_loader_error_t loader_mem_end_cmd(uint32_t entrypoint)
{
mem_end_command_t end_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = MEM_END,
.size = CMD_SIZE(end_cmd),
},
.stay_in_loader = (entrypoint == 0),
.entry_point_address = entrypoint
};
return send_cmd(&end_cmd, sizeof(end_cmd), NULL);
}
esp_loader_error_t loader_sync_cmd(void)
{
sync_command_t sync_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = SYNC,
.size = CMD_SIZE(sync_cmd),
.checksum = 0
},
.sync_sequence = {
0x07, 0x07, 0x12, 0x20,
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
}
};
return send_cmd(&sync_cmd, sizeof(sync_cmd), NULL);
}
esp_loader_error_t loader_write_reg_cmd(uint32_t address, uint32_t value,
uint32_t mask, uint32_t delay_us)
{
write_reg_command_t write_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = WRITE_REG,
.size = CMD_SIZE(write_cmd),
.checksum = 0
},
.address = address,
.value = value,
.mask = mask,
.delay_us = delay_us
};
return send_cmd(&write_cmd, sizeof(write_cmd), NULL);
}
esp_loader_error_t loader_read_reg_cmd(uint32_t address, uint32_t *reg)
{
read_reg_command_t read_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = READ_REG,
.size = CMD_SIZE(read_cmd),
.checksum = 0
},
.address = address,
};
return send_cmd(&read_cmd, sizeof(read_cmd), reg);
}
esp_loader_error_t loader_spi_attach_cmd(uint32_t config)
{
spi_attach_command_t attach_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = SPI_ATTACH,
.size = CMD_SIZE(attach_cmd),
.checksum = 0
},
.configuration = config,
.zero = 0
};
return send_cmd(&attach_cmd, sizeof(attach_cmd), NULL);
}
esp_loader_error_t loader_change_baudrate_cmd(uint32_t baudrate)
{
change_baudrate_command_t baudrate_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = CHANGE_BAUDRATE,
.size = CMD_SIZE(baudrate_cmd),
.checksum = 0
},
.new_baudrate = baudrate,
.old_baudrate = 0 // ESP32 ROM only
};
return send_cmd(&baudrate_cmd, sizeof(baudrate_cmd), NULL);
}
esp_loader_error_t loader_md5_cmd(uint32_t address, uint32_t size, uint8_t *md5_out)
{
spi_flash_md5_command_t md5_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = SPI_FLASH_MD5,
.size = CMD_SIZE(md5_cmd),
.checksum = 0
},
.address = address,
.size = size,
.reserved_0 = 0,
.reserved_1 = 0
};
return send_cmd_md5(&md5_cmd, sizeof(md5_cmd), md5_out);
}
esp_loader_error_t loader_spi_parameters(uint32_t total_size)
{
write_spi_command_t spi_cmd = {
.common = {
.direction = WRITE_DIRECTION,
.command = SPI_SET_PARAMS,
.size = 24,
.checksum = 0
},
.id = 0,
.total_size = total_size,
.block_size = 64 * 1024,
.sector_size = 4 * 1024,
.page_size = 0x100,
.status_mask = 0xFFFF,
};
return send_cmd(&spi_cmd, sizeof(spi_cmd), NULL);
}
__attribute__ ((weak)) void loader_port_debug_print(const char *str)
{
(void)(str);
}

View file

@ -0,0 +1,312 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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 "protocol.h"
#include "protocol_prv.h"
#include "esp_loader_io.h"
#include <stddef.h>
#include <assert.h>
typedef struct __attribute__((packed)) {
uint8_t cmd;
uint8_t addr;
uint8_t dummy;
} transaction_preamble_t;
typedef enum {
TRANS_CMD_WRBUF = 0x01,
TRANS_CMD_RDBUF = 0x02,
TRANS_CMD_WRDMA = 0x03,
TRANS_CMD_RDDMA = 0x04,
TRANS_CMD_SEG_DONE = 0x05,
TRANS_CMD_ENQPI = 0x06,
TRANS_CMD_WR_DONE = 0x07,
TRANS_CMD_CMD8 = 0x08,
TRANS_CMD_CMD9 = 0x09,
TRANS_CMD_CMDA = 0x0A,
TRANS_CMD_EXQPI = 0xDD,
} transaction_cmd_t;
/* Slave protocol registers */
typedef enum {
SLAVE_REGISTER_VER = 0,
SLAVE_REGISTER_RXSTA = 4,
SLAVE_REGISTER_TXSTA = 8,
SLAVE_REGISTER_CMD = 12,
} slave_register_addr_t;
#define SLAVE_STA_TOGGLE_BIT (0x01U << 0)
#define SLAVE_STA_INIT_BIT (0x01U << 1)
#define SLAVE_STA_BUF_LENGTH_POS 2U
typedef enum {
SLAVE_STATE_INIT = SLAVE_STA_TOGGLE_BIT | SLAVE_STA_INIT_BIT,
SLAVE_STATE_FIRST_PACKET = SLAVE_STA_INIT_BIT,
} slave_state_t;
typedef enum {
/* Target to host */
SLAVE_CMD_IDLE = 0xAA,
SLAVE_CMD_READY = 0xA5,
/* Host to target */
SLAVE_CMD_REBOOT = 0xFE,
SLAVE_CMD_COMM_REINIT = 0x5A,
SLAVE_CMD_DONE = 0x55,
} slave_cmd_t;
static uint8_t s_slave_seq_tx;
static uint8_t s_slave_seq_rx;
static esp_loader_error_t write_slave_reg(const uint8_t *data, const uint32_t addr,
const uint8_t size);
static esp_loader_error_t read_slave_reg(uint8_t *out_data, const uint32_t addr,
const uint8_t size);
static esp_loader_error_t handle_slave_state(const uint32_t status_reg_addr, uint8_t *seq_state,
bool *slave_ready, uint32_t *buf_size);
static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value);
esp_loader_error_t loader_initialize_conn(esp_loader_connect_args_t *connect_args)
{
for (uint8_t trial = 0; trial < connect_args->trials; trial++) {
uint8_t slave_ready_flag;
RETURN_ON_ERROR(read_slave_reg(&slave_ready_flag, SLAVE_REGISTER_CMD,
sizeof(slave_ready_flag)));
if (slave_ready_flag != SLAVE_CMD_IDLE) {
loader_port_debug_print("Waiting for Slave to be idle...\n");
loader_port_delay_ms(100);
} else {
break;
}
}
const uint8_t reg_val = SLAVE_CMD_READY;
RETURN_ON_ERROR(write_slave_reg(&reg_val, SLAVE_REGISTER_CMD, sizeof(reg_val)));
for (uint8_t trial = 0; trial < connect_args->trials; trial++) {
uint8_t slave_ready_flag;
RETURN_ON_ERROR(read_slave_reg(&slave_ready_flag, SLAVE_REGISTER_CMD,
sizeof(slave_ready_flag)));
if (slave_ready_flag != SLAVE_CMD_READY) {
loader_port_debug_print("Waiting for Slave to be ready...\n");
loader_port_delay_ms(100);
} else {
break;
}
}
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t send_cmd(const void *cmd_data, uint32_t size, uint32_t *reg_value)
{
command_t command = ((const command_common_t *)cmd_data)->command;
uint32_t buf_size;
bool slave_ready = false;
while (!slave_ready) {
RETURN_ON_ERROR(handle_slave_state(SLAVE_REGISTER_RXSTA, &s_slave_seq_rx, &slave_ready,
&buf_size));
}
if (size > buf_size) {
return ESP_LOADER_ERROR_INVALID_PARAM;
}
/* Start and write the command */
transaction_preamble_t preamble = {.cmd = TRANS_CMD_WRDMA};
loader_port_spi_set_cs(0);
RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble),
loader_port_remaining_time()));
RETURN_ON_ERROR(loader_port_write((const uint8_t *)cmd_data, size,
loader_port_remaining_time()));
loader_port_spi_set_cs(1);
/* Terminate the write */
loader_port_spi_set_cs(0);
preamble.cmd = TRANS_CMD_WR_DONE;
RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble),
loader_port_remaining_time()));
loader_port_spi_set_cs(1);
return check_response(command, reg_value);
}
esp_loader_error_t send_cmd_with_data(const void *cmd_data, size_t cmd_size,
const void *data, size_t data_size)
{
uint32_t buf_size;
bool slave_ready = false;
while (!slave_ready) {
RETURN_ON_ERROR(handle_slave_state(SLAVE_REGISTER_RXSTA, &s_slave_seq_rx, &slave_ready,
&buf_size));
}
if (cmd_size + data_size > buf_size) {
return ESP_LOADER_ERROR_INVALID_PARAM;
}
/* Start and write the command and the data */
transaction_preamble_t preamble = {.cmd = TRANS_CMD_WRDMA};
loader_port_spi_set_cs(0);
RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble),
loader_port_remaining_time()));
RETURN_ON_ERROR(loader_port_write((const uint8_t *)cmd_data, cmd_size,
loader_port_remaining_time()));
RETURN_ON_ERROR(loader_port_write((const uint8_t *)data, data_size,
loader_port_remaining_time()));
loader_port_spi_set_cs(1);
/* Terminate the write */
loader_port_spi_set_cs(0);
preamble.cmd = TRANS_CMD_WR_DONE;
RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble),
loader_port_remaining_time()));
loader_port_spi_set_cs(1);
command_t command = ((const command_common_t *)cmd_data)->command;
return check_response(command, NULL);
}
static esp_loader_error_t read_slave_reg(uint8_t *out_data, const uint32_t addr,
const uint8_t size)
{
transaction_preamble_t preamble = {
.cmd = TRANS_CMD_RDBUF,
.addr = addr,
};
loader_port_spi_set_cs(0);
RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble),
loader_port_remaining_time()));
RETURN_ON_ERROR(loader_port_read(out_data, size, loader_port_remaining_time()));
loader_port_spi_set_cs(1);
return ESP_LOADER_SUCCESS;
}
static esp_loader_error_t write_slave_reg(const uint8_t *data, const uint32_t addr,
const uint8_t size)
{
transaction_preamble_t preamble = {
.cmd = TRANS_CMD_WRBUF,
.addr = addr,
};
loader_port_spi_set_cs(0);
RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble),
loader_port_remaining_time()));
RETURN_ON_ERROR(loader_port_write(data, size, loader_port_remaining_time()));
loader_port_spi_set_cs(1);
return ESP_LOADER_SUCCESS;
}
static esp_loader_error_t handle_slave_state(const uint32_t status_reg_addr, uint8_t *seq_state,
bool *slave_ready, uint32_t *buf_size)
{
uint32_t status_reg;
RETURN_ON_ERROR(read_slave_reg((uint8_t *)&status_reg, status_reg_addr,
sizeof(status_reg)));
const slave_state_t state = status_reg & (SLAVE_STA_TOGGLE_BIT | SLAVE_STA_INIT_BIT);
switch(state) {
case SLAVE_STATE_INIT: {
const uint32_t initial = 0U;
RETURN_ON_ERROR(write_slave_reg((uint8_t *)&initial, status_reg_addr, sizeof(initial)));
break;
}
case SLAVE_STATE_FIRST_PACKET: {
*seq_state = state & SLAVE_STA_TOGGLE_BIT;
*buf_size = status_reg >> SLAVE_STA_BUF_LENGTH_POS;
*slave_ready = true;
break;
}
default: {
const uint8_t new_seq = state & SLAVE_STA_TOGGLE_BIT;
if (new_seq != *seq_state) {
*seq_state = new_seq;
*buf_size = status_reg >> SLAVE_STA_BUF_LENGTH_POS;
*slave_ready = true;
}
break;
}
}
return ESP_LOADER_SUCCESS;
}
static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value)
{
response_t resp;
uint32_t buf_size;
bool slave_ready = false;
while (!slave_ready) {
RETURN_ON_ERROR(handle_slave_state(SLAVE_REGISTER_TXSTA, &s_slave_seq_tx, &slave_ready,
&buf_size));
}
if (sizeof(resp) > buf_size) {
return ESP_LOADER_ERROR_INVALID_PARAM;
}
transaction_preamble_t preamble = {
.cmd = TRANS_CMD_RDDMA,
};
loader_port_spi_set_cs(0);
RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble),
loader_port_remaining_time()));
RETURN_ON_ERROR(loader_port_read((uint8_t *)&resp, sizeof(resp),
loader_port_remaining_time()));
loader_port_spi_set_cs(1);
/* Terminate the read */
loader_port_spi_set_cs(0);
preamble.cmd = TRANS_CMD_CMD8;
RETURN_ON_ERROR(loader_port_write((const uint8_t *)&preamble, sizeof(preamble),
loader_port_remaining_time()));
loader_port_spi_set_cs(1);
common_response_t *common = (common_response_t *)&resp;
if ((common->direction != READ_DIRECTION) || (common->command != cmd)) {
return ESP_LOADER_ERROR_INVALID_RESPONSE;
}
response_status_t *status =
(response_status_t *)((uint8_t *)&resp + sizeof(resp) - sizeof(response_status_t));
if (status->failed) {
log_loader_internal_error(status->error);
return ESP_LOADER_ERROR_INVALID_RESPONSE;
}
if (reg_value != NULL) {
*reg_value = common->value;
}
return ESP_LOADER_SUCCESS;
}

View file

@ -0,0 +1,114 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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 "protocol.h"
#include "protocol_prv.h"
#include "esp_loader_io.h"
#include "slip.h"
#include <stddef.h>
#include <string.h>
static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value, void* resp, uint32_t resp_size);
esp_loader_error_t loader_initialize_conn(esp_loader_connect_args_t *connect_args) {
esp_loader_error_t err;
int32_t trials = connect_args->trials;
do {
loader_port_start_timer(connect_args->sync_timeout);
err = loader_sync_cmd();
if (err == ESP_LOADER_ERROR_TIMEOUT) {
if (--trials == 0) {
return ESP_LOADER_ERROR_TIMEOUT;
}
loader_port_delay_ms(100);
} else if (err != ESP_LOADER_SUCCESS) {
return err;
}
} while (err != ESP_LOADER_SUCCESS);
return err;
}
esp_loader_error_t send_cmd(const void *cmd_data, uint32_t size, uint32_t *reg_value)
{
response_t response;
command_t command = ((const command_common_t *)cmd_data)->command;
RETURN_ON_ERROR( SLIP_send_delimiter() );
RETURN_ON_ERROR( SLIP_send((const uint8_t *)cmd_data, size) );
RETURN_ON_ERROR( SLIP_send_delimiter() );
return check_response(command, reg_value, &response, sizeof(response));
}
esp_loader_error_t send_cmd_with_data(const void *cmd_data, size_t cmd_size,
const void *data, size_t data_size)
{
response_t response;
command_t command = ((const command_common_t *)cmd_data)->command;
RETURN_ON_ERROR( SLIP_send_delimiter() );
RETURN_ON_ERROR( SLIP_send((const uint8_t *)cmd_data, cmd_size) );
RETURN_ON_ERROR( SLIP_send(data, data_size) );
RETURN_ON_ERROR( SLIP_send_delimiter() );
return check_response(command, NULL, &response, sizeof(response));
}
esp_loader_error_t send_cmd_md5(const void *cmd_data, size_t cmd_size, uint8_t md5_out[MD5_SIZE])
{
rom_md5_response_t response;
command_t command = ((const command_common_t *)cmd_data)->command;
RETURN_ON_ERROR( SLIP_send_delimiter() );
RETURN_ON_ERROR( SLIP_send((const uint8_t *)cmd_data, cmd_size) );
RETURN_ON_ERROR( SLIP_send_delimiter() );
RETURN_ON_ERROR( check_response(command, NULL, &response, sizeof(response)) );
memcpy(md5_out, response.md5, MD5_SIZE);
return ESP_LOADER_SUCCESS;
}
static esp_loader_error_t check_response(command_t cmd, uint32_t *reg_value, void* resp, uint32_t resp_size)
{
esp_loader_error_t err;
common_response_t *response = (common_response_t *)resp;
do {
err = SLIP_receive_packet(resp, resp_size);
if (err != ESP_LOADER_SUCCESS) {
return err;
}
} while ((response->direction != READ_DIRECTION) || (response->command != cmd));
response_status_t *status = (response_status_t *)((uint8_t *)resp + resp_size - sizeof(response_status_t));
if (status->failed) {
log_loader_internal_error(status->error);
return ESP_LOADER_ERROR_INVALID_RESPONSE;
}
if (reg_value != NULL) {
*reg_value = response->value;
}
return ESP_LOADER_SUCCESS;
}

View file

@ -0,0 +1,125 @@
/* Copyright 2020-2023 Espressif Systems (Shanghai) CO LTD
*
* 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 "slip.h"
#include "esp_loader_io.h"
static const uint8_t DELIMITER = 0xC0;
static const uint8_t C0_REPLACEMENT[2] = {0xDB, 0xDC};
static const uint8_t DB_REPLACEMENT[2] = {0xDB, 0xDD};
static inline esp_loader_error_t peripheral_read(uint8_t *buff, const size_t size)
{
return loader_port_read(buff, size, loader_port_remaining_time());
}
static inline esp_loader_error_t peripheral_write(const uint8_t *buff, const size_t size)
{
return loader_port_write(buff, size, loader_port_remaining_time());
}
esp_loader_error_t SLIP_receive_data(uint8_t *buff, const size_t size)
{
uint8_t ch;
for (uint32_t i = 0; i < size; i++) {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
if (ch == 0xDB) {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
if (ch == 0xDC) {
buff[i] = 0xC0;
} else if (ch == 0xDD) {
buff[i] = 0xDB;
} else {
return ESP_LOADER_ERROR_INVALID_RESPONSE;
}
} else {
buff[i] = ch;
}
}
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t SLIP_receive_packet(uint8_t *buff, const size_t size)
{
uint8_t ch;
// Wait for delimiter
do {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
} while (ch != DELIMITER);
// Workaround: bootloader sends two dummy(0xC0) bytes after response when baud rate is changed.
do {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
} while (ch == DELIMITER);
buff[0] = ch;
RETURN_ON_ERROR( SLIP_receive_data(&buff[1], size - 1) );
// Wait for delimiter
do {
RETURN_ON_ERROR( peripheral_read(&ch, 1) );
} while (ch != DELIMITER);
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t SLIP_send(const uint8_t *data, const size_t size)
{
uint32_t to_write = 0; // Bytes ready to write as they are
uint32_t written = 0; // Bytes already written
for (uint32_t i = 0; i < size; i++) {
if (data[i] != 0xC0 && data[i] != 0xDB) {
to_write++; // Queue this byte for writing
continue;
}
// We have a byte that needs encoding, write the queue first
if (to_write > 0) {
RETURN_ON_ERROR( peripheral_write(&data[written], to_write) );
}
// Write the encoded byte
if (data[i] == 0xC0) {
RETURN_ON_ERROR( peripheral_write(C0_REPLACEMENT, 2) );
} else {
RETURN_ON_ERROR( peripheral_write(DB_REPLACEMENT, 2) );
}
// Update to start again after the encoded byte
written = i + 1;
to_write = 0;
}
// Write the rest of the bytes that didn't need encoding
if (to_write > 0) {
RETURN_ON_ERROR( peripheral_write(&data[written], to_write) );
}
return ESP_LOADER_SUCCESS;
}
esp_loader_error_t SLIP_send_delimiter(void)
{
return peripheral_write(&DELIMITER, 1);
}

View file

@ -0,0 +1,30 @@
cmake_minimum_required(VERSION 3.5)
if (CONFIG_ESP_SERIAL_FLASHER)
zephyr_include_directories(
"${ZEPHYR_CURRENT_MODULE_DIR}/include"
"${ZEPHYR_CURRENT_MODULE_DIR}/port"
"${ZEPHYR_CURRENT_MODULE_DIR}/private_include"
)
zephyr_interface_library_named(esp_flasher)
zephyr_library()
zephyr_library_sources(${ZEPHYR_CURRENT_MODULE_DIR}/src/esp_loader.c
${ZEPHYR_CURRENT_MODULE_DIR}/src/esp_targets.c
${ZEPHYR_CURRENT_MODULE_DIR}/src/protocol_common.c
${ZEPHYR_CURRENT_MODULE_DIR}/src/protocol_uart.c
${ZEPHYR_CURRENT_MODULE_DIR}/src/slip.c
${ZEPHYR_CURRENT_MODULE_DIR}/src/md5_hash.c
${ZEPHYR_CURRENT_MODULE_DIR}/port/zephyr_port.c
)
target_compile_definitions(esp_flasher INTERFACE SERIAL_FLASHER_INTERFACE_UART)
zephyr_library_link_libraries(esp_flasher)
if(DEFINED MD5_ENABLED OR CONFIG_SERIAL_FLASHER_MD5_ENABLED)
target_compile_definitions(esp_flasher INTERFACE -DMD5_ENABLED=1)
endif()
endif()

View file

@ -0,0 +1,16 @@
config ESP_SERIAL_FLASHER
bool "Enable ESP serial flasher library"
default y
select CONSOLE_SUBSYS
help
Select this option to enable the ESP serial flasher library.
config ESP_SERIAL_FLASHER_UART_BUFSIZE
int "ESP Serial Flasher UART buffer size"
default 512
help
Buffer size for UART TX and RX packets
if ESP_SERIAL_FLASHER
rsource "../Kconfig"
endif

View file

@ -0,0 +1,5 @@
name: esp-flasher
build:
cmake: zephyr
kconfig: zephyr/Kconfig

View file

@ -13,3 +13,4 @@ ADD_SCENE(wifi_marauder, script_stage_edit, ScriptStageEdit)
ADD_SCENE(wifi_marauder, script_stage_add, ScriptStageAdd)
ADD_SCENE(wifi_marauder, script_stage_edit_list, ScriptStageEditList)
ADD_SCENE(wifi_marauder, sniffpmkid_options, SniffPmkidOptions)
ADD_SCENE(wifi_marauder, flasher, Flasher)

View file

@ -1,5 +1,7 @@
#include "../wifi_marauder_app_i.h"
#include "../wifi_marauder_flasher.h"
char* _wifi_marauder_get_prefix_from_cmd(const char* command) {
int end = strcspn(command, " ");
char* prefix = (char*)malloc(sizeof(char) * (end + 1));
@ -101,13 +103,24 @@ void wifi_marauder_scene_console_output_on_enter(void* context) {
view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewConsoleOutput);
// Register callbacks to receive data
wifi_marauder_uart_set_handle_rx_data_cb(
app->uart,
wifi_marauder_console_output_handle_rx_data_cb); // setup callback for general log rx thread
// setup callback for general log rx thread
if(app->flash_mode) {
wifi_marauder_uart_set_handle_rx_data_cb(
app->uart,
wifi_marauder_flash_handle_rx_data_cb); // setup callback for general log rx thread
} else {
wifi_marauder_uart_set_handle_rx_data_cb(
app->uart,
wifi_marauder_console_output_handle_rx_data_cb); // setup callback for general log rx thread
}
wifi_marauder_uart_set_handle_rx_data_cb(
app->lp_uart,
wifi_marauder_console_output_handle_rx_packets_cb); // setup callback for packets rx thread
if(app->flash_mode) {
wifi_marauder_flash_start_thread(app);
}
// Get ready to send command
if((app->is_command && app->selected_tx_string) || app->script) {
const char* prefix =
@ -183,6 +196,10 @@ void wifi_marauder_scene_console_output_on_exit(void* context) {
furi_delay_ms(50);
}
if(app->flash_mode) {
wifi_marauder_flash_stop_thread(app);
}
// Unregister rx callback
wifi_marauder_uart_set_handle_rx_data_cb(app->uart, NULL);
wifi_marauder_uart_set_handle_rx_data_cb(app->lp_uart, NULL);

View file

@ -0,0 +1,92 @@
#include "../wifi_marauder_app_i.h"
enum SubmenuIndex {
SubmenuIndexBoot,
SubmenuIndexPart,
SubmenuIndexApp,
SubmenuIndexFlash,
};
static void wifi_marauder_scene_flasher_callback(void* context, uint32_t index) {
WifiMarauderApp* app = context;
scene_manager_set_scene_state(app->scene_manager, WifiMarauderSceneFlasher, index);
// browse for files
FuriString* predefined_filepath = furi_string_alloc_set_str(MARAUDER_APP_FOLDER);
FuriString* selected_filepath = furi_string_alloc();
DialogsFileBrowserOptions browser_options;
dialog_file_browser_set_basic_options(&browser_options, ".bin", &I_Text_10x10);
// TODO refactor
switch(index) {
case SubmenuIndexBoot:
if(dialog_file_browser_show(
app->dialogs, selected_filepath, predefined_filepath, &browser_options)) {
strncpy(
app->bin_file_path_boot,
furi_string_get_cstr(selected_filepath),
sizeof(app->bin_file_path_boot));
}
break;
case SubmenuIndexPart:
if(dialog_file_browser_show(
app->dialogs, selected_filepath, predefined_filepath, &browser_options)) {
strncpy(
app->bin_file_path_part,
furi_string_get_cstr(selected_filepath),
sizeof(app->bin_file_path_part));
}
break;
case SubmenuIndexApp:
if(dialog_file_browser_show(
app->dialogs, selected_filepath, predefined_filepath, &browser_options)) {
strncpy(
app->bin_file_path_app,
furi_string_get_cstr(selected_filepath),
sizeof(app->bin_file_path_app));
}
break;
case SubmenuIndexFlash:
// TODO error checking
scene_manager_next_scene(app->scene_manager, WifiMarauderSceneConsoleOutput);
break;
}
furi_string_free(selected_filepath);
furi_string_free(predefined_filepath);
}
void wifi_marauder_scene_flasher_on_enter(void* context) {
WifiMarauderApp* app = context;
Submenu* submenu = app->submenu;
submenu_set_header(submenu, "Browse for files to flash");
submenu_add_item(
submenu, "Bootloader", SubmenuIndexBoot, wifi_marauder_scene_flasher_callback, app);
submenu_add_item(
submenu, "Partition Table", SubmenuIndexPart, wifi_marauder_scene_flasher_callback, app);
submenu_add_item(
submenu, "Application", SubmenuIndexApp, wifi_marauder_scene_flasher_callback, app);
submenu_add_item(
submenu, "[>] FLASH", SubmenuIndexFlash, wifi_marauder_scene_flasher_callback, app);
submenu_set_selected_item(
submenu, scene_manager_get_scene_state(app->scene_manager, WifiMarauderSceneFlasher));
view_dispatcher_switch_to_view(app->view_dispatcher, WifiMarauderAppViewSubmenu);
}
bool wifi_marauder_scene_flasher_on_event(void* context, SceneManagerEvent event) {
//WifiMarauderApp* app = context;
UNUSED(context);
UNUSED(event);
bool consumed = false;
return consumed;
}
void wifi_marauder_scene_flasher_on_exit(void* context) {
WifiMarauderApp* app = context;
submenu_reset(app->submenu);
}

View file

@ -121,6 +121,7 @@ const WifiMarauderItem items[NUM_MENU_ITEMS] = {
{"Update", {"ota", "sd"}, 2, {"update -w", "update -s"}, NO_ARGS, FOCUS_CONSOLE_END, NO_TIP},
{"Reboot", {""}, 1, {"reboot"}, NO_ARGS, FOCUS_CONSOLE_END, NO_TIP},
{"Help", {""}, 1, {"help"}, NO_ARGS, FOCUS_CONSOLE_START, SHOW_STOPSCAN_TIP},
{"Reflash ESP32 (WIP)", {""}, 1, {""}, NO_ARGS, FOCUS_CONSOLE_END, NO_TIP},
{"Scripts", {""}, 1, {""}, NO_ARGS, FOCUS_CONSOLE_END, NO_TIP},
{"Save to flipper sdcard", // keep as last entry or change logic in callback below
{""},
@ -149,6 +150,17 @@ static void wifi_marauder_scene_start_var_list_enter_callback(void* context, uin
item->focus_console;
app->show_stopscan_tip = item->show_stopscan_tip;
// TODO cleanup
if(index == NUM_MENU_ITEMS - 3) {
// flasher
app->is_command = false;
app->flash_mode = true;
view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventStartFlasher);
return;
}
app->flash_mode = false;
if(!app->is_command && selected_option_index == 0) {
// View Log from start
view_dispatcher_send_custom_event(app->view_dispatcher, WifiMarauderEventStartLogViewer);
@ -260,6 +272,10 @@ bool wifi_marauder_scene_start_on_event(void* context, SceneManagerEvent event)
scene_manager_set_scene_state(
app->scene_manager, WifiMarauderSceneStart, app->selected_menu_index);
scene_manager_next_scene(app->scene_manager, WifiMarauderSceneSniffPmkidOptions);
} else if(event.event == WifiMarauderEventStartFlasher) {
scene_manager_set_scene_state(
app->scene_manager, WifiMarauderSceneStart, app->selected_menu_index);
scene_manager_next_scene(app->scene_manager, WifiMarauderSceneFlasher);
}
consumed = true;
} else if(event.type == SceneManagerEventTypeTick) {

View file

@ -46,7 +46,9 @@ void wifi_marauder_scene_text_input_on_enter(void* context) {
// Setup view
WIFI_TextInput* text_input = app->text_input;
// Add help message to header
if(app->special_case_input_step == 1) {
if(app->flash_mode) {
wifi_text_input_set_header_text(text_input, "Enter destination address");
} else if(app->special_case_input_step == 1) {
wifi_text_input_set_header_text(text_input, "Enter source MAC");
} else if(0 == strncmp("ssid -a -g", app->selected_tx_string, strlen("ssid -a -g"))) {
wifi_text_input_set_header_text(text_input, "Enter # SSIDs to generate");

View file

@ -86,6 +86,8 @@ WifiMarauderApp* wifi_marauder_app_alloc() {
view_dispatcher_add_view(
app->view_dispatcher, WifiMarauderAppViewSubmenu, submenu_get_view(app->submenu));
app->flash_mode = false;
scene_manager_next_scene(app->scene_manager, WifiMarauderSceneStart);
return app;

View file

@ -4,7 +4,7 @@
extern "C" {
#endif
#define WIFI_MARAUDER_APP_VERSION "v0.4.0"
#define WIFI_MARAUDER_APP_VERSION "v0.5.0"
typedef struct WifiMarauderApp WifiMarauderApp;

View file

@ -26,7 +26,7 @@
#include <lib/toolbox/path.h>
#include <dialogs/dialogs.h>
#define NUM_MENU_ITEMS (18)
#define NUM_MENU_ITEMS (19)
#define WIFI_MARAUDER_TEXT_BOX_STORE_SIZE (4096)
#define WIFI_MARAUDER_TEXT_INPUT_STORE_SIZE (512)
@ -113,6 +113,13 @@ struct WifiMarauderApp {
int special_case_input_step;
char special_case_input_src_addr[20];
char special_case_input_dst_addr[20];
// For flashing - TODO: put into its own struct?
char bin_file_path_boot[100];
char bin_file_path_part[100];
char bin_file_path_app[100];
FuriThread* flash_worker;
bool flash_mode;
};
// Supported commands:

View file

@ -9,5 +9,6 @@ typedef enum {
WifiMarauderEventStartSettingsInit,
WifiMarauderEventStartLogViewer,
WifiMarauderEventStartScriptSelect,
WifiMarauderEventStartSniffPmkidOptions
WifiMarauderEventStartSniffPmkidOptions,
WifiMarauderEventStartFlasher
} WifiMarauderCustomEvent;

View file

@ -0,0 +1,200 @@
#include "wifi_marauder_flasher.h"
FuriStreamBuffer* flash_rx_stream; // TODO make safe
WifiMarauderApp* global_app; // TODO make safe
FuriTimer* timer; // TODO make
static uint32_t _remaining_time = 0;
static void _timer_callback(void* context) {
UNUSED(context);
if(_remaining_time > 0) {
_remaining_time--;
}
}
static esp_loader_error_t _flash_file(WifiMarauderApp* app, char* filepath, uint32_t addr) {
// TODO cleanup
esp_loader_error_t err;
static uint8_t payload[1024];
File* bin_file = storage_file_alloc(app->storage);
// open file
if(!storage_file_open(bin_file, filepath, FSAM_READ, FSOM_OPEN_EXISTING)) {
storage_file_close(bin_file);
storage_file_free(bin_file);
dialog_message_show_storage_error(app->dialogs, "Cannot open file");
return ESP_LOADER_ERROR_FAIL;
}
uint64_t size = storage_file_size(bin_file);
/*
// TODO packet drops with higher BR?
err = esp_loader_change_transmission_rate(230400);
if (err != ESP_LOADER_SUCCESS) {
char err_msg[256];
snprintf(
err_msg,
sizeof(err_msg),
"Cannot change transmission rate. Error: %u\n",
err);
storage_file_close(bin_file);
storage_file_free(bin_file);
loader_port_debug_print(err_msg);
return;
}
furi_hal_uart_set_br(FuriHalUartIdUSART1, 230400);
// TODO remember to change BR back!
*/
loader_port_debug_print("Erasing flash...this may take a while\n");
err = esp_loader_flash_start(addr, size, sizeof(payload));
if(err != ESP_LOADER_SUCCESS) {
storage_file_close(bin_file);
storage_file_free(bin_file);
char err_msg[256];
snprintf(err_msg, sizeof(err_msg), "Erasing flash failed with error %d\n", err);
loader_port_debug_print(err_msg);
return err;
}
loader_port_debug_print("Start programming\n");
while(size > 0) {
size_t to_read = MIN(size, sizeof(payload));
uint16_t num_bytes = storage_file_read(bin_file, payload, to_read);
err = esp_loader_flash_write(payload, num_bytes);
if(err != ESP_LOADER_SUCCESS) {
char err_msg[256];
snprintf(err_msg, sizeof(err_msg), "Packet could not be written! Error: %u\n", err);
storage_file_close(bin_file);
storage_file_free(bin_file);
loader_port_debug_print(err_msg);
return err;
}
size -= num_bytes;
}
loader_port_debug_print("Finished programming\n");
// TODO verify
storage_file_close(bin_file);
storage_file_free(bin_file);
return ESP_LOADER_SUCCESS;
}
static int32_t wifi_marauder_flash_bin(void* context) {
WifiMarauderApp* app = (void*)context;
esp_loader_error_t err;
// alloc global objects
flash_rx_stream = furi_stream_buffer_alloc(RX_BUF_SIZE, 1);
timer = furi_timer_alloc(_timer_callback, FuriTimerTypePeriodic, app);
loader_port_debug_print("Connecting\n");
esp_loader_connect_args_t connect_config = ESP_LOADER_CONNECT_DEFAULT();
err = esp_loader_connect(&connect_config);
if(err != ESP_LOADER_SUCCESS) {
char err_msg[256];
snprintf(err_msg, sizeof(err_msg), "Cannot connect to target. Error: %u\n", err);
loader_port_debug_print(err_msg);
}
if(!err) {
loader_port_debug_print("Connected\n");
loader_port_debug_print("Flashing bootloader (1/3)\n");
err = _flash_file(app, app->bin_file_path_boot, 0x1000);
}
if(!err) {
loader_port_debug_print("Flashing partition table (2/3)\n");
err = _flash_file(app, app->bin_file_path_part, 0x8000);
}
if(!err) {
loader_port_debug_print("Flashing app (3/3)\n");
err = _flash_file(app, app->bin_file_path_app, 0x10000);
loader_port_debug_print("Done flashing. Please reset the board manually.\n");
}
// done
// cleanup
furi_stream_buffer_free(flash_rx_stream);
flash_rx_stream = NULL;
furi_timer_free(timer);
return 0;
}
void wifi_marauder_flash_start_thread(WifiMarauderApp* app) {
global_app = app;
app->flash_worker = furi_thread_alloc();
furi_thread_set_name(app->flash_worker, "WifiMarauderFlashWorker");
furi_thread_set_stack_size(app->flash_worker, 2048);
furi_thread_set_context(app->flash_worker, app);
furi_thread_set_callback(app->flash_worker, wifi_marauder_flash_bin);
furi_thread_start(app->flash_worker);
}
void wifi_marauder_flash_stop_thread(WifiMarauderApp* app) {
furi_thread_join(app->flash_worker);
furi_thread_free(app->flash_worker);
}
esp_loader_error_t loader_port_read(uint8_t* data, uint16_t size, uint32_t timeout) {
size_t read = furi_stream_buffer_receive(flash_rx_stream, data, size, pdMS_TO_TICKS(timeout));
if(read < size) {
return ESP_LOADER_ERROR_TIMEOUT;
} else {
return ESP_LOADER_SUCCESS;
}
}
esp_loader_error_t loader_port_write(const uint8_t* data, uint16_t size, uint32_t timeout) {
UNUSED(timeout);
wifi_marauder_uart_tx((uint8_t*)data, size);
return ESP_LOADER_SUCCESS;
}
void loader_port_enter_bootloader(void) {
// unimplemented
}
void loader_port_delay_ms(uint32_t ms) {
furi_delay_ms(ms);
}
void loader_port_start_timer(uint32_t ms) {
_remaining_time = ms;
furi_timer_start(timer, pdMS_TO_TICKS(1));
}
uint32_t loader_port_remaining_time(void) {
return _remaining_time;
}
extern void wifi_marauder_console_output_handle_rx_data_cb(
uint8_t* buf,
size_t len,
void* context); // TODO cleanup
void loader_port_debug_print(const char* str) {
if(global_app)
wifi_marauder_console_output_handle_rx_data_cb((uint8_t*)str, strlen(str), global_app);
}
void loader_port_spi_set_cs(uint32_t level) {
UNUSED(level);
// unimplemented
}
void wifi_marauder_flash_handle_rx_data_cb(uint8_t* buf, size_t len, void* context) {
UNUSED(context);
if(flash_rx_stream) {
furi_stream_buffer_send(flash_rx_stream, buf, len, 0);
} else {
// done flashing
if(global_app) wifi_marauder_console_output_handle_rx_data_cb(buf, len, global_app);
}
}

View file

@ -0,0 +1,10 @@
#pragma once
#include "wifi_marauder_app_i.h"
#include "wifi_marauder_uart.h"
#define SERIAL_FLASHER_INTERFACE_UART /* TODO why is application.fam not passing this via cdefines */
#include "esp_loader_io.h"
void wifi_marauder_flash_start_thread(WifiMarauderApp* app);
void wifi_marauder_flash_stop_thread(WifiMarauderApp* app);
void wifi_marauder_flash_handle_rx_data_cb(uint8_t* buf, size_t len, void* context);

View file

@ -112,4 +112,4 @@ void wifi_marauder_uart_free(WifiMarauderUart* uart) {
furi_hal_console_enable();
free(uart);
}
}