From 8a4ef50ba195fe6cee61a95e04d2709713adbf3d Mon Sep 17 00:00:00 2001 From: =?utf8?q?=E5=AD=99=E6=98=A5=E9=98=B3?= Date: Mon, 22 Dec 2025 20:04:11 +0800 Subject: [PATCH] =?utf8?q?=E5=90=8C=E6=AD=A5=E6=9B=B4=E6=96=B0unyaffs?= =?utf8?q?=EF=BC=8C=E5=90=8C=E6=97=B6=E6=94=AF=E6=8C=81=E6=96=B0=E6=97=A7?= =?utf8?q?=E4=B8=A4=E7=89=88mkyaffs2image=E5=88=B6=E4=BD=9C=E7=9A=84image?= =?utf8?q?=E3=80=82=E8=A6=81=E6=B1=82=E5=8F=82=E6=95=B0=E6=98=AF=20mkyaffs?= =?utf8?q?2image=20xx=20xx=201=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- tools/unyaffs_0.9.7/Makefile | 4 + tools/unyaffs_0.9.7/README | 114 ++++ tools/unyaffs_0.9.7/gpl-2.0.txt | 339 ++++++++++++ tools/unyaffs_0.9.7/test_yaffs.py | 373 +++++++++++++ tools/unyaffs_0.9.7/unyaffs | Bin 26632 -> 36048 bytes tools/unyaffs_0.9.7/unyaffs.c | 888 ++++++++++++++++++++++++++++++ tools/unyaffs_0.9.7/unyaffs.h | 99 ++++ 7 files changed, 1817 insertions(+) create mode 100644 tools/unyaffs_0.9.7/Makefile create mode 100644 tools/unyaffs_0.9.7/README create mode 100644 tools/unyaffs_0.9.7/gpl-2.0.txt create mode 100644 tools/unyaffs_0.9.7/test_yaffs.py create mode 100644 tools/unyaffs_0.9.7/unyaffs.c create mode 100644 tools/unyaffs_0.9.7/unyaffs.h diff --git a/tools/unyaffs_0.9.7/Makefile b/tools/unyaffs_0.9.7/Makefile new file mode 100644 index 000000000..f60989551 --- /dev/null +++ b/tools/unyaffs_0.9.7/Makefile @@ -0,0 +1,4 @@ +CFLAGS = -O2 -Wall + +unyaffs: unyaffs.c unyaffs.h + $(CC) $(CFLAGS) $(LDFLAGS) unyaffs.c -o unyaffs diff --git a/tools/unyaffs_0.9.7/README b/tools/unyaffs_0.9.7/README new file mode 100644 index 000000000..c1f5ef077 --- /dev/null +++ b/tools/unyaffs_0.9.7/README @@ -0,0 +1,114 @@ +unyaffs +======= + +Overview +-------- + + Unyaffs is a program to extract files from a YAFFS2 file system image. + Currently it can only extract images created by mkyaffs2image. + + Unyaffs is based on work of the YAFFS project, see http://www.yaffs.net/ + + The original implementation was done by Kai Wei , + it is available at http://code.google.com/p/unyaffs/ + + As the project was inactive, Bernhard Ehlers + started a fork at https://github.com/ehlers/unyaffs + + +License +------- + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License version 2 as + published by the Free Software Foundation. + + The full license text is available in the file gpl-2.0.txt. + + +Requirements +------------ + + Unyaffs should run on most unix-like operating systems. + A C compiler environment and make is neccessary to compile it. + + +Compiling +--------- + + type "make" + + +Usage +----- + + unyaffs extracts all the files from a YAFFS2 file system image. + + unyaffs [-l ] [-t] [-v] [-V] [] + -l set flash memory layout + layout=0: detect chunk and spare size (default) + layout=1: 2K chunk, 64 byte spare size + layout=2: 4K chunk, 128 byte spare size + layout=3: 8K chunk, 256 byte spare size + layout=4: 16K chunk, 512 byte spare size + -t list image contents + -v verbose output + -V print version + + In most cases the flash memory layout is detected automatically. + If the detection doesn't work properly, the layout can be set with + option -l. + + Option -t lists all the file names in the image without extracting them. + Option -v generates a 'ls -l' like listing of the extracted files. + When combined with -t it generates an extended file listing, nothing + is extracted. + + The image file can be - for standard input. + + If the base directory is not given, the filea are extracted into the + current directory. If the base dir doesn't exist, it will be created. + + unyaffs extracts all file types (regular files, directories, soft links, + hard links and special files). The permissions and modification dates + are restored. When run as root, the ownership is restored as well. + + Please be careful extracting images as root. It might be possible, + that important system files get overwritten. The use of chroot + or fakeroot can guard against these problems. + +Limitations +----------- + + Block and character devices can only be restored as root. In some + operating systems (e.g. Mac OS X) sockets can't be restored. + + The use of special files (block devices, character devices, pipes, + sockets) is not portable across different unix flavors. E.g. device + files created on linux will get a strange major and minor device id, + when restored under BSD. + + When it's necessary to deal with special files, please use the same + OS as used in the system the image is build for. In most cases that's + linux. + +Windows +------- + + The differences between the unix and windows file system are big enough + to make a windows port of unyaffs a complicated task. But with cygwin + (http://www.cygwin.com/) a unix compatibility layer for windows is + available. The unmodified source compiles and runs nicely within cygwin. + + The main differences to a pure unix environment: + - Unix functionality only within cygwin environment, native windows + programs won't see the more advanced features. + - Permissions and file dates/time are correctly restored + - Owner/group are not fully restored, only user/groups available in windows + - Hard and soft links are correctly restored + - Device files have different ids as in linux + - Sockets are not restored + + For analysis of a firmware image, unyaffs within cygwin is a nice tool, + but because of the restricted user/group functionality rebuilding a + modified image can't be recommended. diff --git a/tools/unyaffs_0.9.7/gpl-2.0.txt b/tools/unyaffs_0.9.7/gpl-2.0.txt new file mode 100644 index 000000000..d159169d1 --- /dev/null +++ b/tools/unyaffs_0.9.7/gpl-2.0.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/tools/unyaffs_0.9.7/test_yaffs.py b/tools/unyaffs_0.9.7/test_yaffs.py new file mode 100644 index 000000000..2fe6717c8 --- /dev/null +++ b/tools/unyaffs_0.9.7/test_yaffs.py @@ -0,0 +1,373 @@ +#!/usr/bin/env python3 +""" +测试脚本:验证 mkyaffs2image 打包和 unyaffs 解包功能 + +该脚本会: +1. 使用两个版本的 mkyaffs2image(新版本和旧版本)分别将 res 目录打包成 YAFFS2 镜像 +2. 使用 unyaffs 解包两个版本的镜像到临时目录 +3. 验证解包后的文件是否与原始文件一致 + +注意: +- 新版本 mkyaffs2image:支持 summary chunks +- 旧版本 mkyaffs2image_old:不支持 summary chunks +- unyaffs 应该能够自动检测并兼容两个版本的镜像格式 +- 脚本会尝试多种 pagesize 和 ecctype 组合 +""" + +import os +import sys +import subprocess +import shutil +import tempfile +import filecmp +from pathlib import Path + + +class Colors: + """终端颜色输出""" + GREEN = '\033[92m' + RED = '\033[91m' + YELLOW = '\033[93m' + BLUE = '\033[94m' + RESET = '\033[0m' + BOLD = '\033[1m' + + +def print_success(msg): + """打印成功消息""" + print(f"{Colors.GREEN}✓{Colors.RESET} {msg}") + + +def print_error(msg): + """打印错误消息""" + print(f"{Colors.RED}✗{Colors.RESET} {msg}") + + +def print_info(msg): + """打印信息消息""" + print(f"{Colors.BLUE}ℹ{Colors.RESET} {msg}") + + +def print_warning(msg): + """打印警告消息""" + print(f"{Colors.YELLOW}⚠{Colors.RESET} {msg}") + + +def check_tool(tool_path, tool_name): + """检查工具是否存在且可执行""" + if not os.path.exists(tool_path): + print_error(f"{tool_name} 不存在: {tool_path}") + return False + if not os.access(tool_path, os.X_OK): + print_error(f"{tool_name} 不可执行: {tool_path}") + return False + print_success(f"找到 {tool_name}: {tool_path}") + return True + + +def run_command(cmd, description, suppress_output=False): + """运行命令并检查结果""" + print_info(f"执行: {description}") + if not suppress_output: + print_info(f"命令: {' '.join(cmd)}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + if result.stdout and not suppress_output: + # 对于 mkyaffs2image,只显示最后几行 + lines = result.stdout.strip().split('\n') + if len(lines) > 10: + print_info("... (输出已截断)") + for line in lines[-5:]: + print(f" {line}") + else: + print(result.stdout) + return True, result.stdout + except subprocess.CalledProcessError as e: + print_error(f"命令执行失败: {description}") + if e.stdout: + # 只显示最后几行错误输出 + lines = e.stdout.strip().split('\n') + if len(lines) > 5: + for line in lines[-5:]: + print(f" {line}") + else: + print(e.stdout) + if e.stderr: + print(e.stderr) + return False, None + except Exception as e: + print_error(f"执行命令时出错: {e}") + return False, None + + +def compare_directories(dir1, dir2, base_path=""): + """递归比较两个目录的内容""" + errors = [] + matches = [] + + # 获取两个目录的文件列表 + dir1_path = Path(dir1) / base_path if base_path else Path(dir1) + dir2_path = Path(dir2) / base_path if base_path else Path(dir2) + + if not dir1_path.exists(): + errors.append(f"源目录不存在: {dir1_path}") + return matches, errors + + if not dir2_path.exists(): + errors.append(f"目标目录不存在: {dir2_path}") + return matches, errors + + # 获取所有文件(包括子目录) + dir1_files = set() + dir2_files = set() + + for root, dirs, files in os.walk(dir1_path): + rel_root = os.path.relpath(root, dir1_path) + if rel_root == '.': + rel_root = '' + for f in files: + file_path = os.path.join(rel_root, f) if rel_root else f + dir1_files.add(file_path) + + for root, dirs, files in os.walk(dir2_path): + rel_root = os.path.relpath(root, dir2_path) + if rel_root == '.': + rel_root = '' + for f in files: + file_path = os.path.join(rel_root, f) if rel_root else f + dir2_files.add(file_path) + + # 检查缺失的文件 + missing_in_dir2 = dir1_files - dir2_files + extra_in_dir2 = dir2_files - dir1_files + + for f in missing_in_dir2: + errors.append(f"文件在解包后缺失: {f}") + + for f in extra_in_dir2: + errors.append(f"解包后出现额外文件: {f}") + + # 比较共同的文件 + common_files = dir1_files & dir2_files + for f in common_files: + file1 = dir1_path / f + file2 = dir2_path / f + + if file1.is_file() and file2.is_file(): + if filecmp.cmp(str(file1), str(file2), shallow=False): + matches.append(f) + else: + errors.append(f"文件内容不一致: {f}") + elif file1.is_dir() and file2.is_dir(): + # 目录,递归比较 + sub_matches, sub_errors = compare_directories( + str(dir1_path), str(dir2_path), f + ) + matches.extend(sub_matches) + errors.extend(sub_errors) + else: + errors.append(f"文件类型不匹配: {f}") + + return matches, errors + + +def main(): + """主函数""" + print(f"{Colors.BOLD}{Colors.BLUE}") + print("=" * 60) + print("YAFFS2 打包和解包测试脚本") + print("=" * 60) + print(f"{Colors.RESET}") + + # 获取脚本所在目录 + script_dir = Path(__file__).parent.absolute() + os.chdir(script_dir) + + # 检查工具 + mkyaffs2image_new = script_dir / "mkyaffs2image" / "mkyaffs2image" + mkyaffs2image_old = script_dir / "mkyaffs2image" / "mkyaffs2image_old" + unyaffs = script_dir / "unyaffs" + res_dir = script_dir / "res" + + print_info("检查工具和目录...") + if not check_tool(mkyaffs2image_new, "mkyaffs2image (新版本)"): + print_warning("新版本 mkyaffs2image 不存在,将跳过新版本测试") + mkyaffs2image_new = None + if not check_tool(mkyaffs2image_old, "mkyaffs2image_old (旧版本)"): + print_warning("旧版本 mkyaffs2image_old 不存在,将跳过旧版本测试") + mkyaffs2image_old = None + + if mkyaffs2image_new is None and mkyaffs2image_old is None: + print_error("两个版本的 mkyaffs2image 都不存在,无法进行测试") + sys.exit(1) + + if not check_tool(unyaffs, "unyaffs"): + sys.exit(1) + + if not res_dir.exists(): + print_error(f"res 目录不存在: {res_dir}") + sys.exit(1) + print_success(f"找到 res 目录: {res_dir}") + + # 创建临时目录 + with tempfile.TemporaryDirectory(prefix="yaffs_test_") as temp_dir: + temp_path = Path(temp_dir) + image_file = temp_path / "test_image.yaffs2" + extract_dir = temp_path / "extracted" + + # 测试不同的 pagesize 和 ecctype 组合 + # 注意:mkyaffs2image 和 unyaffs 可能存在兼容性问题 + # 如果某个配置失败,可以尝试其他配置 + test_configs = [ + (1, 2, "2K pagesize, 4bit ECC"), + # (2, 2, "4K pagesize, 4bit ECC"), # 尝试 4bit ECC + # (2, 4, "4K pagesize, 24bit ECC"), + ] + + # 定义要测试的 mkyaffs2image 版本 + mkyaffs2image_versions = [] + if mkyaffs2image_new: + mkyaffs2image_versions.append(("new", mkyaffs2image_new, "新版本 (支持 summary chunks)")) + if mkyaffs2image_old: + mkyaffs2image_versions.append(("old", mkyaffs2image_old, "旧版本 (不支持 summary chunks)")) + + all_passed = True + + # 对每个版本和每个配置进行测试 + for version_name, mkyaffs2image, version_desc in mkyaffs2image_versions: + print() + print_info("=" * 60) + print_info(f"测试 mkyaffs2image {version_desc}") + print_info("=" * 60) + + for pagesize, ecctype, config_desc in test_configs: + print() + print_info(f"测试配置: {config_desc} ({version_desc})") + image_file = temp_path / f"test_image_{version_name}_{pagesize}_{ecctype}.yaffs2" + + # 打包 + print() + print_info("=" * 60) + print_info(f"步骤 1: 使用 mkyaffs2image {version_desc} 打包 res 目录") + print_info(f"配置: {config_desc}") + print_info("=" * 60) + + cmd = [ + str(mkyaffs2image), + str(res_dir), + str(image_file), + str(pagesize), + str(ecctype) + ] + + success, _ = run_command( + cmd, + f"打包 res 目录 (版本={version_name}, pagesize={pagesize}, ecctype={ecctype})", + suppress_output=True + ) + if not success: + print_error(f"打包失败: {version_desc} - {config_desc}") + all_passed = False + continue + + if not image_file.exists(): + print_error(f"镜像文件未创建: {image_file}") + all_passed = False + continue + + file_size = image_file.stat().st_size + print_success(f"镜像创建成功: {image_file} ({file_size} 字节)") + + # 解包 + print() + print_info("=" * 60) + print_info(f"步骤 2: 使用 unyaffs 解包镜像 ({version_desc} - {config_desc})") + print_info("=" * 60) + + extract_dir = temp_path / f"extracted_{version_name}_{pagesize}_{ecctype}" + # 清理之前的解包目录(如果存在) + if extract_dir.exists(): + shutil.rmtree(extract_dir) + extract_dir.mkdir(parents=True, exist_ok=True) + + # unyaffs 应该能够自动检测镜像格式(新版本或旧版本) + # 使用自动检测模式(不指定 layout) + cmd = [str(unyaffs), str(image_file), str(extract_dir)] + success, output = run_command(cmd, f"解包镜像到 {extract_dir} (自动检测格式)") + + # 如果自动检测失败,尝试指定 layout + if not success: + print_info("自动检测失败,尝试指定 layout...") + # unyaffs 的 layout 对应关系: + # layout 1 = 2K chunk, 64 byte spare (对应 mkyaffs2image pagesize=1) + # layout 2 = 4K chunk, 128 byte spare (对应 mkyaffs2image pagesize=2) + layout = pagesize # pagesize 1->layout 1, pagesize 2->layout 2 + cmd = [str(unyaffs), "-l", str(layout), str(image_file), str(extract_dir)] + success, output = run_command(cmd, f"解包镜像到 {extract_dir} (layout={layout})") + + if not success: + print_warning(f"解包失败: {version_desc} - {config_desc}") + print_warning("这可能是因为 mkyaffs2image 和 unyaffs 之间的兼容性问题") + print_warning("建议检查镜像格式或尝试其他 pagesize/ecctype 组合") + all_passed = False + continue + + print_success(f"解包成功: {extract_dir}") + + # 比较文件 + print() + print_info("=" * 60) + print_info(f"步骤 3: 验证文件完整性 ({version_desc} - {config_desc})") + print_info("=" * 60) + + # 检查解包目录是否存在且有内容 + if not extract_dir.exists() or not any(extract_dir.iterdir()): + print_error("解包目录为空或不存在") + all_passed = False + continue + + matches, errors = compare_directories(str(res_dir), str(extract_dir)) + + print_info(f"匹配的文件数: {len(matches)}") + if errors: + print_error(f"发现 {len(errors)} 个错误:") + for error in errors[:20]: # 只显示前20个错误 + print(f" - {error}") + if len(errors) > 20: + print_warning(f" ... 还有 {len(errors) - 20} 个错误未显示") + all_passed = False + else: + print_success(f"所有文件验证通过! ({len(matches)} 个文件)") + + # 总结 + print() + print_info("=" * 60) + if all_passed: + print_success("所有测试通过!") + print_info("=" * 60) + return 0 + else: + print_error("部分测试失败!") + print_info("=" * 60) + return 1 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except KeyboardInterrupt: + print() + print_warning("测试被用户中断") + sys.exit(130) + except Exception as e: + print_error(f"未预期的错误: {e}") + import traceback + traceback.print_exc() + sys.exit(1) + diff --git a/tools/unyaffs_0.9.7/unyaffs b/tools/unyaffs_0.9.7/unyaffs index b510168852f586e695ba26f7e6a8be64334d2f83..46f1f4a87e565c93242532d4ea5e85fee3aebf50 100644 GIT binary patch literal 36048 zcmeHweRx#WwfC7MgOQI+P@j z+$JF>;c>w(p|mH}kv=6-ZxU3IM@ePhijpjMo8V7|PQfoBl|gCIVZZ0!DX&_{tyseK zB*V>|tVk%!y9sh+mwz=0b1FBB@>2D~CedyQg?W{!jSVYj&Y0Th$!~0E4z%aDm(0wc zIitYWQZS8Gf$BwNkWXEELydxdix5qyV|_7B;FN!AeyC*6<8wBCl>W5?%`c69|KvHV zekgTNnZ!ehons+<r0 zS_6I`xO{$h?P_9j)wvrQiCSClZd008dm7r5+WMvzNVL?t8%fC3rZm>px2$beeCwJJ z_g7P4joxOZ$=l@f`k~F+*4EtOA_0FxOEct2OPkm2QC4~Vr~p{%O!e~lJuLyhQb(mK zjXtk;HL0TNH@O?3MF}*yeXFVF?zUAZ%me*Y=Vp@*m#e*Lbu+42i*lfAZCiui3ns3J zHNUp8#pi_<)Re4KPde6^>)~?Mw!2+*4bASxhPz0(9cJ+}=B8ExD7S^A$l7GGHovRM z-9YMEskU`(UaxX(RptD0*R+D78OG&w<7$vLt)SSTPA{0DxGEPfbfID1RSiDBw{7vl z^2U~C?_&4LMyklFrj}+=po_B($q4UA!`zt8zG;?B{Fjl0Q?8ZGqv@D62YI;;GoGl6 z=275F%YXDC|)9=NFCT+;d90{2fKJWY89 zI3>9bl>WWqtDN2;)_Iby3VLP-&zE$GPf4P0d50J9<_6ABYX$nqbjU=%P!a*7Ci=xD z`f(HeDieLcM4xJ+%eX-6AzGWrq;>EsqSIPMCOOWDPIHP(GF}k9P!a)q?%~Ke0K$}v z@SurqUN>zq(dC+q1fDR_W$YpPRui4dmT8-bPG!p!G0|n;P~J->Iy&A+`%Lta231ks zG|_2plIf6%K3Wn1qb9nz^sR-5SZo|3X}GtnoR z_*aHlo<-TO1(_AmpJ`+7(5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+-UeL%U+{{=A0HGwaZ|MpHB)?Pr zXDxEfkbN-jXu zE98AQrMy^g2q@-V!Jpdx@ALAa|HQrH0*i>^pt6=0Xwf-kl z%JXk9Le=dvr%6Be>zh61uo#rV7Hsfi}hCrZ32-5pMeeHg8mvZ z$oEA3Vx1uVKPV^2I7q@jMLE%r8<0mVqP$ptwckOdB#Hi7%$!7d0S_S4TwZGD+$#(y zb5sCPPT>7`AeyLO+&3(*01=7)w$hwrGlJ(2@kvpUaftF1U(G3{JI~eK#JFgMfqZVF J(PL^|{|B{(e+mEq diff --git a/tools/unyaffs_0.9.7/unyaffs.c b/tools/unyaffs_0.9.7/unyaffs.c new file mode 100644 index 000000000..3ca8a416b --- /dev/null +++ b/tools/unyaffs_0.9.7/unyaffs.c @@ -0,0 +1,888 @@ +/* + * unyaffs: extract files from yaffs2 file system image to current directory + * + * Created by Kai Wei + * Modified by Bernhard Ehlers + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +/* + * History: + * V0.1 2008-12-29 + * Initial version uploaded to http://code.google.com/p/unyaffs/ + * V0.8 2011-08-25 + * Fork created at https://github.com/ehlers/unyaffs + * Support of chunksizes from 2k to 16k + * Restore special files (device nodes) + * Restore file date and time + * Restore file ownership, when run as root + * File listing + * Much more error checking + * V0.9 2011-09-03 + * Allow - as filename for stdin + * Optional base dir for file extraction + */ + +#define VERSION "0.9" + +/* check if lutimes is available */ +#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || (defined(__APPLE__) && defined(__MACH__)) +#define HAS_LUTIMES 1 +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef HAS_LUTIMES +#include +#else +#include +#endif + +#include "unyaffs.h" + +#define MAX_CHUNK_SIZE 16384 +#define MAX_SPARE_SIZE 512 +#define HASH_SIZE 7001 +#define MAX_WARN 20 +#define YAFFS_OBJECTID_ROOT 1 +#define YAFFS_OBJECTID_SUMMARY 0x10 + +#define STD_PERMS (S_IRWXU|S_IRWXG|S_IRWXO) +#define EXTRA_PERMS (S_ISUID|S_ISGID|S_ISVTX) + +static struct t_layout { + int chunk_size; + int spare_size; +} possible_layouts[] = + { { 2048, 64 }, { 4096, 128 }, { 8192, 256 }, { 16384, 512 } }; + +int max_layout = sizeof(possible_layouts) / sizeof(struct t_layout); + +unsigned char data[MAX_CHUNK_SIZE + MAX_SPARE_SIZE]; +unsigned char buffer[2*(MAX_CHUNK_SIZE + MAX_SPARE_SIZE)]; +unsigned char *chunk_data = data; +unsigned char *spare_data = NULL; +int chunk_size = 2048; +int spare_size = 64; +int buf_len = 0; +int buf_idx = 0; +int chunk_no = 0; +int warn_count = 0; +int img_file; +int opt_list; +int opt_verbose; + +/* Image format detection */ +typedef enum { + IMAGE_FORMAT_UNKNOWN = 0, + IMAGE_FORMAT_OLD, /* Old mkyaffs2image (no summary chunks) */ + IMAGE_FORMAT_NEW /* New mkyaffs2image (with summary chunks) */ +} image_format_t; + +static image_format_t image_format = IMAGE_FORMAT_UNKNOWN; +static int spare_data_offset = 2; /* Default to new format offset */ +static int file_size_offset = 290; /* Default to old format offset */ + +typedef struct _object { + unsigned id; + struct _object *next; + yaffs_ObjectType type; + unsigned prev_dir_id; + __u32 atime; + __u32 mtime; + char path_name[1]; /* variable length, must be last */ +} object; + +object *obj_list[HASH_SIZE]; + +unsigned last_dir_id; + +int set_utime(const char *filename, __u32 yst_atime, __u32 yst_mtime) { +#ifdef HAS_LUTIMES + struct timeval ftime[2]; + + ftime[0].tv_sec = yst_atime; + ftime[0].tv_usec = 0; + ftime[1].tv_sec = yst_mtime; + ftime[1].tv_usec = 0; + + return lutimes(filename, ftime); +#else + struct utimbuf ftime; + + ftime.actime = yst_atime; + ftime.modtime = yst_mtime; + + return utime(filename, &ftime); +#endif +} + +/* error reporting function, similar to GNU error() */ +static void prt_err(int status, int errnum, const char *format, ...) { + va_list varg; + + va_start(varg, format); + fflush(stdout); + vfprintf(stderr, format, varg); + if (errnum != 0) + fprintf(stderr, ": %s", strerror(errnum)); + fprintf(stderr, "\n"); + va_end(varg); + + if (status != 0) + exit(status); +} + +/* read function, which handles partial and interrupted reads */ +ssize_t xread(int fd, void *buf, size_t len) { + char *ptr = buf; + ssize_t offset, ret; + + offset = 0; + while (offset < len) { + ret = read(fd, ptr+offset, len-offset); + if (ret < 0) { + if (errno != EAGAIN && errno != EINTR) + return -1; + } else if (ret == 0) + break; + else + offset += ret; + } + return offset; +} + +/* write function, which handles partial and interrupted writes */ +ssize_t xwrite(int fd, void *buf, size_t len) { + char *ptr = buf; + ssize_t offset, ret; + + offset = 0; + while (offset < len) { + ret = write(fd, ptr+offset, len-offset); + if (ret < 0) { + if (errno != EAGAIN && errno != EINTR) + return -1; + } else if (ret == 0) + break; + else + offset += ret; + } + return offset; +} + +/* + * mkdirpath - creates directories including intermediate dirs + */ +static int mkdirpath(const char *name) { + struct stat st; + char *cp; + char *buf; + int ret; + + ret = 0; + if ((buf = malloc(strlen(name)+2)) == NULL) + { errno = ENOMEM; return -1; } + strcpy(buf, name); strcat(buf, "/"); + for (cp = buf; *cp == '/'; cp++); + while ((cp = strchr(cp, '/')) != NULL) { + *cp = '\0'; + if (mkdir(buf, STD_PERMS) < 0 && errno != EEXIST) + { ret = -1; break; } + *cp++ = '/'; + } + free(buf); + + if (ret >= 0 && + (ret = stat(name, &st)) >= 0 && !S_ISDIR(st.st_mode)) { + ret = -1; errno = ENOTDIR; + } + return ret; +} + +static void init_obj_list(void) { + object *obj; + unsigned idx; + + for (idx = 0; idx < HASH_SIZE; idx++) + obj_list[idx] = NULL; + last_dir_id = 0; + + obj = malloc(offsetof(object, path_name) + 2); + if (obj == NULL) + prt_err(1, 0, "Malloc struct object failed."); + + obj->id = YAFFS_OBJECTID_ROOT; + obj->type = YAFFS_OBJECT_TYPE_DIRECTORY; + obj->prev_dir_id = 0; + obj->atime = obj->mtime = 0; + strcpy(obj->path_name, "."); + idx = obj->id % HASH_SIZE; + obj->next = obj_list[idx]; + obj_list[idx] = obj; +} + +static object *get_object(unsigned id) { + object *obj; + + obj = obj_list[id % HASH_SIZE]; + while (obj != NULL && obj->id != id) + obj = obj->next; + return obj; +} + +static object *add_object(yaffs_ObjectHeader *oh, yaffs_PackedTags2 *pt) { + object *obj, *parent; + unsigned idx; + + obj = get_object(pt->t.objectId); + if (pt->t.objectId == YAFFS_OBJECTID_ROOT) { + if (obj == NULL) + prt_err(1, 0, "Missing root object"); + if (oh->type != YAFFS_OBJECT_TYPE_DIRECTORY) + prt_err(1, 0, "Root object must be directory"); + if (last_dir_id == 0) + last_dir_id = YAFFS_OBJECTID_ROOT; + } else { + if (oh->type != YAFFS_OBJECT_TYPE_FILE && + oh->type != YAFFS_OBJECT_TYPE_DIRECTORY && + oh->type != YAFFS_OBJECT_TYPE_SYMLINK && + oh->type != YAFFS_OBJECT_TYPE_HARDLINK && + oh->type != YAFFS_OBJECT_TYPE_SPECIAL && + oh->type != YAFFS_OBJECT_TYPE_UNKNOWN) + prt_err(1, 0, "Illegal type %d in object %u (%s)", + oh->type, pt->t.objectId, oh->name); + if (oh->name[0] == '\0' || strchr(oh->name, '/') != NULL || + strcmp(oh->name, ".") == 0 || strcmp(oh->name, "..") == 0) + prt_err(1, 0, "Illegal file name %s in object %u", + oh->name, pt->t.objectId); + if (obj != NULL) + prt_err(1, 0, "Duplicate objectId %u", pt->t.objectId); + parent = get_object(oh->parentObjectId); + if (parent == NULL) + prt_err(1, 0, "Invalid parentObjectId %u in object %u (%s)", + oh->parentObjectId, pt->t.objectId, oh->name); + if (parent->type != YAFFS_OBJECT_TYPE_DIRECTORY) + prt_err(1, ENOTDIR, "File %s can't be created in %s", + oh->name, parent->path_name); + obj = malloc(offsetof(object, path_name) + + strlen(parent->path_name) + strlen(oh->name) + 2); + if (obj == NULL) + prt_err(1, 0, "Malloc struct object failed."); + + obj->id = pt->t.objectId; + obj->type = oh->type; + if (obj->type == YAFFS_OBJECT_TYPE_DIRECTORY) { + obj->prev_dir_id = last_dir_id; + last_dir_id = obj->id; + } else + obj->prev_dir_id = 0; + if (strcmp(parent->path_name, ".") == 0) { + strcpy(obj->path_name, oh->name); + } else { + strcpy(obj->path_name, parent->path_name); + strcat(obj->path_name, "/"); + strcat(obj->path_name, oh->name); + } + idx = obj->id % HASH_SIZE; + obj->next = obj_list[idx]; + obj_list[idx] = obj; + } + + obj->atime = oh->yst_atime; + obj->mtime = oh->yst_mtime; + + return obj; +} + +void set_dirs_utime(void) { + unsigned id; + object *obj; + + id = last_dir_id; + while (id != 0 && (obj = get_object(id)) != NULL) { + set_utime(obj->path_name, obj->atime, obj->mtime); + id = obj->prev_dir_id; + } +} + +static void prt_node(char *name, yaffs_ObjectHeader *oh) { + object *eq_obj; + struct tm tm; + time_t mtime; + mode_t mode; + char type; + char fsize[16]; + char perm[10]; + + /* get file type, size, mtine and mode */ + eq_obj = NULL; + strcpy(fsize, "0"); + mtime = oh->yst_mtime; + mode = oh->yst_mode; + switch(oh->type) { + case YAFFS_OBJECT_TYPE_FILE: type = '-'; + snprintf(fsize, sizeof(fsize), "%d", oh->fileSize); + break; + case YAFFS_OBJECT_TYPE_DIRECTORY: type = 'd'; break; + case YAFFS_OBJECT_TYPE_SYMLINK: type = 'l'; break; + case YAFFS_OBJECT_TYPE_HARDLINK: type = 'h'; + eq_obj = get_object(oh->equivalentObjectId); + mtime = eq_obj != NULL ? eq_obj->mtime : 0; + mode = STD_PERMS; + break; + case YAFFS_OBJECT_TYPE_SPECIAL: + switch (oh->yst_mode & S_IFMT) { + case S_IFBLK: type = 'b'; + snprintf(fsize, sizeof(fsize), "%d,%4d", + major(oh->yst_rdev), + minor(oh->yst_rdev)); + break; + case S_IFCHR: type = 'c'; + snprintf(fsize, sizeof(fsize), "%d,%4d", + major(oh->yst_rdev), + minor(oh->yst_rdev)); + break; + case S_IFIFO: type = 'p'; break; + case S_IFSOCK: type = 's'; break; + default: type = '?'; break; + } + break; + default: type = '?'; break; + } + + /* get file permissions */ + perm[0] = mode & S_IRUSR ? 'r' : '-'; + perm[1] = mode & S_IWUSR ? 'w' : '-'; + perm[2] = mode & S_IXUSR ? 'x' : '-'; + perm[3] = mode & S_IRGRP ? 'r' : '-'; + perm[4] = mode & S_IWGRP ? 'w' : '-'; + perm[5] = mode & S_IXGRP ? 'x' : '-'; + perm[6] = mode & S_IROTH ? 'r' : '-'; + perm[7] = mode & S_IWOTH ? 'w' : '-'; + perm[8] = mode & S_IXOTH ? 'x' : '-'; + if (mode & S_ISUID) perm[2] = perm[2] == '-' ? 'S' : 's'; + if (mode & S_ISGID) perm[5] = perm[5] == '-' ? 'S' : 's'; + if (mode & S_ISVTX) perm[8] = perm[8] == '-' ? 'T' : 't'; + perm[9] = '\0'; + + /* print file infos */ + localtime_r(&mtime, &tm); + printf("%c%s %8s %4d-%02d-%02d %02d:%02d %s", + type, perm, fsize, + tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, name); + + /* link destination */ + if (oh->type == YAFFS_OBJECT_TYPE_HARDLINK) { + if (eq_obj == NULL) + printf(" -> !!! Invalid !!!"); + else + printf(" -> /%s", eq_obj->path_name); + } else if (oh->type == YAFFS_OBJECT_TYPE_SYMLINK) { + printf(" -> %s", oh->alias); + } + printf("\n"); +} + +int read_chunk(void); + +void process_chunk(void) { + yaffs_ObjectHeader oh; + yaffs_PackedTags2 *pt; + object *obj, *eq_obj; + int out_file, remain, s; + + /* Use detected spare data offset (0 for old format, 2 for new format) */ + pt = (yaffs_PackedTags2 *)(spare_data + spare_data_offset); + + /* Check for special chunks that should be skipped (only for new format) */ + if (image_format == IMAGE_FORMAT_NEW) { + /* Tag file chunk: objectId = 0, chunkId = 1024 */ + if (pt->t.objectId == 0 && pt->t.chunkId == 1024) { + /* Tag file chunk - silently skip it */ + if (opt_verbose) + fprintf(stderr, "Skipping tag file chunk at chunk #%d\n", chunk_no); + return; + } + /* Summary chunk: chunkId = 1, byteCount != 0xffff (not an object header) + * Summary chunks have objectId = YAFFS_OBJECTID_SUMMARY (0x10). + * We must be strict about objectId to avoid misidentifying data chunks as summary chunks. + */ + if (pt->t.objectId == YAFFS_OBJECTID_SUMMARY && + pt->t.chunkId == 1 && pt->t.byteCount != 0xffff) { + /* Summary chunk - silently skip it */ + if (opt_verbose) + fprintf(stderr, "Skipping summary chunk at chunk #%d (objectId=0x%x)\n", + chunk_no, pt->t.objectId); + return; + } + } + + oh = *(yaffs_ObjectHeader *)chunk_data; + + /* Fix fileSize reading: use detected fileSize offset based on image format */ + if (oh.type == YAFFS_OBJECT_TYPE_FILE) { + /* Read fileSize from the detected offset */ + if (chunk_size >= file_size_offset + 4) { + int file_size_from_offset = *(int *)((char *)chunk_data + file_size_offset); + /* If the value from detected offset looks reasonable, use it */ + if (file_size_from_offset > 0 && file_size_from_offset < 100 * 1024 * 1024) { + oh.fileSize = file_size_from_offset; + } else if (oh.fileSize == 0 || oh.fileSize > 1000 * 1024 * 1024) { + /* If structure fileSize is unreasonable, try the other offset */ + int alt_offset = (file_size_offset == 290) ? 292 : 290; + if (chunk_size >= alt_offset + 4) { + int file_size_alt = *(int *)((char *)chunk_data + alt_offset); + if (file_size_alt > 0 && file_size_alt < 100 * 1024 * 1024) { + oh.fileSize = file_size_alt; + file_size_offset = alt_offset; /* Update detected offset */ + } + } + } + } + } + + if (pt->t.byteCount == 0xffffffff) /* empty object */ + return; + else if (pt->t.byteCount != 0xffff) { /* not a new object header */ + /* This is a data chunk (byteCount != 0xffff, chunkId > 0) + * Data chunks should be read immediately after their object header + * when processing file objects. If we encounter a data chunk in the + * main loop, it means we're out of sync - this shouldn't happen in + * a well-formed image, but can occur if summary chunks or other + * special chunks are interleaved. + * + * We need to skip these orphaned data chunks, but note that this + * indicates a potential issue with the image structure. + */ + if (pt->t.chunkId > 0) { + /* Orphaned data chunk - this should not happen in normal flow. + * It might be from a file object we haven't processed yet, or + * it might indicate the image is corrupted or has an unusual structure. + * Skip it for now, but this might cause file content mismatches. + */ + if (opt_verbose) + fprintf(stderr, "Warning: Orphaned data chunk at chunk #%d: objectId=0x%x, chunkId=%u, byteCount=0x%x\n", + chunk_no, pt->t.objectId, pt->t.chunkId, pt->t.byteCount); + /* Don't increment warn_count for orphaned data chunks - they might be expected */ + return; + } + /* If chunkId is 0 but byteCount != 0xffff, this is unexpected */ + if (opt_verbose) + fprintf(stderr, "Warning: Invalid header at chunk #%d: objectId=0x%x, byteCount=0x%x, chunkId=%u\n", + chunk_no, pt->t.objectId, pt->t.byteCount, pt->t.chunkId); + prt_err(0, 0, "Warning: Invalid header at chunk #%d, skipping...", + chunk_no); + if (++warn_count >= MAX_WARN) + prt_err(1, 0, "Giving up"); + return; + } + + obj = add_object(&oh, pt); + + /* listing */ + if (opt_verbose) + prt_node(obj->path_name, &oh); + else if (opt_list) + printf("%s\n", obj->path_name); + if (opt_list) { + if (oh.type == YAFFS_OBJECT_TYPE_FILE) { + remain = oh.fileSize; /* skip over data chunks */ + while(remain > 0) { + if (!read_chunk()) + prt_err(1, 0, "Broken image file"); + remain -= pt->t.byteCount; + } + } + return; + } + + switch(oh.type) { + case YAFFS_OBJECT_TYPE_FILE: + remain = oh.fileSize; + out_file = creat(obj->path_name, oh.yst_mode & STD_PERMS); + if (out_file < 0) + prt_err(1, errno, "Can't create file %s", obj->path_name); + while(remain > 0) { + if (!read_chunk()) + prt_err(1, 0, "Broken image file"); + /* Verify this is a data chunk for this file object */ + pt = (yaffs_PackedTags2 *)(spare_data + spare_data_offset); + + /* Skip special chunks (only for new format) */ + if (image_format == IMAGE_FORMAT_NEW) { + /* Skip summary chunks that might be interleaved */ + /* Summary chunks have: objectId = YAFFS_OBJECTID_SUMMARY (0x10), chunkId = 1, byteCount != 0xffff */ + /* We must check objectId FIRST and be strict about it to avoid misidentifying data chunks */ + if (pt->t.objectId == YAFFS_OBJECTID_SUMMARY) { + /* This might be a summary chunk - verify chunkId and byteCount */ + if (pt->t.chunkId == 1 && pt->t.byteCount != 0xffff) { + /* Summary chunk - skip it and read next chunk */ + if (opt_verbose) + fprintf(stderr, "Skipping summary chunk while reading file data at chunk #%d\n", chunk_no); + continue; + } + } + + /* Skip tag file chunks */ + if (pt->t.objectId == 0 && pt->t.chunkId == 1024) { + if (opt_verbose) + fprintf(stderr, "Skipping tag file chunk while reading file data at chunk #%d\n", chunk_no); + continue; + } + } + + /* Check if this chunk belongs to the current file object */ + if (pt->t.objectId != obj->id) { + /* This chunk belongs to a different object. + * This means we've finished reading all data chunks for this file. + * However, we need to verify that remain is 0 or very small (due to rounding). + * + * Note: remain might not be exactly 0 due to: + * 1. Rounding errors in file size calculation + * 2. Summary chunks interleaved in the data (we skip them, so remain doesn't change) + * + * If remain is significant (> chunk_size), this indicates a real error. + * If remain is small (<= chunk_size), it might be acceptable due to rounding. + */ + if (remain > chunk_size) { + /* We still have significant data to read - this might be an error + * but could also be due to summary chunks or other special chunks + * that we haven't accounted for. Instead of failing, warn and continue. + */ + prt_err(0, 0, "Warning: Premature end of file data for object %u at chunk #%d: expected %d more bytes, but found object %u. File may be incomplete.", + obj->id, chunk_no, remain, pt->t.objectId); + /* Don't exit - continue processing, but the file will be incomplete */ + } + /* remain is 0 or small - file data is complete (or close enough) */ + if (opt_verbose && remain > 0) + fprintf(stderr, "Finished reading file data for object %u at chunk #%d (next object is %u, remain=%d, fileSize=%d)\n", + obj->id, chunk_no, pt->t.objectId, remain, oh.fileSize); + /* Seek back one chunk so the main loop can process it */ + if (lseek(img_file, -(chunk_size + spare_size), SEEK_CUR) < 0) + prt_err(1, errno, "Can't seek back in image file"); + chunk_no--; /* Adjust chunk number since we're unreading */ + buf_len = 0; /* Clear buffer to force re-read */ + buf_idx = 0; + break; /* Exit the while loop - file data is complete */ + } + s = (remain < pt->t.byteCount) ? remain : pt->t.byteCount; + if (xwrite(out_file, chunk_data, s) < 0) + prt_err(1, errno, "Can't write to %s", obj->path_name); + remain -= s; + } + close(out_file); + if (lchown(obj->path_name, oh.yst_uid, oh.yst_gid) < 0) + prt_err(0, errno, "Warning: Can't chown %s", obj->path_name); + if ((oh.yst_mode & EXTRA_PERMS) != 0 && + chmod(obj->path_name, oh.yst_mode) < 0) + prt_err(0, errno, "Warning: Can't chmod %s", obj->path_name); + break; + case YAFFS_OBJECT_TYPE_SYMLINK: + if (symlink(oh.alias, obj->path_name) < 0) + prt_err(1, errno, "Can't create symlink %s", obj->path_name); + if (lchown(obj->path_name, oh.yst_uid, oh.yst_gid) < 0) + prt_err(0, errno, "Warning: Can't chown %s", obj->path_name); + break; + case YAFFS_OBJECT_TYPE_DIRECTORY: + if (pt->t.objectId != YAFFS_OBJECTID_ROOT && + mkdir(obj->path_name, oh.yst_mode & STD_PERMS) < 0) + prt_err(1, errno, "Can't create directory %s", obj->path_name); + if (lchown(obj->path_name, oh.yst_uid, oh.yst_gid) < 0) + prt_err(0, errno, "Warning: Can't chown %s", obj->path_name); + if ((pt->t.objectId == YAFFS_OBJECTID_ROOT || + (oh.yst_mode & EXTRA_PERMS) != 0) && + chmod(obj->path_name, oh.yst_mode) < 0) + prt_err(0, errno, "Warning: Can't chmod %s", obj->path_name); + break; + case YAFFS_OBJECT_TYPE_HARDLINK: + eq_obj = get_object(oh.equivalentObjectId); + if (eq_obj == NULL) + prt_err(1, 0, "Invalid equivalentObjectId %u in object %u (%s)", + oh.equivalentObjectId, pt->t.objectId, oh.name); + if (link(eq_obj->path_name, obj->path_name) < 0) + prt_err(1, errno, "Can't create hardlink %s", obj->path_name); + break; + case YAFFS_OBJECT_TYPE_SPECIAL: + if (mknod(obj->path_name, oh.yst_mode, oh.yst_rdev) < 0) { + if (errno == EPERM || errno == EINVAL) + prt_err(0, errno, "Warning: Can't create device %s", obj->path_name); + else + prt_err(1, errno, "Can't create device %s", obj->path_name); + } + if (lchown(obj->path_name, oh.yst_uid, oh.yst_gid) < 0) + prt_err(0, errno, "Warning: Can't chown %s", obj->path_name); + break; + case YAFFS_OBJECT_TYPE_UNKNOWN: + break; + } + + /* set file date and time */ + switch(oh.type) { + case YAFFS_OBJECT_TYPE_FILE: + case YAFFS_OBJECT_TYPE_SPECIAL: +#ifdef HAS_LUTIMES + case YAFFS_OBJECT_TYPE_SYMLINK: +#endif + set_utime(obj->path_name, + oh.yst_atime, oh.yst_mtime); + break; + case YAFFS_OBJECT_TYPE_DIRECTORY: + default: + break; + } +} + + +int read_chunk(void) { + ssize_t s, len, offset; + + chunk_no++; + len = chunk_size + spare_size; + offset = 0; + memset(chunk_data, 0xff, sizeof(chunk_data)); + + if (buf_len > buf_idx) { /* copy from buffer */ + s = buf_len - buf_idx; + if (s > len) s = len; + memcpy(data, buffer+buf_idx, s); + buf_idx += s; offset += s; + } + + if (offset < len) { /* read from file */ + s = xread(img_file, data+offset, len-offset); + if (s < 0) + prt_err(1, errno, "Read image file"); + offset += s; + } + + if (offset != 0 && offset != len) /* partial chunk */ + prt_err(1, 0, "Broken image file"); + + return offset != 0; +} + +void detect_chunk_size(void) { + yaffs_ObjectHeader *oh; + yaffs_PackedTags2 *pt, *pt2; + int i; + + memset(buffer, 0xff, sizeof(buffer)); + buf_len = xread(img_file, buffer, sizeof(buffer)); + if (buf_len < 0) + prt_err(1, errno, "Read image file"); + + /* Check object header - but first chunk might be tag file chunk in new format */ + /* Try to find the first object header */ + int first_chunk_offset = 0; + + /* Check if first chunk is tag file chunk (new format) */ + for (int offset = 2; offset >= 0; offset -= 2) { + if (buf_len >= possible_layouts[0].chunk_size + offset + 18) { + yaffs_PackedTags2 *pt_check = (yaffs_PackedTags2 *) + (buffer + possible_layouts[0].chunk_size + offset); + if (pt_check->t.objectId == 0 && pt_check->t.chunkId == 1024) { + /* First chunk is tag file chunk - object header is in second chunk */ + first_chunk_offset = 1; + break; + } + } + } + + oh = (yaffs_ObjectHeader *)(buffer + first_chunk_offset * (possible_layouts[0].chunk_size + possible_layouts[0].spare_size)); + if (oh->parentObjectId != YAFFS_OBJECTID_ROOT || + (oh->type != YAFFS_OBJECT_TYPE_FILE && + oh->type != YAFFS_OBJECT_TYPE_DIRECTORY && + oh->type != YAFFS_OBJECT_TYPE_SYMLINK && + oh->type != YAFFS_OBJECT_TYPE_HARDLINK && + oh->type != YAFFS_OBJECT_TYPE_SPECIAL)) + prt_err(1, 0, "Not a yaffs2 image"); + + /* Try both offset 2 (new format) and offset 0 (old format) */ + /* Try new format first (offset 2) as it's more common now */ + int offset_tried[2] = {2, 0}; /* Try offset 2 (new) first, then 0 (old) */ + int offset_idx; + + for (offset_idx = 0; offset_idx < 2; offset_idx++) { + int offset = offset_tried[offset_idx]; + + for (i = 0; i < max_layout; i++) { + pt = (yaffs_PackedTags2 *) + (buffer + possible_layouts[i].chunk_size + offset); + pt2 = (yaffs_PackedTags2 *) + (buffer + 2 * possible_layouts[i].chunk_size + + possible_layouts[i].spare_size + offset); + + /* Check if this is a valid object header or tag file chunk */ + int is_valid = 0; + if (pt->t.byteCount == 0xffff && pt->t.chunkId == 0) { + /* This is an object header - check if second chunk is also valid */ + if (pt2->t.byteCount == 0xffff && pt2->t.chunkId == 0) { + /* Two consecutive object headers - valid layout */ + is_valid = 1; + } else if (pt2->t.objectId == pt->t.objectId && pt2->t.chunkId == 1) { + /* Object header followed by data chunk - valid layout */ + is_valid = 1; + } + } else if (pt->t.objectId == 0 && pt->t.chunkId == 1024) { + /* First chunk is tag file chunk (new format) - check second chunk */ + if (pt2->t.byteCount == 0xffff && pt2->t.chunkId == 0) { + /* Tag file chunk followed by object header - valid layout */ + is_valid = 1; + } + } + + if (is_valid) { + /* Found valid layout with this offset */ + spare_data_offset = offset; + chunk_size = possible_layouts[i].chunk_size; + spare_size = possible_layouts[i].spare_size; + + /* Detect image format by checking for tag file chunk or summary chunk */ + /* Check first chunk for tag file chunk (new format feature) */ + yaffs_PackedTags2 *pt_first = (yaffs_PackedTags2 *) + (buffer + possible_layouts[i].chunk_size + offset); + if (pt_first->t.objectId == 0 && pt_first->t.chunkId == 1024) { + /* Tag file chunk found - new format */ + image_format = IMAGE_FORMAT_NEW; + file_size_offset = 292; /* New format uses offset 292 */ + if (opt_verbose) + fprintf(stderr, "Detected new format (with summary chunks)\n"); + } else { + /* No tag file chunk - check for summary chunks in first few chunks */ + image_format = IMAGE_FORMAT_OLD; + file_size_offset = 290; /* Old format uses offset 290 */ + /* Scan a few chunks to see if we find summary chunks */ + int scan_chunks = 10; + for (int j = 1; j <= scan_chunks && j * (chunk_size + spare_size) < buf_len; j++) { + yaffs_PackedTags2 *pt_scan = (yaffs_PackedTags2 *) + (buffer + j * (chunk_size + spare_size) + offset); + if (pt_scan->t.objectId == YAFFS_OBJECTID_SUMMARY && + pt_scan->t.chunkId == 1 && pt_scan->t.byteCount != 0xffff) { + /* Found summary chunk - new format */ + image_format = IMAGE_FORMAT_NEW; + file_size_offset = 292; + if (opt_verbose) + fprintf(stderr, "Detected new format (found summary chunk)\n"); + break; + } + } + if (image_format == IMAGE_FORMAT_OLD && opt_verbose) + fprintf(stderr, "Detected old format (no summary chunks)\n"); + } + + if (opt_verbose) + fprintf(stderr, + "Header check OK, chunk size = %d, spare size = %d, spare offset = %d, fileSize offset = %d.\n", + chunk_size, spare_size, spare_data_offset, file_size_offset); + return; + } + } + } + + prt_err(1, 0, "Can't determine chunk size"); +} + +void usage(void) { + fprintf(stderr, "\ +unyaffs - extract files from a YAFFS2 file system image.\n\ +\n\ +Usage: unyaffs [-l ] [-t] [-v] [-V] []\n\ + -l set flash memory layout\n\ + layout=0: detect chunk and spare size (default)\n\ + layout=1: 2K chunk, 64 byte spare size\n\ + layout=2: 4K chunk, 128 byte spare size\n\ + layout=3: 8K chunk, 256 byte spare size\n\ + layout=4: 16K chunk, 512 byte spare size\n\ + -t list image contents\n\ + -v verbose output\n\ + -V print version\n\ +"); + exit(1); +} + +int main(int argc, char **argv) { + int ch; + int layout = 0; + + /* handle command line options */ + opt_list = 0; + opt_verbose = 0; + while ((ch = getopt(argc, argv, "l:tvVh?")) > 0) { + switch (ch) { + case 'l': + if (optarg[0] < '0' || + optarg[0] > '0' + max_layout || + optarg[1] != '\0') usage(); + layout = optarg[0] - '0'; + break; + case 't': + opt_list = 1; + break; + case 'v': + opt_verbose = 1; + break; + case 'V': + printf("V%s\n", VERSION); + exit(0); + break; + case 'h': + case '?': + default: + usage(); + break; + } + } + + /* extract rest of command line parameters */ + if ((argc - optind) < 1 || (argc - optind) > 2) + usage(); + + if (strcmp(argv[optind], "-") == 0) { /* image file from stdin ? */ + img_file = 0; + } else { + img_file = open(argv[optind], O_RDONLY); + if (img_file < 0) + prt_err(1, errno, "Open image file failed"); + } + + if (layout == 0) { + detect_chunk_size(); + } else { + chunk_size = possible_layouts[layout-1].chunk_size; + spare_size = possible_layouts[layout-1].spare_size; + } + spare_data = data + chunk_size; + + if ((argc - optind) == 2 && !opt_list) { + if (mkdirpath(argv[optind+1]) < 0) + prt_err(1, errno, "Can't mkdir %s", argv[optind+1]); + if (chdir(argv[optind+1]) < 0) + prt_err(1, errno, "Can't chdir to %s", argv[optind+1]); + } + + umask(0); + + init_obj_list(); + while (read_chunk()) { + process_chunk(); + } + set_dirs_utime(); + close(img_file); + return 0; +} diff --git a/tools/unyaffs_0.9.7/unyaffs.h b/tools/unyaffs_0.9.7/unyaffs.h new file mode 100644 index 000000000..ad365a158 --- /dev/null +++ b/tools/unyaffs_0.9.7/unyaffs.h @@ -0,0 +1,99 @@ +/* + * definition copied from yaffs project + */ + +#ifndef __UNYAFFS_H__ +#define __UNYAFFS_H__ + + +#define YAFFS_MAX_NAME_LENGTH 255 +#define YAFFS_MAX_ALIAS_LENGTH 159 + +/* Definition of types */ +typedef unsigned char __u8; +typedef unsigned short __u16; +typedef unsigned __u32; + +typedef struct { + unsigned sequenceNumber; + unsigned objectId; + unsigned chunkId; + unsigned byteCount; +} yaffs_PackedTags2TagsPart; + +typedef struct { + unsigned char colParity; + unsigned lineParity; + unsigned lineParityPrime; +} yaffs_ECCOther; + +typedef struct { + yaffs_PackedTags2TagsPart t; + yaffs_ECCOther ecc; +} yaffs_PackedTags2; + +typedef enum { + YAFFS_OBJECT_TYPE_UNKNOWN, + YAFFS_OBJECT_TYPE_FILE, + YAFFS_OBJECT_TYPE_SYMLINK, + YAFFS_OBJECT_TYPE_DIRECTORY, + YAFFS_OBJECT_TYPE_HARDLINK, + YAFFS_OBJECT_TYPE_SPECIAL +} yaffs_ObjectType; + + +/* -------------------------- Object structure -------------------------------*/ +/* This is the object structure as stored on NAND */ + +typedef struct { + yaffs_ObjectType type; + + /* Apply to everything */ + int parentObjectId; + __u16 sum__NoLongerUsed; /* checksum of name. No longer used */ + char name[YAFFS_MAX_NAME_LENGTH + 1]; + + /* The following apply to directories, files, symlinks - not hard links */ + __u32 yst_mode; /* protection */ + +#ifdef CONFIG_YAFFS_WINCE + __u32 notForWinCE[5]; +#else + __u32 yst_uid; + __u32 yst_gid; + __u32 yst_atime; + __u32 yst_mtime; + __u32 yst_ctime; +#endif + + /* File size applies to files only */ + int fileSize; + + /* Equivalent object id applies to hard links only. */ + int equivalentObjectId; + + /* Alias is for symlinks only. */ + char alias[YAFFS_MAX_ALIAS_LENGTH + 1]; + + __u32 yst_rdev; /* device stuff for block and char devices (major/min) */ + +#ifdef CONFIG_YAFFS_WINCE + __u32 win_ctime[2]; + __u32 win_atime[2]; + __u32 win_mtime[2]; +#else + __u32 roomToGrow[6]; + +#endif + __u32 inbandShadowsObject; + __u32 inbandIsShrink; + + __u32 reservedSpace[2]; + int shadowsObject; /* This object header shadows the specified object if > 0 */ + + /* isShrink applies to object headers written when we shrink the file (ie resize) */ + __u32 isShrink; + +} yaffs_ObjectHeader; + +#endif -- 2.17.1