fixes entering bootload messages to be less scary
[RRG-proxmark3.git] / client / src / flash.c
blobd5e2b2fa1fbbcdc2f21cd7c865b73da8d6f43f2b
1 //-----------------------------------------------------------------------------
2 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // See LICENSE.txt for the text of the license.
15 //-----------------------------------------------------------------------------
16 // ELF file flasher
17 //-----------------------------------------------------------------------------
19 #include "flash.h"
21 #include <stdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <ctype.h>
26 #include "ui.h"
27 #include "elf.h"
28 #include "proxendian.h"
29 #include "at91sam7s512.h"
30 #include "util_posix.h"
31 #include "comms.h"
32 #include "commonutil.h"
34 #define FLASH_START 0x100000
36 #define BOOTLOADER_SIZE 0x2000
37 #define BOOTLOADER_END (FLASH_START + BOOTLOADER_SIZE)
39 #define BLOCK_SIZE 0x200
41 #define FLASHER_VERSION BL_VERSION_1_0_0
43 static const uint8_t elf_ident[] = {
44 0x7f, 'E', 'L', 'F',
45 ELFCLASS32,
46 ELFDATA2LSB,
47 EV_CURRENT
50 static int chipid_to_mem_avail(uint32_t iChipID) {
51 int mem_avail = 0;
52 switch ((iChipID & 0xF00) >> 8) {
53 case 0:
54 mem_avail = 0;
55 break;
56 case 1:
57 mem_avail = 8;
58 break;
59 case 2:
60 mem_avail = 16;
61 break;
62 case 3:
63 mem_avail = 32;
64 break;
65 case 5:
66 mem_avail = 64;
67 break;
68 case 7:
69 mem_avail = 128;
70 break;
71 case 9:
72 mem_avail = 256;
73 break;
74 case 10:
75 mem_avail = 512;
76 break;
77 case 12:
78 mem_avail = 1024;
79 break;
80 case 14:
81 mem_avail = 2048;
83 return mem_avail;
86 // Turn PHDRs into flasher segments, checking for PHDR sanity and merging adjacent
87 // unaligned segments if needed
88 static int build_segs_from_phdrs(flash_file_t *ctx, uint32_t flash_size) {
89 uint32_t flash_end = FLASH_START + flash_size;
90 Elf32_Phdr_t *phdr = ctx->phdrs;
91 flash_seg_t *seg;
92 uint32_t last_end = 0;
94 ctx->segments = calloc(sizeof(flash_seg_t) * ctx->num_phdrs, sizeof(uint8_t));
95 if (!ctx->segments) {
96 PrintAndLogEx(ERR, "Out of memory");
97 return PM3_EMALLOC;
99 ctx->num_segs = 0;
100 seg = ctx->segments;
102 PrintAndLogEx(SUCCESS, "Loading usable ELF segments:");
103 for (int i = 0; i < ctx->num_phdrs; i++) {
104 if (le32(phdr->p_type) != PT_LOAD) {
105 phdr++;
106 continue;
108 uint32_t vaddr = le32(phdr->p_vaddr);
109 uint32_t paddr = le32(phdr->p_paddr);
110 uint32_t filesz = le32(phdr->p_filesz);
111 uint32_t memsz = le32(phdr->p_memsz);
112 uint32_t offset = le32(phdr->p_offset);
113 uint32_t flags = le32(phdr->p_flags);
114 if (!filesz) {
115 phdr++;
116 continue;
118 PrintAndLogEx(SUCCESS, " "_YELLOW_("%d")": V 0x%08x P 0x%08x (0x%08x->0x%08x) [%c%c%c] @0x%x",
119 i, vaddr, paddr, filesz, memsz,
120 (flags & PF_R) ? 'R' : ' ',
121 (flags & PF_W) ? 'W' : ' ',
122 (flags & PF_X) ? 'X' : ' ',
123 offset);
124 if (filesz != memsz) {
125 PrintAndLogEx(ERR, "Error: PHDR file size does not equal memory size\n"
126 "(DATA+BSS PHDRs do not make sense on ROM platforms!)");
127 return PM3_EFILE;
129 if (paddr < last_end) {
130 PrintAndLogEx(ERR, "Error: PHDRs not sorted or overlap");
131 return PM3_EFILE;
133 if (paddr < FLASH_START || (paddr + filesz) > flash_end) {
134 PrintAndLogEx(ERR, "Error: PHDR is not contained in Flash");
135 if ((paddr + filesz) > flash_end) {
136 PrintAndLogEx(ERR, "Firmware is probably too big for your device");
137 PrintAndLogEx(ERR, "See README.md for information on compiling for platforms with 256KB of flash memory");
139 return PM3_EFILE;
141 if (vaddr >= FLASH_START && vaddr < flash_end && (flags & PF_W)) {
142 PrintAndLogEx(ERR, "Error: Flash VMA segment is writable");
143 return PM3_EFILE;
146 uint8_t *data;
147 // make extra space if we need to move the data forward
148 data = calloc(filesz + BLOCK_SIZE, sizeof(uint8_t));
149 if (!data) {
150 PrintAndLogEx(ERR, "Error: Out of memory");
151 return PM3_EMALLOC;
153 memcpy(data, ctx->elf + offset, filesz);
155 uint32_t block_offset = paddr & (BLOCK_SIZE - 1);
156 if (block_offset) {
157 if (ctx->num_segs) {
158 flash_seg_t *prev_seg = seg - 1;
159 uint32_t this_end = paddr + filesz;
160 uint32_t this_firstblock = paddr & ~(BLOCK_SIZE - 1);
161 uint32_t prev_lastblock = (last_end - 1) & ~(BLOCK_SIZE - 1);
163 if (this_firstblock == prev_lastblock) {
164 uint32_t new_length = this_end - prev_seg->start;
165 uint32_t this_offset = paddr - prev_seg->start;
166 uint32_t hole = this_offset - prev_seg->length;
167 uint8_t *new_data = calloc(new_length, sizeof(uint8_t));
168 if (!new_data) {
169 PrintAndLogEx(ERR, "Error: Out of memory");
170 free(data);
171 return PM3_EMALLOC;
173 memset(new_data, 0xff, new_length);
174 memcpy(new_data, prev_seg->data, prev_seg->length);
175 memcpy(new_data + this_offset, data, filesz);
176 PrintAndLogEx(INFO, "Note: Extending previous segment from 0x%x to 0x%x bytes",
177 prev_seg->length, new_length);
178 if (hole)
179 PrintAndLogEx(INFO, "Note: 0x%x-byte hole created", hole);
180 free(data);
181 free(prev_seg->data);
182 prev_seg->data = new_data;
183 prev_seg->length = new_length;
184 last_end = this_end;
185 phdr++;
186 continue;
189 PrintAndLogEx(WARNING, "Warning: segment does not begin on a block boundary, will pad");
190 memmove(data + block_offset, data, filesz);
191 memset(data, 0xFF, block_offset);
192 filesz += block_offset;
193 paddr -= block_offset;
196 seg->data = data;
197 seg->start = paddr;
198 seg->length = filesz;
199 seg++;
200 ctx->num_segs++;
202 last_end = paddr + filesz;
203 phdr++;
205 return PM3_SUCCESS;
208 // Sanity check segments and check for bootloader writes
209 static int check_segs(flash_file_t *ctx, int can_write_bl, uint32_t flash_size) {
210 uint32_t flash_end = FLASH_START + flash_size;
211 for (int i = 0; i < ctx->num_segs; i++) {
212 flash_seg_t *seg = &ctx->segments[i];
214 if (seg->start & (BLOCK_SIZE - 1)) {
215 PrintAndLogEx(ERR, "Error: Segment is not aligned");
216 return PM3_EFILE;
218 if (seg->start < FLASH_START) {
219 PrintAndLogEx(ERR, "Error: Segment is outside of flash bounds");
220 return PM3_EFILE;
222 if (seg->start + seg->length > flash_end) {
223 PrintAndLogEx(ERR, "Error: Segment is outside of flash bounds");
224 return PM3_EFILE;
226 if (!can_write_bl && seg->start < BOOTLOADER_END) {
227 PrintAndLogEx(ERR, "Attempted to write bootloader but bootloader writes are not enabled");
228 return PM3_EINVARG;
230 if (can_write_bl && seg->start < BOOTLOADER_END && (seg->start + seg->length > BOOTLOADER_END)) {
231 PrintAndLogEx(ERR, "Error: Segment is outside of bootloader bounds");
232 return PM3_EFILE;
235 return PM3_SUCCESS;
238 static int print_and_validate_version(struct version_information_t *vi) {
239 if (vi->magic != VERSION_INFORMATION_MAGIC) {
240 return PM3_EFILE;
243 // same limit as for ARM image
244 char temp[PM3_CMD_DATA_SIZE - 12] = {0};
245 FormatVersionInformation(temp, sizeof(temp), "", vi);
246 PrintAndLogEx(SUCCESS, _CYAN_("ELF file version") _YELLOW_(" %s"), temp);
248 if (strlen(g_version_information.armsrc) == 9) {
249 if (strncmp(vi->armsrc, g_version_information.armsrc, 9) != 0) {
250 PrintAndLogEx(WARNING, _RED_("ARM firmware does not match the source at the time the client was compiled"));
251 return PM3_EINVARG;
252 } else {
253 return PM3_SUCCESS;
256 return PM3_EUNDEF;
259 // Load an ELF file for flashing
260 int flash_load(flash_file_t *ctx, bool force) {
261 FILE *fd;
262 Elf32_Ehdr_t *ehdr;
263 Elf32_Shdr_t *shdrs = NULL;
264 uint8_t *shstr = NULL;
265 struct version_information_t *vi = NULL;
266 int res = PM3_EUNDEF;
268 fd = fopen(ctx->filename, "rb");
269 if (!fd) {
270 PrintAndLogEx(ERR, _RED_("Could not open file") " %s >>> ", ctx->filename);
271 res = PM3_EFILE;
272 goto fail;
275 PrintAndLogEx(SUCCESS, _CYAN_("Loading ELF file") _YELLOW_(" %s"), ctx->filename);
277 // get filesize in order to malloc memory
278 fseek(fd, 0, SEEK_END);
279 long fsize = ftell(fd);
280 fseek(fd, 0, SEEK_SET);
282 if (fsize <= 0) {
283 PrintAndLogEx(ERR, "Error, when getting filesize");
284 res = PM3_EFILE;
285 fclose(fd);
286 goto fail;
289 ctx->elf = calloc(fsize + 1, sizeof(uint8_t));
290 if (!ctx->elf) {
291 PrintAndLogEx(ERR, "Error, cannot allocate memory");
292 res = PM3_EMALLOC;
293 fclose(fd);
294 goto fail;
297 size_t bytes_read = fread(ctx->elf, 1, fsize, fd);
298 fclose(fd);
300 if (bytes_read != fsize) {
301 PrintAndLogEx(ERR, "Error, bytes read mismatch file size");
302 res = PM3_EFILE;
303 goto fail;
306 ehdr = (Elf32_Ehdr_t *)ctx->elf;
307 if (memcmp(ehdr->e_ident, elf_ident, sizeof(elf_ident))
308 || le32(ehdr->e_version) != 1) {
309 PrintAndLogEx(ERR, "Not an ELF file or wrong ELF type");
310 res = PM3_EFILE;
311 goto fail;
314 if (le16(ehdr->e_type) != ET_EXEC) {
315 PrintAndLogEx(ERR, "ELF is not executable");
316 res = PM3_EFILE;
317 goto fail;
320 if (le16(ehdr->e_machine) != EM_ARM) {
321 PrintAndLogEx(ERR, "Wrong ELF architecture");
322 res = PM3_EFILE;
323 goto fail;
326 if (!ehdr->e_phnum || !ehdr->e_phoff) {
327 PrintAndLogEx(ERR, "ELF has no PHDRs");
328 res = PM3_EFILE;
329 goto fail;
332 if (le16(ehdr->e_phentsize) != sizeof(Elf32_Phdr_t)) {
333 // could be a structure padding issue...
334 PrintAndLogEx(ERR, "Either the ELF file or this code is made of fail");
335 res = PM3_EFILE;
336 goto fail;
339 ctx->num_phdrs = le16(ehdr->e_phnum);
340 ctx->phdrs = (Elf32_Phdr_t *)(ctx->elf + le32(ehdr->e_phoff));
341 shdrs = (Elf32_Shdr_t *)(ctx->elf + le32(ehdr->e_shoff));
342 shstr = ctx->elf + le32(shdrs[ehdr->e_shstrndx].sh_offset);
344 for (uint16_t i = 0; i < le16(ehdr->e_shnum); i++) {
346 if (strcmp(((char *)shstr) + shdrs[i].sh_name, ".version_information") == 0) {
347 vi = (struct version_information_t *)(ctx->elf + le32(shdrs[i].sh_offset));
348 res = print_and_validate_version(vi);
349 break;
352 if (strcmp(((char *)shstr) + shdrs[i].sh_name, ".bootphase1") == 0) {
353 uint32_t offset;
354 memcpy(&offset, ctx->elf + le32(shdrs[i].sh_offset) + le32(shdrs[i].sh_size) - 4, sizeof(uint32_t));
355 if (offset >= le32(shdrs[i].sh_addr)) {
356 offset -= le32(shdrs[i].sh_addr);
357 if (offset < le32(shdrs[i].sh_size)) {
358 vi = (struct version_information_t *)(ctx->elf + le32(shdrs[i].sh_offset) + offset);
359 res = print_and_validate_version(vi);
362 break;
365 if (res == PM3_SUCCESS)
366 return res;
368 // We could not find proper version_information
369 if (res == PM3_EUNDEF)
370 PrintAndLogEx(WARNING, "Unable to check version_information");
372 if (force)
373 return PM3_SUCCESS;
375 PrintAndLogEx(INFO, "Make sure to flash a correct and up-to-date version");
376 PrintAndLogEx(INFO, "You can force flashing this firmware by using the option '--force'");
377 fail:
378 flash_free(ctx);
379 return res;
382 // Prepare an ELF file for flashing
383 int flash_prepare(flash_file_t *ctx, int can_write_bl, int flash_size) {
384 int res = PM3_EUNDEF;
386 res = build_segs_from_phdrs(ctx, flash_size);
387 if (res != PM3_SUCCESS)
388 goto fail;
389 res = check_segs(ctx, can_write_bl, flash_size);
390 if (res != PM3_SUCCESS)
391 goto fail;
393 return PM3_SUCCESS;
395 fail:
396 flash_free(ctx);
397 return res;
400 // Get the state of the proxmark, backwards compatible
401 static int get_proxmark_state(uint32_t *state) {
402 SendCommandBL(CMD_DEVICE_INFO, 0, 0, 0, NULL, 0);
403 PacketResponseNG resp;
404 WaitForResponse(CMD_UNKNOWN, &resp); // wait for any response. No timeout.
406 // Three outcomes:
407 // 1. The old bootrom code will ignore CMD_DEVICE_INFO, but respond with an ACK
408 // 2. The old os code will respond with CMD_DEBUG_PRINT_STRING and "unknown command"
409 // 3. The new bootrom and os codes will respond with CMD_DEVICE_INFO and flags
411 switch (resp.cmd) {
412 case CMD_ACK:
413 *state = DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM;
414 break;
415 case CMD_DEBUG_PRINT_STRING:
416 *state = DEVICE_INFO_FLAG_CURRENT_MODE_OS;
417 break;
418 case CMD_DEVICE_INFO:
419 *state = resp.oldarg[0];
420 break;
421 default:
422 PrintAndLogEx(ERR, _RED_("Error:") " Couldn't get Proxmark3 state, bad response type: 0x%04x", resp.cmd);
423 return PM3_EFATAL;
424 break;
426 return PM3_SUCCESS;
429 // Enter the bootloader to be able to start flashing
430 static int enter_bootloader(char *serial_port_name, bool wait_appear) {
432 uint32_t state = 0;
433 int ret = get_proxmark_state(&state);
434 if (ret != PM3_SUCCESS) {
435 return ret;
438 /* Already in flash state, we're done. */
439 if ((state & DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM) == DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM) {
440 return PM3_SUCCESS;
443 if ((state & DEVICE_INFO_FLAG_CURRENT_MODE_OS) == DEVICE_INFO_FLAG_CURRENT_MODE_OS) {
444 PrintAndLogEx(SUCCESS, _CYAN_("Entering bootloader..."));
446 if (
447 ((state & DEVICE_INFO_FLAG_BOOTROM_PRESENT) == DEVICE_INFO_FLAG_BOOTROM_PRESENT) &&
448 ((state & DEVICE_INFO_FLAG_OSIMAGE_PRESENT) == DEVICE_INFO_FLAG_OSIMAGE_PRESENT)) {
449 // New style handover: Send CMD_START_FLASH, which will reset the board
450 // and enter the bootrom on the next boot.
451 SendCommandBL(CMD_START_FLASH, 0, 0, 0, NULL, 0);
452 PrintAndLogEx(SUCCESS, "(Press and release the button only to " _YELLOW_("abort") ")");
453 } else {
454 // Old style handover: Ask the user to press the button, then reset the board
455 SendCommandBL(CMD_HARDWARE_RESET, 0, 0, 0, NULL, 0);
456 PrintAndLogEx(SUCCESS, "Press and hold down button NOW if your bootloader requires it.");
458 msleep(500);
459 PrintAndLogEx(SUCCESS, _CYAN_("Trigger restart..."));
460 CloseProxmark(g_session.current_device);
461 // Let time to OS to make the port disappear
462 msleep(1000);
464 if (wait_appear == false) {
465 return PM3_SUCCESS;
466 } else if (OpenProxmark(&g_session.current_device, serial_port_name, true, 60, true, FLASHMODE_SPEED)) {
467 PrintAndLogEx(NORMAL, _GREEN_(" found"));
468 return PM3_SUCCESS;
469 } else {
470 PrintAndLogEx(ERR, _RED_("Error:") " Proxmark3 not found.");
471 return PM3_ETIMEOUT;
475 PrintAndLogEx(ERR, _RED_("Error:") " Unknown Proxmark3 mode");
476 return PM3_EFATAL;
479 static int wait_for_ack(PacketResponseNG *ack) {
480 WaitForResponse(CMD_UNKNOWN, ack);
482 if (ack->cmd != CMD_ACK) {
483 PrintAndLogEx(ERR, "Error: Unexpected reply 0x%04x %s (expected ACK)",
484 ack->cmd,
485 (ack->cmd == CMD_NACK) ? "NACK" : ""
487 return PM3_ESOFT;
489 return PM3_SUCCESS;
492 static bool gs_printed_msg = false;
493 static void flash_suggest_update_bootloader(void) {
494 if (gs_printed_msg) {
495 return;
498 PrintAndLogEx(ERR, _RED_("It is recommended that you first" _YELLOW_(" update your bootloader") _RED_(" alone,")));
499 PrintAndLogEx(ERR, _RED_("reboot the Proxmark3 then only update the main firmware") "\n");
500 PrintAndLogEx(NORMAL, "");
501 PrintAndLogEx(ERR, "------------- " _CYAN_("Follow these steps") " -------------------");
502 PrintAndLogEx(NORMAL, "");
503 PrintAndLogEx(ERR, " 1) ./pm3-flash-bootrom");
504 PrintAndLogEx(ERR, " 2) ./pm3-flash-fullimage");
505 PrintAndLogEx(ERR, " 3) ./pm3");
506 PrintAndLogEx(NORMAL, "");
507 PrintAndLogEx(INFO, "---------------------------------------------------");
508 PrintAndLogEx(NORMAL, "");
509 gs_printed_msg = true;
512 static void flash_suggest_update_flasher(void) {
513 PrintAndLogEx(ERR, _RED_("It is recommended that you first " _YELLOW_("update your flasher")));
516 // Go into flashing mode
517 int flash_start_flashing(int enable_bl_writes, char *serial_port_name, uint32_t *max_allowed) {
519 int ret = enter_bootloader(serial_port_name, true);
520 if (ret != PM3_SUCCESS) {
521 return ret;
524 uint32_t state;
525 ret = get_proxmark_state(&state);
526 if (ret != PM3_SUCCESS) {
527 return ret;
530 uint32_t chipinfo = 0;
532 if ((state & DEVICE_INFO_FLAG_UNDERSTANDS_CHIP_INFO) == DEVICE_INFO_FLAG_UNDERSTANDS_CHIP_INFO) {
533 SendCommandBL(CMD_CHIP_INFO, 0, 0, 0, NULL, 0);
534 PacketResponseNG resp;
535 WaitForResponse(CMD_CHIP_INFO, &resp);
536 chipinfo = resp.oldarg[0];
539 int version = BL_VERSION_INVALID;
541 if ((state & DEVICE_INFO_FLAG_UNDERSTANDS_VERSION) == DEVICE_INFO_FLAG_UNDERSTANDS_VERSION) {
543 SendCommandBL(CMD_BL_VERSION, 0, 0, 0, NULL, 0);
544 PacketResponseNG resp;
545 WaitForResponse(CMD_BL_VERSION, &resp);
546 version = resp.oldarg[0];
548 if ((BL_VERSION_MAJOR(version) < BL_VERSION_FIRST_MAJOR) || (BL_VERSION_MAJOR(version) > BL_VERSION_LAST_MAJOR)) {
549 // version info seems fishy
550 version = BL_VERSION_INVALID;
551 PrintAndLogEx(ERR, _RED_("====================== OBS ! ==========================="));
552 PrintAndLogEx(ERR, _RED_("Note: Your bootloader reported an invalid version number"));
553 flash_suggest_update_bootloader();
555 } else if (BL_VERSION_MAJOR(version) < BL_VERSION_MAJOR(FLASHER_VERSION)) {
556 PrintAndLogEx(ERR, _RED_("====================== OBS ! ==================================="));
557 PrintAndLogEx(ERR, _RED_("Note: Your bootloader reported a version older than this flasher"));
558 flash_suggest_update_bootloader();
559 } else if (BL_VERSION_MAJOR(version) > BL_VERSION_MAJOR(FLASHER_VERSION)) {
560 PrintAndLogEx(ERR, _RED_("====================== OBS ! ========================="));
561 PrintAndLogEx(ERR, _RED_("Note: Your bootloader is more recent than this flasher"));
562 flash_suggest_update_flasher();
564 } else {
565 PrintAndLogEx(ERR, _RED_("====================== OBS ! ==========================================="));
566 PrintAndLogEx(ERR, _RED_("Note: Your bootloader does not understand the new" _YELLOW_(" CMD_BL_VERSION") _RED_(" command")));
567 flash_suggest_update_bootloader();
570 uint32_t flash_end = FLASH_START + AT91C_IFLASH_PAGE_SIZE * AT91C_IFLASH_NB_OF_PAGES / 2;
571 *max_allowed = 256;
573 int mem_avail = chipid_to_mem_avail(chipinfo);
574 if (mem_avail != 0) {
576 PrintAndLogEx(INFO, "Available memory on this board: "_YELLOW_("%uK") " bytes\n", mem_avail);
578 if (mem_avail > 256) {
579 if (BL_VERSION_MAJOR(version) < BL_VERSION_MAJOR(BL_VERSION_1_0_0)) {
580 PrintAndLogEx(ERR, _RED_("====================== OBS ! ======================"));
581 PrintAndLogEx(ERR, _RED_("Your bootloader does not support writing above 256k"));
582 flash_suggest_update_bootloader();
583 } else {
584 flash_end = FLASH_START + AT91C_IFLASH_PAGE_SIZE * AT91C_IFLASH_NB_OF_PAGES;
585 *max_allowed = mem_avail;
589 } else {
590 PrintAndLogEx(INFO, "Available memory on this board: "_RED_("UNKNOWN")"\n");
591 PrintAndLogEx(ERR, _RED_("====================== OBS ! ======================================"));
592 PrintAndLogEx(ERR, _RED_("Note: Your bootloader does not understand the new" _YELLOW_(" CHIP_INFO") _RED_(" command")));
593 flash_suggest_update_bootloader();
596 if (enable_bl_writes) {
597 PrintAndLogEx(INFO, "Permitted flash range: 0x%08x-0x%08x", FLASH_START, flash_end);
598 } else {
599 PrintAndLogEx(INFO, "Permitted flash range: 0x%08x-0x%08x", BOOTLOADER_END, flash_end);
602 if ((state & DEVICE_INFO_FLAG_UNDERSTANDS_START_FLASH) == DEVICE_INFO_FLAG_UNDERSTANDS_START_FLASH) {
604 if (enable_bl_writes) {
605 SendCommandBL(CMD_START_FLASH, FLASH_START, flash_end, START_FLASH_MAGIC, NULL, 0);
606 } else {
607 SendCommandBL(CMD_START_FLASH, BOOTLOADER_END, flash_end, 0, NULL, 0);
609 PacketResponseNG resp;
610 return wait_for_ack(&resp);
612 } else {
613 PrintAndLogEx(ERR, _RED_("====================== OBS ! ========================================"));
614 PrintAndLogEx(ERR, _RED_("Note: Your bootloader does not understand the new" _YELLOW_(" START_FLASH") _RED_(" command")));
615 flash_suggest_update_bootloader();
617 return PM3_SUCCESS;
620 // Reboot into bootloader
621 int flash_reboot_bootloader(char *serial_port_name, bool wait_appear) {
622 return enter_bootloader(serial_port_name, wait_appear);
625 static int write_block(uint32_t address, uint8_t *data, uint32_t length) {
626 uint8_t block_buf[BLOCK_SIZE];
627 memset(block_buf, 0xFF, BLOCK_SIZE);
628 memcpy(block_buf, data, length);
629 PacketResponseNG resp;
630 #if defined ICOPYX
631 SendCommandBL(CMD_FINISH_WRITE, address, 0xff, 0x1fd, block_buf, length);
632 #else
633 SendCommandBL(CMD_FINISH_WRITE, address, 0, 0, block_buf, length);
634 #endif
635 int ret = wait_for_ack(&resp);
636 if (ret && resp.oldarg[0]) {
637 uint32_t lock_bits = resp.oldarg[0] >> 16;
638 bool lock_error = resp.oldarg[0] & AT91C_MC_LOCKE;
639 bool prog_error = resp.oldarg[0] & AT91C_MC_PROGE;
640 bool security_bit = resp.oldarg[0] & AT91C_MC_SECURITY;
641 PrintAndLogEx(NORMAL, "%s", lock_error ? " Lock Error" : "");
642 PrintAndLogEx(NORMAL, "%s", prog_error ? " Invalid Command or bad Keyword" : "");
643 PrintAndLogEx(NORMAL, "%s", security_bit ? " Security Bit is set!" : "");
644 PrintAndLogEx(NORMAL, " Lock Bits: 0x%04x", lock_bits);
646 return ret;
649 static const char ice[] =
650 "...................................................................\n @@@ @@@@@@@ @@@@@@@@ @@@@@@@@@@ @@@@@@ @@@ @@@\n"
651 " @@! !@@ @@! @@! @@! @@! @@! @@@ @@!@!@@@\n !!@ !@! @!!!:! @!! !!@ @!@ @!@!@!@! @!@@!!@!\n"
652 " !!: :!! !!: !!: !!: !!: !!! !!: !!!\n : :: :: : : :: ::: : : : : : :: : \n"
653 _RED_(" . .. .. . . .. ... . . . . . .. . ");
655 // Write a file's segments to Flash
656 int flash_write(flash_file_t *ctx) {
657 int len = 0;
659 PrintAndLogEx(SUCCESS, "Writing segments for file: %s", ctx->filename);
661 char ice2[sizeof(ice)] = {0};
662 char ice3[sizeof(ice)] = {0};
663 memcpy_filter_ansi(ice2, ice, sizeof(ice), !g_session.supports_colors);
664 memcpy_filter_emoji(ice3, ice2, sizeof(ice2), g_session.emoji_mode);
665 size_t ice3len = strlen(ice3);
667 for (int i = 0; i < ctx->num_segs; i++) {
668 flash_seg_t *seg = &ctx->segments[i];
670 uint32_t length = seg->length;
671 uint32_t blocks = (length + BLOCK_SIZE - 1) / BLOCK_SIZE;
672 uint32_t end = seg->start + length;
674 PrintAndLogEx(SUCCESS, " 0x%08x..0x%08x [0x%x / %u blocks]", seg->start, end - 1, length, blocks);
675 fflush(stdout);
676 int block = 0;
677 uint8_t *data = seg->data;
678 uint32_t baddr = seg->start;
680 while (length) {
681 uint32_t block_size = length;
682 if (block_size > BLOCK_SIZE) {
683 block_size = BLOCK_SIZE;
686 if (write_block(baddr, data, block_size) < 0) {
687 PrintAndLogEx(ERR, "Error writing block %d of %u", block, blocks);
688 return PM3_EFATAL;
691 data += block_size;
692 baddr += block_size;
693 length -= block_size;
694 block++;
696 if (len < ice3len) {
697 fprintf(stdout, "%c", ice3[len++]);
698 } else {
700 if ((len - ice3len) % 67 == 0) {
701 fprintf(stdout, "\n");
703 fprintf(stdout, ".");
704 len++;
706 fflush(stdout);
708 PrintAndLogEx(NORMAL, " " _GREEN_("ok"));
709 fflush(stdout);
711 return PM3_SUCCESS;
714 // free a file context
715 void flash_free(flash_file_t *ctx) {
717 if (!ctx) {
718 return;
721 if (ctx->filename != NULL) {
722 free(ctx->filename);
723 ctx->filename = NULL;
726 if (ctx->elf) {
727 free(ctx->elf);
728 ctx->elf = NULL;
729 ctx->phdrs = NULL;
730 ctx->num_phdrs = 0;
733 if (ctx->segments) {
735 for (int i = 0; i < ctx->num_segs; i++) {
736 free(ctx->segments[i].data);
739 free(ctx->segments);
740 ctx->segments = NULL;
741 ctx->num_segs = 0;
745 // just reset the unit
746 int flash_stop_flashing(void) {
747 SendCommandBL(CMD_HARDWARE_RESET, 0, 0, 0, NULL, 0);
748 msleep(100);
749 return PM3_SUCCESS;