]> git.zerfleddert.de Git - proxmark3-svn/blob - client/flash.c
Comms refactor (prerequisite of libproxmark work) (#371)
[proxmark3-svn] / client / flash.c
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2010 Hector Martin "marcan" <marcan@marcansoft.com>
3 //
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
6 // the license.
7 //-----------------------------------------------------------------------------
8 // ELF file flasher
9 //-----------------------------------------------------------------------------
10
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdlib.h>
14 #include <inttypes.h>
15 #include <unistd.h>
16
17 #include "proxmark3.h"
18 #include "util.h"
19 #include "util_posix.h"
20 #include "flash.h"
21 #include "elf.h"
22 #include "proxendian.h"
23 #include "usb_cmd.h"
24 #include "comms.h"
25
26 // FIXME: what the fuckity fuck
27 unsigned int current_command = CMD_UNKNOWN;
28
29 #define FLASH_START 0x100000
30 #define FLASH_SIZE (256*1024)
31 #define FLASH_END (FLASH_START + FLASH_SIZE)
32 #define BOOTLOADER_SIZE 0x2000
33 #define BOOTLOADER_END (FLASH_START + BOOTLOADER_SIZE)
34
35 #define BLOCK_SIZE 0x200
36
37 static const uint8_t elf_ident[] = {
38 0x7f, 'E', 'L', 'F',
39 ELFCLASS32,
40 ELFDATA2LSB,
41 EV_CURRENT
42 };
43
44 void CloseProxmark(receiver_arg* conn, char* serial_port_name) {
45 pthread_mutex_lock(&conn->recv_lock);
46
47 // Block the port from being used by anything
48 serial_port* my_port = GetSerialPort();
49 SetSerialPort(NULL);
50
51 // Then close the port.
52 uart_close(my_port);
53 pthread_mutex_unlock(&conn->recv_lock);
54
55 // Fix for linux, it seems that it is extremely slow to release the serial port file descriptor /dev/*
56 unlink(serial_port_name);
57 }
58
59 bool OpenProxmark(char* serial_port_name) {
60 serial_port *new_port = uart_open(serial_port_name);
61 if (new_port == INVALID_SERIAL_PORT || new_port == CLAIMED_SERIAL_PORT) {
62 //poll once a second
63 return false;
64 }
65
66 SetSerialPort(new_port);
67 return true;
68 }
69
70 // Turn PHDRs into flasher segments, checking for PHDR sanity and merging adjacent
71 // unaligned segments if needed
72 static int build_segs_from_phdrs(flash_file_t *ctx, FILE *fd, Elf32_Phdr *phdrs, int num_phdrs)
73 {
74 Elf32_Phdr *phdr = phdrs;
75 flash_seg_t *seg;
76 uint32_t last_end = 0;
77
78 ctx->segments = malloc(sizeof(flash_seg_t) * num_phdrs);
79 if (!ctx->segments) {
80 fprintf(stderr, "Out of memory\n");
81 return -1;
82 }
83 ctx->num_segs = 0;
84 seg = ctx->segments;
85
86 fprintf(stderr, "Loading usable ELF segments:\n");
87 for (int i = 0; i < num_phdrs; i++) {
88 if (le32(phdr->p_type) != PT_LOAD) {
89 phdr++;
90 continue;
91 }
92 uint32_t vaddr = le32(phdr->p_vaddr);
93 uint32_t paddr = le32(phdr->p_paddr);
94 uint32_t filesz = le32(phdr->p_filesz);
95 uint32_t memsz = le32(phdr->p_memsz);
96 uint32_t offset = le32(phdr->p_offset);
97 uint32_t flags = le32(phdr->p_flags);
98 if (!filesz) {
99 phdr++;
100 continue;
101 }
102 fprintf(stderr, "%d: V 0x%08x P 0x%08x (0x%08x->0x%08x) [%c%c%c] @0x%x\n",
103 i, vaddr, paddr, filesz, memsz,
104 flags & PF_R ? 'R' : ' ',
105 flags & PF_W ? 'W' : ' ',
106 flags & PF_X ? 'X' : ' ',
107 offset);
108 if (filesz != memsz) {
109 fprintf(stderr, "Error: PHDR file size does not equal memory size\n"
110 "(DATA+BSS PHDRs do not make sense on ROM platforms!)\n");
111 return -1;
112 }
113 if (paddr < last_end) {
114 fprintf(stderr, "Error: PHDRs not sorted or overlap\n");
115 return -1;
116 }
117 if (paddr < FLASH_START || (paddr+filesz) > FLASH_END) {
118 fprintf(stderr, "Error: PHDR is not contained in Flash\n");
119 return -1;
120 }
121 if (vaddr >= FLASH_START && vaddr < FLASH_END && (flags & PF_W)) {
122 fprintf(stderr, "Error: Flash VMA segment is writable\n");
123 return -1;
124 }
125
126 uint8_t *data;
127 // make extra space if we need to move the data forward
128 data = malloc(filesz + BLOCK_SIZE);
129 if (!data) {
130 fprintf(stderr, "Out of memory\n");
131 return -1;
132 }
133 if (fseek(fd, offset, SEEK_SET) < 0 || fread(data, 1, filesz, fd) != filesz) {
134 fprintf(stderr, "Error while reading PHDR payload\n");
135 free(data);
136 return -1;
137 }
138
139 uint32_t block_offset = paddr & (BLOCK_SIZE-1);
140 if (block_offset) {
141 if (ctx->num_segs) {
142 flash_seg_t *prev_seg = seg - 1;
143 uint32_t this_end = paddr + filesz;
144 uint32_t this_firstblock = paddr & ~(BLOCK_SIZE-1);
145 uint32_t prev_lastblock = (last_end - 1) & ~(BLOCK_SIZE-1);
146
147 if (this_firstblock == prev_lastblock) {
148 uint32_t new_length = this_end - prev_seg->start;
149 uint32_t this_offset = paddr - prev_seg->start;
150 uint32_t hole = this_offset - prev_seg->length;
151 uint8_t *new_data = malloc(new_length);
152 if (!new_data) {
153 fprintf(stderr, "Out of memory\n");
154 free(data);
155 return -1;
156 }
157 memset(new_data, 0xff, new_length);
158 memcpy(new_data, prev_seg->data, prev_seg->length);
159 memcpy(new_data + this_offset, data, filesz);
160 fprintf(stderr, "Note: Extending previous segment from 0x%x to 0x%x bytes\n",
161 prev_seg->length, new_length);
162 if (hole)
163 fprintf(stderr, "Note: 0x%x-byte hole created\n", hole);
164 free(data);
165 free(prev_seg->data);
166 prev_seg->data = new_data;
167 prev_seg->length = new_length;
168 last_end = this_end;
169 phdr++;
170 continue;
171 }
172 }
173 fprintf(stderr, "Warning: segment does not begin on a block boundary, will pad\n");
174 memmove(data + block_offset, data, filesz);
175 memset(data, 0xFF, block_offset);
176 filesz += block_offset;
177 paddr -= block_offset;
178 }
179
180 seg->data = data;
181 seg->start = paddr;
182 seg->length = filesz;
183 seg++;
184 ctx->num_segs++;
185
186 last_end = paddr + filesz;
187 phdr++;
188 }
189 return 0;
190 }
191
192 // Sanity check segments and check for bootloader writes
193 static int check_segs(flash_file_t *ctx, int can_write_bl) {
194 for (int i = 0; i < ctx->num_segs; i++) {
195 flash_seg_t *seg = &ctx->segments[i];
196
197 if (seg->start & (BLOCK_SIZE-1)) {
198 fprintf(stderr, "Error: Segment is not aligned\n");
199 return -1;
200 }
201 if (seg->start < FLASH_START) {
202 fprintf(stderr, "Error: Segment is outside of flash bounds\n");
203 return -1;
204 }
205 if (seg->start + seg->length > FLASH_END) {
206 fprintf(stderr, "Error: Segment is outside of flash bounds\n");
207 return -1;
208 }
209 if (!can_write_bl && seg->start < BOOTLOADER_END) {
210 fprintf(stderr, "Attempted to write bootloader but bootloader writes are not enabled\n");
211 return -1;
212 }
213 }
214 return 0;
215 }
216
217 // Load an ELF file and prepare it for flashing
218 int flash_load(flash_file_t *ctx, const char *name, int can_write_bl)
219 {
220 FILE *fd = NULL;
221 Elf32_Ehdr ehdr;
222 Elf32_Phdr *phdrs = NULL;
223 int num_phdrs;
224 int res;
225
226 fd = fopen(name, "rb");
227 if (!fd) {
228 fprintf(stderr, "Could not open file '%s': ", name);
229 perror(NULL);
230 goto fail;
231 }
232
233 fprintf(stderr, "Loading ELF file '%s'...\n", name);
234
235 if (fread(&ehdr, sizeof(ehdr), 1, fd) != 1) {
236 fprintf(stderr, "Error while reading ELF file header\n");
237 goto fail;
238 }
239 if (memcmp(ehdr.e_ident, elf_ident, sizeof(elf_ident))
240 || le32(ehdr.e_version) != 1)
241 {
242 fprintf(stderr, "Not an ELF file or wrong ELF type\n");
243 goto fail;
244 }
245 if (le16(ehdr.e_type) != ET_EXEC) {
246 fprintf(stderr, "ELF is not executable\n");
247 goto fail;
248 }
249 if (le16(ehdr.e_machine) != EM_ARM) {
250 fprintf(stderr, "Wrong ELF architecture\n");
251 goto fail;
252 }
253 if (!ehdr.e_phnum || !ehdr.e_phoff) {
254 fprintf(stderr, "ELF has no PHDRs\n");
255 goto fail;
256 }
257 if (le16(ehdr.e_phentsize) != sizeof(Elf32_Phdr)) {
258 // could be a structure padding issue...
259 fprintf(stderr, "Either the ELF file or this code is made of fail\n");
260 goto fail;
261 }
262 num_phdrs = le16(ehdr.e_phnum);
263
264 phdrs = malloc(le16(ehdr.e_phnum) * sizeof(Elf32_Phdr));
265 if (!phdrs) {
266 fprintf(stderr, "Out of memory\n");
267 goto fail;
268 }
269 if (fseek(fd, le32(ehdr.e_phoff), SEEK_SET) < 0) {
270 fprintf(stderr, "Error while reading ELF PHDRs\n");
271 goto fail;
272 }
273 if (fread(phdrs, sizeof(Elf32_Phdr), num_phdrs, fd) != num_phdrs) {
274 fprintf(stderr, "Error while reading ELF PHDRs\n");
275 goto fail;
276 }
277
278 res = build_segs_from_phdrs(ctx, fd, phdrs, num_phdrs);
279 if (res < 0)
280 goto fail;
281 res = check_segs(ctx, can_write_bl);
282 if (res < 0)
283 goto fail;
284
285 free(phdrs);
286 fclose(fd);
287 ctx->filename = name;
288 return 0;
289
290 fail:
291 if (phdrs)
292 free(phdrs);
293 if (fd)
294 fclose(fd);
295 flash_free(ctx);
296 return -1;
297 }
298
299 // Get the state of the proxmark, backwards compatible
300 static int get_proxmark_state(uint32_t *state)
301 {
302 UsbCommand c;
303 c.cmd = CMD_DEVICE_INFO;
304 SendCommand(&c);
305 UsbCommand resp;
306 while (!WaitForResponse(CMD_ANY, &resp)) {
307 // Keep waiting for a response
308 msleep(100);
309 }
310
311 // Three outcomes:
312 // 1. The old bootrom code will ignore CMD_DEVICE_INFO, but respond with an ACK
313 // 2. The old os code will respond with CMD_DEBUG_PRINT_STRING and "unknown command"
314 // 3. The new bootrom and os codes will respond with CMD_DEVICE_INFO and flags
315
316 switch (resp.cmd) {
317 case CMD_ACK:
318 *state = DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM;
319 break;
320 case CMD_DEBUG_PRINT_STRING:
321 *state = DEVICE_INFO_FLAG_CURRENT_MODE_OS;
322 break;
323 case CMD_DEVICE_INFO:
324 *state = resp.arg[0];
325 break;
326 default:
327 fprintf(stderr, "Error: Couldn't get proxmark state, bad response type: 0x%04" PRIx64 "\n", resp.cmd);
328 return -1;
329 break;
330 }
331
332 return 0;
333 }
334
335 // Enter the bootloader to be able to start flashing
336 static int enter_bootloader(receiver_arg* conn, char *serial_port_name)
337 {
338 uint32_t state;
339
340 if (get_proxmark_state(&state) < 0)
341 return -1;
342
343 if (state & DEVICE_INFO_FLAG_CURRENT_MODE_BOOTROM) {
344 /* Already in flash state, we're done. */
345 return 0;
346 }
347
348 if (state & DEVICE_INFO_FLAG_CURRENT_MODE_OS) {
349 fprintf(stderr,"Entering bootloader...\n");
350 UsbCommand c;
351 memset(&c, 0, sizeof (c));
352
353 if ((state & DEVICE_INFO_FLAG_BOOTROM_PRESENT)
354 && (state & DEVICE_INFO_FLAG_OSIMAGE_PRESENT))
355 {
356 // New style handover: Send CMD_START_FLASH, which will reset the board
357 // and enter the bootrom on the next boot.
358 c.cmd = CMD_START_FLASH;
359 SendCommand(&c);
360 fprintf(stderr,"(Press and release the button only to abort)\n");
361 } else {
362 // Old style handover: Ask the user to press the button, then reset the board
363 c.cmd = CMD_HARDWARE_RESET;
364 SendCommand(&c);
365 fprintf(stderr,"Press and hold down button NOW if your bootloader requires it.\n");
366 }
367
368 msleep(100);
369 CloseProxmark(conn, serial_port_name);
370
371 fprintf(stderr,"Waiting for Proxmark to reappear on %s",serial_port_name);
372 do {
373 sleep(1);
374 fprintf(stderr, ".");
375 } while (!OpenProxmark(serial_port_name));
376
377 fprintf(stderr," Found.\n");
378 return 0;
379 }
380
381 fprintf(stderr, "Error: Unknown Proxmark mode\n");
382 return -1;
383 }
384
385 static int wait_for_ack()
386 {
387 UsbCommand resp;
388 while (!WaitForResponse(CMD_ANY, &resp)) {
389 msleep(100);
390 }
391 if (resp.cmd != CMD_ACK) {
392 printf("Error: Unexpected reply 0x%04" PRIx64 " (expected ACK)\n", resp.cmd);
393 return -1;
394 }
395 return 0;
396 }
397
398 // Go into flashing mode
399 int flash_start_flashing(receiver_arg* conn, int enable_bl_writes,char *serial_port_name)
400 {
401 uint32_t state;
402
403 if (enter_bootloader(conn, serial_port_name) < 0)
404 return -1;
405
406 if (get_proxmark_state(&state) < 0)
407 return -1;
408
409 if (state & DEVICE_INFO_FLAG_UNDERSTANDS_START_FLASH) {
410 // This command is stupid. Why the heck does it care which area we're
411 // flashing, as long as it's not the bootloader area? The mind boggles.
412 UsbCommand c = {CMD_START_FLASH};
413
414 if (enable_bl_writes) {
415 c.arg[0] = FLASH_START;
416 c.arg[1] = FLASH_END;
417 c.arg[2] = START_FLASH_MAGIC;
418 } else {
419 c.arg[0] = BOOTLOADER_END;
420 c.arg[1] = FLASH_END;
421 c.arg[2] = 0;
422 }
423 SendCommand(&c);
424 return wait_for_ack();
425 } else {
426 fprintf(stderr, "Note: Your bootloader does not understand the new START_FLASH command\n");
427 fprintf(stderr, " It is recommended that you update your bootloader\n\n");
428 }
429
430 return 0;
431 }
432
433 static int write_block(uint32_t address, uint8_t *data, uint32_t length)
434 {
435 uint8_t block_buf[BLOCK_SIZE];
436
437 memset(block_buf, 0xFF, BLOCK_SIZE);
438 memcpy(block_buf, data, length);
439 UsbCommand c;
440 c.cmd = CMD_FINISH_WRITE;
441 c.arg[0] = address;
442 memcpy(c.d.asBytes, block_buf, length);
443 SendCommand(&c);
444 return wait_for_ack();
445 }
446
447 // Write a file's segments to Flash
448 int flash_write(flash_file_t *ctx)
449 {
450 fprintf(stderr, "Writing segments for file: %s\n", ctx->filename);
451 for (int i = 0; i < ctx->num_segs; i++) {
452 flash_seg_t *seg = &ctx->segments[i];
453
454 uint32_t length = seg->length;
455 uint32_t blocks = (length + BLOCK_SIZE - 1) / BLOCK_SIZE;
456 uint32_t end = seg->start + length;
457
458 fprintf(stderr, " 0x%08x..0x%08x [0x%x / %d blocks]",
459 seg->start, end - 1, length, blocks);
460
461 int block = 0;
462 uint8_t *data = seg->data;
463 uint32_t baddr = seg->start;
464
465 while (length) {
466 uint32_t block_size = length;
467 if (block_size > BLOCK_SIZE)
468 block_size = BLOCK_SIZE;
469
470 if (write_block(baddr, data, block_size) < 0) {
471 fprintf(stderr, " ERROR\n");
472 fprintf(stderr, "Error writing block %d of %d\n", block, blocks);
473 return -1;
474 }
475
476 data += block_size;
477 baddr += block_size;
478 length -= block_size;
479 block++;
480 fprintf(stderr, ".");
481 }
482 fprintf(stderr, " OK\n");
483 }
484 return 0;
485 }
486
487 // free a file context
488 void flash_free(flash_file_t *ctx)
489 {
490 if (!ctx)
491 return;
492 if (ctx->segments) {
493 for (int i = 0; i < ctx->num_segs; i++)
494 free(ctx->segments[i].data);
495 free(ctx->segments);
496 ctx->segments = NULL;
497 ctx->num_segs = 0;
498 }
499 }
500
501 // just reset the unit
502 int flash_stop_flashing() {
503 UsbCommand c = {CMD_HARDWARE_RESET};
504 SendCommand(&c);
505 msleep(100);
506 return 0;
507 }
Impressum, Datenschutz