├── .editorconfig ├── .gitignore ├── .gitlab-ci.yml ├── Android.bp ├── CMakeLists.txt ├── LICENSES ├── CC0-1.0.txt ├── LGPL-2.1-or-later.txt └── MIT.txt ├── README.md ├── docs ├── Doxyfile.in └── fw_env_config.md └── src ├── CMakeLists.txt ├── common.c ├── common.h ├── extended_config.c ├── fw_printenv.c ├── libuboot.h ├── libubootenv.pc.in ├── uboot_env.c ├── uboot_mtd.c └── uboot_private.h /.editorconfig: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Stefano Babic 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | # top-most EditorConfig file 6 | root = true 7 | 8 | # Unix-style newlines with a newline ending every file 9 | [*] 10 | charset = utf-8 11 | end_of_line = lf 12 | insert_final_newline = true 13 | 14 | [CMakeLists.txt] 15 | indent_size = 2 16 | indent_style = space 17 | 18 | [*.{c,h}] 19 | indent_brace_style = K&R 20 | insert_final_newline = true 21 | indent_style = tab 22 | tab_width = 8 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Stefano Babic 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | # 6 | # NOTE! Don't add files that are generated in specific 7 | # subdirectories here. Add them in the ".gitignore" file 8 | # in that subdirectory instead. 9 | # 10 | # Normal rules 11 | # 12 | 13 | *.rej 14 | *.orig 15 | *.a 16 | *.o 17 | *.su 18 | *~ 19 | *.swp 20 | *.patch 21 | *.so 22 | 23 | CMakeFiles/ 24 | Debug/ 25 | Release/ 26 | src/CMakeFiles/ 27 | src/cmake_install.cmake 28 | src/fw_printenv 29 | src/libubootenv.so.* 30 | src/libubootenv_static.a 31 | .vscode 32 | .cproject 33 | .project 34 | .settings 35 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Stefano Babic 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | ubuntu-jammy: 6 | image: ubuntu:jammy 7 | stage: build 8 | before_script: 9 | - export DEBIAN_FRONTEND=noninteractive 10 | - export TZ=Europe/London 11 | - apt-get -qq update 12 | - apt-get install -y build-essential 13 | - apt-get install -y linux-headers-generic 14 | - apt-get install -y linux-libc-dev 15 | - apt-get install -y libyaml-dev 16 | - apt-get install -y cmake 17 | - apt-get install -y zlib1g 18 | - apt-get install -y zlib1g-dev 19 | - apt-get install -y curl 20 | - apt-get install -y git 21 | 22 | script: 23 | - if [ ! -d Debug ];then mkdir Debug;fi 24 | - cd Debug 25 | - cmake -DCMAKE_BUILD_TYPE=Debug .. 26 | - if [ $CI_COMMIT_BRANCH == "coverity_scan" ]; then 27 | curl -o /tmp/cov-analysis-linux64.tgz https://scan.coverity.com/download/linux64 --form project=$COVERITY_SCAN_PROJECT_NAME --form token=$COVERITY_SCAN_TOKEN; 28 | tar xfz /tmp/cov-analysis-linux64.tgz; 29 | cov-analysis-linux64-*/bin/cov-build --dir cov-int make; 30 | tar cfz cov-int.tar.gz cov-int; 31 | curl https://scan.coverity.com/builds?project=$COVERITY_SCAN_PROJECT_NAME --form token=$COVERITY_SCAN_TOKEN --form email=$GITLAB_USER_EMAIL --form file=@cov-int.tar.gz --form version="`git describe --tags`" --form description="`git describe --tags` / $CI_COMMIT_TITLE / $CI_COMMIT_REF_NAME:$CI_PIPELINE_ID "; 32 | fi 33 | - make VERBOSE=1 34 | 35 | reuse: 36 | needs: [] 37 | stage: test 38 | image: 39 | name: fsfe/reuse:latest 40 | entrypoint: [""] 41 | script: 42 | - reuse lint 43 | -------------------------------------------------------------------------------- /Android.bp: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2022 Gary Bisson 2 | // SPDX-License-Identifier: LGPL-2.1-or-later 3 | 4 | cc_library { 5 | name: "libubootenv", 6 | vendor: true, 7 | srcs: [ 8 | "src/uboot_env.c", 9 | ], 10 | shared_libs: ["libz"], 11 | cflags: ["-std=gnu99", "-Wno-pointer-arith", "-Wno-switch"], 12 | export_include_dirs: ["src"], 13 | local_include_dirs: ["src"], 14 | } 15 | 16 | cc_binary { 17 | name: "fw_printenv", 18 | vendor: true, 19 | srcs: ["src/fw_printenv.c"], 20 | shared_libs: ["libubootenv"], 21 | cflags: ["-std=gnu99", "-Wno-date-time"], 22 | } 23 | 24 | cc_binary { 25 | name: "fw_setenv", 26 | vendor: true, 27 | srcs: ["src/fw_setenv.c"], 28 | shared_libs: ["libubootenv"], 29 | cflags: ["-std=gnu99", "-Wno-date-time"], 30 | } 31 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2019-2021 Stefano Babic stefano.babic@swupdate.org. 2 | # 3 | # SPDX-License-Identifier: LGPL-2.1-or-later 4 | 5 | cmake_minimum_required (VERSION 2.6) 6 | project (libubootenv C) 7 | 8 | # The version number. 9 | # set (libubootenv_VERSION_MAJOR 1) 10 | # set (libubootenv_VERSION_MAJOR_VERSION_MINOR 0) 11 | set(VERSION "0.3.6") 12 | SET(SOVERSION "0") 13 | add_definitions(-DVERSION="${VERSION}") 14 | 15 | option(NO_YML_SUPPORT "YML Support") 16 | 17 | if(DEFAULT_CFG_FILE) 18 | add_definitions(-DDEFAULT_CFG_FILE="${DEFAULT_CFG_FILE}") 19 | endif(DEFAULT_CFG_FILE) 20 | 21 | if(DEFAULT_ENV_FILE) 22 | add_definitions(-DDEFAULT_ENV_FILE="${DEFAULT_ENV_FILE}") 23 | endif(DEFAULT_ENV_FILE) 24 | 25 | if(NO_YML_SUPPORT) 26 | add_definitions(-DNO_YAML_SUPPORT) 27 | endif(NO_YML_SUPPORT) 28 | 29 | set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99") 30 | 31 | #set(CMAKE_C_FLAGS_DEBUG "-g") 32 | include_directories ("${PROJECT_SOURCE_DIR}/src") 33 | add_subdirectory (src) 34 | 35 | # first we can indicate the documentation build as an option and set it to ON by default 36 | option(BUILD_DOC "Build documentation" ON) 37 | 38 | if(BUILD_DOC) 39 | # check if Doxygen is installed 40 | find_package(Doxygen) 41 | if(DOXYGEN_FOUND) 42 | # set input and output files 43 | set(DOXYGEN_IN ${CMAKE_CURRENT_SOURCE_DIR}/docs/Doxyfile.in) 44 | set(DOXYGEN_OUT ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile) 45 | 46 | # request to configure the file 47 | configure_file(${DOXYGEN_IN} ${DOXYGEN_OUT} @ONLY) 48 | message("Doxygen build started") 49 | 50 | # note the option ALL which allows to build the docs together with the application 51 | add_custom_target( doc_doxygen ALL 52 | COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_OUT} 53 | WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} 54 | COMMENT "Generating API documentation with Doxygen" 55 | VERBATIM ) 56 | else(DOXYGEN_FOUND) 57 | message("Doxygen need to be installed to generate the doxygen documentation") 58 | endif(DOXYGEN_FOUND) 59 | endif(BUILD_DOC) 60 | -------------------------------------------------------------------------------- /LICENSES/CC0-1.0.txt: -------------------------------------------------------------------------------- 1 | 2 | Creative Commons Zero 1.0 Universal (CC0) 3 | 4 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER. 5 | Statement of Purpose 6 | 7 | The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). 8 | 9 | Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. 10 | 11 | For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. 12 | 13 | 1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: 14 | 15 | the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; 16 | moral rights retained by the original author(s) and/or performer(s); 17 | publicity and privacy rights pertaining to a person`s image or likeness depicted in a Work; 18 | rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; 19 | rights protecting the extraction, dissemination, use and reuse of data in a Work; 20 | database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and 21 | other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. 22 | 2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer`s Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer`s heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer`s express Statement of Purpose. 23 | 24 | 3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer`s express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer`s Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer`s express Statement of Purpose. 25 | 26 | 4. Limitations and Disclaimers. 27 | 28 | No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. 29 | Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. 30 | Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person`s Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. 31 | Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. 32 | 33 | -------------------------------------------------------------------------------- /LICENSES/LGPL-2.1-or-later.txt: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | , 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! 503 | -------------------------------------------------------------------------------- /LICENSES/MIT.txt: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any person obtaining a copy 2 | of this software and associated documentation files (the "Software"), to deal 3 | in the Software without restriction, including without limitation the rights 4 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 5 | copies of the Software, and to permit persons to whom the Software is 6 | furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in 9 | all copies or substantial portions of the Software. 10 | 11 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 12 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 13 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 14 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 15 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 16 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 17 | THE SOFTWARE. 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 6 | libubootenv - Library to access U-Boot environment 7 | ================================================== 8 | 9 | [![pipeline status](https://source.denx.de/swupdate/libubootenv/badges/master/pipeline.svg?ignore_skipped=true)](https://source.denx.de/swupdate/libubootenv/-/commits/master) 10 | [![Coverity Scan Build Status](https://scan.coverity.com/projects/21387/badge.svg)](https://scan.coverity.com/projects/21387) 11 | [![REUSE status](https://api.reuse.software/badge/github.com/sbabic/libubootenv)](https://api.reuse.software/info/github.com/sbabic/libubootenv) 12 | 13 | libubootenv is a library that provides a hardware independent way to access 14 | to U-Boot environment. U-Boot has its default environment compiled board-dependently 15 | and this means that tools to access the environment are also board specific, too. 16 | 17 | Source Code: https://github.com/sbabic/libubootenv 18 | 19 | Documentation (doxygen): https://sbabic.github.io/libubootenv 20 | 21 | Replacement old tools 22 | --------------------- 23 | 24 | Part of the library are the replacement of the "fw_printenv / fw_setenv" tools that 25 | can be used with any board - they accept as parameter a file as initial environment if none is found 26 | on the persistent storage. The syntax for the data configuration file is the same as the one 27 | described in the U-Boot project whilst the syntax of the script file is a subset of the original one. 28 | 29 | Usage fw_printenv [OPTION] 30 | -h, : print this help 31 | -c, --config : configuration file (by default: /etc/fw_env.config) 32 | -f, --defenv : default environment if no one found (by default: /etc/u-boot-initial-env) 33 | -V, : print version and exit 34 | -n, --no-header : do not print variable name 35 | 36 | Usage fw_setenv [OPTION] 37 | -h, : print this help 38 | -c, --config : configuration file (by default: /etc/fw_env.config) 39 | -f, --defenv : default environment if no one found (by default: /etc/u-boot-initial-env) 40 | -V, : print version and exit 41 | -s, --script : read variables to be set from a script 42 | 43 | Script Syntax: 44 | key=value 45 | lines starting with '#' are treated as comment 46 | lines without '=' are ignored 47 | 48 | Script Example: 49 | netdev=eth0 50 | kernel_addr=400000 51 | foo=empty empty empty empty empty empty 52 | bar 53 | 54 | License 55 | ------- 56 | 57 | libubootenv is licensed under LGPL-2.1 58 | 59 | OE / Yocto support 60 | ------------------ 61 | 62 | Recipe is provided in openembedded-core layer https://git.openembedded.org/openembedded-core/tree/meta/recipes-bsp/u-boot/ 63 | 64 | Buildroot support 65 | ----------------- 66 | 67 | Package is provided in https://git.buildroot.net/buildroot/tree/package/libubootenv 68 | 69 | Contributing to the project 70 | --------------------------- 71 | 72 | Contributions are welcome ! You can submit your patches (or post questions 73 | regarding the project) to the swupdate Mailing List: 74 | 75 | swupdate@googlegroups.com 76 | 77 | Please read the [contributing](http://sbabic.github.io/swupdate/contributing.html) 78 | chapter in the documentation how to contribute to the project. 79 | -------------------------------------------------------------------------------- /docs/fw_env_config.md: -------------------------------------------------------------------------------- 1 | 6 | fw_env.config Configuration File- Legacy format 7 | ================================================ 8 | 9 | This is the configuration file for fw_{printenv,setenv} utility. It was defined 10 | in U-Boot project and it is defined here as legacy format. 11 | 12 | Up to two entries are valid, in this case the redundant 13 | environment sector is assumed present. 14 | Notice, that the "Number of Sectors" is not required on NOR and SPI dataflash. 15 | Futhermore, if the Flash Sector Size is omitted, this value is assumed to 16 | be the same as the Environment Size, which is valid for NOR and SPI dataflash. 17 | Device Offset must be prefixed with 0x to be parsed as a hexadecimal value. 18 | 19 | 20 | Structure of the Configuration File 21 | ----------------------------------- 22 | 23 | Entries must be separated by spaces or tabs. 24 | 25 | | Device Name | Device Offset | Environment Size | Flash Sector Size | Number of Sectors | Disable Lock Mechanism | 26 | |------------------|---------------|------------------|-------------------|-------------------|------------------------| 27 | | | | | | | | 28 | 29 | - Device Name: device or file where environment is stored (mandatory) 30 | - Device Offset: offset from start of file or device (mandatory) 31 | - Environment Size: size of environment (in bytes) 32 | - Flash Sector Size: (optional) if not set, it is read from kernel 33 | - Number of Sectors: (optional) number of sectors for environment (mainly used 34 | with raw NAND) 35 | - Disable Lock Mechanism : (optional), 0|1, default=0 (LOCK enabled) 36 | 37 | 38 | NOR Example 39 | ----------- 40 | 41 | | Device Name | Device Offset | Environment Size | Flash Sector Size | Number of Sectors | Disable Lock Mechanism | 42 | |------------------|---------------|------------------|-------------------|-------------------|------------------------| 43 | | /dev/mtd1 | 0x0 | 0x4000 | 0x4000 | | | 44 | | /dev/mtd2 | 0x0 | 0x4000 | 0x4000 | | | 45 | 46 | 47 | MTD SPI Dataflash Example 48 | ------------------------- 49 | 50 | | Device Name | Device Offset | Environment Size | Flash Sector Size | Number of Sectors | Disable Lock Mechanism | 51 | |------------------|---------------|------------------|-------------------|-------------------|------------------------| 52 | | /dev/mtd5 | 0x4200 | 0x4000 | | | | 53 | | /dev/mtd6 | 0x4200 | 0x4000 | | | | 54 | 55 | 56 | NAND Example 57 | ------------ 58 | 59 | | Device Name | Device Offset | Environment Size | Flash Sector Size | Number of Sectors | Disable Lock Mechanism | 60 | |------------------|---------------|------------------|-------------------|-------------------|------------------------| 61 | | /dev/mtd0 | 0x4000 | 0x4000 | 0x20000 | 2 | | 62 | 63 | 64 | Block Device Example 65 | -------------------- 66 | 67 | On a block device a negative offset is treated as a backwards offset from the 68 | end of the device/partition, rather than a forwards offset from the start. 69 | 70 | | Device Name | Device Offset | Environment Size | Flash Sector Size | Number of Sectors | Disable Lock Mechanism | 71 | |------------------|---------------|------------------|-------------------|-------------------|------------------------| 72 | | /dev/mmcblk0 | 0xC0000 | 0x20000 | | | | 73 | | /dev/mmcblk0 | -0x20000 | 0x20000 | | | | 74 | 75 | 76 | VFAT Example 77 | ------------ 78 | 79 | | Device Name | Device Offset | Environment Size | Flash Sector Size | Number of Sectors | Disable Lock Mechanism | 80 | |------------------|---------------|------------------|-------------------|-------------------|------------------------| 81 | | /boot/uboot.env | 0x0 | 0x4000 | | | | 82 | 83 | 84 | UBI Volume Example 85 | ------------------ 86 | 87 | | Device Name | Device Offset | Environment Size | Flash Sector Size | Number of Sectors | Disable Lock Mechanism | 88 | |------------------|---------------|------------------|-------------------|-------------------|------------------------| 89 | | /dev/ubi0_0 | 0x0 | 0x1f000 | 0x1f000 | | | 90 | | /dev/ubi0_1 | 0x0 | 0x1f000 | 0x1f000 | | | 91 | 92 | 93 | UBI Volume by Name Example 94 | -------------------------- 95 | 96 | | Device Name | Device Offset | Environment Size | Flash Sector Size | Number of Sectors | Disable Lock Mechanism | 97 | |------------------|---------------|------------------|-------------------|-------------------|------------------------| 98 | | /dev/ubi0:env | 0x0 | 0x1f000 | 0x1f000 | | | 99 | | /dev/ubi0:redund | 0x0 | 0x1f000 | 0x1f000 | | | 100 | 101 | UBI Volume by Name from MTD Path Example 102 | -------------------------- 103 | 104 | | Device Name | Device Offset | Environment Size | Flash Sector Size | Number of Sectors | Disable Lock Mechanism | 105 | |------------------|---------------|------------------|-------------------|-------------------|------------------------| 106 | | /dev/mtd0:env | 0x0 | 0x1f000 | 0x1f000 | | | 107 | | /dev/mtd0:redund | 0x0 | 0x1f000 | 0x1f000 | | | 108 | 109 | Configuration File in YAML 110 | ========================== 111 | 112 | A YAML format is defined to allow multiple sets of variable. This lets have same 113 | features (redundancy, power-cut safe) for environment that are not bound to the 114 | U-Boot bootloader. 115 | 116 | A set is selected by using the `-m/--namespace` argument. In case the bootloader 117 | tells us where the environment is located by setting the 118 | `/chosen/u-boot,env-config` property in the devicetree, `fw_printenv/fw_setenv` 119 | automatically uses the string from this property as a selector for the namespace 120 | in the YAML config file. 121 | 122 | The sequence `writelist` implements the CONFIG_ENV_WRITEABLE_LIST in U-Boot. The list 123 | is in the same format used in the bootloader: :. See in bootloader documentation 124 | for the list of supported flags. 125 | 126 | ```yaml 127 | uboot: 128 | size : 0x4000 129 | lockfile : /var/lock/fw_printenv.lock 130 | writelist: 131 | - var1:sw 132 | - var2:sw 133 | - var3:dw 134 | devices: 135 | - path : /dev/mtd0 136 | offset : 0xA0000 137 | sectorsize : 0x10000 138 | unlock : yes 139 | - path : /dev/mtd0 140 | offset : 0xB0000 141 | sectorsize : 0x10000 142 | disablelock : yes 143 | 144 | appvar: 145 | size : 0x4000 146 | lockfile : /var/lock/appvar.lock 147 | 148 | devices: 149 | - path : /dev/mtd1 150 | offset : 0 151 | sectorsize : 0x10000 152 | unlock : yes 153 | - path : /dev/mtd1 154 | offset : 0x10000 155 | sectorsize : 0x10000 156 | ``` 157 | -------------------------------------------------------------------------------- /src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2019-2021 Stefano Babic 2 | # 3 | # SPDX-License-Identifier: LGPL-2.1-or-later 4 | cmake_minimum_required (VERSION 2.6) 5 | # Sources and private headers 6 | SET(libubootenv_SOURCES 7 | uboot_env.c 8 | uboot_mtd.c 9 | extended_config.c 10 | common.c 11 | common.h 12 | uboot_private.h 13 | ) 14 | 15 | # Public headers 16 | SET(include_HEADERS 17 | libuboot.h 18 | ) 19 | 20 | include(GNUInstallDirs) # for the CMAKE_INSTALL_LIBDIR variable 21 | 22 | add_library(ubootenv SHARED ${libubootenv_SOURCES} ${include_HEADERS}) 23 | SET_TARGET_PROPERTIES(ubootenv PROPERTIES VERSION ${VERSION} SOVERSION ${SOVERSION}) 24 | 25 | ADD_LIBRARY(ubootenv_static STATIC ${libubootenv_SOURCES} ${include_HEADERS}) 26 | SET_TARGET_PROPERTIES(ubootenv_static PROPERTIES OUTPUT_NAME ubootenv) 27 | add_executable(fw_printenv fw_printenv.c) 28 | target_link_libraries(ubootenv z) 29 | if (NOT NO_YML_SUPPORT) 30 | target_link_libraries(ubootenv yaml) 31 | endif(NOT NO_YML_SUPPORT) 32 | 33 | target_link_libraries(fw_printenv ubootenv) 34 | add_custom_target(fw_setenv ALL ${CMAKE_COMMAND} -E create_symlink fw_printenv fw_setenv) 35 | 36 | install (TARGETS ubootenv ubootenv_static DESTINATION ${CMAKE_INSTALL_LIBDIR}) 37 | install (FILES libuboot.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) 38 | install (TARGETS fw_printenv DESTINATION ${CMAKE_INSTALL_BINDIR}) 39 | install (PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/fw_setenv DESTINATION ${CMAKE_INSTALL_BINDIR}) 40 | 41 | # Handle pkg-config files 42 | set(prefix ${CMAKE_INSTALL_PREFIX}) 43 | set(exec_prefix ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_BINDIR}) 44 | set(includedir ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR}) 45 | set(libdir ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}) 46 | 47 | configure_file(${CMAKE_SOURCE_DIR}/src/libubootenv.pc.in ${CMAKE_BINARY_DIR}/libubootenv.pc @ONLY) 48 | set(LIBUBOOTENV_PKG_CONFIG_FILES ${CMAKE_BINARY_DIR}/libubootenv.pc) 49 | message(STATUS "Generate ${LIBUBOOTENV_PKG_CONFIG_FILES}") 50 | # Install pkg-config files 51 | install(FILES ${LIBUBOOTENV_PKG_CONFIG_FILES} DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) 52 | -------------------------------------------------------------------------------- /src/common.c: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Copyright 2024 3 | * Stefano Babic, 4 | * 5 | * SPDX-License-Identifier: LGPL-2.1-or-later 6 | */ 7 | 8 | #define _GNU_SOURCE 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #ifdef __FreeBSD__ 23 | #include 24 | #define BLKGETSIZE64 DIOCGMEDIASIZE 25 | #else 26 | #include 27 | #endif 28 | 29 | #include "uboot_private.h" 30 | #include "common.h" 31 | 32 | static enum device_type get_device_type(char *device) 33 | { 34 | enum device_type type = DEVICE_NONE; 35 | 36 | if (!strncmp(device, DEVICE_MTD_NAME, strlen(DEVICE_MTD_NAME))) 37 | if (strchr(device, DEVNAME_SEPARATOR)) { 38 | type = DEVICE_UBI; 39 | } else { 40 | type = DEVICE_MTD; 41 | } 42 | else if (!strncmp(device, DEVICE_UBI_NAME, strlen(DEVICE_UBI_NAME))) 43 | type = DEVICE_UBI; 44 | else if (strlen(device) > 0) 45 | type = DEVICE_FILE; 46 | 47 | return type; 48 | } 49 | 50 | int normalize_device_path(char *path, struct uboot_flash_env *dev) 51 | { 52 | char *sep = NULL, *normalized = NULL; 53 | size_t normalized_len = 0, volume_len = 0, output_len = 0; 54 | 55 | /* 56 | * if volume name is present, split into device path and volume 57 | * since only the device path needs normalized 58 | */ 59 | sep = strchr(path, DEVNAME_SEPARATOR); 60 | if (sep) 61 | { 62 | volume_len = strlen(sep); 63 | *sep = '\0'; 64 | } 65 | 66 | if ((normalized = realpath(path, NULL)) == NULL) 67 | { 68 | /* device file didn't exist */ 69 | return -EINVAL; 70 | } 71 | 72 | normalized_len = strlen(normalized); 73 | output_len = sizeof(dev->devname) - 1; /* leave room for null */ 74 | if ((normalized_len + volume_len) > output_len) 75 | { 76 | /* full name is too long to fit */ 77 | free(normalized); 78 | return -EINVAL; 79 | } 80 | 81 | /* 82 | * save normalized path to device file, 83 | * and possibly append separator char & volume name 84 | */ 85 | memset(dev->devname, 0, sizeof(dev->devname)); 86 | strncpy(dev->devname, normalized, output_len); 87 | free(normalized); 88 | 89 | if (sep) 90 | { 91 | *sep = DEVNAME_SEPARATOR; 92 | strncpy(dev->devname + normalized_len, sep, output_len - normalized_len); 93 | } 94 | 95 | return 0; 96 | } 97 | 98 | void set_var_access_type(struct var_entry *entry, const char *pvarflags) 99 | { 100 | if (entry) { 101 | for (int i = 0; i < strlen(pvarflags); i++) { 102 | switch (pvarflags[i]) { 103 | case 's': 104 | entry->type = TYPE_ATTR_STRING; 105 | break; 106 | case 'd': 107 | entry->type = TYPE_ATTR_DECIMAL; 108 | break; 109 | case 'x': 110 | entry->type = TYPE_ATTR_HEX; 111 | break; 112 | case 'b': 113 | entry->type = TYPE_ATTR_BOOL; 114 | break; 115 | case 'i': 116 | entry->type = TYPE_ATTR_IP; 117 | break; 118 | case 'm': 119 | entry->type = TYPE_ATTR_MAC; 120 | break; 121 | case 'a': 122 | entry->access = ACCESS_ATTR_ANY; 123 | break; 124 | case 'r': 125 | entry->access = ACCESS_ATTR_READ_ONLY; 126 | break; 127 | case 'o': 128 | entry->access = ACCESS_ATTR_WRITE_ONCE; 129 | break; 130 | case 'c': 131 | entry->access = ACCESS_ATTR_CHANGE_DEFAULT; 132 | break; 133 | default: /* ignore it */ 134 | break; 135 | } 136 | } 137 | } 138 | } 139 | 140 | struct var_entry *create_var_entry(const char *name) 141 | { 142 | struct var_entry *entry; 143 | 144 | entry = (struct var_entry *)calloc(1, sizeof(*entry)); 145 | if (!entry) 146 | return NULL; 147 | entry->name = strdup(name); 148 | if (!entry->name) { 149 | free(entry); 150 | return NULL; 151 | } 152 | 153 | return entry; 154 | } 155 | 156 | bool check_compatible_devices(struct uboot_ctx *ctx) 157 | { 158 | if (!ctx->redundant) 159 | return true; 160 | 161 | if (ctx->envdevs[0].mtdinfo.type != ctx->envdevs[1].mtdinfo.type) 162 | return false; 163 | if (ctx->envdevs[0].flagstype != ctx->envdevs[1].flagstype) 164 | return false; 165 | if (ctx->envdevs[0].envsize != ctx->envdevs[1].envsize) 166 | return false; 167 | 168 | return true; 169 | } 170 | 171 | int check_env_device(struct uboot_flash_env *dev) 172 | { 173 | int fd, ret; 174 | struct stat st; 175 | 176 | dev->device_type = get_device_type(dev->devname); 177 | if (dev->device_type == DEVICE_NONE) 178 | return -EBADF; 179 | 180 | if (dev->device_type == DEVICE_UBI) { 181 | ret = libubootenv_ubi_update_name(dev); 182 | if (ret) 183 | return ret; 184 | } 185 | 186 | ret = stat(dev->devname, &st); 187 | if (ret < 0) 188 | return -EBADF; 189 | fd = open(dev->devname, O_RDONLY); 190 | if (fd < 0) 191 | return -EBADF; 192 | 193 | if (S_ISCHR(st.st_mode)) { 194 | if (dev->device_type == DEVICE_MTD) { 195 | ret = libubootenv_mtdgetinfo(fd, dev); 196 | if (ret < 0 || (dev->mtdinfo.type != MTD_NORFLASH && 197 | dev->mtdinfo.type != MTD_NANDFLASH)) { 198 | close(fd); 199 | return -EBADF; 200 | } 201 | if (dev->sectorsize == 0) { 202 | dev->sectorsize = dev->mtdinfo.erasesize; 203 | } 204 | } 205 | } 206 | 207 | switch (dev->device_type) { 208 | case DEVICE_FILE: 209 | dev->flagstype = FLAGS_INCREMENTAL; 210 | break; 211 | case DEVICE_MTD: 212 | switch (dev->mtdinfo.type) { 213 | case MTD_NORFLASH: 214 | dev->flagstype = FLAGS_BOOLEAN; 215 | break; 216 | case MTD_NANDFLASH: 217 | dev->flagstype = FLAGS_INCREMENTAL; 218 | }; 219 | break; 220 | case DEVICE_UBI: 221 | dev->flagstype = FLAGS_INCREMENTAL; 222 | break; 223 | default: 224 | close(fd); 225 | return -EBADF; 226 | }; 227 | 228 | /* 229 | * Check for negative offsets, treat it as backwards offset 230 | * from the end of the block device 231 | */ 232 | if (dev->offset < 0) { 233 | uint64_t blkdevsize; 234 | int rc; 235 | 236 | rc = ioctl(fd, BLKGETSIZE64, &blkdevsize); 237 | if (rc < 0) { 238 | close(fd); 239 | return -EINVAL; 240 | } 241 | 242 | dev->offset += blkdevsize; 243 | } 244 | 245 | close(fd); 246 | 247 | return 0; 248 | } 249 | -------------------------------------------------------------------------------- /src/common.h: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Copyright 2024 3 | * Stefano Babic, 4 | * 5 | * SPDX-License-Identifier: LGPL-2.1-or-later 6 | */ 7 | 8 | 9 | #include "uboot_private.h" 10 | 11 | struct var_entry *create_var_entry(const char *name); 12 | void set_var_access_type(struct var_entry *entry, const char *pvarflags); 13 | int normalize_device_path(char *path, struct uboot_flash_env *dev); 14 | int check_env_device(struct uboot_flash_env *dev); 15 | bool check_compatible_devices(struct uboot_ctx *ctx); 16 | -------------------------------------------------------------------------------- /src/extended_config.c: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Copyright 2024 3 | * Stefano Babic, 4 | * 5 | * SPDX-License-Identifier: LGPL-2.1-or-later 6 | */ 7 | 8 | /** 9 | * @file extended_config.c 10 | * 11 | * @brief Implement the extended config file YAML 12 | * 13 | */ 14 | #define _GNU_SOURCE 15 | 16 | #if !defined(NO_YAML_SUPPORT) 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #include "uboot_private.h" 26 | #include "common.h" 27 | 28 | /* yaml_* functions return 1 on success and 0 on failure. */ 29 | enum yaml_status { 30 | SUCCESS = 0, 31 | FAILURE = 1 32 | }; 33 | 34 | enum yaml_state { 35 | STATE_START, /* start state */ 36 | STATE_STREAM, /* start/end stream */ 37 | STATE_DOCUMENT, /* start/end document */ 38 | STATE_SECTION, /* top level */ 39 | 40 | STATE_NAMESPACE, /* Init Configuration Namespace */ 41 | STATE_NAMESPACE_FIELDS, /* namespace key list */ 42 | STATE_NKEY, /* Check key names */ 43 | STATE_NSIZE, /* Size key-value pair */ 44 | STATE_NLOCKFILE, /* Lockfile key-value pair */ 45 | STATE_DEVVALUES, /* Devices key names */ 46 | STATE_WRITELIST, /* List with vars that are accepted by write 47 | * if list is missing, all vars are accepted 48 | * var is in the format name:flags, see U-Boot 49 | * documentation 50 | */ 51 | 52 | STATE_NPATH, 53 | STATE_NOFFSET, 54 | STATE_NSECTORSIZE, 55 | STATE_NUNLOCK, 56 | STATE_STOP /* end state */ 57 | }; 58 | 59 | typedef enum yaml_parse_error_e { 60 | YAML_UNEXPECTED_STATE, 61 | YAML_UNEXPECTED_KEY, 62 | YAML_BAD_DEVICE, 63 | YAML_BAD_DEVNAME, 64 | YAML_BAD_VARLIST, 65 | YAML_DUPLICATE_VARLIST, 66 | YAML_OOM, 67 | } yaml_parse_error_type_t; 68 | 69 | struct parser_state { 70 | enum yaml_state state; /* The current parse state */ 71 | struct uboot_ctx *ctxsets; /* Array of vars set ctx */ 72 | struct uboot_ctx *ctx; /* Current ctx in parsing */ 73 | unsigned int nelem; /* Number of elemets in ctxsets */ 74 | unsigned int cdev; /* current device in parsing */ 75 | yaml_parse_error_type_t error; /* error causing parser to stop */ 76 | yaml_event_type_t event_type; /* event type causing error */ 77 | }; 78 | 79 | static int consume_event(struct parser_state *s, yaml_event_t *event) 80 | { 81 | char *value; 82 | struct uboot_flash_env *dev; 83 | struct uboot_ctx *newctx; 84 | int cdev; 85 | 86 | switch (s->state) { 87 | case STATE_START: 88 | switch (event->type) { 89 | case YAML_STREAM_START_EVENT: 90 | s->state = STATE_STREAM; 91 | break; 92 | default: 93 | s->error = YAML_UNEXPECTED_STATE; 94 | s->event_type = event->type; 95 | return FAILURE; 96 | } 97 | break; 98 | 99 | case STATE_STREAM: 100 | switch (event->type) { 101 | case YAML_DOCUMENT_START_EVENT: 102 | s->state = STATE_DOCUMENT; 103 | break; 104 | case YAML_STREAM_END_EVENT: 105 | s->state = STATE_STOP; 106 | break; 107 | default: 108 | s->error = YAML_UNEXPECTED_STATE; 109 | s->event_type = event->type; 110 | return FAILURE; 111 | } 112 | break; 113 | 114 | case STATE_DOCUMENT: 115 | switch (event->type) { 116 | case YAML_MAPPING_START_EVENT: 117 | s->state = STATE_SECTION; 118 | break; 119 | case YAML_DOCUMENT_END_EVENT: 120 | s->state = STATE_STREAM; 121 | break; 122 | default: 123 | s->error = YAML_UNEXPECTED_STATE; 124 | s->event_type = event->type; 125 | return FAILURE; 126 | } 127 | break; 128 | 129 | case STATE_SECTION: 130 | switch (event->type) { 131 | case YAML_SCALAR_EVENT: 132 | value = (char *)event->data.scalar.value; 133 | newctx = calloc (s->nelem + 1, sizeof(*newctx)); 134 | for (int i = 0; i < s->nelem; i++) { 135 | newctx[i] = s->ctxsets[i]; 136 | } 137 | if (s->ctxsets) free(s->ctxsets); 138 | s->ctxsets = newctx; 139 | s->ctx = &newctx[s->nelem]; 140 | s->ctx->name = strdup(value); 141 | s->nelem++; 142 | s->state = STATE_NAMESPACE; 143 | break; 144 | case YAML_MAPPING_END_EVENT: 145 | s->state = STATE_DOCUMENT; 146 | break; 147 | case YAML_DOCUMENT_END_EVENT: 148 | s->state = STATE_STREAM; 149 | break; 150 | default: 151 | s->error = YAML_UNEXPECTED_STATE; 152 | s->event_type = event->type; 153 | return FAILURE; 154 | } 155 | break; 156 | 157 | case STATE_NAMESPACE: 158 | switch (event->type) { 159 | case YAML_MAPPING_START_EVENT: 160 | s->state = STATE_NAMESPACE_FIELDS; 161 | break; 162 | default: 163 | s->error = YAML_UNEXPECTED_STATE; 164 | s->event_type = event->type; 165 | return FAILURE; 166 | } 167 | break; 168 | 169 | case STATE_NAMESPACE_FIELDS: 170 | switch (event->type) { 171 | case YAML_SCALAR_EVENT: 172 | value = (char *)event->data.scalar.value; 173 | if (!strcmp(value, "size")) { 174 | s->state = STATE_NSIZE; 175 | } else if (!strcmp(value, "lockfile")) { 176 | s->state = STATE_NLOCKFILE; 177 | } else if (!strcmp(value, "devices")) { 178 | s->state = STATE_DEVVALUES; 179 | s->cdev = 0; 180 | } else if (!strcmp(value, "writelist")) { 181 | s->state = STATE_WRITELIST; 182 | } else { 183 | s->error = YAML_UNEXPECTED_KEY; 184 | s->event_type = event->type; 185 | return FAILURE; 186 | } 187 | break; 188 | case YAML_MAPPING_END_EVENT: 189 | s->state = STATE_SECTION; 190 | break; 191 | default: 192 | s->error = YAML_UNEXPECTED_STATE; 193 | s->event_type = event->type; 194 | return FAILURE; 195 | } 196 | break; 197 | 198 | case STATE_NSIZE: 199 | switch (event->type) { 200 | case YAML_SCALAR_EVENT: 201 | value = (char *)event->data.scalar.value; 202 | errno = 0; 203 | s->ctx->size = strtoull(value, NULL, 0); 204 | s->state = STATE_NAMESPACE_FIELDS; 205 | break; 206 | default: 207 | s->error = YAML_UNEXPECTED_STATE; 208 | s->event_type = event->type; 209 | return FAILURE; 210 | } 211 | break; 212 | 213 | case STATE_NLOCKFILE: 214 | switch (event->type) { 215 | case YAML_SCALAR_EVENT: 216 | value = (char *)event->data.scalar.value; 217 | s->ctx->lockfile = strdup(value); 218 | s->state = STATE_NAMESPACE_FIELDS; 219 | break; 220 | default: 221 | s->error = YAML_UNEXPECTED_STATE; 222 | s->event_type = event->type; 223 | return FAILURE; 224 | } 225 | break; 226 | 227 | case STATE_DEVVALUES: 228 | switch (event->type) { 229 | case YAML_MAPPING_START_EVENT: 230 | case YAML_SEQUENCE_START_EVENT: 231 | break; 232 | case YAML_MAPPING_END_EVENT: 233 | dev = &s->ctx->envdevs[s->cdev]; 234 | if (check_env_device(dev) < 0) { 235 | s->error = YAML_BAD_DEVICE; 236 | s->event_type = event->type; 237 | return FAILURE; 238 | } 239 | s->cdev++; 240 | break; 241 | case YAML_SEQUENCE_END_EVENT: 242 | s->state = STATE_NAMESPACE_FIELDS; 243 | break; 244 | case YAML_SCALAR_EVENT: 245 | value = (char *)event->data.scalar.value; 246 | if (s->cdev) 247 | s->ctx->redundant = true; 248 | if (!strcmp(value, "path")) { 249 | s->state = STATE_NPATH; 250 | } else if (!strcmp(value, "offset")) { 251 | s->state = STATE_NOFFSET; 252 | } else if (!strcmp(value, "sectorsize")) { 253 | s->state = STATE_NSECTORSIZE; 254 | } else if (!strcmp(value, "disablelock")) { 255 | s->state = STATE_NUNLOCK; 256 | } else { 257 | s->error = YAML_UNEXPECTED_KEY; 258 | s->event_type = event->type; 259 | return FAILURE; 260 | } 261 | break; 262 | default: 263 | s->error = YAML_UNEXPECTED_STATE; 264 | s->event_type = event->type; 265 | return FAILURE; 266 | } 267 | break; 268 | 269 | case STATE_WRITELIST: 270 | switch (event->type) { 271 | 272 | char *varflag, *name; 273 | struct var_entry *entry; 274 | 275 | case YAML_MAPPING_START_EVENT: 276 | case YAML_SEQUENCE_START_EVENT: 277 | break; 278 | case YAML_MAPPING_END_EVENT: 279 | break; 280 | case YAML_SEQUENCE_END_EVENT: 281 | s->state = STATE_NAMESPACE_FIELDS; 282 | break; 283 | case YAML_SCALAR_EVENT: 284 | value = (char *)event->data.scalar.value; 285 | 286 | /* 287 | * Format is name:flags, split it into two values 288 | */ 289 | varflag = strchr(value, ':'); 290 | if (!varflag || varflag > value + (strlen(value) - 1)) { 291 | s->error = YAML_BAD_VARLIST; 292 | s->event_type = event->type; 293 | return FAILURE; 294 | } 295 | *varflag++ = '\0'; 296 | 297 | /* 298 | * Check there is not yet an entry for this variable 299 | */ 300 | LIST_FOREACH(entry, &s->ctx->writevarlist, next) { 301 | if (strcmp(entry->name, value) == 0) { 302 | s->error = YAML_DUPLICATE_VARLIST; 303 | s->event_type = event->type; 304 | return FAILURE; 305 | } 306 | } 307 | 308 | /* 309 | * Insert variable with its configuration into the list 310 | * of modifiable vars 311 | */ 312 | entry = create_var_entry(value); 313 | if (!entry) { 314 | s->error = YAML_OOM; 315 | s->event_type = event->type; 316 | return FAILURE; 317 | } 318 | set_var_access_type(entry, varflag); 319 | LIST_INSERT_HEAD(&s->ctx->writevarlist, entry, next); 320 | 321 | #if !defined(NDEBUG) 322 | fprintf(stdout, "Writelist: %s flags %s\n", value, varflag); 323 | #endif 324 | break; 325 | default: 326 | s->error = YAML_UNEXPECTED_STATE; 327 | s->event_type = event->type; 328 | return FAILURE; 329 | } 330 | break; 331 | 332 | case STATE_NPATH: 333 | switch (event->type) { 334 | case YAML_SCALAR_EVENT: 335 | dev = &s->ctx->envdevs[s->cdev]; 336 | value = (char *)event->data.scalar.value; 337 | if (normalize_device_path(value, dev) < 0) { 338 | s->error = YAML_BAD_DEVNAME; 339 | s->event_type = event->type; 340 | return FAILURE; 341 | } 342 | dev->envsize = s->ctx->size; 343 | s->state = STATE_DEVVALUES; 344 | break; 345 | default: 346 | s->error = YAML_UNEXPECTED_STATE; 347 | s->event_type = event->type; 348 | return FAILURE; 349 | } 350 | break; 351 | 352 | case STATE_NOFFSET: 353 | switch (event->type) { 354 | case YAML_SCALAR_EVENT: 355 | dev = &s->ctx->envdevs[s->cdev]; 356 | value = (char *)event->data.scalar.value; 357 | dev->offset = strtoull(value, NULL, 0); 358 | s->state = STATE_DEVVALUES; 359 | break; 360 | default: 361 | s->error = YAML_UNEXPECTED_STATE; 362 | s->event_type = event->type; 363 | return FAILURE; 364 | } 365 | break; 366 | 367 | case STATE_NSECTORSIZE: 368 | switch (event->type) { 369 | case YAML_SCALAR_EVENT: 370 | dev = &s->ctx->envdevs[s->cdev]; 371 | value = (char *)event->data.scalar.value; 372 | dev->sectorsize = strtoull(value, NULL, 0); 373 | s->state = STATE_DEVVALUES; 374 | break; 375 | default: 376 | s->error = YAML_UNEXPECTED_STATE; 377 | s->event_type = event->type; 378 | return FAILURE; 379 | } 380 | break; 381 | 382 | case STATE_NUNLOCK: 383 | switch (event->type) { 384 | case YAML_SCALAR_EVENT: 385 | dev = &s->ctx->envdevs[s->cdev]; 386 | value = (char *)event->data.scalar.value; 387 | if (!strcmp(value, "yes")) 388 | dev->disable_mtd_lock = 1; 389 | s->state = STATE_DEVVALUES; 390 | break; 391 | default: 392 | s->error = YAML_UNEXPECTED_STATE; 393 | s->event_type = event->type; 394 | return FAILURE; 395 | } 396 | break; 397 | 398 | case STATE_STOP: 399 | break; 400 | } 401 | return SUCCESS; 402 | } 403 | 404 | int parse_yaml_config(struct uboot_ctx **ctxlist, FILE *fp) 405 | { 406 | yaml_parser_t parser; 407 | yaml_event_t event; 408 | enum yaml_status status; 409 | struct parser_state state; 410 | struct uboot_ctx *ctx; 411 | 412 | if (!yaml_parser_initialize(&parser)) 413 | return -ENOMEM; 414 | 415 | /* Set input file */ 416 | yaml_parser_set_input_file(&parser, fp); 417 | memset(&state, 0, sizeof(state)); 418 | state.state = STATE_START; 419 | do { 420 | if (!yaml_parser_parse(&parser, &event)) { 421 | status = FAILURE; 422 | goto cleanup; 423 | } 424 | status = consume_event(&state, &event); 425 | yaml_event_delete(&event); 426 | if (status == FAILURE) { 427 | goto cleanup; 428 | } 429 | } while (state.state != STATE_STOP); 430 | 431 | if (state.nelem == 0) { 432 | status = FAILURE; 433 | goto cleanup; 434 | } 435 | 436 | state.ctxsets[0].nelem = state.nelem; 437 | 438 | for (int i = 0; i < state.nelem; i++) { 439 | ctx = &state.ctxsets[i]; 440 | ctx->ctxlist = &state.ctxsets[0]; 441 | if (ctx->redundant && !check_compatible_devices(ctx)) { 442 | status = FAILURE; 443 | break; 444 | } 445 | } 446 | 447 | 448 | cleanup: 449 | yaml_parser_delete(&parser); 450 | if (status == FAILURE) { 451 | if (state.ctxsets) free (state.ctxsets); 452 | state.ctxsets = NULL; 453 | } 454 | *ctxlist = state.ctxsets; 455 | return status; 456 | } 457 | #endif 458 | -------------------------------------------------------------------------------- /src/fw_printenv.c: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Copyright 2019 3 | * Stefano Babic, 4 | * 5 | * SPDX-License-Identifier: LGPL-2.1-or-later 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | #include "libuboot.h" 18 | 19 | #ifndef DEFAULT_CFG_FILE 20 | #define DEFAULT_CFG_FILE "/etc/fw_env.config" 21 | #endif 22 | 23 | #ifndef DEFAULT_ENV_FILE 24 | #define DEFAULT_ENV_FILE "/etc/u-boot-initial-env" 25 | #endif 26 | 27 | #define PROGRAM_SET "fw_setenv" 28 | 29 | static struct option long_options[] = { 30 | {"version", no_argument, NULL, 'V'}, 31 | {"no-header", no_argument, NULL, 'n'}, 32 | {"help", no_argument, NULL, 'h'}, 33 | {"config", required_argument, NULL, 'c'}, 34 | {"defenv", required_argument, NULL, 'f'}, 35 | {"script", required_argument, NULL, 's'}, 36 | {"namespace", required_argument, NULL, 'm'}, 37 | {NULL, 0, NULL, 0} 38 | }; 39 | 40 | static void usage(char *program, bool setprogram) 41 | { 42 | fprintf(stdout, "%s (compiled %s)\n", program, __DATE__); 43 | fprintf(stdout, "Usage %s [OPTION]\n", 44 | program); 45 | fprintf(stdout, 46 | " -h, --help : print this help\n" 47 | " -c, --config : configuration file (by default: " DEFAULT_CFG_FILE ")\n" 48 | " -f, --defenv : default environment if no one found (by default: " DEFAULT_ENV_FILE ")\n" 49 | " -m, --namespace : chose one of sets in the YAML file, default first in YAML\n" 50 | " -V, --version : print version and exit\n" 51 | ); 52 | if (!setprogram) 53 | fprintf(stdout, 54 | " -n, --no-header : do not print variable name\n" 55 | ); 56 | else 57 | fprintf(stdout, 58 | " -s, --script : read variables to be set from a script\n" 59 | "\n" 60 | "Script Syntax:\n" 61 | " key=value\n" 62 | " lines starting with '#' are treated as comment\n" 63 | " lines without '=' are ignored\n" 64 | "\n" 65 | "Script Example:\n" 66 | " netdev=eth0\n" 67 | " kernel_addr=400000\n" 68 | " foo=empty empty empty empty empty empty\n" 69 | " bar\n" 70 | "\n" 71 | ); 72 | } 73 | 74 | int main (int argc, char **argv) { 75 | struct uboot_ctx *ctx = NULL; 76 | char *options = "Vc:f:s:nhm:"; 77 | char *cfgfname = NULL; 78 | char *defenvfile = NULL; 79 | char *scriptfile = NULL; 80 | const char *namespace = NULL; 81 | int c, i; 82 | int ret = 0; 83 | void *tmp; 84 | const char *name, *value; 85 | char *progname; 86 | bool is_setenv = false; 87 | bool noheader = false; 88 | bool default_used = false; 89 | struct uboot_version_info *version; 90 | 91 | /* 92 | * As old tool, there is just a tool with symbolic link 93 | */ 94 | 95 | 96 | progname = strrchr(argv[0], '/'); 97 | if (!progname) 98 | progname = argv[0]; 99 | else 100 | progname++; 101 | 102 | if (!strcmp(progname, PROGRAM_SET)) 103 | is_setenv = true; 104 | 105 | while ((c = getopt_long(argc, argv, options, 106 | long_options, NULL)) != EOF) { 107 | switch (c) { 108 | case 'c': 109 | cfgfname = strdup(optarg); 110 | break; 111 | case 'n': 112 | noheader = true; 113 | break; 114 | case 'V': 115 | fprintf(stdout, "%s %u\n", libuboot_version_info()->version, libuboot_version_info()->version_num); 116 | exit(0); 117 | case 'h': 118 | usage(progname, is_setenv); 119 | exit(0); 120 | case 'f': 121 | defenvfile = strdup(optarg); 122 | break; 123 | case 'm': 124 | namespace = strdup(optarg); 125 | break; 126 | case 's': 127 | scriptfile = strdup(optarg); 128 | break; 129 | } 130 | } 131 | 132 | argc -= optind; 133 | argv += optind; 134 | 135 | 136 | if (!cfgfname) 137 | cfgfname = DEFAULT_CFG_FILE; 138 | 139 | /* 140 | * Try first new format, fallback to legacy 141 | */ 142 | ret = libuboot_read_config_ext(&ctx, cfgfname); 143 | if (ret) { 144 | fprintf(stderr, "Cannot initialize environment\n"); 145 | exit(1); 146 | } 147 | 148 | if (!namespace) 149 | namespace = libuboot_namespace_from_dt(); 150 | 151 | if (namespace) 152 | ctx = libuboot_get_namespace(ctx, namespace); 153 | 154 | if (!ctx) { 155 | fprintf(stderr, "Namespace %s not found\n", namespace); 156 | exit (1); 157 | } 158 | 159 | if (!defenvfile) 160 | defenvfile = DEFAULT_ENV_FILE; 161 | 162 | if ((ret = libuboot_open(ctx)) < 0) { 163 | fprintf(stderr, "Cannot read environment, using default\n"); 164 | if ((ret = libuboot_load_file(ctx, defenvfile)) < 0) { 165 | fprintf(stderr, "Cannot read default environment from file\n"); 166 | exit (ret); 167 | } 168 | default_used = true; 169 | } 170 | 171 | if (!is_setenv) { 172 | /* No variable given, print all environment */ 173 | if (!argc) { 174 | tmp = NULL; 175 | while ((tmp = libuboot_iterator(ctx, tmp)) != NULL) { 176 | name = libuboot_getname(tmp); 177 | value = libuboot_getvalue(tmp); 178 | fprintf(stdout, "%s=%s\n", name, value); 179 | } 180 | } else { 181 | for (i = 0; i < argc; i++) { 182 | value = libuboot_get_env(ctx, argv[i]); 183 | if (noheader) 184 | fprintf(stdout, "%s\n", value ? value : ""); 185 | else 186 | fprintf(stdout, "%s=%s\n", argv[i], value ? value : ""); 187 | } 188 | } 189 | } else { /* setenv branch */ 190 | bool need_store = false; 191 | if (scriptfile) { 192 | libuboot_load_file(ctx, scriptfile); 193 | need_store = true; 194 | } else { 195 | for (i = 0; i < argc; i += 2) { 196 | value = libuboot_get_env(ctx, argv[i]); 197 | if (i + 1 == argc) { 198 | if (value != NULL) { 199 | int ret; 200 | 201 | ret = libuboot_set_env(ctx, argv[i], NULL); 202 | if (ret) { 203 | fprintf(stderr, "libuboot_set_env failed: %d\n", ret); 204 | exit(-ret); 205 | } 206 | 207 | need_store = true; 208 | } 209 | } else { 210 | if (value == NULL || strcmp(value, argv[i+1]) != 0) { 211 | int ret; 212 | 213 | ret = libuboot_set_env(ctx, argv[i], argv[i+1]); 214 | if (ret) { 215 | fprintf(stderr, "libuboot_set_env failed: %d\n", ret); 216 | exit(-ret); 217 | } 218 | 219 | need_store = true; 220 | } 221 | } 222 | } 223 | } 224 | 225 | if (need_store || default_used) { 226 | ret = libuboot_env_store(ctx); 227 | if (ret) 228 | fprintf(stderr, "Error storing the env\n"); 229 | } 230 | } 231 | 232 | libuboot_close(ctx); 233 | libuboot_exit(ctx); 234 | 235 | return ret; 236 | } 237 | -------------------------------------------------------------------------------- /src/libuboot.h: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Copyright 2019 3 | * Stefano Babic, 4 | * 5 | * SPDX-License-Identifier: LGPL-2.1-or-later 6 | */ 7 | 8 | #ifdef __cplusplus 9 | #include 10 | 11 | extern "C" { 12 | #endif 13 | 14 | #pragma once 15 | 16 | struct uboot_ctx; 17 | 18 | #define DEVNAME_MAX_LENGTH 256 19 | 20 | #define DEVNAME_SEPARATOR ':' 21 | 22 | /** Configuration passed in initialization 23 | * 24 | */ 25 | struct uboot_env_device { 26 | /** path to device or file where env is stored */ 27 | char *devname; 28 | /** Start offset inside device path */ 29 | long long int offset; 30 | /** size of environment */ 31 | size_t envsize; 32 | /** Size of sector (for MTD) */ 33 | size_t sectorsize; 34 | /** Number of sectors for each environment */ 35 | unsigned long envsectors; 36 | }; 37 | 38 | /** Static structure to return version ionformation 39 | * 40 | */ 41 | struct uboot_version_info { 42 | /** human readable string */ 43 | const char *version; 44 | /** <8 bits major number> | <8 bits minor number> | <8 bits patch number> */ 45 | unsigned int version_num; 46 | }; 47 | 48 | /** @brief Return information about library version 49 | * 50 | * @return Pointer to static uboot_version_info 51 | */ 52 | const struct uboot_version_info *libuboot_version_info(void); 53 | 54 | /** @brief Read U-Boot environment configuration from a file 55 | * 56 | * @param[in] ctx libuboot context 57 | * @param[in] config path to the configuration file 58 | * @return 0 in case of success, else negative value 59 | */ 60 | int libuboot_read_config(struct uboot_ctx *ctx, const char *config); 61 | 62 | /** @brief Read U-Boot environment configuration from a file - new API 63 | * 64 | * @param[in] pointer to array of ctx libuboot context 65 | * @param[in] config path to the configuration file 66 | * @return 0 in case of success, else negative value 67 | */ 68 | int libuboot_read_config_ext(struct uboot_ctx **ctx, const char *config); 69 | 70 | /** @brief Get ctx from namespace 71 | * 72 | * @param[in] ctxlist libuboot context array 73 | * @param[in] name name identifier for the single ctx 74 | * @return 0 in case of success, else negative value 75 | */ 76 | struct uboot_ctx *libuboot_get_namespace(struct uboot_ctx *ctxlist, const char *name); 77 | 78 | /** @brief Look for bootloader namespace from DT 79 | * 80 | * @param[in] ctxlist libuboot context array 81 | * @param[in] name name identifier for the single ctx 82 | * @return 0 in case of success, else negative value 83 | */ 84 | const char *libuboot_namespace_from_dt(void); 85 | 86 | /** @brief Read U-Boot environment configuration from structure 87 | * 88 | * @param[in] ctx libuboot context 89 | * @param[in] envdevs array of two uboot_env_device 90 | * @return 0 in case of success, else negative value 91 | */ 92 | int libuboot_configure(struct uboot_ctx *ctx, 93 | struct uboot_env_device *envdevs); 94 | 95 | /** @brief Import environment from file 96 | * 97 | * Read and parses variable(s) from a file in the same way as 98 | * U-Boot does with "env import -t" 99 | * The file has the format: 100 | * < variable name >=< value > 101 | * Comments starting with "#" are allowed. 102 | * 103 | * @param[in] ctx libuboot context 104 | * @param[in] filename path to the file to be imported 105 | * @return 0 in case of success, else negative value 106 | */ 107 | int libuboot_load_file(struct uboot_ctx *ctx, const char *filename); 108 | 109 | /** @brief Flush environment to the storage 110 | * 111 | * Write the environment back to the storage and handle 112 | * redundant devices. 113 | * 114 | * @param[in] ctx libuboot context 115 | * @return 0 in case of success, else negative value 116 | */ 117 | int libuboot_env_store(struct uboot_ctx *ctx); 118 | 119 | /** @brief Initialize the library 120 | * 121 | * Initialize the library and get the context structure 122 | * 123 | * @param[out] out struct uboot_ctx allocated structure 124 | * @param[in] envdevs environment storage definitions, maybe NULL 125 | * in case this is loaded from configuration file later 126 | * @return 0 in case of success, else negative value 127 | */ 128 | int libuboot_initialize(struct uboot_ctx **out, 129 | struct uboot_env_device *envdevs); 130 | 131 | /** @brief Release all resources and exit the library 132 | * 133 | * @param[in] ctx libuboot context 134 | */ 135 | void libuboot_exit(struct uboot_ctx *ctx); 136 | 137 | /** @brief Load an environment 138 | * 139 | * @param[in] ctx libuboot context 140 | * @return 0 in case of success, else negative value 141 | */ 142 | int libuboot_open(struct uboot_ctx *ctx); 143 | 144 | /** @brief Release an environment 145 | * 146 | * Release allocated resources for the environment, but 147 | * maintain the context. This allows to call 148 | * libuboot_open() again. 149 | * 150 | * @param[in] ctx libuboot context 151 | */ 152 | void libuboot_close(struct uboot_ctx *ctx); 153 | 154 | /** @brief Set a variable 155 | * 156 | * It creates a new variable if not present in 157 | * the database, changes it or drops if value is NULL. 158 | * 159 | * @param[in] ctx libuboot context 160 | * @param[in] varname name of variable to set/change/delete 161 | * @param[in] value new value of variable; in case this is NULL, the variable is dropped 162 | * @return 0 in case of success, else negative value 163 | */ 164 | int libuboot_set_env(struct uboot_ctx *ctx, const char *varname, const char *value); 165 | 166 | /** @brief Get a variable 167 | * 168 | * Return value of a variable as string or NULL if 169 | * variable is not present in the database. 170 | * The returned string must be freed by the caller when not 171 | * used anymore. 172 | * 173 | * @param[in] ctx libuboot context 174 | * @param[in] varname variable name 175 | * @return value in case of success, NULL in case of error 176 | */ 177 | char *libuboot_get_env(struct uboot_ctx *ctx, const char *varname); 178 | 179 | /** @brief Iterator 180 | * 181 | * Return a pointer to an entry in the database 182 | * Used to iterate all variables in the database. 183 | * 184 | * @param[in] ctx libuboot context 185 | * @param[in] next 186 | * @return pointer to next entry or NULL 187 | */ 188 | void *libuboot_iterator(struct uboot_ctx *ctx, void *next); 189 | 190 | /** @brief Accessor to get variable name from DB entry 191 | * 192 | * @param[in] entry element in the database 193 | * @return pointer to name or NULL 194 | */ 195 | const char *libuboot_getname(void *entry); 196 | 197 | /** @brief Accessor to get variable value from DB entry 198 | * 199 | * @param[in] entry element in the database 200 | * @return pointer to name or NULL 201 | */ 202 | const char *libuboot_getvalue(void *entry); 203 | 204 | #ifdef __cplusplus 205 | } 206 | #endif 207 | -------------------------------------------------------------------------------- /src/libubootenv.pc.in: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2019-2021 Stefano Babic 2 | # 3 | # SPDX-License-Identifier: LGPL-2.1-or-later 4 | 5 | prefix=@prefix@ 6 | exec_prefix=@exec_prefix@ 7 | libdir=@libdir@ 8 | includedir=@includedir@ 9 | 10 | Name: libubootenv 11 | Description: Library to access U-Boot environment 12 | Version: @VERSION@ 13 | Libs: -L${libdir} -lubootenv -lz 14 | Cflags: -I${includedir} 15 | -------------------------------------------------------------------------------- /src/uboot_env.c: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Copyright 2019 3 | * Stefano Babic, 4 | * 5 | * SPDX-License-Identifier: LGPL-2.1-or-later 6 | */ 7 | 8 | /** 9 | * @file uboot_env.c 10 | * 11 | * @brief This is the implementation of libubootenv library 12 | * 13 | */ 14 | 15 | #define _GNU_SOURCE 16 | 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | 36 | #include "uboot_private.h" 37 | #include "common.h" 38 | 39 | #if defined(NO_YAML_SUPPORT) 40 | #define parse_yaml_config(ctx,fp) -1 41 | #else 42 | extern int parse_yaml_config(struct uboot_ctx **ctxlist, FILE *fp); 43 | #endif 44 | 45 | #define FREE_ENTRY do { \ 46 | free(entry->name); \ 47 | free(entry->value); \ 48 | free(entry); \ 49 | } while(0) 50 | 51 | /* 52 | * The default lockfile is the same as defined in U-Boot for 53 | * the fw_printenv utilities. Custom lockfile can be set via 54 | * configuration file. 55 | */ 56 | static const char *default_lockname = "/var/lock/fw_printenv.lock"; 57 | static struct uboot_version_info libinfo; 58 | 59 | static int libuboot_lock(struct uboot_ctx *ctx) 60 | { 61 | int lockfd = -1; 62 | lockfd = open(ctx->lockfile ?: default_lockname, O_WRONLY | O_CREAT | O_TRUNC, 0666); 63 | if (lockfd < 0) { 64 | return -EBUSY; 65 | } 66 | if (flock(lockfd, LOCK_EX) < 0) { 67 | close(lockfd); 68 | return -EIO; 69 | } 70 | 71 | ctx->lock = lockfd; 72 | return 0; 73 | } 74 | 75 | static void libuboot_unlock(struct uboot_ctx *ctx) 76 | { 77 | if (ctx && (ctx->lock > 0)) { 78 | flock(ctx->lock, LOCK_UN); 79 | close(ctx->lock); 80 | ctx->lock = -1; 81 | } 82 | } 83 | 84 | static char attr_tostring(type_attribute a) 85 | { 86 | switch(a) { 87 | case TYPE_ATTR_STRING: 88 | return 's'; 89 | case TYPE_ATTR_DECIMAL: 90 | return 'd'; 91 | case TYPE_ATTR_HEX: 92 | return 'x'; 93 | case TYPE_ATTR_BOOL: 94 | return 'b'; 95 | case TYPE_ATTR_IP: 96 | return 'i'; 97 | case TYPE_ATTR_MAC: 98 | return 'm'; 99 | } 100 | 101 | return 's'; 102 | } 103 | 104 | static char access_tostring(access_attribute a) 105 | { 106 | switch(a) { 107 | case ACCESS_ATTR_ANY: 108 | return 'a'; 109 | case ACCESS_ATTR_READ_ONLY: 110 | return 'r'; 111 | case ACCESS_ATTR_WRITE_ONCE: 112 | return 'o'; 113 | case ACCESS_ATTR_CHANGE_DEFAULT: 114 | return 'c'; 115 | } 116 | 117 | return 'a'; 118 | } 119 | 120 | static struct var_entry *__libuboot_get_env(struct vars *envs, const char *varname) 121 | { 122 | struct var_entry *entry; 123 | 124 | LIST_FOREACH(entry, envs, next) { 125 | if (strcmp(varname, entry->name) == 0) 126 | return entry; 127 | } 128 | 129 | return NULL; 130 | } 131 | 132 | static void free_var_entry(struct var_entry *entry) 133 | { 134 | if (entry) { 135 | LIST_REMOVE(entry, next); 136 | free(entry->name); 137 | free(entry->value); 138 | free(entry); 139 | } 140 | } 141 | 142 | static bool validate_int(bool hex, const char *value) 143 | { 144 | const char *c; 145 | 146 | for (c = value; c != value + strlen(value); ++c) { 147 | if (hex && !isxdigit(*c)) 148 | return false; 149 | 150 | if (!hex && !isdigit(*c)) 151 | return false; 152 | } 153 | 154 | return true; 155 | } 156 | 157 | static bool libuboot_validate_flags(struct var_entry *entry, const char *value) 158 | { 159 | bool ok_type = true, ok_access = true; 160 | 161 | switch (entry->access) { 162 | case ACCESS_ATTR_ANY: 163 | ok_access = true; 164 | break; 165 | case ACCESS_ATTR_READ_ONLY: 166 | case ACCESS_ATTR_WRITE_ONCE: 167 | ok_access = false; 168 | break; 169 | case ACCESS_ATTR_CHANGE_DEFAULT: 170 | break; 171 | } 172 | 173 | if (!ok_access) 174 | return false; 175 | 176 | if (!value) 177 | return true; 178 | 179 | switch (entry->type) { 180 | case TYPE_ATTR_STRING: 181 | ok_type = true; 182 | break; 183 | case TYPE_ATTR_DECIMAL: 184 | ok_type = validate_int(false, value); 185 | break; 186 | case TYPE_ATTR_HEX: 187 | ok_type = strlen(value) > 2 && (value[0] == '0') && 188 | (value[1] == 'x' || value [1] == 'X'); 189 | if (ok_type) 190 | ok_type = validate_int(true, value + 2); 191 | break; 192 | case TYPE_ATTR_BOOL: 193 | ok_access = (value[0] == '1' || value[0] == 'y' || value[0] == 't' || 194 | value[0] == 'Y' || value[0] == 'T' || 195 | value[0] == '0' || value[0] == 'n' || value[0] == 'f' || 196 | value[0] == 'N' || value[0] == 'F') && (strlen(value) != 1); 197 | break; 198 | case TYPE_ATTR_IP: 199 | case TYPE_ATTR_MAC: 200 | break; 201 | } 202 | return ok_type; 203 | } 204 | 205 | 206 | /* 207 | * This is used internally with additional parms 208 | */ 209 | static int __libuboot_set_env(struct uboot_ctx *ctx, const char *varname, const char *value, struct var_entry *validate) 210 | { 211 | struct var_entry *entry, *elm, *lastentry; 212 | struct vars *envs = &ctx->varlist; 213 | 214 | /* U-Boot setenv treats '=' as an illegal character for variable names */ 215 | if (strchr(varname, '=')) 216 | return -EINVAL; 217 | 218 | /* 219 | * Giving empty variable name will lead to having "=value" in U-Boot 220 | * environment which will lead to problem during load of it and U-Boot 221 | * will then load default environment. 222 | */ 223 | if (*varname == '\0') 224 | return -EINVAL; 225 | 226 | entry = __libuboot_get_env(envs, varname); 227 | if (entry) { 228 | bool valid = libuboot_validate_flags(entry, value); 229 | if (validate) { 230 | entry->access = validate->access; 231 | entry->type = validate->type; 232 | valid &= libuboot_validate_flags(entry, value); 233 | } 234 | if (!valid) 235 | return -EPERM; 236 | if (!value) { 237 | free_var_entry(entry); 238 | } else { 239 | free(entry->value); 240 | entry->value = strdup(value); 241 | } 242 | return 0; 243 | } 244 | 245 | if (!value) 246 | return 0; 247 | 248 | entry = create_var_entry(varname); 249 | if (!entry) 250 | return -ENOMEM; 251 | 252 | entry->value = strdup(value); 253 | if (!entry->value) { 254 | FREE_ENTRY; 255 | return -ENOMEM; 256 | } 257 | 258 | if (validate) { 259 | entry->access = validate->access; 260 | entry->type = validate->type; 261 | if (!libuboot_validate_flags(entry, value)) { 262 | FREE_ENTRY; 263 | return -EPERM; 264 | } 265 | } 266 | 267 | lastentry = NULL; 268 | LIST_FOREACH(elm, envs, next) { 269 | if (strcmp(elm->name, varname) > 0) { 270 | LIST_INSERT_BEFORE(elm, entry, next); 271 | return 0; 272 | } 273 | lastentry = elm; 274 | } 275 | if (lastentry) 276 | LIST_INSERT_AFTER(lastentry, entry, next); 277 | else 278 | LIST_INSERT_HEAD(envs, entry, next); 279 | 280 | return 0; 281 | } 282 | 283 | static int fileread(struct uboot_flash_env *dev, void *data) 284 | { 285 | int ret = 0; 286 | 287 | if (dev->offset) 288 | ret = lseek(dev->fd, dev->offset, SEEK_SET); 289 | 290 | if (ret < 0) 291 | return ret; 292 | 293 | size_t remaining = dev->envsize; 294 | 295 | while (1) { 296 | ret = read(dev->fd, data, remaining); 297 | 298 | if (ret == 0 && remaining > 0) 299 | return -1; 300 | 301 | if (ret < 0) 302 | break; 303 | 304 | remaining -= ret; 305 | data += ret; 306 | 307 | if (!remaining) { 308 | ret = dev->envsize; 309 | break; 310 | } 311 | } 312 | 313 | return ret; 314 | } 315 | 316 | static int devread(struct uboot_ctx *ctx, unsigned int copy, void *data) 317 | { 318 | int ret; 319 | struct uboot_flash_env *dev; 320 | 321 | if (copy > 1) 322 | return -EINVAL; 323 | 324 | dev = &ctx->envdevs[copy]; 325 | 326 | dev->fd = open(dev->devname, O_RDONLY); 327 | if (dev->fd < 0) 328 | return -EBADF; 329 | 330 | switch (dev->device_type) { 331 | case DEVICE_FILE: 332 | ret = fileread(dev, data); 333 | break; 334 | case DEVICE_MTD: 335 | ret = libubootenv_mtdread(dev, data); 336 | break; 337 | case DEVICE_UBI: 338 | ret = libubootenv_ubiread(dev, data); 339 | break; 340 | default: 341 | ret = -1; 342 | break; 343 | }; 344 | 345 | close(dev->fd); 346 | return ret; 347 | } 348 | 349 | static int fileprotect(struct uboot_flash_env *dev, bool on) 350 | { 351 | const char c_sys_path_1[] = "/sys/class/block/"; 352 | const char c_sys_path_2[] = "/force_ro"; 353 | const char c_dev_name_1[] = "mmcblk"; 354 | const char c_dev_name_2[] = "boot"; 355 | const char c_unprot_char = '0'; 356 | const char c_prot_char = '1'; 357 | const char *devfile = dev->devname; 358 | int ret = 0; // 0 means OK, negative means error 359 | int ret_int = 0; 360 | char *sysfs_path = NULL; 361 | int fd_force_ro; 362 | 363 | // Devices without ro flag at /sys/class/block/mmcblk?boot?/force_ro are ignored 364 | if (strncmp("/dev/block/", dev->devname, 11) == 0) { 365 | devfile = dev->devname + 11; 366 | } else if (strncmp("/dev/", dev->devname, 5) == 0) { 367 | devfile = dev->devname + 5; 368 | } else { 369 | return ret; 370 | } 371 | 372 | ret_int = strncmp(devfile, c_dev_name_1, sizeof(c_dev_name_1) - 1); 373 | if (ret_int != 0) { 374 | return ret; 375 | } 376 | 377 | if (strncmp(devfile + sizeof(c_dev_name_1), c_dev_name_2, sizeof(c_dev_name_2) - 1) != 0) { 378 | return ret; 379 | } 380 | 381 | if (*(devfile + sizeof(c_dev_name_1) - 1) < '0' || 382 | *(devfile + sizeof(c_dev_name_1) - 1) > '9') { 383 | return ret; 384 | } 385 | 386 | if (*(devfile + sizeof(c_dev_name_1) + sizeof(c_dev_name_2) - 1) < '0' || 387 | *(devfile + sizeof(c_dev_name_1) + sizeof(c_dev_name_2) - 1) > '9') { 388 | return ret; 389 | } 390 | 391 | // There is a ro flag, the device needs to be protected or unprotected 392 | ret_int = asprintf(&sysfs_path, "%s%s%s", c_sys_path_1, devfile, c_sys_path_2); 393 | if(ret_int < 0) { 394 | ret = -ENOMEM; 395 | goto fileprotect_out; 396 | } 397 | 398 | if (access(sysfs_path, W_OK) == -1) { 399 | goto fileprotect_out; 400 | } 401 | 402 | fd_force_ro = open(sysfs_path, O_RDWR); 403 | if (fd_force_ro == -1) { 404 | ret = -EBADF; 405 | goto fileprotect_out; 406 | } 407 | 408 | if(on == false){ 409 | ret_int = write(fd_force_ro, &c_unprot_char, 1); 410 | } else { 411 | ret_int = write(fd_force_ro, &c_prot_char, 1); 412 | } 413 | close(fd_force_ro); 414 | 415 | fileprotect_out: 416 | if(sysfs_path) 417 | free(sysfs_path); 418 | return ret; 419 | } 420 | 421 | static int filewrite(struct uboot_flash_env *dev, void *data) 422 | { 423 | int ret = 0; 424 | 425 | ret = fileprotect(dev, false); 426 | if (ret < 0) 427 | return ret; 428 | 429 | if (dev->offset) 430 | ret = lseek(dev->fd, dev->offset, SEEK_SET); 431 | 432 | if (ret < 0) 433 | return ret; 434 | 435 | size_t remaining = dev->envsize; 436 | 437 | while (1) { 438 | ret = write(dev->fd, data, remaining); 439 | 440 | if (ret < 0) 441 | break; 442 | 443 | remaining -= ret; 444 | data += ret; 445 | 446 | if (!remaining) { 447 | ret = dev->envsize; 448 | break; 449 | } 450 | } 451 | 452 | fsync(dev->fd); 453 | 454 | fileprotect(dev, true); // no error handling, keep ret from write 455 | 456 | return ret; 457 | } 458 | 459 | static int devwrite(struct uboot_ctx *ctx, unsigned int copy, void *data) 460 | { 461 | int ret; 462 | struct uboot_flash_env *dev; 463 | 464 | if (copy > 1) 465 | return -EINVAL; 466 | 467 | dev = &ctx->envdevs[copy]; 468 | dev->fd = open(dev->devname, O_RDWR); 469 | if (dev->fd < 0) 470 | return -EBADF; 471 | 472 | switch (dev->device_type) { 473 | case DEVICE_FILE: 474 | ret = filewrite(dev, data); 475 | break; 476 | case DEVICE_MTD: 477 | ret = libubootenv_mtdwrite(dev, data); 478 | break; 479 | case DEVICE_UBI: 480 | ret = libubootenv_ubiwrite(dev, data); 481 | break; 482 | default: 483 | ret = -1; 484 | break; 485 | }; 486 | 487 | close(dev->fd); 488 | 489 | return ret; 490 | } 491 | 492 | const struct uboot_version_info *libuboot_version_info(void) 493 | { 494 | int i; 495 | char *endptr = NULL; 496 | char *start = VERSION; 497 | long val = 0; 498 | libinfo.version = VERSION; 499 | 500 | for (i = 0; i < 3; i++) { 501 | if (!*start) 502 | break; 503 | val = val + (strtol(start, &endptr, 10) << (8 * (2 - i))); 504 | if (start == endptr) 505 | break; 506 | start = endptr + 1; 507 | } 508 | 509 | libinfo.version_num = val; 510 | 511 | return &libinfo; 512 | } 513 | 514 | int libuboot_env_store(struct uboot_ctx *ctx) 515 | { 516 | struct var_entry *entry; 517 | void *image; 518 | char *data; 519 | char *buf; 520 | bool saveflags = false; 521 | size_t size; 522 | uint8_t offsetdata; 523 | int ret; 524 | int copy; 525 | 526 | /* 527 | * Allocate the bigger of the case 528 | */ 529 | image = malloc(sizeof(struct uboot_env_redund) + ctx->size); 530 | if (!image) 531 | return -ENOMEM; 532 | 533 | if (ctx->redundant) 534 | offsetdata = offsetof(struct uboot_env_redund, data); 535 | else 536 | offsetdata = offsetof(struct uboot_env_noredund, data); 537 | 538 | data = (char *)(image + offsetdata); 539 | 540 | buf = data; 541 | LIST_FOREACH(entry, &ctx->varlist, next) { 542 | size = (ctx->size - offsetdata) - (buf - data); 543 | if ((strlen(entry->name) + strlen(entry->value) + 2) > size) 544 | return -ENOMEM; 545 | 546 | if (entry->type || entry->access) 547 | saveflags = true; 548 | 549 | buf += snprintf(buf, size, "%s=%s", entry->name, entry->value); 550 | buf++; 551 | } 552 | 553 | /* 554 | * Now save the .flags 555 | */ 556 | if (saveflags) { 557 | bool first = true; 558 | size = (ctx->size - offsetdata) - (buf - data); 559 | buf += snprintf(buf, size, ".flags="); 560 | 561 | LIST_FOREACH(entry, &ctx->varlist, next) { 562 | size = (ctx->size - offsetdata) - (buf - data); 563 | if (entry->type || entry->access) { 564 | buf += snprintf(buf, size, "%s%s:%c%c", 565 | first ? "" : ",", 566 | entry->name, 567 | attr_tostring(entry->type), 568 | access_tostring(entry->access)); 569 | first = false; 570 | } 571 | } 572 | buf++; 573 | } 574 | *buf++ = '\0'; 575 | 576 | if (ctx->redundant) { 577 | unsigned char flags = ctx->envdevs[ctx->current].flags; 578 | switch(ctx->envdevs[ctx->current].flagstype) { 579 | case FLAGS_INCREMENTAL: 580 | flags++; 581 | break; 582 | case FLAGS_BOOLEAN: 583 | flags = 1; 584 | break; 585 | } 586 | ((struct uboot_env_redund *)image)->flags = flags; 587 | } 588 | 589 | *(uint32_t *)image = crc32(0, (uint8_t *)data, ctx->size - offsetdata); 590 | 591 | copy = ctx->redundant ? (ctx->current ? 0 : 1) : 0; 592 | ret = devwrite(ctx, copy, image); 593 | free(image); 594 | 595 | if (ret == ctx->size) 596 | ret = 0; 597 | 598 | if (ctx->redundant && !ret) { 599 | if (ctx->envdevs[ctx->current].flagstype == FLAGS_BOOLEAN) 600 | ret = libubootenv_set_obsolete_flag(&ctx->envdevs[ctx->current]); 601 | } 602 | 603 | if (!ret) 604 | ctx->current = ctx->current ? 0 : 1; 605 | 606 | return ret; 607 | } 608 | 609 | static int libuboot_load(struct uboot_ctx *ctx) 610 | { 611 | int ret, i; 612 | int copies = 1; 613 | void *buf[2]; 614 | size_t bufsize, usable_envsize; 615 | struct uboot_flash_env *dev; 616 | bool crcenv[2]; 617 | char *line, *next; 618 | uint8_t offsetdata = offsetof(struct uboot_env_noredund, data); 619 | uint8_t offsetcrc = offsetof(struct uboot_env_noredund, crc); 620 | uint8_t offsetflags = offsetof(struct uboot_env_redund, flags); 621 | char *data; 622 | struct var_entry *entry; 623 | 624 | ctx->valid = false; 625 | 626 | bufsize = ctx->size; 627 | if (ctx->redundant) { 628 | copies++; 629 | bufsize += ctx->size; 630 | offsetdata = offsetof(struct uboot_env_redund, data); 631 | offsetcrc = offsetof(struct uboot_env_redund, crc); 632 | } 633 | usable_envsize = ctx->size - offsetdata; 634 | buf[0] = malloc(bufsize); 635 | if (!buf[0]) 636 | return -ENOMEM; 637 | 638 | if (copies > 1) 639 | buf[1] = buf[0] + ctx->envdevs[0].envsize; 640 | 641 | for (i = 0; i < copies; i++) { 642 | data = (char *)(buf[i] + offsetdata); 643 | uint32_t crc; 644 | 645 | dev = &ctx->envdevs[i]; 646 | ret = devread(ctx, i, buf[i]); 647 | if (ret != ctx->size) { 648 | free(buf[0]); 649 | return -EIO; 650 | } 651 | crc = *(uint32_t *)(buf[i] + offsetcrc); 652 | dev->crc = crc32(0, (uint8_t *)data, usable_envsize); 653 | crcenv[i] = dev->crc == crc; 654 | if (ctx->redundant) 655 | dev->flags = *(uint8_t *)(buf[i] + offsetflags); 656 | } 657 | if (!ctx->redundant) { 658 | ctx->current = 0; 659 | ctx->valid = crcenv[0]; 660 | } else { 661 | if (crcenv[0] && !crcenv[1]) { 662 | ctx->valid = true; 663 | ctx->current = 0; 664 | } else if (!crcenv[0] && crcenv[1]) { 665 | ctx->valid = true; 666 | ctx->current = 1; 667 | } else if (!crcenv[0] && !crcenv[1]) { 668 | ctx->valid = false; 669 | ctx->current = 0; 670 | } else { /* both valid, check flags */ 671 | ctx->valid = true; 672 | if (ctx->envdevs[1].flags > ctx->envdevs[0].flags) 673 | ctx->current = 1; 674 | else 675 | ctx->current = 0; 676 | switch (ctx->envdevs[0].flagstype) { 677 | case FLAGS_BOOLEAN: 678 | if (ctx->envdevs[1].flags == 0xFF) 679 | ctx->current = 1; 680 | else if (ctx->envdevs[0].flags == 0xFF) 681 | ctx->current = 0; 682 | break; 683 | case FLAGS_INCREMENTAL: 684 | /* check overflow */ 685 | if (ctx->envdevs[0].flags == 0xFF && 686 | ctx->envdevs[1].flags == 0) 687 | ctx->current = 1; 688 | else if (ctx->envdevs[1].flags == 0xFF && 689 | ctx->envdevs[0].flags == 0) 690 | ctx->current = 0; 691 | break; 692 | } 693 | } 694 | } 695 | 696 | #if !defined(NDEBUG) 697 | fprintf(stdout, "Environment %s, copy %d\n", 698 | ctx->valid ? "OK" : "WRONG", ctx->current); 699 | #endif 700 | 701 | data = (char *)(buf[ctx->current] + offsetdata); 702 | 703 | char *flagsvar = NULL; 704 | 705 | if (ctx->valid) { 706 | for (line = data; *line; line = next + 1) { 707 | char *value; 708 | 709 | /* 710 | * Search the end of the string pointed by line 711 | */ 712 | for (next = line; *next; ++next) { 713 | if ((next - (char *)data) > usable_envsize) { 714 | free(buf[0]); 715 | return -EIO; 716 | } 717 | } 718 | 719 | value = strchr(line, '='); 720 | if (!value) 721 | continue; 722 | 723 | *value++ = '\0'; 724 | 725 | if (!strcmp(line, ".flags")) 726 | flagsvar = strdup(value); 727 | else 728 | __libuboot_set_env(ctx, line, value, NULL); 729 | } 730 | } 731 | 732 | /* 733 | * Parse .flags and set the attributes for a variable 734 | */ 735 | char *pvar; 736 | char *pval; 737 | if (flagsvar) { 738 | #if !defined(NDEBUG) 739 | fprintf(stdout, "Environment FLAGS %s\n", flagsvar); 740 | #endif 741 | unsigned int flagslen = strlen(flagsvar); 742 | pvar = flagsvar; 743 | 744 | while (*pvar && (pvar - flagsvar) < flagslen) { 745 | char *pnext; 746 | pval = strchr(pvar, ':'); 747 | if (!pval) 748 | break; 749 | 750 | *pval++ = '\0'; 751 | pnext = strchr(pval, ','); 752 | if (!pnext) 753 | pnext = flagsvar + strlen(flagsvar); 754 | else 755 | *pnext++ = '\0'; 756 | 757 | entry = __libuboot_get_env(&ctx->varlist, pvar); 758 | set_var_access_type(entry, pval); 759 | pvar = pnext; 760 | } 761 | } 762 | free(flagsvar); 763 | 764 | free(buf[0]); 765 | 766 | return ctx->valid ? 0 : -ENODATA; 767 | } 768 | 769 | #define LINE_LENGTH 2048 770 | int libuboot_load_file(struct uboot_ctx *ctx, const char *filename) 771 | { 772 | FILE *fp; 773 | char *buf; 774 | char *name, *value; 775 | 776 | if (!filename) 777 | return -EBADF; 778 | 779 | if (strcmp(filename, "-") == 0) 780 | fp = fdopen(0, "r"); 781 | else 782 | fp = fopen(filename, "r"); 783 | if (!fp) 784 | return -EACCES; 785 | 786 | buf = (char *)malloc(LINE_LENGTH); 787 | if (!buf) { 788 | fclose(fp); 789 | return -ENOMEM; 790 | } 791 | 792 | while (fgets(buf, LINE_LENGTH, fp)) { 793 | int len = strlen(buf); 794 | 795 | while (len && (buf[len - 1] == '\n' || buf [len - 1] == '\r')) 796 | buf[--len] = '\0'; 797 | 798 | /* Skip comment or empty lines */ 799 | if (len == 0 || buf[0] == '#') 800 | continue; 801 | 802 | value = strchr(buf, '='); 803 | if (!value) 804 | continue; 805 | 806 | *value++ = '\0'; 807 | 808 | name = buf; 809 | 810 | if (!strlen(value)) 811 | value = NULL; 812 | 813 | libuboot_set_env(ctx, name, value); 814 | } 815 | fclose(fp); 816 | free(buf); 817 | 818 | return 0; 819 | } 820 | 821 | int libuboot_read_config_ext(struct uboot_ctx **ctxlist, const char *config) 822 | { 823 | FILE *fp; 824 | char *line = NULL; 825 | size_t bufsize = 0; 826 | int ret = 0; 827 | int ndev = 0; 828 | struct uboot_flash_env *dev; 829 | char *tmp; 830 | int retval = 0; 831 | struct uboot_ctx *ctx; 832 | 833 | if (!config) 834 | return -EINVAL; 835 | 836 | fp = fopen(config, "r"); 837 | if (!fp) 838 | return -EBADF; 839 | 840 | if (!*ctxlist) { 841 | ret = parse_yaml_config(ctxlist, fp); 842 | if (!ret) { 843 | fclose(fp); 844 | return 0; 845 | } 846 | ret = libuboot_initialize(ctxlist, NULL); 847 | if (ret) { 848 | fclose(fp); 849 | return ret; 850 | } 851 | } 852 | ctx = *ctxlist; 853 | 854 | dev = ctx->envdevs; 855 | ctx->size = 0; 856 | rewind(fp); 857 | 858 | int len; 859 | while ((len = getline(&line, &bufsize, fp)) != -1) { 860 | /* skip comments */ 861 | if (line[0] == '#') 862 | continue; 863 | 864 | #if defined(__FreeBSD__) 865 | /* 866 | * POSIX.1-2008 introduced the dynamic allocation conversion 867 | * specifier %m which is not implemented on FreeBSD. 868 | */ 869 | tmp = calloc(1, len + 1); 870 | ret = sscanf(line, "%s %lli %zx %zx %lx %d", 871 | tmp, 872 | #else 873 | (void)len; 874 | ret = sscanf(line, "%ms %lli %zx %zx %lx %d", 875 | &tmp, 876 | #endif 877 | &dev->offset, 878 | &dev->envsize, 879 | &dev->sectorsize, 880 | &dev->envsectors, 881 | &dev->disable_mtd_lock); 882 | 883 | /* 884 | * At least name offset and size should be set 885 | */ 886 | if (ret < 3) { 887 | free(tmp); 888 | continue; 889 | } 890 | 891 | /* 892 | * If size is set but zero, entry is wrong 893 | */ 894 | if (!dev->envsize) { 895 | free(tmp); 896 | retval = -EINVAL; 897 | break; 898 | } 899 | 900 | if (!ctx->size) 901 | ctx->size = dev->envsize; 902 | 903 | if (tmp) { 904 | if (normalize_device_path(tmp, dev) < 0) { 905 | free(tmp); 906 | retval = -EINVAL; 907 | break; 908 | } 909 | free(tmp); 910 | } 911 | 912 | if (check_env_device(dev) < 0) { 913 | retval = -EINVAL; 914 | break; 915 | } 916 | 917 | ndev++; 918 | dev++; 919 | 920 | if (ndev >= 2) { 921 | ctx->redundant = true; 922 | if (!check_compatible_devices(ctx)) 923 | retval = -EINVAL; 924 | break; 925 | } 926 | } 927 | if (ndev == 0) 928 | retval = -EINVAL; 929 | 930 | fclose(fp); 931 | free(line); 932 | 933 | return retval; 934 | } 935 | 936 | int libuboot_read_config(struct uboot_ctx *ctx, const char *config) 937 | { 938 | return libuboot_read_config_ext(&ctx, config); 939 | } 940 | 941 | int libuboot_set_env(struct uboot_ctx *ctx, const char *varname, const char *value) 942 | { 943 | struct var_entry *entry, *entryvarlist = NULL; 944 | if (strchr(varname, '=')) 945 | return -EINVAL; 946 | 947 | /* 948 | * If there is a list of chosen rw vars, 949 | * first check that variable belongs to the list 950 | */ 951 | if (!LIST_EMPTY(&ctx->writevarlist)) { 952 | entryvarlist = __libuboot_get_env(&ctx->writevarlist, varname); 953 | if (!entryvarlist) 954 | return -EPERM; 955 | } 956 | return __libuboot_set_env(ctx, varname, value, entryvarlist); 957 | } 958 | 959 | char *libuboot_get_env(struct uboot_ctx *ctx, const char *varname) 960 | { 961 | struct var_entry *entry; 962 | struct vars *envs = &ctx->varlist; 963 | 964 | entry = __libuboot_get_env(envs, varname); 965 | if (!entry) 966 | return NULL; 967 | 968 | return strdup(entry->value); 969 | } 970 | 971 | const char *libuboot_getname(void *entry) 972 | { 973 | struct var_entry *e = entry; 974 | 975 | return e ? e->name : NULL; 976 | } 977 | 978 | const char *libuboot_getvalue(void *entry) 979 | { 980 | struct var_entry *e = entry; 981 | 982 | return e ? e->value : NULL; 983 | } 984 | 985 | void *libuboot_iterator(struct uboot_ctx *ctx, void *next) 986 | { 987 | if (!next) 988 | return ctx->varlist.lh_first; 989 | else 990 | return ((struct var_entry *)next)->next.le_next; 991 | } 992 | 993 | int libuboot_configure(struct uboot_ctx *ctx, 994 | struct uboot_env_device *envdevs) 995 | { 996 | if (envdevs) { 997 | struct uboot_flash_env *dev; 998 | int i; 999 | dev = &ctx->envdevs[0]; 1000 | for (i = 0; i < 2; i++, envdevs++, dev++) { 1001 | if (!envdevs) 1002 | break; 1003 | memset(dev->devname, 0, sizeof(dev->devname)); 1004 | strncpy(dev->devname, envdevs->devname, sizeof(dev->devname) - 1); 1005 | dev->offset = envdevs->offset; 1006 | dev->envsize = envdevs->envsize; 1007 | dev->sectorsize = envdevs->sectorsize; 1008 | dev->envsectors = envdevs->envsectors; 1009 | 1010 | if (!ctx->size) 1011 | ctx->size = dev->envsize; 1012 | 1013 | if (check_env_device(dev) < 0) 1014 | return -EINVAL; 1015 | 1016 | if (i > 0) { 1017 | ctx->redundant = true; 1018 | if (!check_compatible_devices(ctx)) 1019 | return -EINVAL; 1020 | } 1021 | } 1022 | } 1023 | 1024 | return 0; 1025 | } 1026 | 1027 | struct uboot_ctx *libuboot_get_namespace(struct uboot_ctx *ctxlist, const char *name) 1028 | { 1029 | struct uboot_ctx *ctx; 1030 | int i; 1031 | 1032 | if (!ctxlist) 1033 | return NULL; 1034 | 1035 | /* 1036 | * Be sure to get the whole list, pointer is stored into each 1037 | * CTX pointer in the list 1038 | */ 1039 | if (ctxlist->ctxlist) 1040 | ctxlist = ctxlist->ctxlist; 1041 | for (i = 0, ctx = ctxlist; i < ctxlist->nelem; i++, ctx++) { 1042 | if (!strcmp(ctx->name, name)) 1043 | return ctx; 1044 | } 1045 | 1046 | return NULL; 1047 | } 1048 | 1049 | #define MAX_NAMESPACE_LENGTH 64 1050 | const char *libuboot_namespace_from_dt(void) 1051 | { 1052 | FILE *fp; 1053 | size_t dt_ret; 1054 | char *dt_namespace; 1055 | 1056 | fp = fopen("/proc/device-tree/chosen/u-boot,env-config", "r"); 1057 | if (!fp) 1058 | return NULL; 1059 | 1060 | dt_namespace = malloc(MAX_NAMESPACE_LENGTH); 1061 | if (!dt_namespace) { 1062 | fclose(fp); 1063 | return NULL; 1064 | } 1065 | dt_ret = fread(dt_namespace, 1, MAX_NAMESPACE_LENGTH - 1, fp); 1066 | fclose(fp); 1067 | if (!dt_ret) { 1068 | free(dt_namespace); 1069 | return NULL; 1070 | } 1071 | dt_namespace[dt_ret] = 0; 1072 | return dt_namespace; 1073 | } 1074 | 1075 | int libuboot_initialize(struct uboot_ctx **out, 1076 | struct uboot_env_device *envdevs) { 1077 | struct uboot_ctx *ctx; 1078 | int ret; 1079 | 1080 | *out = NULL; 1081 | ctx = calloc (1, sizeof(*ctx)); 1082 | if (!ctx) 1083 | return -ENOMEM; 1084 | 1085 | ctx->valid = false; 1086 | ret = libuboot_configure(ctx, envdevs); 1087 | 1088 | if (ret < 0) { 1089 | free(ctx); 1090 | return ret; 1091 | } 1092 | 1093 | *out = ctx; 1094 | return 0; 1095 | } 1096 | 1097 | int libuboot_open(struct uboot_ctx *ctx) { 1098 | if (!ctx) 1099 | return -EINVAL; 1100 | libuboot_lock(ctx); 1101 | 1102 | return libuboot_load(ctx); 1103 | } 1104 | 1105 | void libuboot_close(struct uboot_ctx *ctx) { 1106 | struct var_entry *e, *tmp; 1107 | 1108 | if (!ctx) 1109 | return; 1110 | ctx->valid = false; 1111 | libuboot_unlock(ctx); 1112 | 1113 | LIST_FOREACH_SAFE(e, &ctx->varlist, next, tmp) { 1114 | if (e->name) 1115 | free(e->name); 1116 | if (e->value) 1117 | free(e->value); 1118 | LIST_REMOVE(e, next); 1119 | free(e); 1120 | } 1121 | } 1122 | 1123 | void libuboot_exit(struct uboot_ctx *ctx) 1124 | { 1125 | struct uboot_ctx *c; 1126 | int i; 1127 | 1128 | if (!ctx) 1129 | return; 1130 | 1131 | /* passed context might not be list start */ 1132 | if (ctx->ctxlist) { 1133 | ctx = ctx->ctxlist; 1134 | } else { 1135 | /* but in case we don't have a list at all, fixup nelem so that 1136 | * we enter the loop to free the name and lockfile correctly */ 1137 | ctx->nelem = 1; 1138 | } 1139 | 1140 | for (i = 0, c = ctx; i < ctx->nelem; i++, c++) { 1141 | free(c->name); 1142 | free(c->lockfile); 1143 | } 1144 | 1145 | free(ctx); 1146 | } 1147 | -------------------------------------------------------------------------------- /src/uboot_mtd.c: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Copyright 2023 3 | * Stefano Babic, 4 | * 5 | * SPDX-License-Identifier: LGPL-2.1-or-later 6 | */ 7 | 8 | /** 9 | * @file uboot_mtd.c 10 | * 11 | * @brief function used with MTD subsystem 12 | * 13 | */ 14 | 15 | #if !defined(__FreeBSD__) 16 | #define _GNU_SOURCE 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include "uboot_private.h" 39 | 40 | static int ubi_get_dev_id(char *device) 41 | { 42 | int dev_id = -1; 43 | char *sep; 44 | 45 | sep = strrchr(device, 'i'); 46 | if (sep) 47 | sscanf(sep + 1, "%d", &dev_id); 48 | 49 | return dev_id; 50 | } 51 | 52 | static int mtd_get_dev_id(char *device) 53 | { 54 | int dev_id = -1; 55 | char *sep; 56 | 57 | sep = strrchr(device, 'd'); 58 | if (sep) 59 | sscanf(sep + 1, "%d", &dev_id); 60 | 61 | return dev_id; 62 | } 63 | 64 | static int is_nand_badblock(struct uboot_flash_env *dev, loff_t start) 65 | { 66 | int bad; 67 | if (dev->mtdinfo.type != MTD_NANDFLASH) 68 | return 0; 69 | bad = ioctl(dev->fd, MEMGETBADBLOCK, &start); 70 | return bad; 71 | } 72 | 73 | 74 | static int ubi_get_dev_id_from_mtd(char *device) 75 | { 76 | DIR *sysfs_ubi; 77 | struct dirent *dirent; 78 | int mtd_id; 79 | 80 | mtd_id = mtd_get_dev_id(device); 81 | if (mtd_id < 0) 82 | return -1; 83 | 84 | sysfs_ubi = opendir(SYS_UBI); 85 | if (!sysfs_ubi) 86 | return -1; 87 | 88 | while (1) { 89 | int ubi_num, ret; 90 | 91 | dirent = readdir(sysfs_ubi); 92 | if (!dirent) 93 | break; 94 | if (strlen(dirent->d_name) >= 255) { 95 | closedir(sysfs_ubi); 96 | return -1; 97 | } 98 | 99 | ret = sscanf(dirent->d_name, "ubi%d", &ubi_num); 100 | if (ret == 1) { 101 | char filename[DEVNAME_MAX_LENGTH]; 102 | char data[DEVNAME_MAX_LENGTH]; 103 | int fd, n, num_mtd = -1; 104 | 105 | snprintf(filename, sizeof(filename), SYS_UBI_MTD_NUM, ubi_num); 106 | fd = open(filename, O_RDONLY); 107 | if (fd < 0) 108 | continue; 109 | 110 | n = read(fd, data, sizeof(data)); 111 | close(fd); 112 | if (n < 0) 113 | continue; 114 | 115 | if (sscanf(data, "%d", &num_mtd) != 1) 116 | num_mtd = -1; 117 | 118 | if (num_mtd < 0) 119 | continue; 120 | 121 | if (num_mtd == mtd_id) { 122 | closedir(sysfs_ubi); 123 | return ubi_num; 124 | } 125 | } 126 | } 127 | 128 | closedir(sysfs_ubi); 129 | return -1; 130 | } 131 | 132 | static int ubi_get_num_volume(char *device) 133 | { 134 | char filename[DEVNAME_MAX_LENGTH]; 135 | char data[DEVNAME_MAX_LENGTH]; 136 | int dev_id, fd, n, num_vol = -1; 137 | 138 | dev_id = ubi_get_dev_id(device); 139 | if (dev_id < 0) 140 | return -1; 141 | 142 | snprintf(filename, sizeof(filename), SYS_UBI_VOLUME_COUNT, dev_id); 143 | fd = open(filename, O_RDONLY); 144 | if (fd < 0) 145 | return -1; 146 | 147 | n = read(fd, data, sizeof(data)); 148 | if (n < 0) 149 | goto out; 150 | 151 | if (sscanf(data, "%d", &num_vol) != 1) 152 | num_vol = -1; 153 | 154 | out: 155 | close(fd); 156 | return num_vol; 157 | } 158 | 159 | static int ubi_get_volume_name(char *device, int vol_id, char vol_name[DEVNAME_MAX_LENGTH]) 160 | { 161 | char filename[80]; 162 | char data[DEVNAME_MAX_LENGTH]; 163 | int dev_id, fd, n, ret = -1; 164 | 165 | dev_id = ubi_get_dev_id(device); 166 | if (dev_id < 0) 167 | return -1; 168 | 169 | snprintf(filename, sizeof(filename), SYS_UBI_VOLUME_NAME, dev_id, dev_id, vol_id); 170 | fd = open(filename, O_RDONLY); 171 | if (fd < 0) 172 | return -1; 173 | 174 | memset(data, 0, DEVNAME_MAX_LENGTH); 175 | n = read(fd, data, DEVNAME_MAX_LENGTH); 176 | if (n < 0) 177 | goto out; 178 | 179 | memset(vol_name, 0, DEVNAME_MAX_LENGTH); 180 | if (sscanf(data, "%s", vol_name) != 1) 181 | goto out; 182 | 183 | ret = 0; 184 | 185 | out: 186 | close(fd); 187 | return ret; 188 | } 189 | 190 | static int ubi_get_vol_id(char *device, char *volname) 191 | { 192 | int i, n, ret, num_vol, vol_id = -1; 193 | 194 | num_vol = ubi_get_num_volume(device); 195 | if (num_vol < 0) 196 | goto out; 197 | 198 | i = 0; 199 | n = 0; 200 | while ((n < num_vol) && (i < UBI_MAX_VOLUME)) 201 | { 202 | char name[DEVNAME_MAX_LENGTH]; 203 | 204 | ret = ubi_get_volume_name(device, i, name); 205 | if (!ret && !strcmp(name, volname)) { 206 | vol_id = i; 207 | break; 208 | } 209 | 210 | i++; 211 | if (!ret) 212 | n++; 213 | } 214 | 215 | out: 216 | return vol_id; 217 | } 218 | 219 | int libubootenv_ubi_update_name(struct uboot_flash_env *dev) 220 | { 221 | const size_t VOLNAME_MAX_LENGTH = DEVNAME_MAX_LENGTH - 20; 222 | char device[DEVNAME_MAX_LENGTH]; 223 | char volume[VOLNAME_MAX_LENGTH]; 224 | int dev_id, vol_id, fd, ret = -EBADF; 225 | struct stat st; 226 | char *sep; 227 | 228 | if (!strncmp(dev->devname, DEVICE_MTD_NAME, strlen(DEVICE_MTD_NAME))) 229 | { 230 | sep = strchr(dev->devname, DEVNAME_SEPARATOR); 231 | if (sep) 232 | { 233 | memset(device, 0, DEVNAME_MAX_LENGTH); 234 | memcpy(device, dev->devname, sep - dev->devname); 235 | 236 | memset(volume, 0, VOLNAME_MAX_LENGTH); 237 | sscanf(sep + 1, "%s", &volume[0]); 238 | 239 | ret = ubi_get_dev_id_from_mtd(device); 240 | if (ret < 0) { 241 | struct ubi_attach_req req; 242 | 243 | memset(&req, 0, sizeof(struct ubi_attach_req)); 244 | req.ubi_num = UBI_DEV_NUM_AUTO; 245 | req.mtd_num = mtd_get_dev_id(device); 246 | req.vid_hdr_offset = 0; 247 | 248 | fd = open(DEVICE_UBI_CTRL, O_RDONLY); 249 | if (fd == -1) 250 | return -EBADF; 251 | 252 | ret = ioctl(fd, UBI_IOCATT, &req); 253 | close(fd); 254 | if (ret == -1) { 255 | /* Handle race condition where MTD was already being attached. */ 256 | if (errno == EEXIST) { 257 | ret = ubi_get_dev_id_from_mtd(device); 258 | if (ret >= 0) 259 | req.ubi_num = ret; 260 | else 261 | return -EBADF; 262 | } else { 263 | return -EBADF; 264 | } 265 | } 266 | 267 | snprintf(dev->devname, sizeof(dev->devname) - 1, DEVICE_UBI_NAME"%d:%s", req.ubi_num, volume); 268 | } else { 269 | snprintf(dev->devname, sizeof(dev->devname) - 1, DEVICE_UBI_NAME"%d:%s", ret, volume); 270 | } 271 | } else { 272 | return -EBADF; 273 | } 274 | } 275 | 276 | sep = strchr(dev->devname, DEVNAME_SEPARATOR); 277 | ret = 0; 278 | if (sep) 279 | { 280 | memset(device, 0, DEVNAME_MAX_LENGTH); 281 | memcpy(device, dev->devname, sep - dev->devname); 282 | 283 | memset(volume, 0, VOLNAME_MAX_LENGTH); 284 | sscanf(sep + 1, "%s", &volume[0]); 285 | 286 | dev_id = ubi_get_dev_id(device); 287 | if (dev_id < 0) 288 | goto out; 289 | 290 | vol_id = ubi_get_vol_id(device, volume); 291 | if (vol_id < 0) 292 | goto out; 293 | 294 | if (snprintf(dev->devname, sizeof(dev->devname) - 1, "%s_%d", device, vol_id) < 0) 295 | ret = -EBADF; 296 | } 297 | 298 | 299 | out: 300 | return ret; 301 | } 302 | 303 | int libubootenv_mtdread(struct uboot_flash_env *dev, void *data) 304 | { 305 | size_t count; 306 | size_t blocksize; 307 | loff_t start; 308 | int sectors, skip; 309 | int ret = 0; 310 | 311 | switch (dev->mtdinfo.type) { 312 | case MTD_ABSENT: 313 | case MTD_NORFLASH: 314 | if (dev->offset) 315 | if (lseek(dev->fd, dev->offset, SEEK_SET) < 0) { 316 | ret = -EIO; 317 | break; 318 | } 319 | ret = read(dev->fd, data, dev->envsize); 320 | break; 321 | case MTD_NANDFLASH: 322 | if (dev->offset) 323 | if (lseek(dev->fd, dev->offset, SEEK_SET) < 0) { 324 | ret = -EIO; 325 | break; 326 | } 327 | 328 | count = dev->envsize; 329 | start = dev->offset; 330 | blocksize = dev->envsize; 331 | sectors = dev->envsectors ? dev->envsectors : 1; 332 | 333 | while (count > 0) { 334 | skip = is_nand_badblock(dev, start); 335 | if (skip < 0) { 336 | return -EIO; 337 | } 338 | 339 | if (skip > 0) { 340 | start += dev->sectorsize; 341 | sectors--; 342 | if (sectors > 0) 343 | continue; 344 | return -EIO; 345 | } 346 | 347 | if (count > dev->sectorsize) 348 | blocksize = dev->sectorsize; 349 | else 350 | blocksize = count; 351 | 352 | if (lseek(dev->fd, start, SEEK_SET) < 0) { 353 | return -EIO; 354 | } 355 | if (read(dev->fd, data, blocksize) != blocksize) { 356 | return -EIO; 357 | } 358 | start += dev->sectorsize; 359 | data += blocksize; 360 | count -= blocksize; 361 | ret += blocksize; 362 | } 363 | break; 364 | } 365 | 366 | return ret; 367 | } 368 | 369 | int libubootenv_ubiread(struct uboot_flash_env *dev, void *data) 370 | { 371 | int ret = 0; 372 | 373 | ret = read(dev->fd, data, dev->envsize); 374 | 375 | return ret; 376 | } 377 | 378 | int libubootenv_mtdwrite(struct uboot_flash_env *dev, void *data) 379 | { 380 | int ret = 0; 381 | struct erase_info_user erase; 382 | size_t count; 383 | size_t blocksize; 384 | loff_t start; 385 | void *buf; 386 | int sectors, skip; 387 | 388 | switch (dev->mtdinfo.type) { 389 | case MTD_NORFLASH: 390 | case MTD_NANDFLASH: 391 | count = dev->envsize; 392 | start = dev->offset; 393 | blocksize = dev->envsize; 394 | erase.length = dev->sectorsize; 395 | sectors = dev->envsectors ? dev->envsectors : 1; 396 | buf = data; 397 | while (count > 0) { 398 | erase.start = start; 399 | 400 | skip = is_nand_badblock(dev, start); 401 | if (skip < 0) { 402 | ret = -EIO; 403 | goto devwrite_out; 404 | } 405 | 406 | if (skip > 0) { 407 | start += dev->sectorsize; 408 | sectors--; 409 | if (sectors > 0) 410 | continue; 411 | ret = -EIO; 412 | goto devwrite_out; 413 | } 414 | 415 | if (count > dev->sectorsize) 416 | blocksize = dev->sectorsize; 417 | else 418 | blocksize = count; 419 | 420 | /* 421 | * unlock could fail, no check 422 | */ 423 | MTDUNLOCK(dev, &erase); 424 | if (ioctl(dev->fd, MEMERASE, &erase) != 0) { 425 | ret =-EIO; 426 | goto devwrite_out; 427 | } 428 | if (lseek(dev->fd, start, SEEK_SET) < 0) { 429 | ret =-EIO; 430 | goto devwrite_out; 431 | } 432 | if (write(dev->fd, buf, blocksize) != blocksize) { 433 | ret =-EIO; 434 | goto devwrite_out; 435 | } 436 | MTDLOCK(dev, &erase); 437 | start += dev->sectorsize; 438 | buf += blocksize; 439 | count -= blocksize; 440 | ret += blocksize; 441 | } 442 | break; 443 | } 444 | 445 | devwrite_out: 446 | return ret; 447 | } 448 | 449 | int libubootenv_ubi_update_volume(struct uboot_flash_env *dev) 450 | { 451 | int64_t envsize = dev->envsize; 452 | return ioctl(dev->fd, UBI_IOCVOLUP, &envsize); 453 | } 454 | 455 | int libubootenv_ubiwrite(struct uboot_flash_env *dev, void *data) 456 | { 457 | int ret; 458 | 459 | if (libubootenv_ubi_update_volume(dev) < 0) 460 | return -1; 461 | 462 | ret = write(dev->fd, data, dev->envsize); 463 | 464 | return ret; 465 | } 466 | 467 | int libubootenv_mtdgetinfo(int fd, struct uboot_flash_env *dev) 468 | { 469 | return ioctl(fd, MEMGETINFO, &dev->mtdinfo); 470 | } 471 | 472 | int libubootenv_set_obsolete_flag(struct uboot_flash_env *dev) 473 | { 474 | uint8_t offsetflags = offsetof(struct uboot_env_redund, flags); 475 | unsigned char flag = 0; 476 | struct erase_info_user erase; 477 | int ret = 0; 478 | 479 | dev->fd = open(dev->devname, O_RDWR); 480 | if (dev->fd < 0) 481 | return -EBADF; 482 | if (lseek(dev->fd, dev->offset + offsetflags, SEEK_SET) < 0) { 483 | close(dev->fd); 484 | return -EBADF; 485 | } 486 | erase.start = dev->offset; 487 | erase.length = dev->sectorsize; 488 | MTDUNLOCK(dev, &erase); 489 | ret = write(dev->fd, &flag, sizeof(flag)); 490 | if (ret == sizeof(flag)) 491 | ret = 0; 492 | else if (ret >= 0) 493 | ret = -EIO; 494 | MTDLOCK(dev, &erase); 495 | close(dev->fd); 496 | 497 | return ret; 498 | } 499 | #endif 500 | -------------------------------------------------------------------------------- /src/uboot_private.h: -------------------------------------------------------------------------------- 1 | /* 2 | * (C) Copyright 2019 3 | * Stefano Babic, 4 | * 5 | * SPDX-License-Identifier: LGPL-2.1-or-later 6 | */ 7 | 8 | #pragma once 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "libuboot.h" 15 | 16 | #define UBI_MAX_VOLUME 128 17 | 18 | #define DEVICE_MTD_NAME "/dev/mtd" 19 | #define DEVICE_UBI_NAME "/dev/ubi" 20 | #define DEVICE_UBI_CTRL "/dev/ubi_ctrl" 21 | #define SYS_UBI "/sys/class/ubi" 22 | #define SYS_UBI_MTD_NUM "/sys/class/ubi/ubi%d/mtd_num" 23 | #define SYS_UBI_VOLUME_COUNT "/sys/class/ubi/ubi%d/volumes_count" 24 | #define SYS_UBI_VOLUME_NAME "/sys/class/ubi/ubi%d/ubi%d_%d/name" 25 | 26 | #if !defined(__FreeBSD__) 27 | #include 28 | #include 29 | #define MTDLOCK(dev, psector) \ 30 | if (!dev->disable_mtd_lock) ioctl (dev->fd, MEMLOCK, psector) 31 | #define MTDUNLOCK(dev, psector) \ 32 | if (!dev->disable_mtd_lock) ioctl (dev->fd, MEMUNLOCK, psector) 33 | 34 | #define LIST_FOREACH_SAFE(var, head, field, tvar) \ 35 | for ((var) = LIST_FIRST((head)); \ 36 | (var) != NULL && \ 37 | ((tvar) = LIST_NEXT((var), field), 1); \ 38 | (var) = (tvar)) 39 | #else 40 | #define MTD_ABSENT 0 41 | #define MTD_RAM 1 42 | #define MTD_ROM 2 43 | #define MTD_NORFLASH 3 44 | #define MTD_NANDFLASH 4 /* SLC NAND */ 45 | #define MTD_DATAFLASH 6 46 | #define MTD_UBIVOLUME 7 47 | #define MTD_MLCNANDFLASH 8 /* MLC NAND (including TLC) */ 48 | #define MTDLOCK 49 | #define MTDUNLOCK 50 | 51 | #define ENODATA ENODEV 52 | 53 | struct mtd_info_user { 54 | uint8_t type; 55 | uint32_t flags; 56 | uint32_t size; /* Total size of the MTD */ 57 | uint32_t erasesize; 58 | uint32_t writesize; 59 | uint32_t oobsize; /* Amount of OOB data per block (e.g. 16) */ 60 | uint64_t padding; /* Old obsolete field; do not use */ 61 | }; 62 | #endif 63 | 64 | typedef enum { 65 | TYPE_ATTR_STRING, /* default */ 66 | TYPE_ATTR_DECIMAL, 67 | TYPE_ATTR_HEX, 68 | TYPE_ATTR_BOOL, 69 | TYPE_ATTR_IP, 70 | TYPE_ATTR_MAC 71 | } type_attribute; 72 | 73 | typedef enum { 74 | ACCESS_ATTR_ANY, /* default */ 75 | ACCESS_ATTR_READ_ONLY, 76 | ACCESS_ATTR_WRITE_ONCE, 77 | ACCESS_ATTR_CHANGE_DEFAULT, 78 | } access_attribute; 79 | 80 | enum flags_type { 81 | FLAGS_NONE, 82 | FLAGS_BOOLEAN, 83 | FLAGS_INCREMENTAL 84 | }; 85 | 86 | enum device_type { 87 | DEVICE_NONE, 88 | DEVICE_FILE, 89 | DEVICE_MTD, 90 | DEVICE_UBI, 91 | }; 92 | 93 | /** 94 | * U-Boot environment should always be redundant, but 95 | * for compatibility reasons a single copy must 96 | * be also supported. Structure is different because 97 | * there is no flags in the single copy 98 | */ 99 | struct uboot_env_noredund { 100 | /** computed crc32 value */ 101 | uint32_t crc; 102 | /** placeholder to point to the env in flash */ 103 | char data[]; 104 | }; 105 | 106 | struct uboot_env_redund { 107 | /** computed crc32 value */ 108 | uint32_t crc; 109 | /** flags, see flags_type */ 110 | unsigned char flags; 111 | /** placeholder to point to the env in flash */ 112 | char data[]; 113 | }; 114 | 115 | struct uboot_flash_env { 116 | /** path to device or file where env is stored */ 117 | char devname[DEVNAME_MAX_LENGTH]; 118 | /** Start offset inside device path */ 119 | long long int offset; 120 | /** size of environment */ 121 | size_t envsize; 122 | /** Size of sector (for MTD) */ 123 | size_t sectorsize; 124 | /** Number of sectors for each environment */ 125 | long unsigned int envsectors; 126 | /** MTD structure as returned by ioctl() call */ 127 | struct mtd_info_user mtdinfo; 128 | /** Computed CRC on the stored environment */ 129 | uint32_t crc; 130 | /** file descriptor used to access the device */ 131 | int fd; 132 | /** flags (see flags_type) are one byte in the stored environment */ 133 | unsigned char flags; 134 | /** flags according to device type */ 135 | enum flags_type flagstype; 136 | /** type of device (mtd, ubi, file, ....) */ 137 | enum device_type device_type; 138 | /** Disable lock mechanism (required by some flashes */ 139 | int disable_mtd_lock; 140 | }; 141 | 142 | /** Internal structure for an environment variable 143 | */ 144 | struct var_entry { 145 | /** Variable's name */ 146 | char *name; 147 | /** Variable's value */ 148 | char *value; 149 | /** Type of the variable, see access_attribute */ 150 | type_attribute type; 151 | /** Permissions for the variable */ 152 | access_attribute access; 153 | /** Pointer to next element in the list */ 154 | LIST_ENTRY(var_entry) next; 155 | }; 156 | 157 | LIST_HEAD(vars, var_entry); 158 | 159 | /** libubootenv context 160 | */ 161 | struct uboot_ctx { 162 | /** true if the environment is redundant */ 163 | bool redundant; 164 | /** set to valid after a successful load */ 165 | bool valid; 166 | /** size of the environment */ 167 | size_t size; 168 | /** devices where environment is stored */ 169 | struct uboot_flash_env envdevs[2]; 170 | /** Set which device contains the current(last valid) environment */ 171 | int current; 172 | /** semaphore on the environment */ 173 | int lock; 174 | /** pointer to the internal db */ 175 | struct vars varlist; 176 | /** pointer to the writelist (vars that can be set as writable) */ 177 | struct vars writevarlist; 178 | /** name of the set */ 179 | char *name; 180 | /** lockfile */ 181 | char *lockfile; 182 | /** Number of namespaces */ 183 | int nelem; 184 | /** private pointer to list */ 185 | struct uboot_ctx *ctxlist; 186 | }; 187 | 188 | #if defined(__FreeBSD__) 189 | #define libubootenv_mtdgetinfo(fd,dev) (-1) 190 | #define libubootenv_mtdread(dev,data) (-1) 191 | #define libubootenv_mtdwrite(dev,data) (-1) 192 | #define libubootenv_ubiread(dev,data) (-1) 193 | #define libubootenv_ubiwrite(dev,data) (-1) 194 | #define libubootenv_ubi_update_name(dev) (-1) 195 | #define libubootenv_set_obsolete_flag(dev) (-1) 196 | #else 197 | int libubootenv_mtdgetinfo(int fd, struct uboot_flash_env *dev); 198 | int libubootenv_mtdread(struct uboot_flash_env *dev, void *data); 199 | int libubootenv_mtdwrite(struct uboot_flash_env *dev, void *data); 200 | int libubootenv_ubi_update_name(struct uboot_flash_env *dev); 201 | int libubootenv_ubiread(struct uboot_flash_env *dev, void *data); 202 | int libubootenv_ubiwrite(struct uboot_flash_env *dev, void *data); 203 | int libubootenv_set_obsolete_flag(struct uboot_flash_env *dev); 204 | #endif 205 | 206 | 207 | --------------------------------------------------------------------------------