├── LICENSE ├── README.md ├── bootldr.sh ├── bootloader_unpacker.c ├── extras ├── dumper.sh ├── etc │ └── hammerhead.conf ├── img │ └── recovery.cust.hh44.img └── writer.sh └── imgdata_tool.c /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 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 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bootloader unpacker (Nexus 4, 5 and 7) and imgdata tool (Nexus 5) 2 | 3 | An unpacker for the bootloader.img file included in Google's factory images and a tool to unpack, update, create and view the contents of the imgdata.img file contained in bootloader.img files for the Nexus 5 and present on it as partition #17. 4 | 5 | The tools can be used with Nexus smartphones only (no tablet support). 6 | 7 | ## Configuration 8 | 9 | Both adb and fastboot tools should be in your path, as they are used by the dumper.sh and writer.sh scripts. 10 | They can be downloaded as part of the Android SDK tools: http://developer.android.com/sdk/installing/index.html?pkg=tools 11 | 12 | ## The programs 13 | **bootloader_unpacker**: Unpacks the bootloader.img file included in the factory images provided by Google. Outputs them in the working directory. 14 | 15 | Instructions for compilation: 16 | ``` 17 | gcc bootloader_unpacker.c -o bunp 18 | ``` 19 | 20 | Usage: 21 | ``` 22 | ./bunp 23 | ``` 24 | 25 | **imgdata_tool**: Tool to work with the Android imgdata.img present in the bootloader.img for the LG Nexus 5 and listed as partition number 17. It can list the contents and stored options, unpack to PNG, change any of the stored options and change any packed image with a given PNG image. Can also create a new imgdata.img or add images to an existing imgdata.img blob. 26 | 27 | Instructions for compilation include two options to compile: 28 | 29 | ``` 30 | dynamic: gcc -o iunp imgdata_tool.c -lpng 31 | static: gcc -o iunp imgdata_tool.c -lpng -lz -lm -static 32 | ``` 33 | 34 | Usage: 35 | 36 | ``` 37 | ./iunp -l : list info and contents 38 | -x : extract contents in working dir 39 | -u [...] : update "file1" in with given coordinates and size, use - to keep existing value 40 | -r [:X[:Y]] [...] : replace "file1" in with given file and optionally new coordinates 41 | -c [...] : creates a new imgdata.img (overwriting any existing!). 42 | 43 | Arguments X, Y, W, H are 32bit positive integers and can be given as 0x and 0 as well. "file1" name should not be longer than 16 chars, excluding extension, and be in current dir. 44 | ``` 45 | ## Included scripts 46 | **bootldr.sh**: Unpacks the bootloader.img and adds zeroes to the extracted images to have the same size as their corresponding partitions. Output is every processed partition on a newline. This facilitates comparing dumped partitions with those extracted from a bootloader.img file. 47 | 48 | It needs the bootloader_unpacker, so compile bootloader_unpacker: 49 | 50 | ``` 51 | gcc bootloader_unpacker.c -o bunp 52 | ``` 53 | 54 | Usage: 55 | ``` 56 | ./bootldr.sh 57 | ``` 58 | 59 | **writer.sh**: Writes the contents of an image to the flashchip of an Android device. Only tested on hammerhead (LG Nexus 5 Android 4.4) 60 | Needed binaries are: adb, fastboot, netstat and depending on the write method also nc and gzip. See config for options. 61 | 62 | Usage: 63 | ``` 64 | ./writer.sh [device-serial] 65 | ``` 66 | 67 | **dumper.sh**: Dumps the contents of the flashchip or a partition of an Android device. Only tested on hammerhead (LG Nexus 5 Android 4.4) 68 | Needed binaries: adb, fastboot, netstat and depending on the dump method also pv, nc and gzip. See config for options. 69 | 70 | Usage: 71 | ``` 72 | ./dumper.sh [device-serial] 73 | ``` 74 | 75 | 76 | ## Example 77 | So you unlocked your Nexus 5 and want to get rid of the unlocked symbol when you boot your phone. As the factory image is rather large to download just to disable the symbol, you want to dump the imgdata.img partition first: 78 | 79 | ``` 80 | ./dumper.sh ./etc/hammerhead.conf imgdata.img 5555 81 | ``` 82 | 83 | We list the contents of the dumped partition and note the original Width and Height of the unlocked image: 84 | ``` 85 | ./iunp -l imgdata.img 86 | ``` 87 | Then we disable the unlocked symbol (compile the imgdata_tool first!): 88 | ``` 89 | ./iunp -u imgdata.img unlocked:-:-:0:0 90 | ``` 91 | 92 | We verify that the Width and Height are set to 0 for the unlocked image: 93 | ``` 94 | ./iunp -l imgdata.img 95 | ``` 96 | And then we write the changes to our phone: 97 | ``` 98 | ./writer.sh ./etc/hammerhead.conf imgdata.img 5555 99 | ``` 100 | 101 | ## License 102 | 103 | This software is released under the GNU GENERAL PUBLIC license (see LICENSE for details). 104 | -------------------------------------------------------------------------------- /bootldr.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Initially developed at Ghent University as part of a masters thesis promoted 3 | # by prof. dr. ir. Bjorn De Sutter of the Computer Systems Lab in cooperation with ir. Daan Raman from NVISO. 4 | # Author: Christophe Beauval 5 | # Version: 20140220 6 | # Description: Unpacks the bootloader.img and adds zeroes to the extracted 7 | # images to have the same size as their corresponding partitions. 8 | # Instructions: compile bootldr_unpacker: gcc bootloader_unpacker.c -o bunp 9 | # 10 | ### CONFIG BEGIN ### 11 | bunp="./bunp" 12 | 13 | # Keep every partition on a newline, format: partitionname:size_in_bytes 14 | ptable=" 15 | aboot:524288 16 | rpm:524288 17 | tz:524288 18 | sbl1:1048576 19 | sdi:524288 20 | imgdata:3145728 21 | " 22 | ### CONFIG END ### 23 | 24 | [[ ! -f "$1" ]] && echo "Usage: $0 " && exit 2 25 | [[ ! -f "$bunp" ]] && gcc bootloader_unpacker.c -o bunp 26 | 27 | # Unpack with own unpacker, gives partition names on a new line 28 | parts="$("$bunp" "$1")" 29 | 30 | # Add zeroes according to ptable 31 | for part in $parts; do 32 | psize=$(stat -c %s "$part.img") 33 | tsize=$(echo "$ptable" | sed -n "s/^$part://p") 34 | towrite=$(($tsize - $psize)) 35 | dd status=noxfer if=/dev/zero of="$part.img" seek=$psize obs=1 ibs=$towrite count=1 2>/dev/null 36 | done 37 | -------------------------------------------------------------------------------- /bootloader_unpacker.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Initially developed at Ghent University as part of a masters thesis promoted 3 | * by prof. dr. ir. Bjorn De Sutter of the Computer Systems Lab in cooperation with ir. Daan Raman from NVISO. 4 | * Author: Christophe Beauval 5 | * Version: 20140302 6 | * Description: Unpacks the Android bootloader.img 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | /* from AOSP device/lge/hammerhead/releasetools.py */ 15 | /* unsigned int are in big endian */ 16 | 17 | #define BOOTLDR_MAGIC "BOOTLDR!" 18 | #define BOOTLDR_MAGIC_SIZE 8 /* No room for terminating \0 */ 19 | 20 | typedef struct { 21 | char magic[BOOTLDR_MAGIC_SIZE]; 22 | unsigned int num_images; 23 | unsigned int start_offset; 24 | unsigned int bootldr_size; 25 | } bootldrimgh; 26 | 27 | typedef struct { 28 | char name[64]; 29 | unsigned int size; 30 | } img_info; 31 | 32 | int main(int argc, char **argv) { 33 | FILE *img, *out; 34 | void *buf; 35 | char *outname; 36 | bootldrimgh bimg; 37 | img_info *imgs; 38 | unsigned int i = 0; 39 | 40 | if ((argc != 2 && argc != 3) || (argc == 3 && (argv[1][0] != '-' || argv[1][1] != 'v'))) { 41 | printf("Usage: %s [-v] \n", argv[0]); 42 | return EXIT_FAILURE; 43 | } 44 | 45 | if (argc == 2 && !(img = fopen(argv[1], "r"))) { 46 | perror("Error opening file"); 47 | return EXIT_FAILURE; 48 | } 49 | if (argc == 3 && !(img = fopen(argv[2], "r"))) { 50 | perror("Error opening file"); 51 | return EXIT_FAILURE; 52 | } 53 | 54 | /* Read header without img_info struct */ 55 | fread(&bimg, sizeof(bootldrimgh), 1, img); 56 | /* for printing only */ 57 | if (argc == 3) { 58 | bimg.magic[BOOTLDR_MAGIC_SIZE-1] = 0; 59 | printf("magic: %s\n", bimg.magic); 60 | printf("num_images: %d\n", bimg.num_images); 61 | printf("start_offset: %d\n", bimg.start_offset); 62 | printf("bootldr_size: %d\n", bimg.bootldr_size); 63 | } 64 | 65 | /* read img_info headers */ 66 | imgs = malloc(bimg.num_images * sizeof(img_info)); 67 | fread(imgs, sizeof(img_info), bimg.num_images, img); 68 | 69 | fseek(img, bimg.start_offset, SEEK_SET); 70 | 71 | for (i = 0; i < bimg.num_images; ++i) { 72 | /* Output to name.img, needing 5 more chars of mem */ 73 | outname = malloc(strlen(imgs[i].name) + 5); 74 | sprintf(outname, "%s.img", imgs[i].name); 75 | if (!(out = fopen(outname, "w+"))) { 76 | perror("Error opening file"); 77 | return EXIT_FAILURE; 78 | } 79 | if (argc == 3) { 80 | printf("Unpacking image %d = %s to %s (size: %d)\n", i + 1, imgs[i].name, outname, imgs[i].size); 81 | } else { 82 | printf("%s\n", imgs[i].name); 83 | } 84 | if (outname != NULL) free(outname); 85 | 86 | /* Read part of file to buffer */ 87 | buf = malloc(imgs[i].size); 88 | fread(buf, imgs[i].size, 1, img); 89 | 90 | /* Write buffer to file */ 91 | fwrite(buf, imgs[i].size, 1, out); 92 | 93 | fclose(out); 94 | if (buf != NULL) free(buf); 95 | } 96 | 97 | /* Cleaup */ 98 | if (imgs != NULL) free(imgs); 99 | fclose(img); 100 | 101 | return EXIT_SUCCESS; 102 | } 103 | -------------------------------------------------------------------------------- /extras/dumper.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Initially developed at Ghent University as part of a masters thesis promoted 3 | # by prof. dr. ir. Bjorn De Sutter of the Computer Systems Lab in cooperation with ir. Daan Raman from NVISO. 4 | # Author: Christophe Beauval 5 | # Version: 20140502 6 | # Description: Dumps the contents of the flashchip or partition of an Android device. 7 | # Only tested on hammerhead (LG Nexus 5 Android 4.4) 8 | # Instructions: needed binaries: adb, fastboot, netstat (, pv, nc (, gzip)) 9 | # Usage: $0 [device-serial] 10 | 11 | tooldir=$(dirname "$0") 12 | ### CONFIG BEGIN ### 13 | # Location of the adb and fastboot binaries, use binname if within $PATH 14 | 15 | #adb="$tooldir/aosp/adb" 16 | #fb="$tooldir/aosp/fastboot" 17 | 18 | adb="adb" 19 | fb="fastboot" 20 | 21 | ### CONFIG END ### 22 | 23 | # Verify we have working binaries 24 | [[ -z "$(which "$adb")" ]] && echo "Could not find adb-binary $adb, check config in script" && exit 2 25 | [[ -z "$(which "$fb")" ]] && echo "Could not find fastboot-binary $fb, check config in script" && exit 2 26 | 27 | conf="$1" 28 | output="$2" 29 | port="$3" 30 | serial="$4" 31 | 32 | # Verify arguments 33 | [[ $# -lt 3 ]] && echo "Usage: $0 [device-serial]" && exit 2 34 | 35 | # Verify a port is given 36 | ( [[ ! "$port" =~ ^[0-9][0-9]*$ ]] || [[ $port -lt 1 ]] || [[ $port -gt 65535 ]] ) && 37 | echo "Given port $port is not a valid one, should be between 1 and 65535 including." && exit 2 38 | 39 | # Verify port isn't used yet 40 | prtprog="$(netstat -anp 2>/dev/null | grep ":$port.*LISTEN" | cut -d'/' -f2)" 41 | [[ ! -z "$portprog" ]] && echo "Port $port is already used by $prtprog, choose a different one." && exit 2 42 | 43 | # Verify outputfile is availible for writing... 44 | ( ( [[ -f "$output" ]] && [[ ! -w "$output" ]] ) || 45 | ( [[ ! -e "$output" ]] && [[ ! -w "$(dirname "$output")" ]] ) ) && 46 | echo "Cannot write to file $output" && exit 2 47 | # ... and is ok to overwrite if existing 48 | [[ -f "$output" ]] && { 49 | read -p "File $output exists, ok to overwrite? [y/N]: " 50 | [[ ! "$REPLY" =~ ^[yY]$ ]] && echo "Not overwriting $output, aborting." && exit 2 51 | } 52 | 53 | # Verify and load config 54 | [[ ! -f "$conf" ]] && echo "Given config $conf does not exist." && exit 2 55 | . "$conf" 56 | [[ -z "$devdump" ]] && echo "No blockdevice or partition specified to dump, check config." && exit 2 57 | # Verify recovery image exists and the method used 58 | ( [[ -z "$recfile" ]] || [[ ! -f "$recfile" ]] ) && echo "Could not find recoveryimage $recfile, check config" && exit 2 59 | ( [[ -z "$recmethod" ]] || [[ ! "$recmethod" =~ ^(simple|feedback|compressed)$ ]] ) && 60 | echo "Could not find a valid dump method: $recmethod not one of simple, feedback or compressed. Check config." && exit 2 61 | 62 | # Check if device is off, in normal mode or in fastboot 63 | status="unauthorized" 64 | if [[ -z "$serial" ]]; then 65 | status="$("$adb" devices | tail -n2 | head -n1 | awk '{print $2}')" 66 | if [[ "$status" == "of" ]]; then 67 | # Check fastboot 68 | status="$("$fb" devices | awk '{print $2}')" 69 | [[ -z "$status" ]] && echo "No device found through adb or fastboot." && exit 2 70 | fi 71 | else 72 | status="$("$adb" devices | sed -n "s/^$serial\s*//p")" 73 | if [[ -z "$status" ]]; then 74 | # Check fastboot 75 | status="$("$fb" devices | sed -n "s/$serial\s*//p")" 76 | [[ -z "$status" ]] && echo "No device with serial $serial found through adb or fastboot." && exit 2 77 | fi 78 | fi 79 | 80 | # Verify adb access is granted (to be able to reboot) or if we're in fastboot 81 | [[ "$status" == "unauthorized" ]] && echo "Authorize adb access on the smartphone first." && exit 2 82 | if [[ "$status" == "fastboot" ]]; then 83 | [[ -z "$serial" ]] && serial="$("$fb" devices | tail -n1 | awk '{print $1}')" 84 | else 85 | # Reboot smartphone into fastboot first 86 | [[ -z "$serial" ]] && serial="$("$adb" devices | tail -n2 | head -n1 | awk '{print $1}')" 87 | echo "Rebooting device with serial $serial into bootloader." 88 | "$adb" -s $serial reboot bootloader 89 | 90 | # Wait for device to enter bootloader mode for max 30secs 91 | echo -n "Waiting for device with serial $serial to enter bootloader." 92 | secs=0; 93 | while [[ "$("$fb" devices | sed -n "s/^$serial\s*//p")" != "fastboot" ]] && [[ $secs -lt 30 ]]; do 94 | echo -n "." 95 | secs=$(($secs + 1)) 96 | sleep 1 97 | done 98 | echo "" 99 | [[ $secs -eq 30 ]] && echo "Device failed to enter bootloader, aborting." && exit 2 100 | fi 101 | 102 | # Verify device is unlocked 103 | [[ -z "$("$fb" -s $serial oem unlock 2>&1 | grep "Already Unlocked")" ]] && echo "Device is not unlocked, aborting." && exit 2 104 | 105 | # Boot into recovery with custom image 106 | "$fb" -s $serial boot "$recfile" 107 | 108 | # Wait for device to enter recovery mode for max 30secs 109 | echo -n "Waiting for device with serial $serial to enter recovery." 110 | secs=0; 111 | while [[ "$("$adb" devices | sed -n "s/^$serial\s*//p")" != "recovery" ]] && [[ $secs -lt 30 ]]; do 112 | echo -n "." 113 | secs=$(($secs + 1)) 114 | sleep 1 115 | done 116 | echo "" 117 | [[ $secs -eq 30 ]] && echo "Device failed to enter recovery, aborting." && exit 2 118 | 119 | # Start dump on device in new shell, 3 methods to choose from (add arg switch later) 120 | dump_simple() { 121 | echo "Transfer started..." 122 | # Could send to bg and add loop checking size and if transfer is done... 123 | "$adb" -s $serial pull $devdump "$output" 124 | } 125 | 126 | dump_w_output() { 127 | # Prepare for dump: forward port 128 | "$adb" -s $serial forward tcp:$port tcp:$port 129 | 130 | # Includes feedback about current size and speed, needs receiving end 131 | "$adb" -s $serial shell "/sbin/busybox dd if=$devdump | /sbin/busybox nc -l -p $port" 2>/dev/null & 132 | # Accept dump in this shell, wait 2s to connect 133 | echo "Waiting for transfer to start..." 134 | sleep 2 135 | nc 127.0.0.1 $port | pv > "$output" 136 | } 137 | 138 | dump_compressed() { 139 | # Prepare for dump: forward port 140 | "$adb" -s $serial forward tcp:$port tcp:$port 141 | 142 | # We use gzip as it's faster, even though bzip2 compresses better, 143 | # the difference does not translate in a faster send 144 | "$adb" -s $serial shell "/sbin/busybox gzip -c $devdump | /sbin/busybox nc -l -p $port" 2>/dev/null & 145 | # Accept dump in this shell, wait 2s to connect 146 | echo "Waiting for transfer to start..." 147 | sleep 2 148 | nc 127.0.0.1 $port | pv | gunzip -c > "$output" 149 | } 150 | 151 | if [[ "$recmethod" == "simple" ]]; then 152 | dump_simple 153 | elif [[ "$recmethod" == "compressed" ]]; then 154 | dump_compressed 155 | else 156 | # with feedback 157 | dump_w_output 158 | fi 159 | 160 | # Reboot phone like normal 161 | "$adb" -s $serial reboot bootloader 162 | echo -n "Rebooting and waiting for device with serial $serial to enter fastboot boot" 163 | secs=0; 164 | while [[ "$("$fb" devices | sed -n "s/^$serial\s*//p")" != "fastboot" ]] && [[ $secs -lt 30 ]]; do 165 | echo -n "." 166 | secs=$(($secs + 1)) 167 | sleep 1 168 | done 169 | echo "" 170 | [[ $secs -eq 30 ]] && echo "Device failed to enter bootloader, aborting." && exit 2 171 | echo "Finished." 172 | -------------------------------------------------------------------------------- /extras/etc/hammerhead.conf: -------------------------------------------------------------------------------- 1 | # bash-style config 2 | # Var that can be used: $tooldir, this represents the dir root-scriptdir 3 | 4 | # Location of custom recovery.img, needs at least root adb shell access, 5 | # busybox binary with nc and dd and gzip or those seperate is optional 6 | recfile="$tooldir/img/recovery.cust.hh44.img" 7 | 8 | # Which method to use to get the dump: simple, feedback or compressed 9 | recmethod="compressed" 10 | 11 | # Partition or blockdevice to dump | 17 = imgdata 12 | devdump="/dev/block/mmcblk0p17" 13 | -------------------------------------------------------------------------------- /extras/img/recovery.cust.hh44.img: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NVISOsecurity/nexus_5_bootloader_unpacker/32d2fcbf4d4c8cf30955041b1e3eaa501b706cb9/extras/img/recovery.cust.hh44.img -------------------------------------------------------------------------------- /extras/writer.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Initially developed at Ghent University as part of a masters thesis promoted 3 | # by prof. dr. ir. Bjorn De Sutter of the Computer Systems Lab in cooperation with ir. Daan Raman from NVISO. 4 | # Author: Christophe Beauval 5 | # Version: 20140507 6 | # Description: Writes the contents of an image to the flashchip of an Android device. 7 | # Only tested on hammerhead (LG Nexus 5 Android 4.4) 8 | # Instructions: needed binaries: adb, fastboot, netstat (, nc (, gzip)) 9 | # Usage: $0 [device-serial] 10 | 11 | tooldir=$(dirname "$0") 12 | ### CONFIG BEGIN ### 13 | # Location of the adb and fastboot binaries, use binname if within $PATH 14 | #adb="$tooldir/aosp/adb" 15 | #fb="$tooldir/aosp/fastboot" 16 | 17 | adb="adb" 18 | fb="fastboot" 19 | 20 | ### CONFIG END ### 21 | 22 | # Verify we have working binaries 23 | [[ -z "$(which "$adb")" ]] && echo "Could not find adb-binary $adb, check config in script" && exit 2 24 | [[ -z "$(which "$fb")" ]] && echo "Could not find fastboot-binary $fb, check config in script" && exit 2 25 | 26 | conf="$1" 27 | input="$2" 28 | port="$3" 29 | serial="$4" 30 | 31 | # Verify arguments 32 | [[ $# -lt 3 ]] && echo "Usage: $0 [device-serial]" && exit 2 33 | 34 | # Verify a port is given 35 | ( [[ ! "$port" =~ ^[0-9][0-9]*$ ]] || [[ $port -lt 1 ]] || [[ $port -gt 65535 ]] ) && 36 | echo "Given port $port is not a valid one, should be between 1 and 65535 including." && exit 2 37 | 38 | # Verify port isn't used yet 39 | prtprog="$(netstat -anp 2>/dev/null | grep ":$port.*LISTEN" | cut -d'/' -f2)" 40 | [[ ! -z "$portprog" ]] && echo "Port $port is already used by $prtprog, choose a different one." && exit 2 41 | 42 | # Verify inputfile is availible 43 | [[ ! -f "$input" ]] && echo "Cannot read inputfile $input" && exit 2 44 | 45 | # Verify and load config 46 | [[ ! -f "$conf" ]] && echo "Given config $conf does not exist." && exit 2 47 | . "$conf" 48 | [[ -z "$devdump" ]] && echo "No blockdevice or partition specified to write to, check config." && exit 2 49 | # Verify recovery image exists and the method used 50 | ( [[ -z "$recfile" ]] || [[ ! -f "$recfile" ]] ) && echo "Could not find recoveryimage $recfile, check config" && exit 2 51 | ( [[ -z "$recmethod" ]] || [[ ! "$recmethod" =~ ^(simple|feedback|compressed)$ ]] ) && 52 | echo "Could not find a valid write method: $recmethod not one of simple, feedback or compressed. Check config." && exit 2 53 | 54 | # Check if device is off, in normal mode or in fastboot 55 | status="unauthorized" 56 | if [[ -z "$serial" ]]; then 57 | status="$("$adb" devices | tail -n2 | head -n1 | awk '{print $2}')" 58 | if [[ "$status" == "of" ]]; then 59 | # Check fastboot 60 | status="$("$fb" devices | awk '{print $2}')" 61 | [[ -z "$status" ]] && echo "No device found through adb or fastboot." && exit 2 62 | fi 63 | else 64 | status="$("$adb" devices | sed -n "s/^$serial\s*//p")" 65 | if [[ -z "$status" ]]; then 66 | # Check fastboot 67 | status="$("$fb" devices | sed -n "s/$serial\s*//p")" 68 | [[ -z "$status" ]] && echo "No device with serial $serial found through adb or fastboot." && exit 2 69 | fi 70 | fi 71 | 72 | # Verify adb access is granted (to be able to reboot) or if we're in fastboot 73 | [[ "$status" == "unauthorized" ]] && echo "Authorize adb access on the smartphone first." && exit 2 74 | if [[ "$status" == "fastboot" ]]; then 75 | [[ -z "$serial" ]] && serial="$("$fb" devices | tail -n1 | awk '{print $1}')" 76 | else 77 | # Reboot smartphone into fastboot first 78 | [[ -z "$serial" ]] && serial="$("$adb" devices | tail -n2 | head -n1 | awk '{print $1}')" 79 | echo "Rebooting device with serial $serial into bootloader." 80 | "$adb" -s $serial reboot bootloader 81 | 82 | # Wait for device to enter bootloader mode for max 30secs 83 | echo -n "Waiting for device with serial $serial to enter bootloader." 84 | secs=0; 85 | while [[ "$("$fb" devices | sed -n "s/^$serial\s*//p")" != "fastboot" ]] && [[ $secs -lt 30 ]]; do 86 | echo -n "." 87 | secs=$(($secs + 1)) 88 | sleep 1 89 | done 90 | echo "" 91 | [[ $secs -eq 30 ]] && echo "Device failed to enter bootloader, aborting." && exit 2 92 | fi 93 | 94 | # Verify the device is unlocked 95 | [[ -z "$("$fb" -s $serial oem unlock 2>&1 | grep "Already Unlocked")" ]] && echo "Device is not unlocked, aborting." && exit 2 96 | 97 | # Boot into recovery with custom image 98 | "$fb" -s $serial boot "$recfile" 99 | 100 | # Wait for device to enter recovery mode for max 30secs 101 | echo -n "Waiting for device with serial $serial to enter recovery." 102 | secs=0; 103 | while [[ "$("$adb" devices | sed -n "s/^$serial\s*//p")" != "recovery" ]] && [[ $secs -lt 30 ]]; do 104 | echo -n "." 105 | secs=$(($secs + 1)) 106 | sleep 1 107 | done 108 | echo "" 109 | [[ $secs -eq 30 ]] && echo "Device failed to enter recovery, aborting." && exit 2 110 | 111 | # Start write on device in new shell, 3 methods to choose from (add arg switch later) 112 | write_simple() { 113 | echo "Transfer started..." 114 | # Could send to bg and add loop checking size and if transfer is done... 115 | "$adb" -s $serial push "$input" $devdump 116 | } 117 | 118 | write_w_output() { 119 | # Prepare for dump: forward port 120 | "$adb" -s $serial forward tcp:$port tcp:$port 121 | 122 | # Includes feedback about current size and speed, needs receiving end 123 | "$adb" -s $serial shell "/sbin/busybox nc -l -p $port | /sbin/busybox dd of=$devdump status=noxfer" 2>/dev/null & 124 | # Send dump in this shell, wait 2s to connect 125 | echo "Waiting for transfer to start..." 126 | sleep 2 127 | dd if="$input" status=noxfer 2>/dev/null | nc -x 127.0.0.1 $port 128 | } 129 | 130 | write_compressed() { 131 | # Prepare for dump: forward port 132 | "$adb" -s $serial forward tcp:$port tcp:$port 133 | 134 | # We use gzip as it's faster, even though bzip2 compresses better, 135 | # the difference does not translate in a faster send 136 | "$adb" -s $serial shell "/sbin/busybox nc -l -p $port | /sbin/busybox gunzip -c > $devdump" 2>/dev/null & 137 | # Send dump in this shell, wait 2s to connect 138 | echo "Waiting for transfer to start..." 139 | sleep 2 140 | gzip -c "$input" | nc -x 127.0.0.1 $port 141 | } 142 | 143 | if [[ "$recmethod" == "simple" ]]; then 144 | write_simple 145 | elif [[ "$recmethod" == "compressed" ]]; then 146 | write_compressed 147 | else 148 | # with feedback 149 | write_w_output 150 | fi 151 | 152 | # Reboot phone like normal 153 | "$adb" -s $serial reboot bootloader 154 | echo -n "Rebooting and waiting for device with serial $serial to enter fastboot boot" 155 | secs=0; 156 | while [[ "$("$fb" devices | sed -n "s/^$serial\s*//p")" != "fastboot" ]] && [[ $secs -lt 30 ]]; do 157 | echo -n "." 158 | secs=$(($secs + 1)) 159 | sleep 1 160 | done 161 | echo "" 162 | [[ $secs -eq 30 ]] && echo "Device failed to enter bootloader, aborting." && exit 2 163 | echo "Finished." 164 | -------------------------------------------------------------------------------- /imgdata_tool.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Initially developed at Ghent University as part of a masters thesis promoted 3 | * by prof. dr. ir. Bjorn De Sutter of the Computer Systems Lab in cooperation with ir. Daan Raman from NVISO. 4 | * Author: Christophe Beauval 5 | * Version: 20140801 6 | * Description: Unpacks/repacks/packs the Android imgdata.img and converts to/from PNG 7 | * Instructions: Two options to compile: dynamic: gcc -o iunp imgdata_tool.c -lpng 8 | * static: gcc -o iunp imgdata_tool.c -lpng -lz -lm -static 9 | * Usage: $0 -l : list info and contents 10 | * -x : extract contents in working dir 11 | * -u [...] : update "file1" in with given coordinates and size, use - to keep existing value 12 | * -r [:X[:Y]] [...] : replace "file1" in with given file and optionally new coordinates 13 | * -c [...] : creates a new imgdata.img (overwriting any existing!) with contents rest of arguments 14 | * X, Y, W, H are 32bit positive integers and can be given as 0x and 0 as well 15 | * "file1" name should not be longer than IMGDATA_FILE_NAME_SIZE chars, excluding extension, and be in current dir 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #include 26 | 27 | #define IMGDATA_MAGIC "IMGDATA!" 28 | #define IMGDATA_MAGIC_SIZE 8 /* No room for terminating \0 */ 29 | #define IMGDATA_VERSION 1 /* value of unknown = version? */ 30 | #define IMGDATA_FILE_BLOCK_SIZE 512 /* content size has to be multiple of this, padded with zeros, in bytes */ 31 | #define IMGDATA_FILE_NAME_SIZE 16 /* max length of a filename (assuming not including terminating \0) */ 32 | #define IMGDATA_FILE_OFFSET_START 1024 /* start of the first imgdata file in bytes */ 33 | 34 | /* modes this program runs */ 35 | #define RUN_NONE 0 36 | #define RUN_LIST 1 37 | #define RUN_EXTRACT 2 38 | #define RUN_UPDATE 3 39 | #define RUN_REPLACE 4 40 | #define RUN_CREATE 5 41 | 42 | /* marks for changing metadata */ 43 | #define MARK_X 1 44 | #define MARK_Y 2 45 | #define MARK_W 4 46 | #define MARK_H 8 47 | #define MARK_S 16 48 | 49 | /* imgdata.img header */ 50 | typedef struct { 51 | char magic[IMGDATA_MAGIC_SIZE]; 52 | unsigned int unknown; 53 | unsigned int num_files; 54 | unsigned int padding_a; 55 | unsigned int padding_b; 56 | } imgdatahdr; 57 | 58 | /* part of the header, list of metadata of contents */ 59 | typedef struct { 60 | char name[IMGDATA_FILE_NAME_SIZE]; 61 | unsigned int imgwidth; /* max 1080 for LG Nexus 5 */ 62 | unsigned int imgheight; /* max 1920 for LG Nexus 5 */ 63 | unsigned int scrxpos; /* pos on screen, 0 is leftmost */ 64 | unsigned int scrypos; /* pos on screen, 0 is topmost */ 65 | unsigned int offset; /* multiple of IMGDATA_FILE_BLOCK_SIZE */ 66 | unsigned int size; 67 | } imgdata_file; 68 | 69 | /* basic unit of content */ 70 | typedef struct { 71 | unsigned char count; 72 | unsigned char red; 73 | unsigned char green; 74 | unsigned char blue; 75 | } pixelrun; 76 | 77 | /* representation of an encoded image */ 78 | typedef struct { 79 | char name[IMGDATA_FILE_NAME_SIZE + 1]; /* +1 for \0 */ 80 | unsigned int size; 81 | pixelrun *content; 82 | } imgdata_content; 83 | 84 | /* internal representation of cmd args */ 85 | typedef struct { 86 | char name[IMGDATA_FILE_NAME_SIZE + 5]; /* 4 for ".png" and 1 for \0 */ 87 | unsigned int x; /* pos on screen, 0 is leftmost */ 88 | unsigned int y; /* pos on screen, 0 is topmost */ 89 | unsigned int w; /* max 1080 for LG Nexus 5 */ 90 | unsigned int h; /* max 1920 for LG Nexus 5 */ 91 | unsigned int size; /* size */ 92 | unsigned int bsize; /* size of content which is >= size as it's divisible by IMGDATA_FILE_BLOCK_SIZE */ 93 | unsigned char mark; 94 | pixelrun *content; 95 | } arg; 96 | 97 | /* 98 | * Converts content to PNG 99 | */ 100 | int convert_to_png(pixelrun *buf, imgdata_file imgfile, FILE *out) { 101 | /* PNG structs */ 102 | png_structp png_ptr; 103 | png_infop info_ptr; 104 | png_byte row[imgfile.imgwidth * 3]; /* 3 bytes per pixel */ 105 | int i, j = 0, k; 106 | 107 | /* PNG inits */ 108 | png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); 109 | if (!png_ptr) { 110 | return EXIT_FAILURE; 111 | } 112 | 113 | info_ptr = png_create_info_struct(png_ptr); 114 | if (!info_ptr) { 115 | png_destroy_write_struct(&png_ptr, NULL); 116 | return EXIT_FAILURE; 117 | } 118 | 119 | png_init_io(png_ptr, out); 120 | png_set_filter(png_ptr, 0, PNG_FILTER_VALUE_NONE); 121 | /* Fill IHDR */ 122 | png_set_IHDR(png_ptr, info_ptr, 123 | imgfile.imgwidth, 124 | imgfile.imgheight, 125 | 8, 126 | PNG_COLOR_TYPE_RGB, 127 | PNG_INTERLACE_NONE, 128 | PNG_COMPRESSION_TYPE_DEFAULT, 129 | PNG_FILTER_TYPE_DEFAULT); 130 | 131 | png_write_info(png_ptr, info_ptr); 132 | 133 | /* Start making rows, go over the (imgfile.size / 4) pixelruns */ 134 | for (i = 0; i < (imgfile.size >> 2); ++i) { 135 | for (k = 0; k < buf[i].count; ++k) { 136 | row[j] = buf[i].red; 137 | row[j+1] = buf[i].green; 138 | row[j+2] = buf[i].blue; 139 | if (j + 3 == imgfile.imgwidth * 3) { 140 | png_write_row(png_ptr, row); 141 | j = 0; 142 | } else { 143 | j += 3; 144 | } 145 | } 146 | } 147 | 148 | png_write_end(png_ptr, NULL); 149 | 150 | /* cleanup */ 151 | png_destroy_write_struct(&png_ptr, &info_ptr); 152 | 153 | return EXIT_SUCCESS; 154 | } 155 | 156 | void print_usage(char *errmsg) { 157 | if (errmsg != NULL) { 158 | printf("Error: %s\n", errmsg); 159 | } 160 | printf("Usage: -l : list info and contents\n"); 161 | printf(" -x : extract contents in working dir\n"); 162 | printf(" -u [...] : update \"file1\" in with given coordinates and size, use - to keep existing value\n"); 163 | printf(" -r [:X[:Y]] [...] : replace \"file1\" in with given file and optionally new coordinates\n"); 164 | printf(" -c [...] : creates a new (overwriting any existing!) with contents rest of arguments\n"); 165 | printf(" X, Y, W, H are 32bit positive integers and can be given as 0x and 0 as well\n"); 166 | printf(" \"file1\" name should not be longer than %d chars, excluding extension, and be in current dir\n", IMGDATA_FILE_NAME_SIZE); 167 | } 168 | 169 | /* 170 | * Reads the complete header of an imgdata.img 171 | * Returns EXIT_FAILURE if not a valid file or other problems 172 | */ 173 | int read_file_header(FILE *img, imgdatahdr *bimg, imgdata_file **imgs) { 174 | int read = 0; 175 | /* Read header without imgdata_file struct */ 176 | read = fread(bimg, sizeof(imgdatahdr), 1, img); 177 | if (read <= 0) { 178 | return EXIT_FAILURE; 179 | } 180 | /* validate magic */ 181 | if (strncmp(bimg->magic, IMGDATA_MAGIC, IMGDATA_MAGIC_SIZE)) { 182 | return EXIT_FAILURE; 183 | } 184 | 185 | /* read img_info headers */ 186 | *imgs = malloc(bimg->num_files * sizeof(imgdata_file)); 187 | if (*imgs == NULL) { 188 | return EXIT_FAILURE; 189 | } 190 | read = fread(*imgs, sizeof(imgdata_file), bimg->num_files, img); 191 | if (read <= 0) { 192 | free(imgs); 193 | return EXIT_FAILURE; 194 | } 195 | 196 | return EXIT_SUCCESS; 197 | } 198 | 199 | /* 200 | * Creates a new header based on parsed arguments 201 | */ 202 | void create_file_header(imgdatahdr *bimg, imgdata_file **imgs, unsigned int count, arg ufile[]) { 203 | int i, check; 204 | char *dot; 205 | 206 | /* fill imgdatahdr */ 207 | strncpy(bimg->magic, IMGDATA_MAGIC, IMGDATA_MAGIC_SIZE); 208 | bimg->unknown = IMGDATA_VERSION; /* wild guess */ 209 | bimg->num_files = count; 210 | bimg->padding_a = 0; 211 | bimg->padding_b = 0; 212 | 213 | /* fill imgdata_file */ 214 | *imgs = calloc(count, sizeof(imgdata_file)); /* everything zero */ 215 | if (*imgs == NULL) { 216 | perror("Failed calloc of <*imgs> in create_file_header"); 217 | } 218 | 219 | for (i = 0; i < count; ++i) { 220 | /* don't copy the file extension */ 221 | dot = strrchr(ufile[i].name, '.'); 222 | check = IMGDATA_FILE_NAME_SIZE; 223 | if (dot != NULL && dot - ufile[i].name < check) { 224 | check = dot - ufile[i].name; 225 | } 226 | /* have to use (*imgs)[i].X instead of imgs[i]->X to get correct address for i>0 */ 227 | strncpy((*imgs)[i].name, ufile[i].name, check); 228 | (*imgs)[i].offset = IMGDATA_FILE_OFFSET_START; 229 | } 230 | } 231 | 232 | /* 233 | * Reads the encoded images of an imgdata.img 234 | * Returns EXIT_FAILURE if not a valid file or other problems 235 | */ 236 | int read_file_imgs(FILE *img, unsigned int count, imgdata_file *imgs, imgdata_content cont[]) { 237 | int i; 238 | 239 | for (i = 0; i < count; ++i) { 240 | strncpy(cont[i].name, imgs[i].name, IMGDATA_FILE_NAME_SIZE); 241 | cont[i].name[IMGDATA_FILE_NAME_SIZE] = '\0'; 242 | 243 | /* get size in full block 244 | * first -1 in case size == X*BLOCK_SIZE, after that +1 to get complete block */ 245 | cont[i].size = (((imgs[i].size - 1) / IMGDATA_FILE_BLOCK_SIZE) + 1) * IMGDATA_FILE_BLOCK_SIZE; 246 | cont[i].content = malloc(cont[i].size); 247 | if (cont[i].content == NULL) { 248 | printf("Failed to allocate memory for %s: %s\n", cont[i].name, strerror(errno)); 249 | return EXIT_FAILURE; 250 | } 251 | 252 | /* Read content */ 253 | if (fseek(img, imgs[i].offset, SEEK_SET)) { 254 | return EXIT_FAILURE; 255 | } 256 | if (fread(cont[i].content, cont[i].size, 1, img) <= 0) { 257 | return EXIT_FAILURE; 258 | } 259 | } 260 | 261 | return EXIT_SUCCESS; 262 | } 263 | 264 | /* 265 | * Writes the complete header of an imgdata.img 266 | * Returns EXIT_FAILURE if not a valid file or other problems 267 | */ 268 | int write_file_header(FILE *img, imgdatahdr *bimg, imgdata_file **imgs) { 269 | int write = 0; 270 | 271 | /* back to start of file */ 272 | rewind(img); 273 | 274 | /* write main header */ 275 | write = fwrite(bimg, sizeof(imgdatahdr), 1, img); 276 | if (write <= 0) { 277 | return EXIT_FAILURE; 278 | } 279 | 280 | /* write img_info headers */ 281 | write = fwrite(*imgs, sizeof(imgdata_file), bimg->num_files, img); 282 | if (write <= 0) { 283 | free(imgs); 284 | return EXIT_FAILURE; 285 | } 286 | 287 | return EXIT_SUCCESS; 288 | } 289 | 290 | /* 291 | * Writes the given converted images in place of the existing 292 | * Returns EXIT_FAILURE if not a valid file or other problems 293 | */ 294 | int write_file_imgs(FILE *img, imgdata_content cont[], unsigned int icount, arg ufile[], unsigned int ucount) { 295 | int i, j, written; 296 | 297 | /* to start of file content */ 298 | if (fseek(img, IMGDATA_FILE_OFFSET_START, SEEK_SET)) { 299 | return EXIT_FAILURE; 300 | } 301 | 302 | for (i = 0; i < icount; ++i) { 303 | written = 0; 304 | for (j = 0; j < ucount; ++j) { 305 | if (!strncmp(cont[i].name, ufile[j].name, strlen(cont[i].name))) { 306 | if (fwrite(ufile[j].content, ufile[j].bsize, 1, img) <= 0) { 307 | return EXIT_FAILURE; 308 | } 309 | written = 1; 310 | } 311 | } 312 | 313 | /* if not written, content is not replaced, so put back original */ 314 | if (!written) { 315 | if (fwrite(cont[i].content, cont[i].size, 1, img) <= 0) { 316 | return EXIT_FAILURE; 317 | } 318 | } 319 | } 320 | 321 | /* truncate file to exact length */ 322 | if (ftruncate(fileno(img), ftell(img))) { 323 | return EXIT_FAILURE; 324 | } 325 | 326 | return EXIT_SUCCESS; 327 | } 328 | 329 | /* 330 | * Writes the parsed files only, to be used when creating a new container 331 | */ 332 | int write_file_args(FILE *img, arg ufile[], unsigned int count) { 333 | int i; 334 | 335 | /* flush and truncate file to exact start of content */ 336 | if (fflush(img)) { 337 | return EXIT_FAILURE; 338 | } 339 | if (ftruncate(fileno(img), IMGDATA_FILE_OFFSET_START)) { 340 | return EXIT_FAILURE; 341 | } 342 | 343 | /* to start of file content */ 344 | if (fseek(img, IMGDATA_FILE_OFFSET_START, SEEK_SET)) { 345 | return EXIT_FAILURE; 346 | } 347 | 348 | /* write new imgs */ 349 | for (i = 0; i < count; ++i) { 350 | if (fwrite(ufile[i].content, ufile[i].bsize, 1, img) <= 0) { 351 | return EXIT_FAILURE; 352 | } 353 | } 354 | 355 | return EXIT_SUCCESS; 356 | } 357 | 358 | /* 359 | * Prints the info from the imgdata.img header 360 | */ 361 | void list_header_info(imgdatahdr *bimg, imgdata_file *imgs) { 362 | int i; 363 | /* Show complete magic, need to copy so we can terminate */ 364 | char magicstr[IMGDATA_MAGIC_SIZE + 1]; 365 | strncpy(magicstr, bimg->magic, IMGDATA_MAGIC_SIZE); 366 | magicstr[IMGDATA_MAGIC_SIZE] = '\0'; 367 | 368 | printf("magic: %s\n", magicstr); 369 | printf("unknown: %d\n", bimg->unknown); 370 | printf("num_files: %d\n", bimg->num_files); 371 | printf("padding_a: %d\n", bimg->padding_a); 372 | printf("padding_b: %d\n", bimg->padding_b); 373 | 374 | printf(" \twidth\theight\tx-pos\ty-pos\toffset\tsize\n"); 375 | for (i = 0; i < bimg->num_files; ++i) { 376 | printf("File %02d = %16s:\t%d\t%d\t%d\t%d\t%d\t%d\n", i, imgs[i].name, imgs[i].imgwidth, imgs[i].imgheight, imgs[i].scrxpos, imgs[i].scrypos, imgs[i].offset, imgs[i].size); 377 | } 378 | } 379 | 380 | /* 381 | * Extracts the images and converts them to PNG 382 | */ 383 | void extract_contents(FILE *img, int num_files, imgdata_file *imgs) { 384 | FILE *out; 385 | pixelrun *buf; 386 | int i; 387 | 388 | for (i = 0; i < num_files; ++i) { 389 | char outfile[strlen(imgs[i].name) + 5]; 390 | sprintf(outfile, "%s.png", imgs[i].name); 391 | if (!(out = fopen(outfile, "w+"))) { 392 | perror("Error opening file"); 393 | continue; 394 | } 395 | printf("%s\n", outfile); 396 | 397 | /* Read content to buffer */ 398 | fseek(img, imgs[i].offset, SEEK_SET); 399 | buf = malloc(imgs[i].size); 400 | /* Read in completely, sizes are limited with upperbound 401 | max partition size (3MiB on LG Nexus 5) minus header (1KiB)*/ 402 | fread(buf, imgs[i].size, 1, img); 403 | 404 | /* Convert to PNG */ 405 | if (convert_to_png(buf, imgs[i], out) == EXIT_FAILURE) { 406 | printf("Error converting %s to PNG.\n", imgs[i].name); 407 | } 408 | 409 | if (buf != NULL) free(buf); 410 | fclose(out); 411 | } 412 | } 413 | 414 | /* 415 | * Parses the given file(name)s for their coords (and size) 416 | * A MARK_* is put in the arg.mark for each changing value 417 | */ 418 | void parse_args(unsigned int count, char *args[], arg ifile[]) { 419 | int i, max; 420 | char *str, *dot; 421 | 422 | for (i = 0; i < count; ++i) { 423 | ifile[i].mark = 0; 424 | str = strtok(args[i], ":"); 425 | dot = strrchr(args[i], '.'); 426 | max = sizeof(ifile[i].name) - 1; 427 | if ((dot != NULL && dot - args[i] > IMGDATA_FILE_NAME_SIZE) || 428 | (str != NULL && strlen(str) > max) || 429 | (dot == NULL && str != NULL && strlen(str) > IMGDATA_FILE_NAME_SIZE) 430 | ) { 431 | printf("Filename %s too long, skipping\n", str); 432 | continue; 433 | } 434 | strncpy(ifile[i].name, str, max); 435 | ifile[i].name[max] = '\0'; 436 | 437 | /* X-pos */ 438 | str = strtok(NULL, ":"); 439 | if (str != NULL) { 440 | if (*str != '-') { 441 | ifile[i].x = (unsigned int) strtol(str, NULL, 0); 442 | ifile[i].mark += MARK_X; 443 | } 444 | /* Y-pos */ 445 | str = strtok(NULL, ":"); 446 | if (str != NULL) { 447 | if (*str != '-') { 448 | ifile[i].y = (unsigned int) strtol(str, NULL, 0); 449 | ifile[i].mark += MARK_Y; 450 | } 451 | /* width */ 452 | str = strtok(NULL, ":"); 453 | if (str != NULL) { 454 | if (*str != '-') { 455 | ifile[i].w = (unsigned int) strtol(str, NULL, 0); 456 | ifile[i].mark += MARK_W; 457 | } 458 | /* height */ 459 | str = strtok(NULL, ":"); 460 | if (str != NULL) { 461 | if (*str != '-') { 462 | ifile[i].h = (unsigned int) strtol(str, NULL, 0); 463 | ifile[i].mark += MARK_H; 464 | } 465 | } 466 | } 467 | } 468 | } 469 | } 470 | } 471 | 472 | /* 473 | * Updates the header with new coords and sizes 474 | */ 475 | void update_header(imgdata_file *imgs, unsigned int icount, arg ufile[], unsigned int ucount) { 476 | int i, j, check, offchange = 0; 477 | char *dot; 478 | char uname[IMGDATA_FILE_NAME_SIZE + 1]; 479 | 480 | /* loop over packed imgs */ 481 | for (j = 0; j < icount; ++j) { 482 | /* add or subtract possible offset change */ 483 | imgs[j].offset += offchange; 484 | 485 | /* loop over parsed imgs */ 486 | for (i = 0; i < ucount; ++i) { 487 | /* can't use strlen on imgs[j].name as it's uncertain it's nullterminated */ 488 | dot = strrchr(ufile[i].name, '.'); 489 | check = IMGDATA_FILE_NAME_SIZE; 490 | if (dot != NULL && dot - ufile[i].name < check) { 491 | check = dot - ufile[i].name; 492 | } 493 | strncpy(uname, ufile[i].name, check); 494 | uname[check] = '\0'; 495 | if (!strncmp(uname, imgs[j].name, IMGDATA_FILE_NAME_SIZE)) { 496 | if (ufile[i].mark & MARK_X) { 497 | imgs[j].scrxpos = ufile[i].x; 498 | } 499 | if (ufile[i].mark & MARK_Y) { 500 | imgs[j].scrypos = ufile[i].y; 501 | } 502 | if (ufile[i].mark & MARK_W) { 503 | imgs[j].imgwidth = ufile[i].w; 504 | } 505 | if (ufile[i].mark & MARK_H) { 506 | imgs[j].imgheight = ufile[i].h; 507 | } 508 | if (ufile[i].mark & MARK_S) { 509 | /* get how many blocks were used and are used now */ 510 | int iblks, ublks; 511 | /* iblks can be 0 when adding a new image */ 512 | iblks = imgs[j].size == 0 ? 0 : (imgs[j].size / IMGDATA_FILE_BLOCK_SIZE) + 1; 513 | ublks = (ufile[i].size / IMGDATA_FILE_BLOCK_SIZE) + 1; 514 | /* if different amount of blocks are used, update offchange */ 515 | if (ublks - iblks) { 516 | offchange += (IMGDATA_FILE_BLOCK_SIZE * (ublks - iblks)); 517 | } 518 | imgs[j].size = ufile[i].size; 519 | } 520 | } 521 | } 522 | } 523 | } 524 | 525 | /* 526 | * Parses the given files and extracts the size and converts the image to the imgdata format 527 | */ 528 | void parse_png_files(unsigned int count, arg ufile[]) { 529 | int i, num = 8; 530 | png_byte header[num]; 531 | FILE *fp; 532 | png_structp png_ptr; 533 | png_infop info_ptr; 534 | png_color_16 my_background = {0, 0, 0, 0, 0}; 535 | png_color_16p image_background; 536 | png_uint_32 width= 0, height = 0; 537 | png_byte color_type = 0; 538 | png_byte bit_depth = 0; 539 | 540 | for (i = 0; i < count; ++i) { 541 | if (!(fp = fopen(ufile[i].name, "rb"))) { 542 | printf("Problem opening file %s, skipping: %s\n", ufile[i].name, strerror(errno)); 543 | continue; 544 | } 545 | 546 | if (fread(header, 1, num, fp) <= 0) { 547 | printf("Problem reading file %s, skipping: %s\n", ufile[i].name, strerror(errno)); 548 | fclose(fp); 549 | continue; 550 | } 551 | if (png_sig_cmp(header, 0, num)) { 552 | printf("Problem reading file %s, skipping: not a PNG file\n", ufile[i].name); 553 | fclose(fp); 554 | continue; 555 | } 556 | 557 | png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); 558 | if (!png_ptr) { 559 | printf("Problem creating PNG structs for %s, skipping\n", ufile[i].name); 560 | fclose(fp); 561 | continue; 562 | } 563 | 564 | 565 | info_ptr = png_create_info_struct(png_ptr); 566 | if (!info_ptr) { 567 | printf("Problem creating PNG structs for %s, skipping\n", ufile[i].name); 568 | png_destroy_read_struct(&png_ptr, NULL, NULL); 569 | fclose(fp); 570 | continue; 571 | } 572 | 573 | png_init_io(png_ptr, fp); 574 | png_set_sig_bytes(png_ptr, num); 575 | 576 | png_read_info(png_ptr, info_ptr); 577 | 578 | /* Clear alpa channel by making it black */ 579 | if (png_get_bKGD(png_ptr, info_ptr, &image_background)) { 580 | png_set_background(png_ptr, image_background, PNG_BACKGROUND_GAMMA_FILE, 1, 1.0); 581 | } else { 582 | png_set_background(png_ptr, &my_background, PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0); 583 | } 584 | 585 | /* get and set width and height */ 586 | width = png_get_image_width(png_ptr, info_ptr); 587 | height = png_get_image_height(png_ptr, info_ptr); 588 | ufile[i].w = (unsigned int) width; 589 | ufile[i].mark += MARK_W; 590 | ufile[i].h = (unsigned int) height; 591 | ufile[i].mark += MARK_H; 592 | 593 | /* transform PNG to RGB with 8bit depth */ 594 | color_type = png_get_color_type(png_ptr, info_ptr); 595 | bit_depth= png_get_bit_depth(png_ptr, info_ptr); 596 | if (color_type == PNG_COLOR_TYPE_PALETTE) { 597 | png_set_palette_to_rgb(png_ptr); 598 | } 599 | if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { 600 | png_set_gray_to_rgb(png_ptr); 601 | if(bit_depth < 8) { 602 | png_set_expand_gray_1_2_4_to_8(png_ptr); 603 | } 604 | } 605 | if (bit_depth == 16) { 606 | png_set_strip_16(png_ptr); 607 | } 608 | 609 | png_read_update_info(png_ptr, info_ptr); 610 | 611 | /* get pixels and transform to imgdata format */ 612 | if (height > 0 && width > 0) { 613 | png_bytep rows[height]; 614 | int j, k, l = 0, blockcount = 1; 615 | unsigned int prsize = sizeof(pixelrun); 616 | /* should be width * 3 */ 617 | int bwidth = png_get_rowbytes(png_ptr,info_ptr); 618 | 619 | for (j = 0; j < height; ++j) { 620 | rows[j] = malloc(bwidth); 621 | } 622 | png_read_image(png_ptr, rows); 623 | 624 | /* start with 1 block, realloc if more needed */ 625 | ufile[i].content = malloc(IMGDATA_FILE_BLOCK_SIZE); 626 | 627 | /* init first pixelrun */ 628 | if (height > 0 && bwidth > 2) { 629 | ufile[i].content[l].red = rows[0][0]; 630 | ufile[i].content[l].green = rows[0][1]; 631 | ufile[i].content[l].blue = rows[0][2]; 632 | /* count 0 as it'll be increased in the actual filling */ 633 | ufile[i].content[l].count = 0; 634 | } 635 | 636 | /* actual filling */ 637 | for (j = 0; j < height; ++j) { 638 | for (k = 0; k < bwidth; k+=3) { 639 | if (ufile[i].content[l].count != 255 && 640 | ufile[i].content[l].red == rows[j][k] && 641 | ufile[i].content[l].green == rows[j][k+1] && 642 | ufile[i].content[l].blue == rows[j][k+2] 643 | ) { 644 | ++(ufile[i].content[l].count); 645 | } else { 646 | ++l; 647 | if (IMGDATA_FILE_BLOCK_SIZE * blockcount <= l * prsize) { 648 | ++blockcount; 649 | ufile[i].content = realloc(ufile[i].content, blockcount * IMGDATA_FILE_BLOCK_SIZE); 650 | } 651 | ufile[i].content[l].red = rows[j][k]; 652 | ufile[i].content[l].green = rows[j][k+1]; 653 | ufile[i].content[l].blue = rows[j][k+2]; 654 | ufile[i].content[l].count = 1; 655 | } 656 | } 657 | } 658 | ++l; 659 | ufile[i].bsize = blockcount * IMGDATA_FILE_BLOCK_SIZE; 660 | ufile[i].size = l * prsize; 661 | ufile[i].mark += MARK_S; 662 | 663 | /* zero remainder of block for niceness */ 664 | while (l * prsize < ufile[i].bsize) { 665 | ufile[i].content[l].red = 0; 666 | ufile[i].content[l].green = 0; 667 | ufile[i].content[l].blue = 0; 668 | ufile[i].content[l].count = 0; 669 | ++l; 670 | } 671 | 672 | /* cleanup */ 673 | for (j = 0; j < height; ++j) { 674 | free(rows[j]); 675 | } 676 | } 677 | } 678 | } 679 | 680 | /* 681 | * Free the allocated memory for the content 682 | */ 683 | void free_file_imgs(imgdata_content conts[], unsigned int count) { 684 | while (count) { 685 | if (conts[count - 1].content != NULL) { 686 | free(conts[count - 1].content); 687 | } 688 | --count; 689 | } 690 | } 691 | 692 | /* 693 | * Free the allocated memory for the given files 694 | */ 695 | void free_file_args(arg ufile[], unsigned int count) { 696 | while (count) { 697 | if (ufile[count - 1].content != NULL) { 698 | free(ufile[count - 1].content); 699 | } 700 | --count; 701 | } 702 | } 703 | 704 | int main(int argc, char **argv) { 705 | FILE *img; 706 | char fmode[4]; 707 | imgdatahdr bimg; 708 | imgdata_file *imgs; 709 | unsigned char mode = RUN_NONE; 710 | unsigned int count = argc < 3 ? 0 : argc - 3; 711 | 712 | /* default mode is reading, set double \0 for "-u" needing mode rb+ */ 713 | strncpy(fmode, "rb", 4); 714 | 715 | if (argc <= 2) { 716 | print_usage(NULL); 717 | } else if (argv[1][0] == '-' && argv[1][1] == 'l' && argv[1][2] == '\0') { 718 | if (argc == 3) { 719 | mode = RUN_LIST; 720 | } else { 721 | print_usage("give one argument denoting the imgdata.img"); 722 | } 723 | } else if (argv[1][0] == '-' && argv[1][1] == 'x' && argv[1][2] == '\0') { 724 | if (argc == 3) { 725 | mode = RUN_EXTRACT; 726 | } else { 727 | print_usage("give one argument denoting the imgdata.img"); 728 | } 729 | } else if (argv[1][0] == '-' && argv[1][1] == 'u' && argv[1][2] == '\0') { 730 | if (argc >= 4) { 731 | mode = RUN_UPDATE; 732 | fmode[0] = 'r'; 733 | fmode[2] = '+'; 734 | } else { 735 | print_usage("give one argument denoting the imgdata.img and one or more imagenames to update in it"); 736 | } 737 | } else if (argv[1][0] == '-' && argv[1][1] == 'r' && argv[1][2] == '\0') { 738 | if (argc >= 4) { 739 | mode = RUN_REPLACE; 740 | fmode[0] = 'r'; 741 | fmode[2] = '+'; 742 | } else { 743 | print_usage("give one argument denoting the imgdata.img and one or more images to replace in it"); 744 | } 745 | } else if (argv[1][0] == '-' && argv[1][1] == 'c' && argv[1][2] == '\0') { 746 | if (argc >= 4) { 747 | mode = RUN_CREATE; 748 | fmode[0] = 'w'; 749 | } else { 750 | print_usage("give one argument denoting the imgdata.img and one or more images to add in it"); 751 | } 752 | } else { 753 | print_usage("give one argument denoting the imgdata.img and one or more images to update in it"); 754 | } 755 | 756 | if (mode == RUN_NONE) { 757 | return EXIT_FAILURE; 758 | } 759 | 760 | if (!(img = fopen(argv[2], fmode))) { 761 | perror("Error opening file"); 762 | return EXIT_FAILURE; 763 | } 764 | 765 | switch (mode) { 766 | case RUN_LIST: 767 | if (read_file_header(img, &bimg, &imgs) == EXIT_FAILURE) { 768 | print_usage("not a valid imgdata.img"); 769 | } else { 770 | list_header_info(&bimg, imgs); 771 | } 772 | break; 773 | case RUN_EXTRACT: 774 | if (read_file_header(img, &bimg, &imgs) == EXIT_FAILURE) { 775 | print_usage("not a valid imgdata.img"); 776 | } else { 777 | extract_contents(img, bimg.num_files, imgs); 778 | } 779 | break; 780 | case RUN_UPDATE: 781 | if (read_file_header(img, &bimg, &imgs) == EXIT_FAILURE) { 782 | print_usage("not a valid imgdata.img"); 783 | } else { 784 | arg ufile[count]; 785 | parse_args(count, &argv[3], ufile); 786 | update_header(imgs, bimg.num_files, ufile, count); 787 | if (write_file_header(img, &bimg, &imgs) == EXIT_FAILURE) { 788 | printf("An error occured writing the updated header information\n"); 789 | } 790 | } 791 | break; 792 | case RUN_REPLACE: 793 | if (read_file_header(img, &bimg, &imgs) == EXIT_FAILURE) { 794 | print_usage("not a valid imgdata.img"); 795 | } else { 796 | arg ufile[count]; 797 | imgdata_content conts[bimg.num_files]; 798 | 799 | parse_args(count, &argv[3], ufile); 800 | parse_png_files(count, ufile); 801 | 802 | if (read_file_imgs(img, bimg.num_files, imgs, conts) == EXIT_FAILURE) { 803 | printf("An error occured getting the encoded content\n"); 804 | } else { 805 | update_header(imgs, bimg.num_files, ufile, count); 806 | if (write_file_header(img, &bimg, &imgs) == EXIT_FAILURE) { 807 | printf("An error occured writing the updated header information\n"); 808 | } else if (write_file_imgs(img, conts, bimg.num_files, ufile, count) == EXIT_FAILURE) { 809 | printf("An error occured writing the replaced image file\n"); 810 | } 811 | } 812 | free_file_imgs(conts, bimg.num_files); 813 | free_file_args(ufile, count); 814 | } 815 | break; 816 | case RUN_CREATE: 817 | { 818 | arg ufile[count]; 819 | parse_args(count, &argv[3], ufile); 820 | parse_png_files(count, ufile); 821 | 822 | create_file_header(&bimg, &imgs, count, ufile); 823 | 824 | update_header(imgs, count, ufile, count); 825 | if (write_file_header(img, &bimg, &imgs) == EXIT_FAILURE) { 826 | printf("An error occured writing the new header information\n"); 827 | } else if (write_file_args(img, ufile, count) == EXIT_FAILURE) { 828 | printf("An error occured writing the new image file\n"); 829 | } 830 | free_file_args(ufile, count); 831 | } 832 | break; 833 | default: 834 | print_usage("unknown mode to run in"); 835 | return EXIT_FAILURE; 836 | } 837 | 838 | /* Cleanup */ 839 | if (imgs != NULL) free(imgs); 840 | fclose(img); 841 | 842 | return EXIT_SUCCESS; 843 | } 844 | --------------------------------------------------------------------------------