-
Notifications
You must be signed in to change notification settings - Fork 136
/
term.c
2764 lines (2383 loc) · 82.8 KB
/
term.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* avrdude - A Downloader/Uploader for AVR device programmers
* Copyright (C) 2000-2004 Brian S. Dean <bsd@bdmicro.com>
* Copyright (C) 2021-2023 Hans Eirik Bull
* Copyright (C) 2022-2023 Stefan Rueger <stefan.rueger@urclocks.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* $Id$ */
#include <ac_cfg.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdarg.h>
#include <limits.h>
#include <unistd.h>
#include <errno.h>
#include "libavrdude.h"
#if defined(HAVE_LIBREADLINE)
#include <readline/readline.h>
#include <readline/history.h>
#ifdef _MSC_VER
#include "msvc/unistd.h"
#else
#include <unistd.h>
#endif
#ifdef WIN32
#include <windows.h>
#else
#include <sys/select.h>
#endif
#endif
#include "avrdude.h"
struct command {
char *name;
int (*func)(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
size_t fnoff;
char *desc;
};
static int cmd_dump (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_write (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_save (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_flush (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_abort (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_erase (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_pgerase(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_config (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_factory(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_regfile(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_include(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_sig (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_part (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_help (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_quit (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_send (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_parms (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_vtarg (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_varef (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_fosc (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_sck (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_spi (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_pgm (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_verbose(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
static int cmd_quell (const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]);
#define _fo(x) offsetof(PROGRAMMER, x)
struct command cmd[] = {
{ "dump", cmd_dump, _fo(read_byte_cached), "display a memory section as hex dump" },
{ "read", cmd_dump, _fo(read_byte_cached), "alias for dump" },
{ "write", cmd_write, _fo(write_byte_cached), "write data to memory; flash and EEPROM are cached" },
{ "save", cmd_save, _fo(write_byte_cached), "save memory data to file" },
{ "flush", cmd_flush, _fo(flush_cache), "synchronise flash and EEPROM cache with the device" },
{ "abort", cmd_abort, _fo(reset_cache), "abort flash and EEPROM writes, ie, reset the r/w cache" },
{ "erase", cmd_erase, _fo(chip_erase_cached), "perform a chip or memory erase" },
{ "pgerase", cmd_pgerase, _fo(page_erase), "erase one page of flash or EEPROM memory" },
{ "config", cmd_config, _fo(open), "change or show configuration properties of the part" },
{ "factory", cmd_factory, _fo(open), "reset part to factory state" },
{ "regfile", cmd_regfile, _fo(open), "I/O register addresses and contents" },
{ "include", cmd_include, _fo(open), "include contents of named file as if it was typed" },
{ "sig", cmd_sig, _fo(open), "display device signature bytes" },
{ "part", cmd_part, _fo(open), "display the current part information" },
{ "send", cmd_send, _fo(cmd), "send a raw command to the programmer" },
{ "parms", cmd_parms, _fo(print_parms), "display useful parameters" },
{ "vtarg", cmd_vtarg, _fo(set_vtarget), "set or get the target voltage" },
{ "varef", cmd_varef, _fo(set_varef), "set or get the analog reference voltage" },
{ "fosc", cmd_fosc, _fo(set_fosc), "set or get the oscillator frequency" },
{ "sck", cmd_sck, _fo(set_sck_period), "set or get the SCK period or frequency" },
{ "spi", cmd_spi, _fo(setpin), "enter direct SPI mode" },
{ "pgm", cmd_pgm, _fo(setpin), "return to programming mode" },
{ "verbose", cmd_verbose, _fo(open), "display or set -v verbosity level" },
{ "quell", cmd_quell, _fo(open), "display or set -q quell level for progress bars" },
{ "help", cmd_help, _fo(open), "show help message" },
{ "?", cmd_help, _fo(open), "same as help" },
{ "quit", cmd_quit, _fo(open), "synchronise flash/EEPROM cache with device and quit" },
{ "q", cmd_quit, _fo(open), "abbreviation for quit" },
};
#define NCMDS ((int)(sizeof(cmd)/sizeof(struct command)))
static int spi_mode = 0;
static int hexdump_line(char *buffer, unsigned char *p, int n, int pad) {
char *hexdata = "0123456789abcdef";
char *b = buffer;
int i = 0;
int j = 0;
for (i=0; i<n; i++) {
if (i && ((i % 8) == 0))
b[j++] = ' ';
b[j++] = hexdata[(p[i] & 0xf0) >> 4];
b[j++] = hexdata[(p[i] & 0x0f)];
if (i < 15)
b[j++] = ' ';
}
for (i=j; i<pad; i++)
b[i] = ' ';
b[i] = 0;
for (i=0; i<pad; i++) {
if (!((b[i] == '0') || (b[i] == ' ')))
return 0;
}
return 1;
}
static int chardump_line(char *buffer, unsigned char *p, int n, int pad) {
int i;
unsigned char b[128];
// Sanity check
n = n < 1? 1: n > (int) sizeof b? (int) sizeof b: n;
memcpy(b, p, n);
for (int i = 0; i < n; i++)
buffer[i] = isascii(b[i]) && isspace(b[i])? ' ':
isascii(b[i]) && isgraph(b[i])? b[i]: '.';
for (i = n; i < pad; i++)
buffer[i] = ' ';
buffer[i] = 0;
return 0;
}
static int hexdump_buf(const FILE *f, const AVRMEM *m, int startaddr, const unsigned char *buf, int len) {
char dst1[80];
char dst2[80];
int addr = startaddr;
unsigned char *p = (unsigned char *) buf;
while (len) {
int n = 16;
if (n > len)
n = len;
if(addr + n > m->size)
n = m->size - addr;
hexdump_line(dst1, p, n, 48);
chardump_line(dst2, p, n, 16);
term_out("%0*x %s |%s|\n", m->size > 0x10000 ? 5: 4, addr, dst1, dst2);
len -= n;
addr += n;
if (addr >= m->size)
addr = 0;
p += n;
}
return 0;
}
static int cmd_dump(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]) {
static struct mem_addr_len {
int addr;
int len;
const AVRMEM *mem;
} read_mem[32];
static int i;
const char *cmd = tolower(**argv) == 'd'? "dump": "read";
if ((argc < 2 && read_mem[0].mem == NULL) || argc > 4 || (argc > 1 && str_eq(argv[1], "-?"))) {
msg_error(
"Syntax: %s <mem> <addr> <len> # display entire region\n"
" %s <mem> <addr> # start at <addr>\n"
" %s <mem> # Continue displaying memory where left off\n"
" %s # Continue displaying most recently shown <mem>\n"
"Function: display memory section as hex dump\n"
"\n"
"Both the <addr> and <len> can be negative numbers; a negative <addr> starts\n"
"an interval from that many bytes below the memory size; a negative <len> ends\n"
"the interval at that many bytes below the memory size.\n"
"\n"
"The latter two versions of the command page through the memory with a page\n"
"size of the last used effective length (256 bytes default)\n",
cmd, cmd, cmd, cmd
);
return -1;
}
enum { read_size = 256 };
const char *memstr;
if(argc > 1)
memstr = argv[1];
else
memstr = read_mem[i].mem->desc;
const AVRMEM *mem = avr_locate_mem(p, memstr);
if (mem == NULL) {
pmsg_error("(%s) memory %s not defined for part %s\n", cmd, memstr, p->desc);
return -1;
}
int maxsize = mem->size;
if(maxsize <= 0) { // Sanity check
pmsg_error("(%s) cannot read memory %s of size %d\n", cmd, mem->desc, maxsize);
return -1;
}
// Iterate through the read_mem structs to find relevant address and length info
for(i = 0; i < 32; i++) {
if(read_mem[i].mem == NULL)
read_mem[i].mem = mem;
if(read_mem[i].mem == mem) {
if(read_mem[i].len == 0)
read_mem[i].len = maxsize > read_size? read_size: maxsize;
break;
}
}
if(i >= 32) { // Catch highly unlikely case
pmsg_error("(%s) read_mem[] under-dimensioned; increase and recompile\n", cmd);
return -1;
}
// Get start address if present
const char *errptr;
if(argc >= 3 && !str_eq(argv[2], "...")) {
int addr = str_int(argv[2], STR_INT32, &errptr);
if(errptr) {
pmsg_error("(%s) address %s: %s\n", cmd, argv[2], errptr);
return -1;
}
// Turn negative addr value (counting from top and down) into an actual memory address
if (addr < 0)
addr = maxsize + addr;
if (addr < 0 || addr >= maxsize) {
int digits = mem->size > 0x10000? 5: 4;
pmsg_error("(%s) %s address %s is out of range [-0x%0*x, 0x%0*x]\n",
cmd, mem->desc, argv[2], digits, maxsize, digits, maxsize-1);
return -1;
}
read_mem[i].addr = addr;
}
// Get number of bytes to read if present
if (argc >= 3) {
if(str_eq(argv[argc - 1], "...")) {
if (argc == 3)
read_mem[i].addr = 0;
read_mem[i].len = maxsize - read_mem[i].addr;
} else if (argc == 4) {
int len = str_int(argv[3], STR_INT32, &errptr);
if(errptr) {
pmsg_error("(%s) length %s: %s\n", cmd, argv[3], errptr);
return -1;
}
// Turn negative len value (number of bytes from top of memory) into an actual length
if (len < 0)
len = maxsize + len + 1 - read_mem[i].addr;
if (len == 0)
return 0;
if (len < 0) {
pmsg_error("(%s) invalid effective length %d\n", cmd, len);
return -1;
}
read_mem[i].len = len;
}
}
// Wrap around if the memory address is greater than the maximum size
if(read_mem[i].addr >= maxsize)
read_mem[i].addr = 0; // Wrap around
// Trim len if nessary to prevent reading from the same memory address twice
if (read_mem[i].len > maxsize)
read_mem[i].len = maxsize;
uint8_t *buf = malloc(read_mem[i].len);
if (buf == NULL) {
pmsg_error("(%s) out of memory\n", cmd);
return -1;
}
if(argc < 4 && verbose)
term_out(">>> %s %s 0x%x 0x%x\n", cmd, read_mem[i].mem->desc, read_mem[i].addr, read_mem[i].len);
report_progress(0, 1, "Reading");
for (int j = 0; j < read_mem[i].len; j++) {
int addr = (read_mem[i].addr + j) % mem->size;
int rc = pgm->read_byte_cached(pgm, p, read_mem[i].mem, addr, &buf[j]);
if (rc != 0) {
report_progress(1, -1, NULL);
pmsg_error("(%s) error reading %s address 0x%05lx of part %s\n", cmd, mem->desc, (long) read_mem[i].addr + j, p->desc);
if (rc == -1)
imsg_error("%*sread operation not supported on memory %s\n", 7, "", mem->desc);
free(buf);
return -1;
}
report_progress(j, read_mem[i].len, NULL);
}
report_progress(1, 1, NULL);
hexdump_buf(stdout, mem, read_mem[i].addr, buf, read_mem[i].len);
term_out("\v");
free(buf);
read_mem[i].addr = (read_mem[i].addr + read_mem[i].len) % maxsize;
return 0;
}
static size_t maxstrlen(int argc, const char **argv) {
size_t max = 0;
for(int i=0; i<argc; i++)
if(strlen(argv[i]) > max)
max = strlen(argv[i]);
return max;
}
typedef enum {
WRITE_MODE_STANDARD = 0,
WRITE_MODE_FILL = 1,
} Write_mode_t;
static int cmd_write(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]) {
if (argc < 3 || (argc > 1 && str_eq(argv[1], "-?"))) {
msg_error(
"Syntax: write <mem> <addr> <data>[,] {<data>[,]}\n"
" write <mem> <addr> <len> <data>[,] {<data>[,]} ... # Fill, see below\n"
" write <mem> <data> # Any <data> incl file if memory has only 1 byte\n"
" write <mem> <file> # Must be file if memory has more than 1 byte\n"
"Function: write data to memory; flash and EEPROM are normally cached\n"
"\n"
"Ellipsis ... writes <len> bytes padded by repeating the last <data> item.\n"
"\n"
"Both the <addr> and <len> can be negative numbers; a negative <addr> starts\n"
"an interval from that many bytes below the memory size; a negative <len> ends\n"
"the interval at that many bytes below the memory size.\n"
"\n"
"<data> can be binary, octal, decimal or hexadecimal integers, floating point\n"
"numbers or C-style strings and characters. If nothing matches, <data> will be\n"
"interpreted as name of a file containing data. In absence of a :<f> format\n"
"suffix, the terminal will try to auto-detect the file format.\n"
"\n"
"For integers, an optional case-insensitive suffix specifies the data size: HH\n"
"8 bit, H/S 16 bit, L 32 bit, LL 64 bit. Suffix D indicates a 64-bit double, F\n"
"a 32-bit float, whilst a floating point number without suffix defaults to\n"
"32-bit float. Hexadecimal floating point notation is supported. An ambiguous\n"
"trailing suffix, eg, 0x1.8D, is read as no-suffix float where D is part of\n"
"the mantissa; use a zero exponent 0x1.8p0D to clarify.\n"
"\n"
"An optional U suffix makes integers unsigned. Ordinary 0x hex and 0b binary\n"
"integers are always treated as unsigned. +0x, -0x, +0b and -0b numbers with\n"
"an explicit sign are treated as signed unless they have a U suffix. Unsigned\n"
"integers cannot be larger than 2^64-1. If n is an unsigned integer then -n is\n"
"also a valid unsigned integer as in C. Signed integers must fall into the\n"
"[-2^63, 2^63-1] range or a correspondingly smaller range when a suffix\n"
"specifies a smaller type.\n"
"\n"
"Ordinary 0x hex and 0b binary integers with n digits (counting leading zeros)\n"
"use the smallest size of one, two, four and eight bytes that can accommodate\n"
"any n-digit hex/bin integer. If an integer suffix specifies a size explicitly\n"
"the corresponding number of least significant bytes are written, and a\n"
"warning shown if the number does not fit into the desired representation.\n"
"Otherwise, unsigned integers occupy the smallest of one, two, four or eight\n"
"bytes needed. Signed numbers are allowed to fit into the smallest signed or\n"
"smallest unsigned representation: For example, 255 is stored as one byte as\n"
"255U would fit in one byte, though as a signed number it would not fit into a\n"
"one-byte interval [-128, 127]. The number -1 is stored in one byte whilst -1U\n"
"needs eight bytes as it is the same as 0xFFFFffffFFFFffffU.\n"
);
return -1;
}
int i;
int write_mode; // Operation mode, standard or fill
int start_offset; // Which argc argument
int len; // Number of bytes to write to memory
const char *memstr = argv[1]; // Memory name string
const AVRMEM *mem = avr_locate_mem(p, memstr);
if (mem == NULL) {
pmsg_error("(write) memory %s not defined for part %s\n", memstr, p->desc);
return -1;
}
int maxsize = mem->size;
if (argc == 3 && maxsize > 1) {
// Check whether argv[2] might be anything other than a file
Str2data *sd = str_todata(argv[2], STR_ANY & ~STR_FILE, NULL, NULL);
if(sd && sd->type) {
if(sd->type & STR_INTEGER && sd->ll >= -maxsize && sd->ll < maxsize)
pmsg_error("(write) no data specified for %s address %s\n", mem->desc, argv[2]);
else
pmsg_error("(write) no address specified for %s data %s\n", mem->desc, argv[2]);
str_freedata(sd);
return -1;
}
str_freedata(sd);
// Argv[2] might be a file --- keep it in the running for address 0
}
const char *errptr;
int addr = 0;
if(argc >= 4) {
addr = str_int(argv[2], STR_INT32, &errptr);
if(errptr) {
pmsg_error("(write) address %s: %s\n", argv[2], errptr);
return -1;
}
}
// Turn negative addr value (counting from top and down) into an actual memory address
if (addr < 0)
addr = maxsize + addr;
if (addr < 0 || addr >= maxsize) {
int digits = maxsize > 0x10000? 5: 4;
pmsg_error("(write) %s address 0x%0*x is out of range [-0x%0*x, 0x%0*x]\n",
mem->desc, digits, addr, digits, maxsize, digits, maxsize-1);
return -1;
}
// Allocate large enough data and allocation tags space
size_t bufsz = mem->size + 8 + maxstrlen(argc-3, argv+3)+1;
if(bufsz > INT_MAX) {
pmsg_error("(write) too large memory request (%lu)\n", (unsigned long) bufsz);
return -1;
}
unsigned char *buf = calloc(bufsz, 1), *tags = calloc(bufsz, 1);
if(buf == NULL || tags == NULL) {
pmsg_error("(write) out of memory\n");
return -1;
}
// Find the first argument to write to flash and how many arguments to parse and write
if(str_eq(argv[argc - 1], "...")) {
write_mode = WRITE_MODE_FILL;
start_offset = 4;
len = str_int(argv[3], STR_INT32, &errptr);
if(errptr) {
pmsg_error("(write ...) length %s: %s\n", argv[3], errptr);
free(buf); free(tags);
return -1;
}
// Turn negative len value (number of bytes from top of memory) into an actual length number
if (len < 0)
len = maxsize + len - addr + 1;
if (len == 0)
return 0;
if (len < 0 || len > maxsize - addr) {
pmsg_error("(write ...) effective %s start address 0x%0*x and effective length %d not compatible with memory size %d\n",
mem->desc, maxsize > 0x10000? 5: 4, addr, len, maxsize);
return -1;
}
} else {
write_mode = WRITE_MODE_STANDARD;
// With no user specified start address, data starts at argv[2]
// With user specified start address, data starts at a argv[3]
if(argc == 3)
start_offset = 2;
else
start_offset = 3;
len = argc - start_offset;
}
int bytes_grown = 0, filling = 0, recorded = 0, maxneeded = maxsize-addr;
Str2data *sd = NULL;
for (i = start_offset; i < len + start_offset; i++) {
// Handle the next argument
if (i < argc - start_offset + 3) {
str_freedata(sd);
sd = str_todata(argv[i], STR_ANY, p, mem->desc);
if(!sd->type || sd->errstr) {
pmsg_error("(write) data %s: %s\n", argv[i], sd->errstr? sd->errstr: "str_todata");
free(buf); free(tags);
str_freedata(sd);
return -1;
}
if(sd->warnstr)
pmsg_warning("(write) %s\n", sd->warnstr);
// Always write little endian (assume double and int have same endianess)
if(is_bigendian() && sd->size > 0 && (sd->type & STR_NUMBER))
change_endian(sd->a, sd->size);
} else {
filling = 1;
if(!sd)
break;
}
int n = i - start_offset + bytes_grown;
if(sd->type == STR_STRING && sd->str_ptr) {
size_t len = strlen(sd->str_ptr);
for(size_t j = 0; j < len; j++, n++) {
buf[n] = (uint8_t) sd->str_ptr[j];
tags[n] = TAG_ALLOCATED;
}
buf[n] = 0; // Terminating nul
tags[n] = TAG_ALLOCATED;
bytes_grown += (int) len; // Sic: one less than written
} else if(sd->type == STR_FILE && sd->mem && sd->size > 0) {
int end = bufsz - n; // Available buffer size
if(sd->size < end)
end = sd->size;
for(int j = 0; j < end; j++, n++) {
if(sd->mem->tags[j]) {
buf[n] = sd->mem->buf[j];
tags[n] = TAG_ALLOCATED;
}
}
if(end > 0) // Should always be true
bytes_grown += end-1;
} else if(sd->size > 0 && (sd->type & STR_NUMBER)) {
for(int k = 0; k < sd->size; k++, n++) {
buf[n] = sd->a[k];
tags[n] = TAG_ALLOCATED;
}
bytes_grown += sd->size-1;
} else { // Nothing written
bytes_grown--; // Sic: stay stagnat as i increases, but break when filling
if(write_mode == WRITE_MODE_FILL && filling) {
filling = 0;
break;
}
}
recorded = i - start_offset + bytes_grown + 1;
if(recorded >= maxneeded)
break;
}
str_freedata(sd);
// When in fill mode, the maximum size is already predefined
if(write_mode == WRITE_MODE_FILL) {
if(recorded < len) {
pmsg_warning("(write ...) can only fill %d < %d byte%s as last item has zero bytes\n",
recorded, len, str_plural(recorded));
len = recorded;
}
bytes_grown = 0;
} else if(addr + len + bytes_grown > maxsize) {
bytes_grown = maxsize - addr - len;
pmsg_warning("(write) clipping data to fit into %s %s memory\n", p->desc, mem->desc);
}
pmsg_notice2("(write) writing %d byte%s starting from address 0x%02x",
len + bytes_grown, str_plural(len + bytes_grown), addr);
if (write_mode == WRITE_MODE_FILL && filling)
msg_notice2("; remaining space filled with %s", argv[argc - 2]);
msg_notice2("\v");
report_progress(0, 1, avr_has_paged_access(pgm, mem)? "Caching": "Writing");
for (i = 0; i < len + bytes_grown; i++) {
report_progress(i, len + bytes_grown, NULL);
if(!tags[i])
continue;
uint8_t b;
int rc = pgm->write_byte_cached(pgm, p, mem, addr+i, buf[i]);
if (rc == LIBAVRDUDE_SOFTFAIL) {
pmsg_warning("(write) programmer write protects %s address 0x%04x\n", mem->desc, addr+i);
} else if(rc) {
pmsg_error("(write) error writing 0x%02x at 0x%05x, rc=%d\n", buf[i], addr+i, (int) rc);
if (rc == -1)
imsg_error("%*swrite operation not supported on memory %s\n", 8, "", mem->desc);
} else if(pgm->read_byte_cached(pgm, p, mem, addr+i, &b) < 0) {
imsg_error("%*sreadback from %s failed\n", 8, "", mem->desc);
} else { // Read back byte b is now set
int bitmask = avr_mem_bitmask(p, mem, addr+i);
if((b & bitmask) != (buf[i] & bitmask)) {
pmsg_error("(write) verification error writing 0x%02x at 0x%05x cell=0x%02x", buf[i], addr+i, b);
if(bitmask != 0xff)
msg_error(" using bit mask 0x%02x", bitmask);
msg_error("\n");
}
}
}
report_progress(1, 1, NULL);
free(buf);
return 0;
}
static int cmd_save(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]) {
if(argc < 3 || (argc > 1 && str_eq(argv[1], "-?"))) {
msg_error(
"Syntax: save <mem> {<addr> <len>} <file>[:<format>]\n"
"Function: save memory segments to file (default format :r raw binary)\n"
);
return -1;
}
AVRMEM *mem, *omem;
if(!(omem = avr_locate_mem(p, argv[1]))) {
pmsg_error("(save) memory %s not defined for part %s\n", argv[1], p->desc);
return -1;
}
if(argc > 3 && !(argc&1)) {
pmsg_error("(save) need pairs <addr> <len> to describe memory segments\n");
return -1;
}
// Last char of filename is format if the penultimate char is a colon
FILEFMT format = FMT_RBIN;
const char *fn = argv[argc-1];
size_t len = strlen(fn);
if(len > 2 && fn[len-2] == ':') { // Assume format specified
format = fileio_format(fn[len-1]);
if(format == FMT_ERROR) {
pmsg_error("(save) invalid file format :%c; known formats are\n", fn[len-1]);
for(int f, c, i=0; i<62; i++) {
c = i<10? '0'+i: (i&1? 'A': 'a') + (i-10)/2;
f = fileio_format(c);
if(f != FMT_ERROR)
msg_error(" :%c %s\n", c, fileio_fmtstr(f));
}
return -1;
}
len -= 2;
}
char *filename = memcpy(cfg_malloc(__func__, len+1), fn, len);
mem = avr_dup_mem(omem);
int n = argc > 3? (argc-3)/2: 1;
Segment_t *seglist = cfg_malloc(__func__, n*sizeof*seglist);
int ret = -1;
// Build memory segment list
seglist[0].addr = 0; // Defaults to entire memory
seglist[0].len = mem->size;
if(argc > 3) {
for(int cc = 2, i = 0; i < n; i++, cc+=2) {
const char *errstr;
seglist[i].addr = str_int(argv[cc], STR_INT32, &errstr);
if(errstr) {
pmsg_error("(save) address %s: %s\n", argv[cc], errstr);
goto done;
}
seglist[i].len = str_int(argv[cc+1], STR_INT32, &errstr);
if(errstr) {
pmsg_error("(save) length %s: %s\n", argv[cc], errstr);
goto done;
}
}
}
int nbytes = 0; // Total number of bytes to save
for(int i=0; i<n; i++) { // Ensure addr and lengths are non-negative
if(segment_normalise(mem, seglist+i) < 0)
goto done;
nbytes += seglist[i].len;
}
if(nbytes <= 0 && !str_eq(filename, "-"))
pmsg_warning("(save) no file written owing to empty memory segment%s\n",
str_plural(n));
if(nbytes <= 0) {
ret = 0;
goto done;
}
// Read memory from device/cache
report_progress(0, 1, "Reading");
for(int i = 0; i < n; i++) {
for(int j = seglist[i].addr; j < seglist[i].addr + seglist[i].len; j++) {
int rc = pgm->read_byte_cached(pgm, p, mem, j, mem->buf+j);
if(rc < 0) {
report_progress(1, -1, NULL);
pmsg_error("(save) error reading %s address 0x%0*x of part %s\n",
mem->desc, j<16? 1: j<256? 2: j<65536? 4: 5, j, p->desc);
return -1;
}
report_progress(j, nbytes, NULL);
}
}
report_progress(1, 1, NULL);
ret = fileio_segments(FIO_WRITE, filename, format, p, mem, n, seglist);
done:
avr_free_mem(mem);
free(seglist);
free(filename);
return ret < 0? ret: 0;
}
static int cmd_flush(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]) {
if(argc > 1) {
msg_error(
"Syntax: flush\n"
"Function: synchronise flash and EEPROM cache with the device\n"
);
return -1;
}
return pgm->flush_cache(pgm, p) < 0? -1: 0;
}
static int cmd_abort(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]) {
if(argc > 1) {
msg_error(
"Syntax: abort\n"
"Function: abort flash and EEPROM writes, ie, reset the r/w cache\n"
);
return -1;
}
pgm->reset_cache(pgm, p);
return 0;
}
static int cmd_send(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]) {
unsigned char cmd[4], res[4];
const char *errptr;
int rc, len;
if(argc > 5 || (argc < 5 && !spi_mode) || (argc > 1 && str_eq(argv[1], "-?"))) {
msg_error(spi_mode?
"Syntax: send <byte1> [<byte2> [<byte3> [<byte4>]]]\n":
"Syntax: send <byte1> <byte2> <byte3> <byte4>\n"
);
msg_error(
"Function: send a raw command to the programmer\n"
);
return -1;
}
if (spi_mode && (pgm->spi == NULL)) {
pmsg_error("(send) the %s programmer does not support direct SPI transfers\n", pgm->type);
return -1;
}
/* number of bytes to write at the specified address */
len = argc - 1;
/* load command bytes */
for (int i=1; i<argc; i++) {
cmd[i-1] = str_int(argv[i], STR_UINT8, &errptr);
if(errptr) {
pmsg_error("(send) byte %s: %s\n", argv[i], errptr);
return -1;
}
}
led_clr(pgm, LED_ERR);
led_set(pgm, LED_PGM);
rc = spi_mode? pgm->spi(pgm, cmd, res, argc-1): pgm->cmd(pgm, cmd, res);
if(rc < 0)
led_set(pgm, LED_ERR);
led_clr(pgm, LED_PGM);
if(rc >= 0) {
term_out("results:");
for(int i=0; i<len; i++)
term_out(" %02x", res[i]);
term_out("\n");
} else
pmsg_error("(send) pgm->%s() command failed\n", spi_mode? "spi": "cmd");
return rc < 0? -1: 0;
}
static int cmd_erase(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]) {
if (argc > 4 || argc == 3 || (argc > 1 && str_eq(argv[1], "-?"))) {
msg_error(
"Syntax: erase <mem> <addr> <len> # Fill section with 0xff values\n"
" erase <mem> # Fill with 0xff values\n"
" erase # Chip erase (no chache, immediate effect)\n"
"Function: perform a chip or memory erase; flash or EEPROM erase is cached\n"
);
return -1;
}
if (argc > 1) {
const char *memstr = argv[1];
const AVRMEM *mem = avr_locate_mem(p, memstr);
if (mem == NULL) {
pmsg_error("(erase) memory %s not defined for part %s\n", argv[1], p->desc);
return -1;
}
const char *args[] = {"write", memstr, "", "", "0xff", "...", NULL};
// erase <mem>
if (argc == 2) {
args[2] = "0";
args[3] = "-1";
}
// erase <mem> <addr> <len>
else {
args[2] = argv[2];
args[3] = argv[3];
}
return cmd_write(pgm, p, 6, args);
}
term_out("erasing chip ...\n");
// Erase chip and clear cache
int rc = pgm->chip_erase_cached(pgm, p);
if(rc == LIBAVRDUDE_SOFTFAIL) {
pmsg_info("(erase) emulating chip erase by writing 0xff to flash ");
const AVRMEM *flm = avr_locate_flash(p);
if(!flm) {
msg_error("but flash not defined for part %s?\n", p->desc);
return -1;
}
int addr, beg = 0, end = flm->size-1;
if(pgm->readonly) {
for(addr=beg; addr < flm->size; addr++)
if(!pgm->readonly(pgm, p, flm, addr)) {
beg = addr;
break;
}
if(addr >= flm->size) {
msg_info("but all flash is write protected\n");
return 0;
}
for(addr=end; addr >= 0; addr--)
if(!pgm->readonly(pgm, p, flm, addr)) {
end = addr;
break;
}
}
msg_info("[0x%04x, 0x%04x]; undo with abort\n", beg, end);
for(int addr=beg; addr <= end; addr++)
if(!pgm->readonly || !pgm->readonly(pgm, p, flm, addr))
if(pgm->write_byte_cached(pgm, p, flm, addr, 0xff) == -1)
return -1;
return 0;
}
if(rc) {
pmsg_error("(erase) programmer %s failed erasing the chip\n", pgmid);
return -1;
}
return 0;
}
static int cmd_pgerase(const PROGRAMMER *pgm, const AVRPART *p, int argc, const char *argv[]) {
if(argc != 3 || (argc > 1 && str_eq(argv[1], "-?"))) {
msg_error(
"Syntax: pgerase <mem> <addr>\n"
"Function: erase one page of flash or EEPROM memory\n"
);
return -1;
}
const char *memstr = argv[1];
const AVRMEM *mem = avr_locate_mem(p, memstr);
if(!mem) {
pmsg_error("(pgerase) memory %s not defined for part %s\n", memstr, p->desc);
return -1;
}
if(!avr_has_paged_access(pgm, mem)) {
pmsg_error("(pgerase) %s memory cannot be paged addressed by %s\n", memstr, pgmid);
return -1;
}
int maxsize = mem->size;
const char *errptr;
int addr = str_int(argv[2], STR_INT32, &errptr);
if(errptr) {
pmsg_error("(pgerase) address %s: %s\n", argv[2], errptr);
return -1;
}
if (addr < 0 || addr >= maxsize) {
pmsg_error("(pgerase) %s address 0x%05x is out of range [0, 0x%05x]\n", mem->desc, addr, maxsize-1);
return -1;
}
if(pgm->page_erase_cached(pgm, p, mem, (unsigned int) addr) < 0) {
pmsg_error("(pgerase) unable to erase %s page at 0x%05x\n", mem->desc, addr);
return -1;
}
return 0;
}
// Config command
static const int MAX_PAD = 10; // Align value labels if difference between their lengths is less than this
typedef union { // Lock memory can be 1 or 4 bytes
uint8_t b[4];
uint32_t i;
} fl_t;
typedef struct { // Fuses and lock bits
uint16_t fuses[16]; // pdicfg fuse has two bytes
uint32_t lock;
int fread[16], lread;
int islock;
uint32_t current;
} Fusel_t;
typedef struct {
const Configitem_t *t; // Configuration bitfield table
const char *memstr; // Memory name but could also be "lockbits"
const char *alt; // Set when memstr is an alias
int match; // Matched by user request
int ok, val, initval; // Has value val been read OK? Initval == -1 if not known
} Cfg_t;
typedef struct { // Context parameters to be passed to functions
int verb, allscript, flheaders, allv, vmax, printfactory;
} Cfg_opts_t;
// Cache the contents of the fuse and lock bits memories that a particular Configitem is involved in
static int getfusel(const PROGRAMMER *pgm, const AVRPART *p, Fusel_t *fl, const Cfg_t *cci, const char **errpp) {
const char *err = NULL;
char *tofree;
int islock;
islock = str_starts(cci->memstr, "lock");
if((islock && cci->t->memoffset != 0) ||
(!islock && (cci->t->memoffset < 0 || cci->t->memoffset >= (int) (sizeof fl->fuses/sizeof*fl->fuses)))) {
err = cache_string(tofree = str_sprintf("%s's %s has invalid memoffset %d", p->desc, cci->memstr, cci->t->memoffset));
free(tofree);
goto back;
}
if(islock && fl->lread) { // Cached lock OK
fl->current = fl->lock;
fl->islock = 1;
goto back;
}
if(!islock && fl->fread[cci->t->memoffset]) { // Cached fuse OK
fl->current = fl->fuses[cci->t->memoffset];
fl->islock = 0;
goto back;
}